Я хотел бы сделать что-то вроде этого:
$builder->add('firstname', 'text', array(
'myCustomOption' => 'optionValue'
));
поэтому я могу использовать myCustomOption
в myForm.html.twig следующим образом:
{% block form_row -%}
{{ myCustomOption }}
{%- endblock form_row %}
Но в этом случае я получаю:
Опция "myCustomOption" не существует. Известные варианты: [..]
Это ответ: Тип расширения
Это позволяет расширять желаемый тип email/phone/checkbox
или text/entity/choice
группы text/entity/choice
или даже всю доступную form
. (Помните, что один элемент может содержать несколько типов. Например, ввод email
будет типом form, text, email
)
Просто создайте класс расширения:
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TextTypeExtension extends AbstractTypeExtension {
public function getExtendedType() {
return 'form'; // What type should be extended
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
// Add optional option - you can also add required options
// and available values of this option
$resolver->setOptional(array('myOption'));
}
public function buildView(FormView $view, FormInterface $form, array $options) {
// You can put any logic here
// For example 'myOption' => 'big' can be transformed to
// 'myOption' => '300px'
if (array_key_exists('myOption', $options)) {
// Add your option to twig template
$view->vars['myOption'] = $options['myOption'];
}
}
}
добавить класс в качестве сервиса:
services:
acme_demo_bundle.image_type_extension:
class: Acme\DemoBundle\Form\Extension\TextTypeExtension
tags:
- { name: form.type_extension, alias: form }
и теперь вы можете сделать:
$builder->add('MyInput', 'text', array('myOption' => array('whateverYouNeed')));
Источник: http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html
Попробуйте что-то вроде этого:
class MyTextType extends AbstractType
{
public function getParent()
{
return 'text';
}
public function getName()
{
return 'my_text';
}
....
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults([
'myOption' => null
])
;
}
....
}
определение услуги:
acme_demo_bundle.text_type:
class: Acme\DemoBundle\Form\Type\MyTextType
tags:
- { name: form.type, alias: my_text }
Применение:
$builder->add('someName', 'my_text', ['myOption' => $value])
attr
, чтобы в шаблоне ветки я мог использоватьattr.myCustomOption
.An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in form_div_layout.html.twig at line 326.
сгенерированоAn exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in form_div_layout.html.twig at line 326.