gpt4 book ai didi

php - 如何在 Symfony 3 中集成 Select2 JS

转载 作者:行者123 更新时间:2023-12-05 05:23:40 25 4
gpt4 key购买 nike

我将向您展示如何将 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)}}

这是它的外观图片:

enter image description here

最佳答案

您还可以通过向表单构建器元素添加一个数据属性,然后将一个全局 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。

关于php - 如何在 Symfony 3 中集成 Select2 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37071430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com