我有3个实体:User
,Report
和ReportCategory
。
用户可以将报告放在一个ReportCategory中。在用户实体中有一个列表,允许用户使用ReportCategories。这很好用 - 我使用了一个具有userID和reportCategoryId的connectionTable。
现在我在Controller中创建一个数组,以获取当前登录用户的所有ReportCategories:
public function newAction()
{
$entity = new Report();
$form = $this->createCreateForm($entity);
$userId = $this->get('security.context')->getToken()->getUser()->getId();
$user = $this->getDoctrine()->getRepository('MyBundle:User')->find($userId);
$userReportCategories = array();
foreach($user->getReportCategories() as $reportCategory)
{
$userReportCategories[] = $reportCategory->getId();
}
return array(
'entity' => $entity,
'form' => $form->createView(),
'userReportCategories' => $userReportCategories
);
}
如何只将这些值设置为我的树枝模板字段?当我创建一个自己的字段时,它不是由Doctrine管理的!
{{ form_row(form.reportCategory, {'attr': {'class': 'form-control'}, 'label': 'Category'}) }}
感谢任何帮助!!!
更新: 我的ReportType如下所示:
class ReportType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('reportCategory')
->add('creationDate', 'date', array(
'data' => new \DateTime()
))
->add('headline')
->add('text')
->add('user')
;
}
....
答案 0 :(得分:1)
创建表单类并添加事件侦听器,以便表单知道用户。以下是Symfony文档中How to dynamically Generate Forms Based on user Data的改编。 [无法保证准确捕捉您的需求]。
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\ORM\EntityRepository;
// ...
class ReportFormType extends AbstractType
{
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// grab the user, do a quick sanity check that one exists
$user = $this->securityContext->getToken()->getUser();
if (!$user) {
throw new \LogicException(
'The ReportFormType cannot be used without an authenticated user!'
);
}
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($user) {
$form = $event->getForm();
$formOptions = array(
'class' => 'Acme\DemoBundle\Entity\ReportCategory',
'property' => 'category',
'query_builder' => function (EntityRepository $er) use ($user) {
// build a custom query
// return $er->createQueryBuilder('c')
->select('category')
->where('user = $user);
},
);
// create the field, this is similar the $builder->add()
// field name, field type, data, options
$form->add('userReportCategories', 'entity', $formOptions);
}
);
}
// ...
}
public function newAction()
{
$entity = new Report();
$form = $this->createForm(new ReportFormType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}