高级FORM Symfony 2.7 [英] Advanced FORM Symfony 2.7

查看:68
本文介绍了高级FORM Symfony 2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单有点问题。我已经做了表格课,我需要表单领域,这将是无线电或选择。选择我需要从另一种形式的数据库中选择。

i have a little problem with form. I have made form class and i need form field which will be like radio or select. Choices for select i need to pull from DB of another form. Here is the code so pls tell me where is my problem and how to solve it.

我想在创建POST时选择可用页面(它们的名称)和存储,所以我知道每个帖子它属于哪个页面,并为每个页面查询和显示该页面的帖子..

I want to have option when i create POST to choose from available pages (their names) and store that so i know for each post to which page it belongs and for each page i do query and show posts for that page..

<?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.
}
}


推荐答案

你不使用 实体字段类型。它会是这样的:

Why don't you use entity field type. It would be smth like this:

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

如果你需要更复杂的话,那么只需 findAll 对于此字段,您可以使用 query_builder 选项:

If you need smth more complicated then just findAll for this field, you could use query_builder option:

    ->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;
        } 
    ))

这篇关于高级FORM Symfony 2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆