【问题标题】:Advanced FORM Symfony 2.7高级 FOR​​M Symfony 2.7
【发布时间】:2015-12-04 10:09:32
【问题描述】:

我的表格有点问题。我已经制作了表单类,我需要类似于收音机或选择的表单字段。选择的选择我需要从另一种形式的数据库中提取。这是代码,请告诉我问题出在哪里以及如何解决。

我希望在创建 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.
}
}

【问题讨论】:

标签: forms symfony


【解决方案1】:

你为什么不使用entity field type。应该是这样的:

->add('belongToPage', 'entity', array(
        'class' => 'Class\Namespace\Class',
        'property' => 'name',
        'label' => 'choice_field_label'
    ))

如果你需要更复杂的东西,那么这个字段只需要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;
        } 
    ))

【讨论】:

  • 谢谢,这是我一直在寻找的答案。我找到了有关实体类型的信息,但我不知道你可以在数组中传递属性,所以它返回了整个类,我得到了类似 can 的错误不将类转换为字符串类型.. 有了属性,我可以准确地提取我需要的字符串..
  • @Constantine1001,没问题!只需将其标记为答案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
相关资源
最近更新 更多