Search code examples
phpcontrollersymfony-1.4doctrine-1.2

Call a method from an action


I have a question class with an $id property and a getId() method. I also have an index action in the controller in which I wish to display the number of answers to that question.

class questionActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {          
        $q_id = $this->getQuestion()->getId();

        $this->answers = Doctrine_Core::getTable('answer')
                                                ->createQuery('u')
                                                ->where('u.question_id = ?', $q_id)
                                                ->execute();
  }

In my indexSuccess template:

<?php if ($answers) : ?>
  <p><?php echo count($answers) ?> answers to this request.</p>
<?php endif; ?>

However, this results in an Error: call to undefined method.

If I assign the value of $q_id manually, everything works perfectly.

How can I assign it with a call to the method getId() from the action? Should that call even be in the controller?


Solution

  • You receive that error because getQuestion() is not implemented in the controller.

    I will assume you are passing the question id as a GET parameter.

    In this case you could try something like:

      class questionActions extends sfActions {
    
        public function executeIndex(sfWebRequest $request) {
          $q_id = $request->getParameter('question_id');
    
          $question = Doctrine_Core::getTable('question')->find($q_id);
    
          $this->answers = Doctrine_Core::getTable('answer')
            ->createQuery('u')
            ->where('u.question_id = ?', $question->getId())
            ->execute();
        }
    

    Or better

    class questionActions extends sfActions {
    
      public function executeIndex(sfWebRequest $request) {
        $q_id = $request->getParameter('question_id');
        $question = Doctrine_Core::getTable('question')->find($q_id);
        $this->answers = $question->getAnswers();
      }