Zend_Form - multiple forms on same page

a 夏天 提交于 2019-12-08 05:48:50

问题


Having multiple forms in one page, when i submit one of them, how can i tell wich one was submitted?

I thought about generating uniqe ids for each from, and saving them as hidden fields and to the user-session - while this is a solution, the problem with it is that there is no good place to remove old ids from the session.

Any better ideas how to solve this problem?

Thanks in advance!


回答1:


First of all: have you considered sending the two forms to two different actions? That way you can handle each form separately in an action each. This should be the "best-pratice" if you're using the Zend MVC component.

The other option is to check for the value of the submit button which will be included in the request, e.g.

<input type="submit" name="save" value="form1" />
// in PHP:
// $_POST["save"] will contain "form1"

<input type="submit" name="save" value="form2" />
// in PHP:
// $_POST["save"] will contain "form2"

Be careful as the value-attribute will be rendered as the button's label.

So perhaps you want to distingush the forms by different submit-button names:

<input type="submit" name="save-form1" value="Submit" />
// in PHP:
// $_POST["save-form1"] will contain "Submit"

<input type="submit" name="save-form2" value="Submit" />
// in PHP:
// $_POST["save-form2"] will contain "Submit"

EDIT:

During the comment-dialog between the OP and myself the following seems to be a possible solution:

class My_Form_Base extends Zend_Form
{
    private static $_instanceCounter = 0;

    public function __construct($options = null)
    {
        parent:: __construct($options);

        self::$_instanceCounter++;
        $this->addElement('hidden', 'form-id', 
            sprintf('form-%s-instance-%d', $this->_getFormType(), self::$_instanceCounter);
    }

    protected _getFormType()
    {
        return get_class($this);
    }
}

class My_Form_Type1 extends My_Form_Base
{
    public function init()
    {
        // more form initialization
    }
}

class My_Form_Type2 extends My_Form_Base
{
    public function init()
    {
        // more form initialization
    }
}



回答2:


some errors in you code, shoudl be something like this:

class Application_Form_Idee_Base extends Zend_Form
{
    private static $_instanceCounter = 0;

    public function __construct($options = null)
    {
        parent::__construct($options);

        self::$_instanceCounter++;
        $this->addElement('hidden', 'form-id', array(
            'value' => sprintf('form-%s-instance-%s', $this->_getFormType(), self::$_instanceCounter))
        );
    }

    protected function _getFormType()
    {
        return get_class($this);
    }

}


来源:https://stackoverflow.com/questions/1170857/zend-form-multiple-forms-on-same-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!