I have the need of creating a page with multiple forms on it that have 'copies' and 'printer_id' fields on them. Each form has, or might need separate validation values.
My first attempts ended up with the other form with the same field names getting the values from the submitted form as shown
However after some trial and error I got a solution that works as desired. I have posted the working solution at https://github.com/jmcd73/cakephp4-modelless-forms
I tried a number of approaches but in the end each form needs to have completely independent fieldNames so that it does not access either the GET parameters, context or data from the other form. Tweaking 'valueSources' didn't fix the problem.
There are some minor problems that arise by using unique fieldnames for each modelless form instance
- You may need to strip the custom prefixes from the control names if you want to use them down stream. Your forms will POST values such as
[ 'left-copies => 10 ]
and you may want to make that into[ 'copies' => 10 ]
- The auto-magic labelling gets funky with the custom field names (.e.g. instead of "Copies" derived from a control name of "copies" it becomes "Left Copies" derived from 'left-copies'. You will have to specify the label names in your control options array
- Instead of a select named 'printer_id' being auto-filled with options from the
$printers
variable view variable you have to manually specify the options for you select control
<?= $this->Form->control(
$formName . '-printer_id',
[
'label' => "Printer",
'empty' => '(select)',
'options' => $printers
]
); ?>
Eventually I got it working as expected and found I could also inject different validation parameters for each form. With custom field names the forms no longer grabbed the values from the other form on the page.
What is nice with CakePHP 4 and the new modelless forms is that the validation criteria you set in the custom form class seems to be available via javascript prompts
The secret is to add methods to custom form class you create with bin/cake bake form CustomFormName
command.
So when you instantiate the class you also add some custom methods to it and then call those methods to configure it for the specific form on the page. The example on Github shows these methods. Have a look on github under src/Form/CustomPrintSuccessForm.php
for an example.
0 Comments