我想创建一个带有下拉列表和文本字段的表单。我的下拉列表包含我的代理实体的值和我的文本字段一个星期数。我想根据我连接的用户设置默认值,但我不知道如何。
我已经修改了我的实体、我的表单和我的控制器:
我与我的代理关系有一个实体周:
class Week
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* @ORM\ManyToOne(targetEntity="Agency", inversedBy="week", cascade={"persist"})
* @ORM\JoinColumn(name="agency_id", referencedColumnName="id")
*/
private $agency;
/**
* @var integer
*
* @ORM\Column(name="week_number", type="integer")
*/
private $week_number;
/**
* @var \DateTime
*
* @ORM\Column(name="week_start", type="datetime")
*/
private $week_start;
/**
* @var \DateTime
*
* @ORM\Column(name="week_end", type="datetime")
*/
private $week_end;
public function getAgency()
{
return $this->agency;
}
.... public function get.....
}
然后是我的代理实体:
class Agency
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=50)
*/
private $name;
/**
* @var integer
*
* @ORM\Column(name="nb_team", type="integer")
*/
private $nb_team;
/**
* @var \DateTime
*
* @ORM\Column(name="date_creation", type="datetime")
*/
private $date_creation;
/**
*
* @ORM\OneToMany(targetEntity="Week", mappedBy="agency", cascade={"persist"})
*/
private $week;
public function .....
}
我的表格:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('agency', 'entity', array(
'class' => 'MyProjectBundle:Agency',
'property' => 'name',
/* 'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
return $er->createQueryBuilder('a')->orderBy('a.name', 'ASC');
},*/
'attr' => array('onchange' => 'javascript:this.form.submit();')
))->add('week_number', 'text');
}
我的控制器:
$num_week = 4;
$id = 3;
$agency_id = $em->getRepository('MyProjectBundle:Agency')->find($id);
$week = $em->getRepository('MyProjectBundle:Week')->WeekExiste($num_week, $week_start, $agency_id);
$form2 = $this->createForm(new FormType(), $week);
if ($request->isMethod('POST')) {
$form2->bind($request);
$data = $form2->getData();
$agency = $data['agency'];
}
else {
$agency = $em->getRepository('MyProjectBundle:Agency')->find($id);
}
$week 返回一个正确的实体。我的表单适用于 week_number 字段,但我的下拉列表没有选择我在控制器中设置的代理机构。