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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵