[ZF] Zend_Form : Remove the submit-button value from url parameters

Zend_Formでフォームエレメントを作る場合にはnameが必須なんだけど、
GET送信するとnameがあるばかりにボタンまでURLに含まれてしまうので
Redirectorによる回避策を試してみた。

検索のフォーム。methodをpostにする。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Application_Form_Search extends Zend_Form
{
    functions init(){
    $this->setMethod('post')
        ->clearDecorators()
        ->addDecorator('FormElements')
        ->addDecorator('HtmlTag',array('tag'=>'div', 'class' => 'zend_form'))
        ->addDecorator('Form');
             
    $this->addElement('text', 'keyword', array(
        'label'      => 'Keyword',
        'required'   => true
    ));
     
    $this->addElement('submit',
        'submit',
        array(
            'label'    => 'Search',
            'required' => false,
            'ignore'   => true
        )
    );
    }
}

検索する場所は仮にindexとして、index.phtmlには検索フォームを表示しておく。

getRequest()->isPost()で送信された値があり、バリーデーションもtrueなら
送信された値($params)からボタンを削除(unset)する。
アクションヘルパーのRedirectorに$paramsを渡してsearchActionにリダイレクトする。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public function indexAction()
{
    $this->view->searchForm = $this->_searchForm;
     
    $request = $this->getRequest();
    $params = $request->getPost();
     
    if($request->isPost() && $this->_searchForm->isValid($params)){
        unset($params['submit']);
        $this->_helper->Redirector->setGotoSimple('search', null, null, $params);
    }else{
        $this->view->data = $this->_mapper->fetchAll();
    }
}

※$this->_searchForm —> instance of Application_Form_Search
※$this->_mapper —> instance of DataMapper

searchActionに飛ばされた時、検索キーはZendライクなGETパラメーター(/key/value/のパターン)になっているので、
getRequest()->getParams()でキーワードとかを取り出して使う。

1
2
3
4
5
6
7
8
9
10
11
public function searchAction()
{
    $request = $this->getRequest();
    $params = $request->getParams();
     
    $this->view->data = $this->_mapper->search($params);
    $this->view->searchForm = $this->_searchForm->populate($params);
     
    $this->render('index');
     
}

コメントを残す

This site uses Akismet to reduce spam. Learn how your comment data is processed.