I'm writing a unit test and I can't pass the validation for a datetime field. This is my entity with the field that causes problems:
class Page
{
/**
* #var \DateTime
* #Assert\NotBlank(message="NOT_EMPTY")
* #ORM\Column(name="end_date", type="datetime", nullable=true)
*/
private $date;
}
And here is my unit test:
$form = $crawler->filter('#addNew')->form();
$date = new \DateTime();
$params = array(
'formpage[title]' => 'Unitest sample',
'formpage[date]' => $date->format('Y-m-d H:i:s')
);
$form->setValues($params);
$client->submit($form);
This is the error I caught using the debugger, $form->isValid() returns false:
Symfony\Component\Validator\ConstraintViolation
This value is not valid
Unable to reverse value for property path "date": Date parsing failed: U_PARSE_ERROR
Any idea what the problem could be? Thanks in advance.
I think it's failing because of the expected format.
It seems you've defined your widget as a single_text but haven't specified the format (or the one you specified doesn't coincide with the one you're sending). The default format is yyyy-MM-dd if widget is single_text ( no H:i:s part).
Correct this and it should work.
Related
Hi guys i am working with laravel 5.7 while inserting data im getting issue of "Data Missing" but the data is inserting as well but still getting error here im sharing part of my code
Model
public function setApplicationDateAttribute($input)
{
if($input != '') {
$this->attributes['application_date'] = Carbon::createFromFormat(config('quickadmin.date_format'), $input)->format('Y-m-d');
}else{
$this->attributes['application_date'] = '';
}
}
this is the funtion which is checking the date format for input data Now this is a file in my config folder named quickadmin i will show you the code of it
return [
/**
* Datepicker configuration:
*/
'date_format' => 'Y-m-d',
'date_format_jquery' => 'yy-mm-dd',
'time_format' => 'H:i:s',
'time_format_jquery' => 'HH:mm:ss',
/**
* Quickadmin settings
*/
'route' => 'admin',
'homeRoute' => 'admin',
'defaultRole' => 1];
Now here is the code of Controller
$locumApplications = ModelName::create([
'user_id' => $request->user_id,
'locum_id' => $request->locum_id,
'application_date' => $request->application_date
]);
it insert the data but give me error and if i remove the line 'application_date' => $request->application_date it still show me the error
here i attached the error image
Your config: config('quickadmin.date_format') is Y-m-d
You are trying to set attributes
Carbon::createFromFormat(config('quickadmin.date_format'), $input)->format('Y-m-d');
Your $input ($request->application_date) must be on Y-m-d format
Should be work
\Carbon\Carbon::createFromFormat('Y-m-d', '2019-03-14')->format('Y-m-d') //OP: 2019-03-14
Your date input and set attributes value look like the same format
Can you try overriding the default format in YourModel like below:
class YourModel extends Model {
protected $dateFormat = 'Y-m-d'; // add your date format
}
I have an API which takes multiple input values. One of them is a date.
When the date is sent, all is fine.
But, when the user isn't sending a date, I have an error 500 with this error message:
Invalid datetime "Some invalid data", expected format Y-m-d\TH:i:sP.
So I wanted to check if the data sent had the format required.
But I don't understand how things are working, hope you can help.
This is what I have
/**
*
* #Rest\Post(
* path = "/signup",
* name = "api_users_add"
* )
* #Rest\View(StatusCode=201, serializerGroups={"user_detail"})
* #ParamConverter(
* "user",
* converter="fos_rest.request_body",
* options={"deserializationContent"={"groups"={"Deserialize"}}},
* )
* #ParamConverter(
* "profile",
* converter="fos_rest.request_body",
* options={"deserializationContent"={"groups"={"Deserialize"}}},
* )
*/
public function postUserAction(Request $request, User $user, Profile $profile)
{
if (!preg_match("^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$",$profile->getBirth())){
return new JsonResponse([
'success' => false,
'message' => "Date d'anniversaire au mauvais format"
]);
}
}
But in fact, I never go into this condition, the error 500 is triggered before.
I guess this has something to do with the #ParamConverter from Profile who can't "deserialize" when birth is not a DateTime.
Thing is, I would like to check what is sent (as I did into my condition) in order to avoid this internal error. But I can't find where this is handled on my code.
Thanks for the help.
Considering this : symfony doc for Param converter fos rest bundle
What I am looking for is to find where the validationErrors are specified.
I have a function in Symfony3 that posts data to a mysql database. The function looks like this:
/**
* #Route("/LegoPieces")
* #METHOD("POST")
* #View()
*
* #Annotations\QueryParam(
* name="piece", nullable=false, description="piece"
* )
* #Annotations\QueryParam(
* name="type", nullable=false, description="type"
* )
* #Annotations\QueryParam(
* name="startDate", nullable=false, description="Start Date YYYY-MM-DD HH:MM:SS (Should be in the future)"
* )
* #Annotations\QueryParam(
* name="endDate", nullable=false, description="End Date YYYY-MM-DD HH:MM:SS (Should be no more than 3 weeks in the future)"
* )
*/
public function postAction(ParamFetcherInterface $paramFetcher)
{
$piece = $paramFetcher->get('piece');
$type = $paramFetcher->get('type');
$start = $paramFetcher->get('startDate');
$end = $paramFetcher->get('endDate');
$startDate = DateTime::createFromFormat('Y-m-d H:i:s', $start);
$endDate = DateTime::createFromFormat(' Y-m-d H:i:s', $end);
$em = $this->getDoctrine()->getManager('default');
$data = new LegoPieces();
$data->setPiece($piece);
$data->setType($type);
$data->setStartDate($startDate);
$data->setEndDate($endDate);
$em->persist($data);
$em->flush();
return new JsonResponse("LegoPieces Added Successfully", 200);
}
When I replace the variables ($piece, $type, $startDate, $endDate) with strings the post request works. But when I try to make a post request through something like Postman or javascript like this:
fetch("http://localhost:8000/LegoPieces", {
method: "POST",
body: {
startDate: this.startDate,
endDate: this.endDate,
piece: this.piece,
type: this.type
}
}).then(response => response.json())
);
});
I get a 500 error! I don't understand- thanks for your help!
Look in your logs what is your error.
But you have to improve your controller ! You don't use Symfony Form and you don't have any validations. Even if your haven't 500 error now, you will have some in the future if you don't respect your entity types.
I also don't understand why you use a post request and don't pass all your parameters in your body. You only use get parameters in the url.
Without knowing what exception makes that 500 - you know nothing :(
Try to see response body
Without that info - i have only one idea .
If you arw working on dev envionment , then youur js request simply may not see routes (and the other stuff)
clear all contents of cache folder
rm -rf var/cache/*
and
php bin/console c:w -e prod
I have a model with such field:
/**
* #var datetimetz
*
* #ORM\Column(name="effective_from", type="datetimetz", nullable=false)
*/
private $effectiveFrom;
in the form builder I present it as:
->add('effectiveFrom', 'datetime', array(
'date_widget' => 'single_text',
'time_widget' => 'single_text',
'date_format' => 'Y-MM-dd',
'with_seconds' => true
))
So it is rendered as two different input fields.
Let's suppose I've specified 2012-07-31 in the date field and 16:15:18 in the time field.
I press submit and var_dump() the entity. The bind date becomes 1970-07-31 16:15:18. And with any date only year is recognized in wrong way :-S
If I don't change date and time widgets - then everything works as expected.
Any suggestions?
Well, it is symfony documentation bug.
yyyy (lower case) should be used.
I've filled the bug https://github.com/symfony/symfony-docs/pull/1045 and I hope it will be fixed soon
public function configure()
{
$this->widgetSchema['start_date'] = new sfWidgetFormInput();
$this->widgetSchema['end_date'] = new sfWidgetFormInput();
$this->validatorSchema->setPostValidator( new sfValidatorOr ( array(
new sfValidatorAnd( array
(new sfValidatorSchemaCompare('start_date', sfValidatorSchemaCompare::NOT_EQUAL, null),
new sfValidatorSchemaCompare('end_date', sfValidatorSchemaCompare::EQUAL, null)
)),
new sfValidatorSchemaCompare('start_date', sfValidatorSchemaCompare::LESS_THAN_EQUAL, 'end_date',
array('throw_global_error' => false), array('invalid' => 'The start date ("%left_field%") must be before the end date ("%right_field%")')))));
}
I've got following input dates which I want to check if the end date isn't before the start date:
Input: Start => 31/03/10 End=> 07/03/10
Output: The start date (2010-03-31) must be before the end date (2010-03-07)
Can you in some way change the date output? I need the error message to set the date format the same as the input.
Also my input fields are set with the wrong date format when the error appears.
Tried several things, but no luck at this moment. Didn't find a solution or information on symfony it self.
I'm using symfony version 1.2.11
I found a the solution together with a colleague.
After some tryouts, we found the solution to my initial problem. Instead of using that post validator, we wrote are own validator.
class StartBeforeEndDateValidator extends sfValidatorBase {
public function configure($options = array(), $messages = array()) {
parent::configure($options, $messages);
$this->addMessage('Invalid_daterange', 'Start date (%start%) must be before End date (%end%)!');
}
public function doClean($values) {
sfContext::getInstance()->getConfiguration()->loadHelpers('Date');
$timestampStart = sfContext::getInstance()->getI18N()->getTimestampForCulture($values['start_date'], sfContext::getInstance()->getUser()->getCulture());
$timestampEnd = sfContext::getInstance()->getI18N()->getTimestampForCulture($values['end_date'], sfContext::getInstance()->getUser()->getCulture());
if(format_date($timestampStart) > format_date($timestampEnd)){
throw new sfValidatorError($this, 'Invalid_daterange', array('start' => $values['start_date'], 'end' => $values['end_date']));
}
}
}
Usage of the validator in the symfony form:
public function configure() {
$this->widgetSchema['start_date'] = new sfWidgetFormInput();
$this->widgetSchema['end_date'] = clone $this->widgetSchema['start_date'];
$this->validatorSchema['start_date'] = new DateValidator();
$this->validatorSchema['end_date'] = clone $this->validatorSchema['start_date'];
$this->validatorSchema->setPostValidator(new StartBeforeEndDateValidator());
}
This was the solution to have always the same date format when it's being validated and when the validation is trigger with an error, the format of the date is correctly returned in the same date format as it was set.
Now one other "problem" that we encountered was when the save happened, the date format wasn't right for mysql. So we override the save function in our symfony form and apply the right date format.
example:
public function save($con = null){
$var = new Object();
if($this->taintedValues['id']!= ""){
$var->setId($this->taintedValues['id']);
}
$var->setStartDate(DateUtils::getIsoDateForCulture($this->taintedValues['start_date']));
$var->setEndDate(DateUtils::getIsoDateForCulture($this->taintedValues['end_date']));
$var->setIcpm($this->taintedValues['icpm']);
$var->save($con);
}
So once the validation is valid, it will perform the save function and set the right date format before actually save it into the database.
Hope that this is helpful for other people who had this problem.