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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!