Using a form from a different presenter

Say you have a search form on a page that lists customers but you also want the same form on the main dashboard page. You have two options: either define your form in a third place and use that definition in both createComponent… methods, or you can create it with createComponent… in BasePresenter and inherit it by both the CustomerPresenter and the DashboardPresenter. Or you can use a hack.

To be honest, there’s no real reason why you would want to use a hack when you have two comfortable and legitimate options. For me it was just a mind twisting practice. I wanted to find a way to define the form in CustomerPresenter and somehow use that definition in DashboardPresenter.

Here’s the form owner code. Typically a presenter that handles administration of certain entity.

  1. class CustomerPresenter extends BasePresenter {
  2.   public function createComponentCustomersFilterForm($name, $parent = NULL) {
  3.     if (!isset($parent)) {
  4.       $parent = $this;
  5.     }
  6.     $form = new NAppForm($parent, $name);
  8.     $form->addText(‘name’, ‘Company or Contact Name’);
  9.     $form->addSubmit(‘search’, ‘Search’);
  11.     $form->onSuccess[] = callback($this, ‘customersFilterSubmitted’);
  13.     return $form;
  14.   }
  16.   public function customersFilterSubmitted($form) {
  17.      // do your magic
  18.   }
  19. }

And here’s a factory method in the other presenter that also needs to use the form.

  1. class DashboardPresenter extends BasePresenter {
  2.   public function createComponentCustomersFilterForm($name) {
  3.     $customerPresenter = new CustomerPresenter;
  4.     $form = $customerPresenter->createComponentCustomersFilterForm(‘customersFilterForm’, $this);
  5.     $form[‘name’]->caption = ‘Name’;  // you can manipulate the form elements the same way you’re used to
  7.     $url = $this->link(‘Customer:default’, array(‘do’ => $name.self::NAME_SEPARATOR.‘submit’));
  8.     $form->setAction($url);
  10.     return $form;
  11.   }
  12. }


Leave a Reply