我瘋了,因爲如果我從實體字段中選擇客戶端,它會正確填充名爲提議的第二個實體字段。然後我選擇動態生成的提案,但是當我保存表單時,它會正確保存表單,但不填寫提案字段。我跟着Symfony的教程大約可以發現hereSymfony2動態表單修改不保存生成的數據
這是我的FormType代碼的動態表單:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('client', 'entity', array(
'class' => 'AppBundle\Entity\Client',
'property' => 'name',
'label' => 'Client:',
'empty_value' => '',
'required' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC');
},
));
$formModifier = function (FormInterface $form, Client $client = null) {
$proposals = null === $client ? array() : $this->em->getRepository('AppBundle:Proposals')->findBy(
array('client'=>$client->getId()),
array('id' => 'DESC'));
$form->add('proposal', 'entity', array(
'class' => 'AppBundle\Entity\Proposal',
'choice_label' => 'subject',
'placeholder' => '',
'choices' => $proposals,
'label' => 'Proposal',
'required' => false
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$client = null;
$data = $event->getData();
if(!empty($data)) {
$client = $data->getClient();
}
$formModifier($event->getForm(), $client);
}
);
$builder->get('client')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$client = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $client);
}
);
這是價格預定實體,屬於誰的形式之一。
class Prenotazione {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Client", inversedBy="prenotazioni")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
private $client;
/**
* @ORM\OneToOne(targetEntity="Proposal", inversedBy="prenotazione")
* @ORM\JoinColumn(name="proposal_id", referencedColumnName="id")
*/
private $proposal;
public function getId() {
return $this->id;
}
public function setProposal(\AppBundle\Entity\Proposal $proposal = null)
{
$this->proposal = $proposal;
return $this;
}
public function getProposal() {
return $this->proposal;
}
public function setClient(\AppBundle\Entity\Client $client = null)
{
$this->client = $client;
return $this;
}
public function getClient()
{
return $this->client;
}
}
我在哪裏錯了?
你能告訴我們你的實體嗎? –
我第二@PawełMikołajczuk。在問題中添加了 – ctatro85
。謝謝。 –