Cakephp3: Using NULL in Form input as options - forms

I am trying to get null inserted into my database by using a FormHelper input.
Options should be:
<?= $this->Form->input('preferedtimeformat', [
'label' => __('prefered representation of date and time'),
'options' => [
NULL => __('standard of your locale'),
'yyyy-MM-ddThh:mm:ss.sTZD' => __('ISO 8601 (yyyy-MM-ddThh:mm:ss.sTZD)'),
'eee, dd MMM yyyy hh:mm:ss xx' => __('RFC 2822 (eee, dd MMM yyyy hh:mm:ss xx)'),
'h:m:s d.M.yyyy' => __('german style (h:m:s d.M.yyyy)'),
'd.M.yyyy h:m:s' => __('invers german style (d.M.yyyy h:m:s)')
...some more options...
]
]) ?>
This should help the user specifying another Datetimeformat if he wants or needs to. Time::i18nFormat() accepts null as Datetimeformat and then uses the presets of the locale you give to it.
But creating a user with the NULL option from a form doesn't work, so I get an empty string ant not null saved into the database.
Is there any better solution than checking in the controller for an empty string and replacing it by NULL?

Of course you'll end up a string in the database, HTML can only "send" strings, all input received by PHP is of type string, and your database column is a string type too.
If you want an empty string to be treated as NULL, you should use a mutator in the correspending entity, which turns '' into null, for example something like
class Xyz extends Entity
{
protected function _setPreferedtimeformat($value)
{
if (empty($value)) {
return null;
}
return $value;
}
}
See also Cookbook > Database Access & ORM > Entities > Accessors & Mutators

Related

Set default value for date in Sonata

I have a date that I'd like to set as the default value the current date and most of the posts suggest to add the 'data' => new \DateTime() but there are two issues with that in Sonata:
if I change the date to a random one or even leave it empty, it will still save in the database the current one
in the edit view it will override the date from the create view and the value will still be the current date
My code:
$form->add('startDate', DateType::class, [
'required' => false,
'label' => 'Starting date',
'data' => new \DateTime("now"),
'constraints' => ...
])
]);
What am I missing?
The data attribute will overwrite data in all cases, as you can read here in DateType Field#data.
What you can do is set a default value in the entity instead as described in What is the best way to set defaults values of a Symfony object?
In the entity, you would have the following:
private $startDate = new \DateTime("now");
The downside of this is that it also adds the default value when the entity is created outside of Sonata.

how to hide date time from the return view?

I use Yii2 framework and I have a column named "datacreation" (type DATE TIME and value CURRENT TIMESTAMP).
Also, I have this code in my view:
[
'attribute' => 'datacreazione',
'value' => function ( $model ) {
$stampa= "";
if( $model->Utenteupdate ){
$tip1= $model->Utenteupdate;
$tip1= ($tip1) ? User::findOne($tip1) : null;
$tip1n= ($tip1) ? $tip1->id : "";
$stampa= ($tip1n);
}
return $model->datacreazione." utente ".$stampa;
},
'label' => 'Data creazione']
This show me the result: "2020-07-15 11:33:00 utente 734".
Now, I would to hide the date and the timestamp. At the end, the result that I wish is "utente 734", without other information about date and time. I hope to be clear.
Anyone can help me with this code please?
Thank you!!!!
You build the showed text in one anonymous associated to the param value
then in this anonymous function just return the string for utente 734
return "utente ".$stampa;

Getting CakePHP 3 to output dates in yyyy-mm-dd format

CakePHP 3.5.13. I am getting some records from MySQL which are stored as DATE fields. For example: 2018-07-30
I want Cake to output the dates in that format. However, it is converting them to British dd/mm/yyyy format. So the example above comes out as 30/07/2018 in my template files.
The data returned from the database looks like this:
'date' => object(Cake\I18n\FrozenDate) {
'time' => '2018-07-30T00:00:00+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
},
In my config/app.php the locale is set to en_GB:
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_GB'),
I assume this is the reason it's displaying all of the dates in this way.
All I am doing in the template is displaying the data returned from the database - no conversion is occurring within my code:
// In a controller
$RevisionSubstances = TableRegistry::get('RevisionSubstances');
$revision_comments = $RevisionSubstances->find('all')->toArray();
debug($revision_comments); // format is '2018-07-30T00:00:00+00:00'
// In the template
echo $revision_comments['date']; // format is '30/07/2018'
How do I get the dates to be output in yyyy-mm-dd format?
I had a look at these resources but can't see the answer:
https://book.cakephp.org/3.0/en/core-libraries/time.html
https://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-dates

Accessing normalized form data in a controller in Symofny 2

I had to add a form event listener (PRE_SUBMIT) to my FormType in order to set a default value of a field based on the value of another field submitted by the user:
//In my FormType:
public function onPreSubmit(FormEvent $event)
{
$formData = $event->getData();
if (empty($formData['time_until'])) {
$date = new \DateTime($formData['time_from']);
$date->add(new \DateInterval('PT1H'));
$formData['time_until'] = $date->format('Y-m-d H:i');
}
$event->setData($formData);
}
time_unti key is set and later its value is mapped onto the form's time_until field which is of datetime type:
->add('time_until', datetime, [
'required' => false,
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'yyyy-MM-dd HH:mm',
'label' => false,
])
No problem so far. However, I need to have access to the normalized values of the form fields in my controller, and not DateTime objects that are present on the form after the call to $form->handleRequest($request);
By "normalized", I mean I want to be able to do:
$form->get('time_until') and have a string in the form 'yyyy-MM-dd HH:mm' returned, and not the DateTime object stored in the form under time_until key.
Advice would be much appreciated. Thank you!
you could just add some attribute $normalizedTimeUntil in your form type class + add getter getNormalizedTimeUntil() that would return this value. Then in Form event you can set this attribute and in controller you can pull it out of form type object with the getter function
or you can add non-mapped string form field timeUntilString (http://symfony.com/doc/current/reference/forms/types/form.html#mapped) and fill it in form event
or you can add transformer (http://symfony.com/doc/current/cookbook/form/data_transformers.html) to transform this Datetime object into string. This would be convienent if you for example need to store date in string form in the database). Then form field getter would return string in controller (and would get stored in the db in string also)

Formatting Datetime field in a Symfony2 form to display full months

I am using a formType in Symfony2, and one of the fields is of type DateTime.
I would like to display the months as full months (and preferably in a language other than English).
If my field type had been birthday, thus without time, it would have been easy:
$builder->add('appointment', 'birthday', array
(
'format' => 'dd - MMMM - yyyy',
'widget' => 'choice'
'required' => true
));
But the field is now defined as:
$builder->add('appointment', 'datetime', array
(
'required' => true
// ????
));
How can I render this field type using 5 dropdown lists (day, month, year, hour, minute), with the months being full text items? And how can I define an array with the month names in another language?
I suggest that you create your own field type by choosing the birthday type as a parent. You can follow these simple steps to do this.
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AppointmentType extends AbstractType{
//...
public function getParent()
{
return 'birthday';
}