How to use the swWidgetFormGMapAddress widget ?

The previous post explains how to create a multifield widget, the widget was a google map address field. Now I will explain how to use it in your form.

preview-multifield-widget

Installation

  1. Install swToolboxPlugin
  1. clear your cache

Usage

Let’s try to create a simple form with a nested form. Both forms have a swWidgetFormGMapAddress widget, validators are also set to swValidatorGMapAddress.

  class NestedGmapWidgetForm extends sfForm  
  {  
    public function configure()  
    {  
      $this->widgetSchema['nested_map'] = new swWidgetFormGMapAddress;  
      $this->validatorSchema['nested_map'] = new swValidatorGMapAddress;  
    }  
  }  

  class DemoGmapWidgetForm extends sfForm  
  {  
    public function configure()  
    {  
      $this->widgetSchema['map'] = new swWidgetFormGMapAddress;  
      $this->validatorSchema['map'] = new swValidatorGMapAddress;  

      $this->embedForm('nested_form', new NestedGmapWidgetForm);  

      $this->widgetSchema->setNameFormat('demo[%s]');  
    }  
  }

The action to instantiate the form and handle the post action

  public function executeDemoGmapWidget(sfWebRequest $request)  
  {  
    /* Define the defaults value for the current demo */  
    $defaults = array(  
      'map' => array('lng' => 2.294359, 'lat' => 48.858205, 'address' => 'La tour eiffel, Paris, France'),  
      'nested_form' => array(  
        'nested_map' => array('address' => 'type an address ...')  
      )  
    );  

    $this->form = new DemoGmapWidgetForm;  
    $this->form->setDefaults($defaults);  

    /* handle the post action */  
    if($request->isMethod('post'))  
    {  
      /* bind the post values */  
      $this->form->bind($request->getParameter('demo'));  

      if($this->form->isValid())  
      {  
        /* retrieve the validated value */  
        $info = $this->form->getValue('map');  

        // do the work with with info  
        // this should be done in the form with you are working with model's forms  
      }  
    }  
  }

The template is set to :

  <?php /* use asset helper to include javascripts from the widget  */ ?>  
  <?php include_javascripts_for_form($form) ?>  

  <?php /* include the google map api script  */ ?>  
  <?php echo sw_google_map_api() ?>  

  <h1>Gmap Widget Demo</h1>  

  <form action="" method="POST">  
    <table>  
      <?php /* echo the form  */ ?>  
      <?php echo $form ?>  
    </table>      
    <input type="submit" />  
  </form>

Conclusion

This was a pretty quick article to show how easy is to use the widget, thanks to the sfForm framework. You can see a live demo here : http://rabaix.net/labs/demo-gmap-widget