简体   繁体   English

如何使用select2 v4为标签创建symfony表单类型

[英]How create a symfony form type for tags with select2 v4

Im trying to update an already-created form type ( TagsType ) from select2 v3 to v4. 我正在尝试将已创建的表单类型( TagsType )从select2 v3更新到v4。 But I found the problem that the new select2 use selects instead of text field. 但是我发现了新的select2使用selects而不是文本字段的问题。 The following code works fine with v3. 以下代码在v3上正常运行。

class TagsType extends AbstractType
{

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addViewTransformer(new StringToArrayTransformer());
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $attr = isset($view->vars['attr']) ? $view->vars['attr'] : [];

        $view->vars['attr'] = array_merge($attr, ['data-toggle' => 'tags']);
    }

    /**
     * @inheritdoc
     */
    public function getParent()
    {
        return 'text';
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'tags';
    }
}

StringToArrayTransformer: StringToArrayTransformer:

class StringToArrayTransformer implements DataTransformerInterface
{

    /**
     * @inheritdoc
     */
    public function transform($value)
    {
        if (!$value ) {
            return [];
        }

        if (!is_array($value)) {
            throw new TransformationFailedException('Expected a Array.');
        }

        return implode(',', $value);
    }

    /**
     * @inheritdoc
     */
    public function reverseTransform($value)
    {
        if (null === $value) {
            return [];
        }

        if (!is_string($value)) {
            throw new TransformationFailedException('Expected a String.');
        }

        return explode(',', $value);
    }
}

The above code works fine with a Entity with field of type simple_array (comma separated). 上面的代码对于带有类型为simple_array (逗号分隔)的字段的Entity可以正常工作。 I need do the same but using the new vesion of select2. 我需要做同样的事情,但是要使用select2的新版本。

Refactoring: 重构:

class TagsType extends AbstractType
{

   /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $attr = isset($view->vars['attr']) ? $view->vars['attr'] : [];

        $view->vars['attr'] = array_merge($attr, ['data-toggle' => 'tags']);
    }

    /**
     * @inheritdoc
     */
    public function getParent()
    {
        return 'choice';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['multiple' => true]);
    }


    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'tags';
    }
}

The refactor generate a select tag with multiple but empty. 重构生成带有多个但为空的选择标签。 And when try to add some option ( Tag ) the validation fails because dynamic creation of new options in the select. 并且当尝试添加某些选项( Tag )时,验证会失败,因为在select中动态创建了新选项。

My questions: 我的问题:

  • How to implement a choice with dynamic options in symfony? 如何在symfony中使用动态选项实现选择?
  • How to set default choices from field data (array) 如何从字段数据(数组)设置默认选项

Forget all about ',' and convert string to array or vice versa and save each Tag entity individually. 忘记所有有关','的信息,并将字符串转换为数组,反之亦然,并分别保存每个Tag实体。

So, to make your form compatible with select2-v4.x you need one EntityType field with 'multiple' attribute set to TRUE. 因此,要使您的表单与select2-v4.x兼容,您需要一个EntityType字段,其“ multiple”属性设置为TRUE。

Every thing is handled by symfony, each option(s) in select tag of your form is connected to its entity. 每件事都是由symfony处理的,表单的select标签中的每个选项都与其实体相连。

I just found this solution and it works for me, but I don't know maybe some things are missing... 我刚刚找到了这个解决方案,它对我有用,但我不知道可能缺少了一些东西...

Very old question, but I found it from Search engine. 很老的问题,但是我是从搜索引擎找到的。 I tried to make it with simple_array + data transformer — it's wrong way (as @YaserKH said). 我试图用simple_array +数据转换器来实现它-这是错误的方式(如@YaserKH所说)。 Better to make tags as entity Tag etc. (you can find in the official docs ). 最好将标签制作为实体标签等。(您可以在官方文档中找到)。 But if you need simple solution for some reasons (as me): 但是,如果由于某些原因(例如我)需要简单的解决方案:

  1. Create Text type column in database (not simple_array) 在数据库中创建文本类型列(不是simple_array)
  2. Define it as HiddenType in form builder: 在表单构建器中将其定义为HiddenType:
    $builder->add('tagsForSearch', HiddenType::class, [ 'required' => false ])
  1. Make twig like: 使树枝像:
    {{ form_row(form.tagsForSearch) }}
    <select id="tags" multiple="multiple">
        {% for tag in form.tagsForSearch.vars.value|split(',')|default %}
            <option value="{{ tag|raw }}" selected="selected">{{ tag|raw }}</option>
        {% endfor %}
    </select>
  1. And script: 和脚本:
$('#tags').select2({
    tags: true
});
$('#form').submit(function () {
    var tags = $('#tags').select2().val().join(',');
    $('#{{ form.tags.vars.id }}').val(tags);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM