Change foreign key select box as radio button symfony

on

Symfony form generates the select box using foreign key reference automatically by magic function __tostring(). But in some cases, we need to modify select box into radio buttons or checkbox. We are going to see how to change foreign key select box as radio button symfony.

Let’s take a symfony jobeet tutorial for help. In this tutorial job category is automatically generates the drop down in job form. Let’s change the drop down into radio and check box.

How to change the foreign key drop down as radio button?

Change your form file as below,  In sfWidgetFormDoctrineChoice widget function add your model and expand true options.

class JobeetJobForm extends BaseJobeetJobForm
{
  public function configure()
  {
     $this->widgetSchema['category_id'] = new sfWidgetFormDoctrineChoice(array('model'=>'JobeetCategory','expanded'=>true));
  }
}

symfony forignkey radiobutton

How to change the foreign key select box as Check box?

Change your form file as below,  In sfWidgetFormDoctrineChoice widget function add your model and expand true and multiple true options.

class JobeetJobForm extends BaseJobeetJobForm
{
  public function configure()
  {
     $this->widgetSchema['category_id'] = new sfWidgetFormDoctrineChoice(array('model'=>'JobeetCategory','expanded'=>true,'multiple'=>true));
  }
}

symfony forignkey checkbox

You can find more useful resource from symfony widget documentation.

 

 

Symfony 2 render entity select box to radio buttons and check box

Above we have seen how render radio and check box from foreign key select box in symfony1.x version. I updated this post for symfony2 version as well.

Radio Button

Expand option making our work very simple in simfony2. This option will be false in default.

$builder->add('category_id','entity',array('expanded'=>true,'property' => 'name','class' => 'AcmeJobeetBundle:Category','query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')->where('c.isActive = :isActive')->setParameter('isActive', '1')->orderBy('c.name', 'ASC');
}));

Checkbox

Multiple option giving this feature. This option will be false in default.

$builder->add('category_id','entity',array('expanded'=>true,'multiple'=>true,'property' => 'name','class' => 'AcmeJobeetBundle:Category','query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c')->where('c.isActive = :isActive')->setParameter('isActive', '1')->orderBy('c.name', 'ASC');
}));

Feel free  to give useful feed back.

Posted in Symfony2 and tagged , by .

About Gowri

I am professional web developer with 8+ years experience. PHP, jQuery, WordPress, Angular and Ionic are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.