Issue using CJuiDatePicker with different formats - php

I am using CJuiDatePicker in my form and I need to use two different formats: mm/dd/yy to be shown and dd/mm/yy to be sent in $_POST.
$questionario->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $modeloDoQuestionario,
'attribute' => 'data_preenchimento',
'language' => 'en',
'options' => array(
'showAnim' => 'fold',
'showButtonPanel' => true,
'showOn' => 'both',
'dateFormat' => 'dd/mm/yy',
'altField' => '#Questionarios_data_preenchimento',
'altFormat' => 'mm/dd/yy',
),
'htmlOptions' => array(
'style' => 'height:14px;'
),
));
This is the field in HTML:
<input style="height:14px;" id="Questionarios_data_preenchimento" name="Questionarios[data_preenchimento]" type="text" />
But I still get the mm/dd/yy format in $_POST... What can be wrong?

You can put in the configuration file: 'main.php' something like this:
'widgetFactory' => array(
'widgets' => array(
'CJuiDatePicker' => array(
'scriptFile' => 'jquery-ui.min.js',
'language' => 'en',
'options' => array(
'dateFormat' => 'dd/mm/yy',
'showAnim' => 'fold',
'fontSize' => '0.85em',
),
),
),
),
With this ever that you call a 'CJuiDatePicker' widget will inherit this format.

I was looking for the same thing and have a slightly different solution.
I was mainly looking for on form pages to display the date as DD-MM-YYYY and save in the database as YYYY-MM-DD.
Regardless of changing the dateFormat option on CJuiDatePicker and even trying to use altFormat (using altField as well as apparently this is necessary) option, the date did not show in the desired format, granted if I were to change the date, the format would be shown correctly.
So I created a Custom class in components and created two methods, one to reformat the date to the DD-MM-YYYY format and one to format the date to the correct YYYY-MM-DD to be saved in the database.
Here is the Custom class (the file is called Custom.php and kept in components.)
class Custom
{
/*
**This method formats the date to be human readble ie 21-06-2013
*/
public function reformatDate($date)
{
if($date == '0000-00-00')
{
$newDate = '00-00-0000';
return $newDate;
}
elseif($date == '')
{
return $date;
}
else
{
$newDate = date("d-m-Y", strtotime($date));
return $newDate;
}
}
/*
**This method formats the date to the correct format according to the database
*/
public function formatDate($date)
{
if($date == '00-00-0000')
{
$newDate = '0000-00-00';
return $newDate;
}
elseif($date == '')
{
return $date;
}
else
{
$newDate = date("Y-m-d", strtotime($date));
return $newDate;
}
}
}
Now that I had methods to change the dates to the correct formats. On the _form page I declared at the top, under the initiation of the form.
$model->date_required = Custom::reformatDate($model->date_required);
$model->date_created = Custom::reformatDate($model->date_created);
$model->date_completed = Custom::reformatDate($model->date_completed);
This now results in the date being shown correctly, both when the _form page is viewed and the date is changed via the CJuiDatePicker as i still use the dateFormat option to show the correct format when the date is changed.
Lastly I added to both the create and update actions of the controller the following.
if(isset($_POST['Tickets']))
{
$model->attributes=$_POST['Tickets'];
$model->date_created = Custom::formatDate($model->date_created);
$model->date_required = Custom::formatDate($_POST['Tickets']['date_required']);
$model->date_completed = Custom::formatDate($_POST['Tickets']['date_completed']);
if($model->save())
So before the data is then saved back to the database I format the date to the correct format and pop it into the database.
I'm not expert and only a few month into Yii and about 9 months into PHP. I know there are all sorts of before and after save methods and this may not be the best way to do it, in fact if there is a better way I am all ears. But for now this is working for me. hope ths helps someone.
/* Small Update */
After speaking with a colleague who has been doing this stuff for about a decade. he said it would be much cleaner to remove the code I placed on the form page under the form initiation and move it rather into the controller, so for example my update method appears like so
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$model->date_required = Custom::reformatDate($model->date_required);
$model->date_created = Custom::reformatDate($model->date_created);
$model->date_completed = Custom::reformatDate($model->date_completed);
So rather than reformatting the dates on the form page, it is done directly after loadModel, keeping the view cleaner.

Related

Data missing error in laravel while date format is correct and data is stored as well but still getting error

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
}

DateTime not save properly in cakephp 3.x with bootstrap datetimepicker

i am using cakephp 3.x, i have one form in which one field is of date. in backend i am using mysql.
my field structure in mysql is dob of type date.
now in cakephp 3.x i had use below syntax to create input.
echo $this->Form->input('dob', array(
'label' => (__('Date of Birth')),
'type' => 'text',
'required' => false,
'class' => 'form-control date'
));
and i had used bootstrap datetimepicker like,
$('.date').datetimepicker({
format: 'YYYY-MM-DD'
});
now when i submit the form at and i print_r the request data at that time i got this field like this
[
....
'dob' => '2016-02-11',
....
]
but when i save the record and look in database then it show me random date like 2036-10-25
can anyone help me please?
and this is the Final General Solution,
//File : src/Model/Table/PatientsTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Event\Event;
use ArrayObject;
use Cake\I18n\Time;
class PatientsTable extends Table
{
...
...
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
if (isset($data['dob'])) {
$data['dob'] = Time::parseDate($data['dob'], 'Y-M-d');
}
}
}
You declared dob type as date but tried to save date in string format instead of date time format. Try this
use Cake\I18n\Time;
$this->request->data['dob']= Time::parseDate($this->request->data['dob'],'Y-M-d');

Change timezone for CGridView

I am currently working on a web application that will allow me to change the timezone during the execution. I started to test some cases, but it unfortunately doesn't work for the CGridView.
Working tests
This code here works for changing the timezone. I use the setTimeZone() function wich is a wrapper of the date_default_timezone_set() function.
Yii::app()->setTimeZone("America/Montreal");
echo "mtl:".date("Y-m-d H:i", 1396624849)."<br>";
Yii::app()->setTimeZone("Asia/Gaza");
echo "gz:".date("Y-m-d H:i", 1396624849);
The output is making a lot of sens (mtl:2014-04-04 11:20, gz:2014-04-04 18:20).
CGridView implementation
When I try the exact same line in a view with a CGridView, it doesn't work and displays only my default date format. Here is the code:
Yii::app()->setTimeZone("Asia/Gaza");
echo Yii::app()->getTimeZone();
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'reports-grid',
'dataProvider'=>$dataProvider,
'filter'=>$filtersForm,
'columns'=>array(
array(
'header'=>'Date',
'name'=>'inserted',
'type'=>'raw',
'value'=>'date(Yii::app()->params->dateformat, strtotime($data->inserted));'
),
),
));
The output date stays the same even if I change the time zone for America/Montreal.
What was tried so far
Adding the setTimeZone() function to a function with the date definition, as so:
'value'=>function($data){
Yii::app()->setTimeZone("America/Montreal");
return date(Yii::app()->params->dateformat, strtotime($data->inserted));
}
The result was the same as before.
Conclusion
Why is it not working? Is there a way to change the timezone dynamically in Yii? Is it possible that it doesn't work because the CGridView is built with eval operations?
Try this, it should work.
$dateTime = new DateTime();
$dateTime->setTimezone(new DateTimeZone('Asia/Gaza'));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'reports-grid',
'dataProvider'=>$dataProvider,
'filter'=>$filtersForm,
'columns'=>array(
array(
'header'=>'Date',
'name'=>'inserted',
'type'=>'raw',
'value'=>function($data) use ($dateTime){
$dateTime->setTimestamp(strtotime($data->inserted));
return $dateTime->format(Yii::app()->params->dateformat);
}
))
));
By setting the timezone outsite of the function and using it inside, it should all work fine.
try this:
'value' => function($data){
Yii::app()->setTimeZone("Asia/Gaza");
return date(Yii::app()->params->dateformat, strtotime($data->inserted));
},

Filter Date using Date Picker in Yii

I have generated my crud screens using gii.. I have a search form, where i have put a date picker, where i give the user to select the date he wants.
But the problem is that i have the date stored in seconds in the database.
and i know that i can convert the date using strtotime. But then how do i filter using the search method in my model?
this is my date picker
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'ordering_date',
'id'=>'ordering_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
and this is my search method in my model. I want to compare the ordering_date
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
//echo $this->ordering_date;
$criteria=new CDbCriteria;
$criteria->compare('order_id',$this->order_id);
$criteria->compare('customer_id',$this->customer_id);
$criteria->compare('delivery_address_id',$this->delivery_address_id);
$criteria->compare('billing_address_id',$this->billing_address_id);
$criteria->compare('ordering_date',$this->ordering_date);
$criteria->compare('ordering_done',$this->ordering_done,true);
$criteria->compare('ordering_confirmed',$this->ordering_confirmed);
$criteria->compare('payment_method',$this->payment_method);
$criteria->compare('shipping_method',$this->shipping_method);
$criteria->compare('comment',$this->comment,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('total_price',$this->total_price);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
Try this:
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'ordering_date',
'options' => array('dateFormat' => 'mm-dd-yy',),
And search
$begindate = CDateTimeParser::parse($this->ordering_date, 'MM-dd-yyyy');
$enddate = $begindate + 24* 60*60;
$criteria->addBetweenCondition('ordering_date', $begindate, $enddate);
Either do a $this->ordering_date = strtotime($this->ordering_date); before you compare or $criteria->compare('ordering_date', strtotime($this->ordering_date));

symfony sfValidatorSchemaCompare and dateformat output problem

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.

Categories