【问题标题】:How to Integrate Select2 JS in Symfony 3如何在 Symfony 3 中集成 Select2 JS
【发布时间】:2016-05-06 11:38:09
【问题描述】:

我将向你展示如何将Select2 集成到 Symfony3 项目中!

首先,将这 3 个链接添加到 base.html.twig 页面。

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<link href ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

第二,在CompanyType.php添加:

 use Symfony\Bridge\Doctrine\Form\Type\EntityType;

 class CompanyType extends AbstractType  {
     /**
      * @param FormBuilderInterface $builder
      * @param array $options
      */
     public function buildForm(FormBuilderInterface $builder, array $options)
     {
  $builder
        ->add('country',EntityType::class, array(
                 'attr'=>array('class'=>"country",),
                 'label'=>'Country of The Head fice',                     

                  'choices_as_values' => true, //               
                 'class' => 'QSCORBundle\Entity\CountryMaps',
                 'choice_label' => 'Country_Name',
 
             ))

    ->add(...)  
}
  ...
 }

之后,在你的实体文件Country.php 上添加:

public function __toString()
    {
        // TODO: Implement __toString() method.

       return $this->getCountryName();
    }

最后,在您的模板文件xxx.html.twig 中写下:

<script type="text/javascript">
                $(document).ready(function() {
                        $(".country").select2();
                });
</script>
{{ form_widget(form.country)}}

这是它的外观图片:

【问题讨论】:

    标签: php symfony jquery-select2 symfony-3.4


    【解决方案1】:

    您也可以通过将数据属性添加到表单构建器元素,然后将全局 JavaScript 文件包含到您的站点中来处理 select2,无需将其添加到每个 twig 文件中。

    p>

    例如;

    $builder
        ->add('country', 'entity', [
            'class' => 'EntityType::class',
            'label'=>'Country of The Head fice',
            'choices_as_values' => true, //               
            'class' => 'QSCORBundle\Entity\CountryMaps',
            'choice_label' => 'Country_Name',
            'attr' => ['data-select' => 'true']
    ]);
    

    然后在站点范围的 js 文件中添加;

    $('select[data-select="true"]').select2();
    

    这样,任何具有data-select="true" 数据属性的选择都将应用select2。

    【讨论】:

    • 感谢您的回答,我们还可以为所有选择表单创建 class="selectsymfony" 并在我的 JS 中创建 $('selectsymfony').select2();在你的回答中你忘记了 ('select[data-select="true"') 中的 "]" ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多