In my ZF2 aplication I have multiple modules and one of them is "Search". It provides a search form, the search logic and a list of courses found in the database:
Form class
namespace Search\Form;
...
class CourseSearchForm extends Form {
private $cities;
public function __construct(array $cities) {
parent::__construct('courseSearch');
$this->setCities($cities);
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'keyword',
'attributes' => array(
'type' => 'text',
),
));
$this->add(array(
'name' => 'city',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Stadt',
'value_options' => $this->cities
),
));
// ...
}
public function setCities(array $cities) {
$this->cities = $cities;
}
}
Controller class
namespace Search\Controller;
...
class SearchController extends AbstractActionController {
protected $courseTable;
public function searchAction() {
return $this->redirect()->toRoute('search-courses');
}
public function searchCoursesAction() {
$form = $this->getServiceLocator()->get('Search\Form\CourseSearchForm');
$request = $this->getRequest();
if ($request->isPost()) {
$courseSearchInput = new CourseSearchInput();
$form->setInputFilter($courseSearchInput->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$courseSearchInput->exchangeArray($form->getData());
$courses = $this->getCourseTable()->findAllByCriteria($courseSearchInput);
} else {
$courses = null;
}
} else {
$courses = null;
}
return new ViewModel(array(
'form' => $form,
'courses' => $courses,
'cities' => $this->getServiceLocator()->get('Cache\Model\CityStorage')->getCities(),
));
}
/**
* Gets a CourseTable object.
* @return Search\Model\CourseTable
*/
function getCourseTable() {
if (!$this->courseTable) {
$serviceLocator = $this->getServiceLocator();
$this->courseTable = $serviceLocator->get('Search\Model\CourseTable');
}
return $this->courseTable;
}
}
List view in /module/Search/view/search/search/search-courses.phtml
...
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('search-courses'));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('keyword'));
echo $this->formRow($form->get('city'));
// ...
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
<?php
if ($courses instanceof Zend\Db\ResultSet\ResultSetInterface) {
echo $this->render('search/search/list-courses.phtml', array(
'courses' => $courses
));
}
?>
Now the search form should be displayed on every page of the website. How can I implement such global form view? Is there a "standard" way / best practice to do this?
Thx