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

Unable to set form fields using setDefault in editAction

Hello,

I am using Phalcon 1.3.4 on Wampserver (Windows 7). I am using the code generated by DevTools for the Controller. For each line of code containing setDefault() in editAction() as shown below:

$this->tag->setDefault("co_comp_iid", $ro_client_m->co_comp_iid);

I get an error like below, i.e. for each field in the form I get a similar error:

[22-May-2015 17:35:38 Asia/Calcutta] PHP Notice:  Access to undefined property RAB\Models\RoClientM::co_comp_iid in C:\Wamp\www\relord\app\controllers\RoClientMController.php on line 107

If I do not use Forms and use the code as shown below then it works fine for each field without any error.

<td align="right"> <label for="co_comp_iid">Comp Iid</label>  </td>    
<td align="left">{{ text_field("co_comp_iid", "type" : "numeric") }} </td>

The View code is:

<td><label for="co_comp_iid">Comp Iid</label></td><td>{{ form.render("co_comp_iid") }}</td>

Form code is:

$co_comp_iid = new Text('co_comp_iid');
$this->add($co_comp_iid);

The Model and database table contain the co_comp_iid field so there is no reason for this error to appear.

Thanks Amal



51.1k
Accepted
answer

In your form:

class Form
{
    public function initialize($entity = null, $options = null)
    {
        $co_comp_iid = new Text('co_comp_iid');

        if ($options['edit'] === true) {
            $co_comp_iid->setDefault($entity->co_comp_iid);
        }

        $this->add($co_comp_iid);
    }
}

In your controller:

use Form;
use Model;

class Controller
{
    public function addAction()
    {
        $form = new Form();
        $this->view->form = $form;
    }

    public function editAction($id)
    {
        $entity = Model::findFirstById($id);

        if (!$entity) {
            throw new \Exception('Object not found');
        }

        $form = new Form($entity, ['edit' => true]);
        $this->view->form = $form;
    }
}


15.2k

I think you can also check $entity is null in the form instead of using edit option

In your form:

class Form
{
  public function initialize($entity = null, $options = null)
  {
      $co_comp_iid = new Text('co_comp_iid');

      if ($options['edit'] === true) {
          $co_comp_iid->setDefault($entity->co_comp_iid);
      }

      $this->add($co_comp_iid);
  }
}

In your controller:

use Form;
use Model;

class Controller
{
  public function addAction()
  {
      $form = new Form();
      $this->view->form = $form;
  }

  public function editAction($id)
  {
      $entity = Model::findFirstById($id);

      if (!$entity) {
          throw new \Exception('Object not found');
      }

      $form = new Form($entity, ['edit' => true]);
      $this->view->form = $form;
  }
}