0
好的,下面是我想要做的事情的快速概覽。我有一個與「ClientDomain」實體有關係的「客戶」實體。我需要一個表單,向我顯示給定客戶端的所有ClientDomain列表。在控制器中,我知道我需要過濾哪些客戶端,但我不確定如何將這些信息傳遞給formBuilder。如何讓symfony 2表單從動態值返回實體
繼承人是我迄今爲止:
//src/NameSpace/ClientBundle/Entity/Client.php
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Client{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $client_id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\OneToMany(targetEntity="ClientDomain", mappedBy="client")
*/
protected $domains;
...
}
而且形式:
//src/LG/ClientBundle/Form/ClientDomainSelectionForm.php
namespace LG\ProjectBundle\Form\Projects;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ClientDomainSelectionForm extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('client_domain', 'entity', array(
'class' => 'LG\ClientBundle\Entity\ClientDomain',
'query_builder'=> function(EntityRepository $er) {
return $er->createQueryBuilder('cd')
/* NEEDS TO FIND DOMAINS BY CLIENT X */
},
'property' => 'domain',
'label' => 'Domain: '
));
}
}
然後終於控制器:
//src/LG/ClientBundle/Controller/DomainSelectorController.php
namespace LG/ClientBundle/Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use LG\ClientBundle\Entity\Client;
use LG\ClientBundle\Entity\ClientDomain;
use LG\ClientBundle\Entity\ClientActiveDomain;
use LG\ClientBundle\Form\ClientDomainSelectionForm;
/**
* @Route("")
*/
class DomainSelectorController extends Controller{
/**
* @Route("/client/{client_slug}/select-domain", name="lg.client.clientdomainselection.selectclient")
* @Template
*/
public function selectDomainAction(Request $request, Client $client){
$activeDomain = new ClientActiveDomain();
$form = $this->createForm(new ClientDomainSelectionForm(), $activeDomain);
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($activeDomain);
$em->flush();
return $this->redirect(/*huge long url*/);
}
}
return array(
'form' => $form->createView(),
);
}
}
正如你可以看到我有機會獲得控制器中的客戶端實體只是不知道如何將其提供給表單構建器,以便它僅返回th域當前客戶。
實際上,您應該創建一個必需的選項'client'而不是使用構造函數,因爲構造函數在創建表單的第一個實例時僅調用一次。所以,如果你有兩種不同客戶的表格,他們將被綁定到第一種表格的客戶端。另一方面,選項不共享。 – 2013-03-02 09:19:36
客戶端只需在創建時設置即可。一旦完成,實體的所有編輯都是可能的,因爲教義已經知道客戶端。但是我可以看到你的用例在另一個應用程序中可能發生的地方。感謝您的意見。 – Chausser 2013-03-04 19:31:51