Zend_Formでフォームエレメントを作る場合にはnameが必須なんだけど、
GET送信するとnameがあるばかりにボタンまでURLに含まれてしまうので
Redirectorによる回避策を試してみた。
検索のフォーム。methodをpostにする。
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にリダイレクトする。
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()でキーワードとかを取り出して使う。
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');
}