We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Variable being lost when passing to a form

Hi There,

I am currently working on a project and something very odd is occuring. I am instantiating a form and passing a variable to it from the controller. However, the variable is not being passed. If I perform a var_dump() in the controller on the last line before it is passed to the form, I can see the variable as expected. However, if I perform the same var_dump() command on the first line of the form, it returns NULL. I have attached a code snippet below, which works correctly on other controllers and forms:

Here is the code in the controller

public function someAction($var){
    $form = new formExample(); 
    var_dump($var); //Outputs Correct Variable 
    $form->initialize($var); 
    $this->view->form = $form; 
}

Here is the code in the form.

class formExample extends FormBase
  {
      public function initialize($var)
      {
          var_dump($var); //Outputs NULL
      }
  }

If anyone could provide advice it would be greatly appreciated.

Regards



77.7k
Accepted
answer

Form::initialize() is a "magic" method of Phalcon replacing __construct(), it will automatically be called when you create a new instance, you shouldn't call it manually.

So because you create the instance with empty parameters, nothing gets passed in to initialize. Also, there is a limitation for the parameter types: The first (if provided) has to be an object and the second an array.

I think this would work:

public function someAction($var){
    $form = new formExample($var);  // $var has to be an object
    $this->view->form = $form; 
}
class formExample extends FormBase
  {
      public function initialize($var)
      {
          var_dump($var); // Dumbs object passed in to constructor
      }
  }

Lajos,

Thanks very much, this has solved my issue.

Regards, Ben

Form::initialize() is a "magic" method of Phalcon replacing __construct(), it will automatically be called when you create a new instance, you shouldn't call it manually.

So because you create the instance with empty parameters, nothing gets passed in to initialize. Also, there is a limitation for the parameter types: The first (if provided) has to be an object and the second an array.

I think this would work:

public function someAction($var){
   $form = new formExample($var);  // $var has to be an object
   $this->view->form = $form; 
}
class formExample extends FormBase
 {
     public function initialize($var)
     {
         var_dump($var); // Dumbs object passed in to constructor
     }
 }