问题
My App ist running, but when I use a custom Form-Field-Type (shtumi_daterange) like:
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options)
{
$dateRange4 = new DateRange('m/d/Y');
$dateRange4->parseData('03/27/2012 - 04/05/2012');
$builder->add('builddate', "shtumi_daterange", array('required'=>false, 'default'=>$dateRange4));
}
the this error occurs:
Uncaught exception 'Symfony\Component\Form\Exception\FormException' with
message 'Could not load type "shtumi_daterange"' in
../vendor/symfony/form/Symfony/Component/Form/FormRegistry.php:95
I think, I need something like:
<?php
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => $path_ext_dir_abs . '/views',
'twig.form.templates' => array('form_div_layout_custom.html.twig'),
'form.type.shtumi_daterange' => 'Shtumi\UsefulBundle\Form\Type\DateRangeType',
));
but I just dont know/find the right symtax!
From the symfony documentation, I found this example how to register a custom form field type, but I can't transform this to get it run with silex:
services:
form.type.gender:
class: Acme\DemoBundle\Form\Type\GenderType
arguments:
- "%genders%"
tags:
- { name: form.type, alias: gender }
回答1:
You do not need to register it to be able to use it. You can pass a new instance as the second parameter of add:
use Shtumi\UsefulBundle\Form\Type\DateRangeType;
/* ... */
public function buildForm(FormBuilderInterface $builder, array $options)
{
$dateRange4 = new DateRange('m/d/Y');
$dateRange4->parseData('03/27/2012 - 04/05/2012');
$builder->add('builddate', new DateRangeType(), array('required'=>false, 'default'=>$dateRange4));
}
It's mentioned in the document you linked.
回答2:
I achieved this by extending the FormServiceProvider.
use Symfony\Component\Form\FormFactoryInterface;
$app->extend('form.factory', function (FormFactoryInterface $factory) {
$factory->addType(new MyType());
return $factory;
});
来源:https://stackoverflow.com/questions/11915618/how-can-i-register-a-custom-form-field-type-in-silex-twig