Symfony - returns JSON from a peer method call in action

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

I need to get these elements in JSON.

My peer method is similar:

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:

 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 elements. The problem is how to return all elements in JSON?

I tried using:

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

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

thanks

+4
source share
4 answers

It seems that json_encode() doesn't like the way propel objects are created.

Another solution would be to force Propel to return to the main 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; } 
+3
source

Propel 1.6:

  • object-> toJSON ();
  • gallery-> ExportTo ('JSON');
+3
source

json_encode / json_decode can only encode / decode PHP arrays, not objects. Variable

 $words 

will be an array of Item objects, so the output you wrote.

There are basically two solutions. You write your own json encoder that works for objects, for example, the first comment here:

http://php.net/manual/en/function.json-encode.php

or you write a function that converts Item objects to PHP arrays, for example here:

http://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html

+1
source

You can also call toArray() on your objects.

 $words = ItemPeer::searchFromArticleRequest($this->word); $wordsArray = array(); foreach ($words as $word) { $wordsArray[] = $word->toArray(); } return $this->renderText(json_encode($wordsArray)); 

Propel 1.6 will have a toJSON() method for individual objects or for a whole set of objects.

+1
source

Source: https://habr.com/ru/post/1345116/


All Articles