简体   繁体   中英

symfony 2 Dynamic drop down menus

How do i crate a dynamic drop down lists using symfony 2 i have something like this,

$builder->add('gender', 'choice', array(
         'choices'  => array(1 => 'campus1', 2 => 'campus2'),
         'required' => false,
));

i dont want to hard code anything and i dont want it to be on the twig or front end side, i would like to have someting in the controller. here is the entity that needs to be loaded into the drop down

<?php

namespace Test\Bundle\TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Campus
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="..\Entity\CampusRepository")
 */
class Campus
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="University", inversedBy="campus")
 * @ORM\JoinColumn(name="university_id", referencedColumnName="id")
 */
private $university;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Length(
 *                  min=3,
 *                  max=35,
 *                  minMessage= "Name Field should contains at least 3 characters",
 *                  maxMessage = "Name Field Cannot contain more than 35 characters"
 *               )
 * @Assert\Regex(pattern="/[^a-z\s-]/i", match=false , message="Name can only contain letters")
 */
private $name;

/**
 * @var string
 * @ORM\Column(name="address", type="string", length=255)
 * @Assert\NotBlank()
 * @Assert\Length(
 *                 min = 10,
 *                 max = 80,
 *                 minMessage = "Address must be more specific",
 *                 maxMessage = "80 characters limit exceeded"
 *              )
 */
private $address;


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 * @return Campus
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string 
 */
public function getName()
{
    return $this->name;
}

/**
 * Set address
 *
 * @param string $address
 * @return Campus
 */
public function setAddress($address)
{
    $this->address = $address;

    return $this;
}

/**
 * Get address
 *
 * @return string 
 */
public function getAddress()
{
    return $this->address;
}

/**
 * Set university
 *
 * @param \Test\Bundle\TestBundle\Entity\University $university
 * @return Campus
 */
public function setUniversity(\Test\Bundle\TestBundle\Entity\University $university = null)
{
    $this->university = $university;

    return $this;
}

/**
 * Get university
 *
 * @return \Test\Bundle\TestBundle\Entity\University 
 */
public function getUniversity()
{
    return $this->university;
}

}

when the drop down is selected and form submitted i will be using the other fields from the entity so i need the entire object when the form is submitted.

so how do i populate it with data from a datbase using symfony2 features?

well it´s as simple as build an array and pass it

$camps=$em->getRepository('TestTestBundle:Campus')->findAll();
$choices=array();
foreach ($camps as $campus) {
    $choices[$campus->getId()] = $campus->getName();
}
$builder->add('gender', 'choice', array(
         'choices'  => $choices,
         'required' => false,
));

you can get the entity then by finding it by id

Use the Entity form field type, which is a special type of choice field that's designed to load options from a Doctrine entity. eg:

$builder->add('campus', 'entity', array(
    'class' => 'TestBundleTestBundle:Campus',
    'property' => 'name',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('c')
            ->orderBy('c.name', 'ASC');
    },
));

When the form is submitted, the form data for the 'campus' field will be an instance of the Campus class. If your form data is an entity rather than an array, then that entity will need to have a corresponding 'campus' field which represents a relationship with the Campus entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM