0
votes
  • I have a 'users' table with many fields like username, name, email, password, sex, birthday, avatar, etc. I have described all of them in the Users model of my ZF2 application using the InputFilter.

The problem is the following: - I have some forms like main settings (with only the name, sex and birthday fields in) and I would like to edit only these three fields in the database via this form (and respectively to edit other fields like password and email in other forms in other pages of the site). However, it doesn't seem to work:

$request = $this->getRequest();
    if ($request->isPost()) {
        $users = new Users();
        $form->setInputFilter($users->getInputFilter());
        $form->setData($request->getPost());

        if ($form->isValid()) {
            $users->exchangeArray($form->getData());
            $this->getUsersTable()->editUser($users, $userInfo->user_id);
            $message = 'Профилът ви беше успешно променен!';
        }
    }

Here is the form that I want to update only the fields name, birthday and sex.

And here is the model:

public function editUser(Users $user, $userID) {
    $data = array(
        'name' => $user->name,
        'birthday' => $user->birthday,
        'sex' => $user->sex,
    );

    $this->tableGateway->update($data, array('user_id' => $userID));
}

$form->getMessages() returns an empty array and var_dump($form->isValid) returns boolean false. If I delete all other MySQL fields and filters in the InputFilter and I keep only the three fields (name, birthday and sex) in the model, it's all ok and the form validation works. But when I describe all other fields of the 'users' table in the model, it doesn't. Hope I explained it well. Any ideas?

1

1 Answers

3
votes

You can use Validation Groups to only validate certain fields when you only want to save partial data:

http://framework.zend.com/manual/2.0/en/modules/zend.form.quick-start.html#validation-groups

for example:

$form->setValidationGroup('name', 'sex', 'birthday');
$form->setData($data);
if ($form->isValid()) {
    // Contains only the "name", "sex", "birthday"
    $data = $form->getData();
}