Reputation: 5084
Hi Im trying to create custom field
like here but after adding to service.yml
services:
griffin.type.datetime_to_string:
class: griffin\CoreBundle\Form\DateTimeType
arguments: ["@doctrine.orm.entity_manager"]
tags:
- { name: form.type, alias: datetime_to_string }
Im getting Catchable Fatal Error: Argument 1 passed to griffin\CoreBundle\Form\DataTransformer\DateTimeToStringTransformer::__construct() must implement interface Doctrine\Common\Persistence\ObjectManager, null given
any one had this problem ?
EDIT
namespace griffin\CoreBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use griffin\CoreBundle\Form\DataTransformer\DateTimeToStringTransformer;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Description of DateTimeType
*
* @author skowron-line
*/
class DateTimeType extends AbstractType {
private $om;
public function __construnct(ObjectManager $om) {
$this->om = $om;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
var_dump($this->om);
$transformer = new DateTimeToStringTransformer($this->om);
$builder->addModelTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'invalid_message' => 'err',
));
}
public function getParent() {
return 'text';
}
public function getName() {
return 'datetime_to_string';
}
}
and in my controller
$form = $this->createForm(new KlientType(), $klient);
Upvotes: 1
Views: 854
Reputation: 52483
If you want to use a custom FormType as a service ( because you need to have services or parameters injected ) you must add the field to your builder with it's service name (or alias) and not with new CustomFormType().
$builder->add('date', 'datetime_to_string', array(
// ...
))
DateTime to string conversion is already provided by Symfony since 2.0.
Have a look at Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer
You can transform the date field into a text input with the "widget" option set to "single_text" and the format option set to your desired text-representation.
$builder->add('publishedAt', 'date', array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
));
Transformed into a text input this field can easily be integrated with common JavaScript Datepickers. Consider using that one instead of your own implementation.
Tip:
You don't have to surround the injected service with " in yml.
services:
griffin.type.datetime_to_string:
class: griffin\CoreBundle\Form\DateTimeType
arguments: [@doctrine.orm.entity_manager]
tags:
- { name: form.type, alias: datetime_to_string }
This often leads to errors when copy/pasting from tutorials on the net where symbols are auto-converted into something different than "real" question marks.
Upvotes: 1