Symfony Docs say that we can use birthday date in forms. but they have not given any example how to use that
Can anyone please tell me where do I need to write birthday in doctrine entity?
The Birthday is the form_widget.
ex. in controller:
$form = $this->createFormBuilder($task)
->add('task', 'text')
->add('yearOfBirth', 'birthday')
->getForm();
This widget can be mapped to DateTime field
/**
* #var date $yearOfBirth
*
* #ORM\Column(name="year_of_birth", type="datetime")
* #Assert\DateTime()
*/
private $yearOfBirth;
Here you got reference to docs about this field:
http://symfony.com/doc/current/reference/forms/types/birthday.html
Regards,
Max
$builder->add('dateOfBirth', 'birthday');
You have plenties of example on the internet:
How to display months in full text for Date fields in Symfony2?
http://j-place.developpez.com/tutoriels/php/creer-premiere-application-web-avec-symfony2/#LX-A
Related
I'm working in a bundle where the user creates a "comision" using a form, and I'm trying to check that the user still have "credit". So I created a custom validator that queries past comisions and throws an error if credit is not enough.
My problem is that if the user submits a date with a wrong format in the "date" field (i.e. 32-13-20122 24:05) Symfony still tries to run my custom validation and I get all sort of errors (because $comision->getDate() is null and not a valid DateTime object).
I'm getting this error:
clone method called on non-object
I can also check if value of $comision->getDate() is a valid datetime in my custom validator, but it seems to me that it should be not necessary since I added this rules in the date property.
This is my entity (simplified)
/**
* #MyValidation\TotalHours()
*/
class Comision
{
/**
* #ORM\Column(type="datetime")
* #Assert\DateTime()
* #Assert\NotNull()
*/
protected $date;
/**
* #ORM\Column(type="decimal", nullable=false, scale=1)
* #Assert\NotBlank()
*/
protected $hours;
...
My form class ...
class NewComisionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', DateTimeType::class, array(
'widget' => 'single_text',
'label' => 'Starting date and time',
'format' => 'dd/MM/yyyy HH:mm'
))
->add('hours', ChoiceType::class, array(
'label'=> 'How many hours',
'choices' => array(
'1:00' => 1,
'1:30' => 1.5,
'2:00' => 2,
'2:30' => 2.5,
'3:00' => 3
)
))
...
And my cutom validator that checks past comisions to find if user still has "credit"
public function validate($comision, Constraint $constraint)
{
$from = clone $comision->getDate();
$from->modify('first day of this month');
$to = clone $comision->getDate();
$to->modify('last day of this month');
$credit = $this->em->getRepository("ComisionsBundle:Comision")->comisionsByDate($comision,$from, $to);
...
One way would be to group your constraints as described in the docs.
This way your can define two groups of contraints whereas the second group will be validated only if all constraints in the first group are valid.
Regarding your use case, you could put your custom constraint in a different group than the default one to be sure your have a proper $comision DateTime object.
To do this, you can use the GroupSequence feature. In this case, an object defines a group sequence, which determines the order groups should be validated.
https://symfony.com/doc/current/validation/sequence_provider.html
The solution should look like this:
/**
* #MyValidation\TotalHours(groups={"Strict"})
* #Assert\GroupSequence({"Comision", "Strict"})
*/
class Comision
In this way, it will first validate all constraints in the group Comision (which is the same as the Default group). Only if all constraints in that group are valid, the second group, Strict, will be validated, making sure $comision->getDate() will have a DateTime instance.
IIRC data transformers run before validation, you can go with data transformer for your date:
https://symfony.com/doc/current/form/data_transformers.html
and then in data transformer check if the date is valid and if not throw an error.
I’m trying to persist an entity with doctrine, the entity has a date attribute and this, apparently, is generating the error.
This is how the attribute is declared in the entity:
/**
* #var date
*
* #ORM\Column(name="fecha", type="date")
* #ORM\Id
*/
private $fecha;
And this is how I create the Entity at controller and the code to persist it with doctrine:
$estadistica = new EstadisticaTerceros();
$fecha = date_create_from_format('Y-m-d', '2017-05-04');
$estadistica->setFecha($fecha);
//Set other attributes
$em = $this->getDoctrine()->getManager();
$em->persist($estadistica);
$em = $this->getDoctrine()->getManager();
$em->flush();
In the table the attribute is date type.
And this is the error screen:
Any idea?
I am assuming that your fecha column is not the primary key of the table. So you can drop the #ORM\Id annotation from that column:
/**
* #var \DateTime
*
* #ORM\Column(name="fecha", type="date")
*/
private $fecha;
date_create_from_format is also an alias for DateTime::createFromFormat and I'd recommend using that just so it's a little more explicit that you are creating a \DateTime:
$fecha = \DateTime::createFromFormat('Y-m-d', '2017-05-04');
If $estadistica->setFecha is expecting a string, just pass it the ISO 8601 date string '2017-05-04' directly instead of converting it to a DateTime instance.
Here you have answer for similiar question:
doctrine DateTime could not be converted to string
You should pass the string into Your entity. With DateTime class instance You could do it as follows:
$estadistica->setFecha($fecha->format('Y-m-d'));
I'm usinf Symfony 3.2.9 with Sonata-admin bundle.
I've create this field in my Entity component:
/**
* #var \DateTime $verificat
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $verificat;
In his admin class there is this function:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->add('verificat','datetime',array('label' => 'Data verificació','format' => 'd/M/Y H:mm'));
}
My problem is that it transforms the date like 2017/Jun/12 13:0606. Where I want to show minutes it shows the month number in the year.
I'd like to know how to show minuts, and even better, how to build any pattern format.
Try looking what the format literals actually mean and how the date_format function works:
http://php.net/manual/en/function.date.php
m stands for month while i stands for minutes.
Try
'd/m/Y H:i'
According to this http://symfony.com/doc/2.8/reference/forms/types/date.html#format I created this form type:
->add('warranty', DateType::class, array(
'widget' => 'single_text',
'format' => 'yyyy-MM-dd')
)
Here what i have in my entity
/**
* #ORM\Column(
* type="date"
* )
*
* #JMS\Groups("list")
* #Assert\NotBlank()
*
* #var \DateTime
*/
protected $warranty;
And I'm trying to save date like this 2012-12-12.
And this works fine, bun when I tried to get back data from DB i got this
2012-12-12T00:00:00+0200
I need work only with date, not datetime, can some one help me?
Doctrine maps date sql fields to an instance of \DateTime class which always has time stored (set to zero).
You can consider using the date twig filter:
http://twig.sensiolabs.org/doc/filters/date.html
Or if you have localised pages, the localised date filter using the intl extension:
http://twig.sensiolabs.org/doc/extensions/intl.html
I have an entity with an array field data (doctrine array). I want to create a symfony form for this entity and i would like include this field in it.
So, the question is:
Is there any way to use custom type as form field in Symfony?
This is form field:
/**
* #var array
*
* #ORM\Column(name="dates", type="array")
*/
private $dates;
This is formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('dates') // i want to use ->add('dates','array') but type 'array' is not allowed
;
}
This is data i want to save:
$dates = array(
'birthday' => \DateTime('1995'),
'wedding' => \DateTime('2001'),
// and so on
)
As far as there is no built-in data type, you should add your custom one. It'll be enough to extend simple text field (TextType) with a DataTransformer which can do array<->json transformation.
Let's assume, your custom type will be YourBundle\Form\Type\JSONArrayType. To use it in your form as a regular field you should register in your bundle config:
json_array_type.service:
class: YourBundle\Form\Type\JSONArrayType
tags:
- { name: form.type, alias: json_array_type }
And then you can use it in your form type like $builder->add('dates', 'json_array_type')
For more information see How to Create a Custom Form Field Type