Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy this function doesn't return the value? - Symfony2
    primarykey
    data
    text
    <p>In the actions of my controller I often select a row from a table in the database by its id, so I separated this to a function. But every time when I do this I make a check if something was returned by the query, so I want to separate this to the function, too. Here is my code:</p> <p>This function is in a Controller, which is extended by my Contoller in which are these actions:</p> <pre><code>protected function findById($id, $class) { $result = $this-&gt;getEM()-&gt;getRepository('EMMyFriendsBundle:'.$class)-&gt;find($id); if($result == null) { return false; } else { return $result; } } </code></pre> <p>And this is my Controller:</p> <pre><code>class FriendController extends Controller { private $em; private $friend; private function init($id) { $this-&gt;em = $this-&gt;getEM(); $this-&gt;friend = $this-&gt;findById($id, 'Friend'); if(!$this-&gt;friend) { return $this-&gt;render('EMMyFriendsBundle:Friend:error.html.twig', array( 'item' =&gt; 'friend')); } } /* * Displays all the information about a concrete friend */ public function displayAction($id) { $this-&gt;init($id); if($this-&gt;friend-&gt;getCategory() != null) { $category = $this-&gt;friend-&gt;getCategory()-&gt;getName(); } else { $category = null; } return $this-&gt;render('EMMyFriendsBundle:Friend:friend.html.twig', array( 'friend' =&gt; $this-&gt;friend, 'category' =&gt; $category)); } // ... } </code></pre> <p>When I choose an ID, which don't exist (like 38743874) it goes to the if-part in the init function, but doesn't render the template error.html.twig :( But if I take this part</p> <pre><code>if(!$this-&gt;friend) { return $this-&gt;render('EMMyFriendsBundle:Friend:error.html.twig', array( 'item' =&gt; 'friend')); } </code></pre> <p>out of the <code>init()</code> function and put it in <code>displayAction($id)</code> just after calling <code>$this-&gt;init($id)</code>, it works. But I don't want to write this in every single action of that controller. Any ideas how to separate it to avoid code duplication?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload