CakePHP 2.0 Determine which submit button has been clicked

后端 未结 4 1746
暖寄归人
暖寄归人 2021-02-06 00:20

In CakePHP 1.3 you can create a form with multiple submit buttons:

echo $this->Form->submit(\'Submit 1\', array(\'name\'=>\'submit\');
echo $this->Fo         


        
4条回答
  •  一向
    一向 (楼主)
    2021-02-06 00:59

    Generally it is a bad practise to use the same name for both submit buttons. There should be a "submit" key in the $_POST and $this->request->data

    I tested this in CakePHP 2.1.1 as shown below:

    The view code:

    Form->create('Message', array('action'=>'test')); 
    //  Extra test input field
    echo $this->Form->input('test');
    ?>
    
    
    Form->submit('Yes', array('div'=>false, 'name'=>'submit')); echo $this->Form->submit('No', array('div'=>false, 'name'=>'submit')); ?>
    Form->end()?>

    The in the controller in $this->request->data:

    array(
        'submit' => 'Yes',
        'Message' => array(
            'test' => 'TestFieldTest'
        )
    )
    

    And in $_POST:

    array(
        '_method' => 'POST',
        'data' => array(
            'Message' => array(
                'test' => 'TestFieldTest'
            )
        ),
        'submit' => 'Yes'
    )
    

    You can also give the two submits different names:

    echo $this->Form->submit('Yes', array('div'=>false, 'name'=>'submitY')); 
    echo $this->Form->submit('No', array('div'=>false, 'name'=>'submitN')); 
    

    This way you can differ them in the $_POST or $this->request->data, because the keys will be the submits' names:

    array(
        'submitY' => 'Yes',
        'Message' => array(
            'test' => 'foo'
        )
    )
    
    array(
        '_method' => 'POST',
        'data' => array(
            'Message' => array(
                'test' => 'Bar'
            )
        ),
        'submitY' => 'Yes'
    )
    

    Then to determine which button is pressed you can use a simple isset($_POST['']) or over $this->request->data ?

提交回复
热议问题