I have a form that has to handle some elements as part of an array.
echo $this->Form->control('config.sys_file_id', ['type' => 'number']);
echo $this->Form->control('click_enlarge', ['type' => 'checkbox']);
echo $this->Form->control('config.max_width', ['type' => 'number']);
echo $this->Form->control('config.max_height', ['type' => 'number']);
echo $this->Form->control('config.fixed_width', ['type' => 'number']);
echo $this->Form->control('config.fixed_height', ['type' => 'number']);
This would work fine, except I need to handle config.sys_file_id
with some JS.
I know that I have to call $this->Form->unlockField()
, but I can’t figure out the right syntax to use when the field is part of an array.
So far I’ve tried
$this->Form->unlockField('sys_file_id');
$this->Form->unlockField('config');
$this->Form->unlockField('config.sys_file_id');
$this->Form->unlockField('config[sys_file_id]');
but the request still gets black-holed by the SecurityComponent
.
I have stumbled upon these two questions How to 'unlock' a field in a CakePHP form when it is part of a hasMany association and UnlockField not working in CakePHP but they are both very old and refer to CakePHP 2, while I’m using CakePHP 4.
2
Answers
The correct syntax for unlocking the input (when is an array) from the view is with a dot:
https://api.cakephp.org/4.4/class-Cake.View.Helper.FormHelper.html#unlockField()
But make sure to use
$this->Form->unlockField()
between the$this->Form->create()
and$this->Form->end();
:If you place
$this->Form->unlockField('config.sys_file_id');
outside the formend()
orcreate()
you’ll get a CakePHP exception:I tested this code on CakePHP 4.4 Strawbery and it works.
If your JAVASCRIPT code is altering other fields by mistake, your problem is there.
I had the same issue ,because I placed the Form->unlockField(‘myField’); ?> before the $this->Form->end() line, and it was no working, but I fixed moving the unlockField method after the $this->Form->create() line. Now it works!