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

Pass model object from volt template to controller

Hi All,

I understant that I can pass a model object from controller to the volt template easily. E.g.

$this->view->myobjects

from volt viewers, I can access myobjects

Question is: how do this the otherway arround please? I.e. pass myobjects TO controller.

Please help. Thanks a lot in advance

What you mean ? View is a generated html displayed in borwser. If you want pass something to controller you have to made request to server. If you want to pass some data you have to make put/post request with form/params and get them in the controller.



2.2k

Thanks for your prompt reply.

All Model properties are in the form. Currently, I have to extract myobjects properties via getPost individually, e.g. in the controller's saveAction function, I do: myobjects->prop1 = $this->request->getPost("prop1"); myobjects->prop2 = $this->request->getPost("prop2"); myobjects->prop3 = $this->request->getPost("prop3"); .......................

I was wondering if I could just do above in a single line: myobjects = $this->request->getPost("myobjects");

Thanks



2.2k

Purpose: I don't wish to change the controller when database schema changes



93.7k
Accepted
answer
edited Oct '15

Hey,

you can do something like

foreach ($this->request->getPost() as $key => $value) {
    $myobjects->$key = $value;
}

But i strongly recommend to limit the fields that can be modified this way if u are saving them in database.

For example a simple setup, like so:

$allowedFields = array('title', 'description');
foreach ($allowedFields as $field) { 
    $myobjects->$field = $this->request->getPost($field); 
}


2.2k

thanks a lot.

security is handled in Model beforeSave function.

If the info helped you, you can mark as resolved so other users with similar problem can use it.



2.2k

Should I just click "Accept Answer"? Other wise, please advise how.

Thanks

Yes, click on the answer which solved your problem.

edited Oct '15

You can also just get whole post without argument and when use whitelist when create/update entity.

@jwang628 @Jurigag

Yeah Jurigag solution is even cleaner. Going to leave it as reference here in case someone needs it:

$robot = new Robots();
$robot->save(
    $_POST,
    array(
        'name',
        'type'
    )
);

More info here: https://docs.phalcon.io/en/latest/reference/models.html#creating-updating-records

edited Oct '15

Well still you shouldnt use $_POST array. Just use $this->request->getPost();

Yep you are right, i just copied the example from the docs.



2.2k

thanks a lot, all.