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

Create object in Model

Hi,

I want to create a new object when I save an Object in the 'beforeSave()' method. I don't understand why my member is always empty when I save it.

Here is my model :

    <?php
    use Phalcon\Mvc\Model;

    class Pictures extends Model {

      public $id_item;                  
      public $filename;                 
      public $legend;                       
      public $date;                     
      public $online;                       

      public function initialize() {

          $this->belongsTo("id_item", "Items", "id");                   //FK from Items

      }

      public function beforeSave() {

          $auth = $this->getDI()->getSession()->get('auth');
          $user_id = $auth['user_id'];
          $account_id = $auth['account_id'];

          $item = new Items();

          $item->id_account = $account_id;
          $item->id_owner = $user_id;
          $item->publication_date = date("Y-m-d H:i:s");
          $item->revision = 1;
          $item->read = 0;

          $item->save();

          $this->id_item = $item->id;

      }

    }

And in my controller I'll create Pictures :

            $new_picture = new Pictures();

            $new_picture->filename = $explodeFilename[0].'.jpg';
            $new_picture->online = 'true';

            if(!$new_picture->save()){
              foreach ($new_picture->getMessages() as $message) {
                $messages .= $message.' -- ';
              };
              echo 'Message: '.$messages;
            }

So... This doesn't work I don't know why. The error said "id_item is required".

It seems that there is something wrong in my beforeSave() when I'm trying to set my id_item member.

Could you help me ?

edited Dec '15

Phalcon is checking related model alias for notNull in validation. Just change beforeSave to beforeValidation or disable checking nulls:

\Phalcon\Mvc\Model::setup(array(
    'notNullValidations' => false
));