我的表格有点问题。我已经制作了表格类,我需要表格字段,就像收音机或选择一样。选择的选择我需要从另一种形式的数据库中提取。这是代码所以请告诉我我的问题在哪里以及如何解决。
当我创建POST以便从可用页面(他们的名字)中进行选择时我想要选择并存储我知道的每个帖子它所属的页面以及每个页面我都会查询并显示该页面的帖子。
<?php
namespace AppBundle\AppForm;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\Page;
class PostForm extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('content', 'textarea')
->add('visible', 'choice', array(
'choices' => array(
'Yes' => 1,
'No' => 0
)
))
->add('belongToPage', 'choice', array(
'choices' => array (
new Page()
// here i want to pull from class Page names of
//all pages stored and to present
// this names for options in form field
),
'choices_as_values' => true,
'choice_label' => 'getName'
//getName is function from class Page which returns name of page(s)
))
->add('save', 'submit', array('label' => 'Create Post'));
}
public function getName()
{
// TODO: Implement getName() method.
}
}
答案 0 :(得分:1)
为什么不使用entity
field type。它会像这样:
->add('belongToPage', 'entity', array(
'class' => 'Class\Namespace\Class',
'property' => 'name',
'label' => 'choice_field_label'
))
如果您需要更复杂的smth,那么此字段只需findAll
,您可以使用query_builder
选项:
->add('belongToPage', 'entity', array(
'class' => 'Class\Namespace\Class',
'property' => 'name',
'label' => 'choice_field_label',
'query_builder' => function(EntityRepository $er) {
return $er->findAllPagesForPostForm();
//Where findAllPagesForPostForm is the name of method in your
// pagesRepo which returns queryBuilder,
//instead of this you could just write your custom query like
//$qb = $er->createQueryBuilder('p');
//$qb->andWhere(...);
//return $qb;
}
))