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
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;
}
Propel 1.6:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With