Symfony World blog is not maintained anymore. Check new sys.exit() programming blog.

(symfony) multiple select default value

Scene from "Pulp Fiction" by Quentin Tarantino (1994)

Symfony framework provides an easy way of defining default form values (you can find related post here). But you may find problems to define default values of a multiple select (m:n relation) widget.

example

We are given two models:

  • Offer - representing a business offer which is available online
  • Localization - representing geographical region
Two models above share a typical m:n relation, represented by OfferLocalization model, which means that a specific Offer is available in chosen regions.

We want the offer form to display default values for the localizations_list widget (the OfferLocalization m:n relation). Let's say, we want Localizations 3 and 5 (by id) to be the default ones, just like in the picture below (showing regions in Poland):

Unfortunately, the following code will not work:

$this->setDefault('localizations_list', array(3,5));
in the configure() method since the BaseOfferForm class has the public function updateDefaultsFromObject() method implemented (generated by Doctrine):
  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();
    if (isset($this->widgetSchema['localizations_list']))
    {
      $this->setDefault('localizations_list', $this->object->Localizations->getPrimaryKeys());
    }
  }

solution

You can simply override this method in the OfferForm class:

  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();
    if ($this->isNew())
    {
      $this->setDefault('localizations_list', array(3,5));
    }
  }
and you're done!

No comments:

Post a Comment