datetimepicker - duplicate display when select and get data - yii2

I'm using datetime picker in Yii2
DateTimePicker::widget([
'name' => 'dp_1',
'options' => [ 'id' => 'time_picker'],
'pluginOptions' => [
'todayHighlight' => true,
]
])
and get value like this:
var date = $("#time_picker").datetimepicker('getDate').getTime()/1000;
but when I select it display duplicate :
I have no idea about this ,please help me

Instead of
var date = $("#time_picker").datetimepicker('getDate').getTime()/1000;
Use
var date = $("#time_picker").val();
Because, First time you used DateTimePicker. It's Ok. While getting the value again for DateTimePicker, You are again initializing it $("#time_picker").datetimepicker...
So, My opinion is to use var date = $("#time_picker").val(); and do all calculations after getting date value.

Related

TYPO3 9 LTS type casting error on mysql time field for TCA type input / dbType time saving empty field

I'm trying to have a time input in TYPO3 9 LTS working together with MySQL 5.7.24.
In the ext_tables.sql the field gets defined like this:
some_field time default NULL
In the TCA the field gets defined like this:
'some_field' => [
'exclude' => 1,
'label' => 'Some field',
'config' => [
'type' => 'input',
'dbType' => 'time',
'eval' => 'time',
],
],
When saving the record in the backend without a time input (which should be possible) I'm getting the error:
These fields of record 1 in table "some_table" have not been saved correctly: some_field! The values might have changed due to type casting of the database.
When looking at the database record the some_field field gets the value 00:00:00 (although the db default is NULL).
When selecting a time the record can be saved and opened without error.
Is this a bug in TYPO3 or how could I fix this behavior?
The bug can be solved by having the following eval:
'eval' => 'time,null',
That means you have given the wrong type for the value on your ext_tables.sql. Additionally, TYPO3 v9 has renderTypes.
Try something like that:
ext_tables.sql
begin int(11) DEFAULT '0' NOT NULL
TCA
'begin' => [
'exclude' => true,
'label' => 'LLL:EXT:your_ext/Resources/Private/Language/locallang_db.xlf:tx_yourext_domain_model_modelname.begin',
'config' => [
'type' => 'input',
'renderType' => 'inputDateTime',
'size' => 10,
'eval' => 'datetime',
'default' => time()
],
],
Additional information!
If you want to display the time in FrontEnd you could use something like that
<f:format.date>{dateObject.begin}</f:format.date>
If you want to modify how it looks, you can use the format attribute as well:
<f:format.date format="%d. %B %Y">{dateObject.begin}</f:format.date>
More about that here: TYPO3 Date format

Custom filter in Gridview (Regular or Overdue)

I have a registration_date column where I store the date that the customer was registered in the company (example: 2015-06-12). You'll need to filter if the customer has a failed or overdue registration (if registration_date is longer than 365 days).
In the preview screen I can display this condition, but I need to display as a filter in Gridview with 2 options (Regular or Overdue).
[
'attribute' => 'registration_date',
'format' => 'raw',
'value' => function ($model) {
return $model->getRegistration($model->registration_date);
},
'filter' => [Regular or Overdue], ????
'contentOptions' => $contentOptions,
'headerOptions' => $headerOptions,
],
How do I make this check in model ClientSearch?
What I understand is that you want to add a filter on the column registration_date which is as a Date type column, which should have 2 options Regular and Overdue and should filter the records based on
Regular
The option should filter out all the records that have the registration_date difference smaller than or equal to 365 days.
Overdue
The option should filter out all the records that have the registration_date difference from the current date greater than 365 days.
Your gridview column will look like below
GridView Changes
If the above is correct then, first of all, add the following configuration in your gridview column configuration. we will provide an active-dropdown in the filter option and assign it a name registration_status.
Note: I have used select2 for the dropdown you can use the default if you do not want, and change the $searchModel to the exact name for the client search model that you are passing to the filterModel option in your gridview.
[
'filter' => \kartik\widgets\Select2::widget ( [
'data' => $searchModel->statusOptions(),
'model' => $searchModel ,
'attribute' => 'registration_status' ,
'options' => [
'placeholder' => 'Registration Status' ,
'class' => 'form-control' ,
'id' => 'registration_status' ,
] ,
'theme' => \kartik\widgets\Select2::THEME_BOOTSTRAP ,
'pluginOptions' => [
'allowClear' => true ,
] ,
] ) ,
'attribute' => 'created_at' ,
'label' => Yii::t ( 'app' , 'Registration Date' ) ,
] ,
Without Select2
[
'filter' => Html::activeDropDownList ( $searchModel , 'registration_status' , $searchModel->statusOptions () , [ 'prompt' => 'Select Registration status' ] ) ,
'attribute' => 'created_at' ,
'label' => Yii::t ( 'app' , 'Registration Date' ) ,
] ,
ClientSearch Changes
Add the constants on top of your ClientSearch model.
const STATUS_OVERDUE = 'overdue';
const STATUS_REGULAR = 'regular';
Add the function statusOptions() inside the ClientSearch model.
public function statusOptions() {
return [
self::STATUS_OVERDUE => 'Overdue' ,
self::STATUS_REGULAR => 'Regular'
];
}
Add a public property registration_status inside the search model.
public $registration_status
Add this field we created to the safe list inside the rules()
function.
function rules(){
return [
//other rules
[ [.... , 'registration_status' ] , 'safe' ] ,
];
}
Then the next thing is to accomplish the SQL condition which would filter out the records, you can use MySQL functions, DATEDIFF() and CURDATE(), like DATEDIFF(CURDATE(),registration_date)>365.
So add the following inside the search() function of the search model before the last line return $dataProvider.
if ( $this->registration_status === self::STATUS_OVERDUE ) {
$query->andFilterWhere ( [ '>' , 'DATEDIFF(NOW(),registration_date)' , 365 ] );
} else if ( $this->registration_status === self::STATUS_REGULAR ) {
$query->andFilterWhere ( [ '<=' , 'DATEDIFF(NOW(),registration_date)' , 365 ] );
}
Now you can filter the records based on the selected option and if you clear out the options in the drop-down it will show all of the records.

How to add currentdatetime when data inserted on table

I got these errors on my script error log iam using php version 5.3 and this is my code :
// add entry
$sql = "INSERT INTO plugin_reward_ppd_detail (reward_user_id, download_ip, file_id, download_country_group_id, download_date, reward_amount, status)
VALUES (:reward_user_id, :download_ip, :file_id, :download_country_group_id, :download_date, :reward_amount, 'pending')";
$vals = array('reward_user_id' => $file->userId,
'download_ip' => $usersIp,
'file_id' => $file->id,
'download_country_group_id' => $countryGroupId,
**'download_date' => sqlDateTime(),**
'reward_amount' => $rewardAmount);
$db->query($sql, $vals);
}
I got error on this exactly :
'download_date' => sqlDateTime()
if you want add current time on download_date column you can try this one
use DATE(''YYYY-MM-DD HH:MM:SS');
$vals = array('reward_user_id' => $file->userId,
'download_ip' => $usersIp,
'file_id' => $file->id,
'download_country_group_id' => $countryGroupId,
'download_date' =>DATE('YYYY-MM-DD HH:MM:SS'),
'reward_amount' => $rewardAmount);
$db->query($sql, $vals);
}
OR
other wise set download_date MySQL data-type: TIMESTAMP –
Defulat value select : CURRENT_TIMESTAMP
This an advanced version of DATETIME datatype. It has the same format as before. Unlike DATETIME, TIMESTAMP stores the current date and time on the creation of the table and on every update automatically. You do
not need to change its value every time

How do I update the last_updated column default set to CURRENT_TIMESTAMP?

I am using Gii generated CRUD . There is a column last_updated which default set to CURRENT_TIMESTAMP in phpmyadmin.
when I create the row row it takes current Date and time .
But when I Update the row it takes the previous date and time (date n time when row creted).
I want , when I update the row it should take current Date n Time?
how to achieve this?
Add this behaviour into your model.Or create a common model Which extends to all your models and add it there. so that you need not rewrite in all the models.
public function behaviors() {
return[
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => date('Y-m-d H:i:s'),
],
];
}
You can set it like:
$model->updated_at = time();
or
$model->touch('updated_at');
to make the field get the current timestamp!
In your ActiveRecord, extend function beforeSave() like this:
public function beforeSave($insert) {
//...
$this->last_updated = time();
return parent::beforeSave($insert);
}
Or, as Saberi pointed out, TimestampBehavior can be used to fill in current timestamp to your active record's attributes. Use this code to do it as part of the saving process (similar to calling beforeSave()):
use yii\db\Expression;
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'updatedAtAttribute' => 'last_updated',
'value' => new Expression('NOW()'),
],
];
}
Or, use $model->touch('last_updated'); to simply update the timestamp of an existing record
See here

2amigos/yii2-date-picker-widget year validation

I am using 2amigos/yii2-date-picker-widget.After selecting the date, user can edit the year which can be invalid like 10/30/0233. (m/d/Y)
I want to restrict user to enter invalid year, or to allow the date between specific year range only. without making the datefield readonly. How can I achieve this.
echo $form->field($model, 'date')->widget(DatePicker::className(), [
'addon' => '<i class="fa fa-calendar" aria-hidden="true"></i>',
'class' => 'form-control',
'clientOptions' => [
'autoclose' => true,
'format' => Yii::$app->params['dateFormat'],
],
]);
I have solved it using custom validator as follows
add rule for date as follows
['my_date', 'validYear'], // custom validator to check year range
Then define custom rule as follows
public function validYear($attribute, $params) {
$date = DateTime::createFromFormat("m/d/Y", $this->my_date);
$year = $date->format("Y");
$year_range = range(date('Y'), date('Y')+20, 1);
if(!empty($year) && !in_array($year, $year_range)){
$this->addError($attribute,"Please select valid date");
}
}
Though it works perfectly for me, If anyone has more appropriate solution, please suggest.