Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony - returning JSON from a peer method call in an action

I have some code that checks a parameter and the calls a peer method to get me items from the DB.

What I need to get is these items in JSON.

My peer method is like:

public static function searchFromRequest($word)
{
    $c = new Criteria();
    $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID);
    $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);
    $c->addAnd(self::ARTICLE_ID, null, Criteria::ISNOTNULL);
    $c->addAscendingOrderByColumn(self::TITLE);
    return self::doSelect($c);
}

and my action is:

public function executeSearch()
{
    $this->word = $this->getRequestParameter('word');
    $this->content_type = $this->getRequestParameter('content_type');
    if($this->content_type == 'article')
    {
        $words = ItemPeer::searchFromRequest($this->word);
    }
    else
    { 
       echo "Nothing here";
    }

I can var_dump($words) and I get an array (collection) of items. The problem is, how do I return all of the items in JSON?

I've tried using:

        $this->getResponse()->setHttpHeader('Content-type', 'application/json');
        $words = ItemPeer::searchFromArticleRequest($this->word);
        return $this->renderText(json_encode($words));

But this just returns loads of empty JSON brackets: [{},{},{},{},{},{},{},{},{},{},{},{},{},{}]

Thanks

like image 844
terrid25 Avatar asked Feb 24 '23 17:02

terrid25


2 Answers

It seems that json_encode() doesn't like the way Propel Objects are built.

Another solution could be forcing Propel to returnin basic associative objects, using XXXPeer::doSelectStmt()

public static function searchFromRequest($word, $returnPropelObjects = true)
{
    $c = new Criteria();
    $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID);
    $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);
    $c->addAnd(self::ARTICLE_ID, null, Criteria::ISNOTNULL);
    $c->addAscendingOrderByColumn(self::TITLE);

    if ($returnPropelObjects)
      return self::doSelect($c);

    $stmt = self::doSelectStmt($c);
    $results = array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $results[] = $row;
    }
    return $results;
}
like image 120
Frosty Z Avatar answered Apr 26 '23 21:04

Frosty Z


Propel 1.6:

  • object->toJSON();
  • collection->exportTo('JSON');
like image 31
Evgeni Nabokov Avatar answered Apr 26 '23 23:04

Evgeni Nabokov