phpsymfonydoctrinetagsposts

Symfony2 - Setting up a tag cloud in the side bar


I'm looking to recreate the tag cloud sidebar you normally see in blogs where the user selects on a tag and it brings up all posts that has that specific tag.

Right now I am having trouble figuring how to setup the query.

I have the query to pull all the tags:

$blogTags = $this->createQueryBuilder('b')
        ->select('b.tags')
        ->getQuery()
        ->getResult();

    return $blogTags;

But how do I set it up to where it pulls up only the posts by that tag selected by the user from a group of tags in the sidebar?

I have the code that stores the tags and weights them in the sidebar, I'm looking for the next step to link the tags to their specific posts.

getsTags()

public function getTags()
{
    $blogTags = $this->createQueryBuilder('b')
        ->select('b.tags')
        ->getQuery()
        ->getResult();

    $tags = array();

    foreach ($blogTags as $blogTag) {
        $tags = array_merge(explode(",", $blogTag['tags']), $tags);
    }

    foreach ($tags as $tag) {
        $tag = trim($tag);
    }

    return $tags;
}

getTagWeights()

public function getTagWeights($tags)
{
    $tagWeights = array();
    if (empty($tags))
        return $tagWeights;

    foreach ($tags as $tag)
    {
        $tagWeights[$tag] = (isset($tagWeights[$tag])) ? $tagWeights[$tag] + 1 : 1;
    }
    // Shuffle the tags
    uksort($tagWeights, function() {
        return rand() > rand();
    });

    $max = max($tagWeights);

    // Max of 5 weights
    $multiplier = ($max > 5) ? 5 / $max : 1;
    foreach ($tagWeights as &$tag)
    {
        $tag = ceil($tag * $multiplier);
    }

    return $tagWeights;
}

Solution

  • Hope this helps others from spending hrs and hrs on this.

    public function getPostsByTags($tag)
    {
        $query = $this->createQueryBuilder('b')
            ->where('b.tags like :tag')
            ->setParameter('tag', '%'.$tag.'%');
    
        return $query->getQuery()->getResult();
    }