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.

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

报告相同问题?

悬赏问题

  • ¥20 Html备忘录页面制作
  • ¥15 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?
  • ¥20 数学建模来解决我这个问题
  • ¥15 计算机网络ip分片偏移量计算头部是-20还是-40呀
  • ¥15 stc15f2k60s2单片机关于流水灯,时钟,定时器,矩阵键盘等方面的综合问题
  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?
  • ¥15 django5安装失败