duanchuaiwan0063 2015-01-01 22:37
浏览 33
已采纳

如何在Symfony2表单中获取实体字段的可能值?

I created and maintain a little bundle to serialize Symfony2 Symfony\Component\Form\Form objects.

When I have a entity field in a formType, I would like to get the possible values for this field.

For example : If I have a form for the entity spaceship, with an entity field for the destination, which is a planet object.

With Symfony\Component\Form\Form::createView(), I would get a variable which will result in a <select> tag which multiple choices using form_widget().

What I want to know is : how, in a PHP service, can I get this set of possible values ? I tried Symfony\Component\Form\Form::getData() and other similar functions on the form and his entity field child, but it doesn't return to me the set of values in my database.

Does anyone know the way to get these values ?

(PS: sorry for my poor english.)

EDIT: As asked, the part of my bundle which is used to serialize a form object :

<?php
namespace WTech\FormBundle\Transformer;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
 * {@inheritdoc}
 */
class FormTransformer
{
    /** @var Request **/
    private $request;

    /**
     * {@inheritdoc}
     */
    public function __construct(RequestStack $request)
    {
        $this->request = $request->getMasterRequest();
    }

    /**
     * {@inheritdoc}
     */
    public function serializeForm(Form $form)
    {
        $fields = array_keys($form->all());
        $nbFields = count($fields);
        $config = $form->getConfig();

        $attributes = $config->getOptions();
        // Building the basic Form data
        $data = [
            'name' => $form->getName(),
            'action' => $this->buildAction($config->getAction()),
            'method' => $config->getMethod(),
            'attributes' => $attributes,
            'children' => [],
            'csrf' => $this->buildCsrfToken($config)
        ];

        // Look over the form fields
        for($i = 0; $i < $nbFields; ++$i)
        {
            $field = $form->get($fields[$i]);
            $children = $field->all();

            // If there is children, we ignore the current field (type repeated)
            // And we build the children fields
            if(count($children) > 0)
            {
                $this->addChildrenToFields($data, $field->getConfig()->getName(), $children);
                continue;
            }
            $this->buildField($data, $field);
        }
        return json_encode($data);
    }

    /**
     * {@inheritdoc}
     */
    public function addChildrenToFields(&$data, $parentName, $children)
    {
        reset($children);

        while($key = key($children))
        {
            $this->buildField($data, $children[$key], "[$parentName]");
            next($children);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function buildField(&$data, $field, $parentName = '')
    {
        $name = $field->getName();
        $key = "{$parentName}[{$name}]";
        $config = $field->getConfig();
        $type = $config->getType()->getInnerType()->getName();

        $attributes = $config->getOptions();
        $data['children'][$key] = [
            'type' => $type,
            'label' => $this->buildLabel($name, $attributes),
            'label_class' => $this->buildLabelClass($attributes),
            'div_class' => $this->buildDivClass($attributes),
            'class' => $this->buildClass($attributes),
            'translation_domain' => $this->buildTranslationDomain($attributes)
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildAction($primaryAction)
    {
        return
            (!empty($primaryAction))
            ? $primaryAction
            : $this->request->getPathInfo()
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildLabel($name, $attributes)
    {
        return
            (isset($attributes['label']))
            ? $attributes['label']
            : $name
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildLabelClass($attributes)
    {
        return
            (isset($attributes['attr']['label_class']))
            ? $attributes['attr']['label_class']
            : ''
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildDivClass($attributes)
    {
        return
            (isset($attributes['attr']['div_class']))
            ? $attributes['attr']['div_class']
            : ''
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildClass($attributes)
    {
        return
            (isset($attributes['attr']['class']))
            ? $attributes['attr']['class']
            : ''
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildTranslationDomain($attributes)
    {
        return
            (isset($attributes['translation_domain']))
            ? $attributes['translation_domain']
            : ''
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildCsrfToken(FormConfigInterface $config)
    {
        if($config->hasOption('csrf_provider'))
        {
            return [
                'token' => $config->getOption('csrf_provider')->generateCsrfToken($config->getOption('intention')),
                'field_name' => "{$config->getName()}[{$config->getOption('csrf_field_name')}]"
            ];
        }
        return false;
    }
}
  • 写回答

1条回答 默认 最新

  • doujubeng2942 2015-01-02 02:40
    关注

    Alright so the solution is pretty simple. The entity form type has a choice_list option returning a Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList object. This will enable you to find the values that are stored in the form type after they are loaded from the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥100 有偿求易语言word文档取doc和docx页数方法或模块
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低
  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi