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

Forms: Skip running one (or more) setter on the entity/model when $Form->isValid() is executed - but still validate it

I'm using Phalcon's Form class, with validation on the form (not the model). There's a $User model object set as the entity on the form, like so...

$User = User::findFirstById($user_id);
$Form = new UserEditForm($User);
$isValid = $Form->isValid($this->request->getPost());

When isValid() is executed, it sets all the values in the $User entity automatically, which is great most of the time. But sometimes I want some fields to be skipped (for setting only), but still validated on. Is there a way to have Phalcon skip running the setter for one or more fields, but still include them for validation?

An example of why I want to do this right now, is that the system I'm building requires usernames to be moderated by admins. So while I still want to display and validate the "username" field, I don't actually want the value to be automatically set by $User->setUsername() - as it needs to first go through the moderation system.

At the moment I'm just handling this by changing the form field name to something this isn't a real field, i.e. "pendingUsername" so that it can't be set. I guess this is safe, but feels a bit hacky.

Also there doesn't seem to be a "Forms" category on the forum here, is there a reason for that? Not sure if I'm posting in the right category.



33.8k

I think you maybe should add an argument to the initializator of the form class:

public function initialize($skip = false)
{
    // ...
    if ($skip === true)
    {
        // Access every field you want to skip and set its value to NULL.
        // I think is something like "$this->get('userName')->value = null", but don't remember well.
    }
    // ...
}


3.1k

Hey thanks for the response. But sure if I really understood it though?

If I set the value to null, then the field can't be validated can it? I still want the field and its value in the form object, and to validate it. I just don't want it to be automatically set on the entity model as well.