I have a user object with a birthday column:
/**
* Birthday
*
* #ORM\Column(type="date", nullable=true)
*/
protected $birthday;
In the registration form i add the birthday widget as followed:
->add('birthday', 'birthday')
But when I send the form, I get This value is not valid error for that field.
I've tried some alternatives, but none of them worked:
->add('birthday', 'date')
->add('birthday', 'date', array('input' => 'string'))
Does anyone have a solution?
Dumb mistake..!!
My timezone settings in php.ini was invalid which caused the date transformer to throw an exception
In you want to insert string as input into a date field, you should use the option : 'widget' => 'single_text'
$builder->add('date_created', 'date', array(
'widget' => 'single_text',
'format' => 'YYYY-MM-dd',
));
Related
I am working on php 7.4.30, symfony 4.4.39, sonata-project/admin-bundle 3.98.2
I have a form, with some "required" fields. Some fields are required by default
$form
->tab('Main')
->with('Main', ['class' => 'col-md-8'])
->add('name', null, ['label' => 'Event name'])
->add('title', null, ['label' => 'Title'])
->add('startDatetime', DateTimePickerType::class, ['label' => 'Start date'])
->add('endDatetime', DateTimePickerType::class, ['label' => 'End date'])
->add('language', null, ['label' => 'Language'])
->add('description', SimpleFormatterType::class, [
'label' => 'Description',
'required' => true,
'format' => 'richhtml',
'ckeditor_context' => 'short',
'ckeditor_image_format' => 'material',
'attr' => [
'style' => 'height: 400px'
]
])
->add('place', ModelListType::class, ['label' => 'Place', 'help' => 'Event place'])
->add('link', null, ['label' => 'Ссылка', 'help' => 'Page link'])
...
Entity:
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private string $description;
/**
* #var Place
*
* #ORM\ManyToOne(targetEntity="Place")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="place_id", referencedColumnName="id", nullable=false)
* })
*/
private Place $place;
If form fields are empty, then when "Submit" button is submitted, frontend validation is not working for fields 'description' and 'place'. For other empty fields ('name','title','startDatetime','endDatetime','link') frontend validation is working good and tooltips are appearing on required form fields after click on "Submit" button
So after wrong submitting with empty field, there are server Exceptions appearing, such as:
When attempt to edit item:
TypeError InvalidArgumentException
Expected argument of type "string", "null" given at property path "description".
TypeError InvalidArgumentException
Expected argument of type "App\Entity\Place", "null" given at property path "place".
When attempt to creating new item:
PDOException Exception NotNullConstraintViolationException ModelManagerException
Failed to create object: App\Entity\Event
I know if I change entities properties with null type default - error will not throw. And then it possible to check empty fields on server after submitting. But I need exactly frontend validation. Is it possible?
Expected:
Frontend validation is working good for fields 'description' and 'place', and tooltips are appearing for these required form fields after click on "Submit" button
I have a classic form, with a few 'entity' type fields and one collection type fields. Those aren't causing any issue.
When I put data in all the field, except the description field, as I want it to be null or empty, and submit, my form is processed but the new entity not added to the database, as if the description field needed to be field.
Then I'm redirected to the same form with all data entered gone, as if it had been added in the database.
I've checked the field mapping, which is set to nullable :
/**
* #var string
*
* #ORM\Column(name="description_activite", type="text", nullable=true)
*/
private $descriptionActivite;
public function getDescriptionActivite(){return $this->descriptionActivite;}
public function setDescriptionActivite($value){$this->descriptionActivite=$value;return $this;}
And the field description in the formType file :
->add('descriptionActivite', 'textarea', array(
'label' => 'Description',
'attr' => array(
'class' => 'form-control',
// 'required' => false
)
))
I've also checked the database just in case, the field is created as a may be null field, I really don't know where that problem is coming from. Anyone ran into this already? Thanks
For those who meet the same problem, I solved it by :
Checking database if field may be null (was not the issue but would have been later)
Checking annotation, see if the field is set as nullable
AND LAST
->add('descriptionActivite', 'textarea', array(
'label' => 'Description',
'required' => false,
'attr' => array(
'class' => 'form-control',
)
))
the required option was place in the 'attr' array(), when it should not have, my bad.
Scenario
I have start and end fields in my entity of type DateTime.
/**
* #ORM\Column(type="datetime")
* #var \DateTime
*/
private $start;
/**
* #ORM\Column(type="datetime", nullable=true)
* #var \DateTime
*/
private $end;
I want to modify only the time of these values, so I build a form with fields declaration like that:
->add('start', TimeType::class, [
'widget' => 'single_text',
])
->add('end', TimeType::class, [
'widget' => 'single_text',
])
Sample values
Sample value of these fields before update are (formatted: 'Y-m-d h:i:s'): 2018-07-01 17:30:00
Form input
17:50
Expected result
2018-07-01 17:50:00
Actual result
1970-01-01 17:50:00
Is there a way to render and modify only the time part of the DateTime object with the form without touching the date part?
In theory you would need to write your own data transformer which would take your input, validate and merge specific fields with existing data. You would also need to cover an edge case where someone submits the time, but existing data is empty at the time.
From the looks of it, there is currently no existing transformer which meets your requirements, but it would be relatively easy to write your own. The problem that I see with this is that you will need to make your transformer aware of model-data and merge incoming data with existing one. For me, this would be sign of bad design and clear violation of responsibility.
If you're still up for it, you can check out these:
How to Use Data Transformers
And one of the existing date transformers:
DateTimeToStringTransformer
However, my approach would be to listen to SUBMIT event on a particular field and intercept the submitted data.
This is an example I managed to write quickly:
$inData = [
'start_date' => new \DateTime(),
];
// Shows local date: 2018-07-07 23:28
dump($inData);
$form = $this->createForm(PartialTimeType::class, $inData);
$form->submit([
'start_date' => '23:50',
]);
$outData = $form->getData();
// Should show 2018-07-07 23:50
dump($outData);
PartialTimeType:
$builder
->add('start_date', TimeType::class, [
'label' => 'Start time',
'widget' => 'single_text'
]);
$builder->get('start_date')->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
/** #var \DateTime $modelData */
$modelData = $event->getForm()->getData();
/** #var \DateTime $data */
$data = $event->getData();
$data->setDate(
(int)$modelData->format('Y'),
(int)$modelData->format('m'),
(int)$modelData->format('d')
);
});
I am sure that you could write your own extension of TimeType which encapsulates this behavior our of box...
Hope this helps...
when i submit a form and run form validation then it gaves me this error but my form validation is working on other page
In that file \vendor\laravel\framework\src\Illuminate\Validation\Validator.php
/**
* Handle dynamic calls to class methods.
*
* #param string $method
* #param array $parameters
* #return mixed
*
* #throws \BadMethodCallException
*/
public function __call($method, $parameters)
{
$rule = Str::snake(substr($method, 8));
if (isset($this->extensions[$rule])) {
return $this->callExtension($rule, $parameters);
}
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
Errror= Method Illuminate\Validation\Validator::validateRequest does not exist
Maybe you wrote request instead of required? Like here:
$data = $request->validate([
'field' => 'request|string|max:255',
]);
Trying to fire validateRequest method suggest you were trying to use 'request' validation rule which doesn't exist.
All valid rules you can find here, but I think you just made a typo.
You should use a Validator facade class
In you Controller
use Validator;
See link Laravel validation
You can validate the form as below:
public function formSubmit(Request $request){
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
]);
$customer =Customer::insert([
'name' => $request->name,
'address' => $request->address,
'phone' => $request->phone
]);
dd($customer);
echo "Data send Successfully";
}
you may try this method
$request->validate([
'sex' => ['required',Rule::in('f','m')]
]);
this one is worked for me
$request-> validate([
'name'=>'required',
'email'=>'required|email'|'unique:admins',
'password '=>'required|min:5|max:12'
After how many minutes of debugging the error was there's an extra '' in required and a space after 'password '. Please see corrected code below
$request-> validate([
'name'=>'required',
'email'=>'required|email|unique:admins',
'password'=>'required|min:5|max:12'
In my case, I forget to import Validator file and just added this line at the top of controller file where I was using Validator in function
use Illuminate\Support\Facades\Validator;
and it worked like a charm.
In my case I just misspelled required a few times.
Currently i'm working with PHP 5.6.2 in my laptop and the server has 5.5.0 both has configurated timezone to "America/Bogota"
the entity has a field like
/**
* #var \DateTime
* #Column(name="start_date", type="datetime")
* #NotNull()
*/
protected $startDate;
and the entity type is defined like
$builder
->add('startDate', 'date', array(
'input' => 'datetime',
'widget' => 'single_text',
));
the data passed is formatted like 2015-01-15T06:11:37-0500 in my laptop that date is correct but in the server is invalid
I don't know why you are facing this problem, but I would advice you to specify the date format in the form like follows:
Also change date to datetime.
$builder
->add('startDate', 'datetime', array(
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'yyyy-MM-ddThh:ii:ss'
));
Hope this helps.