我正在尝试将jQuery select2
库手动集成到我的Symfony表单中,以替代我的选择框。
按照手册我已添加到页眉:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
此外,我修改了表单类,为每个选择添加了attr
:
->add('kontoWinien', EntityType::class, array(
'class' => 'AppBundle\Entity\konto',
'attr' => array('class'=>'select2')
))
我修改过的Twig模板:
{{ form_start(form) }}
<SCRIPT type="text/javascript">
$(document).ready(function() {
$(".select2").select2();
});
</SCRIPT>
{{ form_widget(form) }}
{{ form_end(form) }}
然而仍未加载select2 。
symfony3生成的HTML代码如下所示:
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
</head>
<form name="dziennik" method="post">
<script type="text/javascript">
$(document).ready(function() {
$(".select2").select2();
});
</script>
<select id="dziennik_kontoWinien" name="dziennik[kontoWinien]" class="select2 form-control">
你能告诉我我做错了什么吗?
答案 0 :(得分:2)
就像fcpauldiaz说的那样,你需要先加载jquery。我把你的代码加载了jquery(和一些选项,所以我们可以看到它工作)并且它工作正常。
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />
<!-- Loading jquery here--><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
</head>
<form name="dziennik" method="post">
<script type="text/javascript">
$(document).ready(function() {
$(".select2").select2();
});
</script>
<select id="dziennik_kontoWinien" name="dziennik[kontoWinien]" class="select2 form-control">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
答案 1 :(得分:1)
试试这个
<script type="text/javascript">
$('select').select2();
</script>