formscakephpsubmit-buttoncakephp-4.x

How to detect which button was used to submit the form?


I can't seem to detect a button press in cakephp4. In cake3 it was easy.

In Form I have:

echo $this->Form->button('View Data', [
    'name' => 'viewdata',
    'type' => 'submit',
    'class' => 'btn btn-primary'
]); 

In Controller I have:

if ($this->request->is('post') ) {
    .... 
    debug($this->request->getDdata());
    if (!empty($this->request->getData('viewdata'))) {

I click the button and I see 'viewdata'='' so it detects the button has been clicked but its made the value = null? and I can't invoke the button press function of viewdata.

https://book.cakephp.org/4/en/views/helpers/form.html#creating-buttons-and-submit-elements


Solution

  • The value is not null, it's an empty string. So you could for example do a strict check for that exact value, ie:

    if ($this->request->getData('viewdata') === '') {
        // view data submit button was used
    }
    

    Or just check for the keys existence by comparing against null:

    if ($this->request->getData('viewdata') !== null) {
        // view data submit button was used
    }