首先,添加您的新FormType字段:。
<?php
// src/Acme/Form/Type/DatalistType
namespace Acme\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DatalistType extends AbstractType
{
public function getParent()
{
return TextType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired(['choices']);
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['choices'] = $options['choices'];
}
public function getName()
{
return 'datalist';
}
}
Run Code Online (Sandbox Code Playgroud)
在services.yml:
form.type.datalist_type:
class: Acme\Form\Type\DatalistType
tags:
- { name: form.type, alias: datalist }
Run Code Online (Sandbox Code Playgroud)
你有表单主题吗?如果是,请跳到下一步,如果不是,请在其中创建一个新app/Resources/views/Form/fields.html.twig主题并将您的默认 Twig 主题更改为它:
# app/config/config.yml
twig:
form_themes:
- ':Form:fields.html.twig'
Run Code Online (Sandbox Code Playgroud)
现在为表单主题中的新字段定义一个模板:
{% block datalist_widget %}
<input list="{{ id }}_list" {{ block('widget_attributes') }}{% if value is not empty %}value="{{ value }}"{% endif %}>
<datalist id="{{ id }}_list">
{% for choice in choices %}
<option value="{{ choice }}"></option>
{% endfor %}
</datalist>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
使用您的领域FormType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('country', DatalistType::class, ['choices' => ['a', 'b']]);
}
Run Code Online (Sandbox Code Playgroud)
而不是['a', 'b']你需要以某种方式从数据库加载你的选择,我建议将它们在形式上的选项,最简单的解决方案。
| 归档时间: |
|
| 查看次数: |
4354 次 |
| 最近记录: |