0
votes

I have a form in my CakePHP 3 project that edits user data. In my case an admin user can edit other users their roles.

When posting the form (actual request is a 'PUT' because of the edit), I get both the role and the id of the user.

The request data:

Array
(
    [role] => admin
    [id] => 2
)

This incoming data complete and correct. However, when I add the data to either '->newEntity' or '->patchEntity', the role is taken correctly, but id is just not added.

$user = $this->Users->newEntity($this->request->data, array('validate' => 'edit'));

$user = $this->Users->newEntity();
$user = $this->Users->patchEntity($user, $this->request->data, array('validate' => 'edit'));

In both case above I get the role, but not the id. Both give the following array:

Array
(
     [role] => admin
)

I use a custom validator, because only the id and role needs to validate for editing.

public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->requirePresence('username', 'create')
        ->notEmpty('username');

    $validator
        ->requirePresence('password', 'create')
        ->notEmpty('password');

    $validator
        ->allowEmpty('role');

    return $validator;
}

public function validationEdit(Validator $validator)
{
    $validator
        ->integer('id')
        ->requirePresence('id')
        ->notEmpty('id');

    $validator
        ->allowEmpty('role');

    return $validator;
}

I tried adding more restrictions to the 'edit' validator, but the id is never added regardless. The 'edit' validator is being used though. Changing the validate parameter to 'default' gives all the expected errors from the default validator, however the id is still not added.

Is there something obvious I am missing here? I should be some basic CakePHP stuff.

1
Did you bake your edit action? Your code doesn't look like it, if you do you usually see how it works. get() always, plus a patchEntity() call when posted. There is no newEntity() for edits.mark
I did bake, however I did add the validationEdit functionDijkeMark
No you did not, or there wouldnt be any newEntity() in the code...mark
I did bake at the start. Then I started adding stuf when I couldn't work it out. But it works now ^^DijkeMark

1 Answers

2
votes

You don't need newEntity for editing existing record, If you are trying to edit role of user then just do:

$user = $this->Users->get($this->request->data['id']);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        if ($this->Users->save($user)) {
            // updated
        }
     }