Transfer of date to the database - mysql

the beginner in Yii, connected DatePicker in GridView, but when I set date, in the Database nothing changes, there are old values. I do not understand how to make so that data came to the Database.
View:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'avito_login',
'avito_password',
'Region',
"City",
"legal_entity",
"manager_contact_phone",
"avito_user_id",
"teg",
[
'label' => 'Date begin subscription',
'value' => function ($model, $key, $value) {
return \kartik\date\DatePicker::widget([
'name' => 'date_subscription',
'model' => $model,
'value' => $model->date_subscription,
'type' => DatePicker::TYPE_INPUT,
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'autoclose' => true,
],
'pluginEvents'=>[
'changeDate'=>"function(e) {[jQuery.ajax({ url: '/admin/clients/date-subscription', type: 'post', contentType: 'application/x-www-form-urlencoded', dataType: 'html', data: { data: this.value }, success: function (data) { alert(data) });
}",
],
]);
},
'format' => 'raw',
],
?>
Controller
public function actionDateSubscription()
{
$datesubscription = Yii::$app->request->post('date_subscription');
}
Nothing occurs, fields with date stopped being active

You basically need to bind an ajax call to the datepicker which sends the date to the server controller/action which updates the new date into the database and sends the response back to the frontend, where if everything is OK it refreshes the gridview to reflect the new date.
Here is a similar answer which uses toggle-switch to update the database status column, you can have the general idea about the process.
The only thing that is different in your case is that you have to use the pluginEvents option to specify the changeDate event and bind the ajax call to that event like below
[
'label' => 'Date begin subscription',
'value' => function ($model, $key, $value) {
return \kartik\date\DatePicker::widget([
'name' => 'date_subscription',
'model' => $model,
'value' => $model->date_subscription,
'type' => DatePicker::TYPE_INPUT,
'pluginOptions' => [
'format' => 'yyyy-mm-dd',
'autoclose' => true,
],
'pluginEvents'=>[
'changeDate'=>"function(e) { //call your ajax fuction here }",
]
]);
},
'format' => 'raw',
],
Note: if you have aloowed date_subscription to be empty/null then make sure you call the ajax in the clearDate event too along with the changeDate.
For a complete list of events See the DOCS

Related

Show Select2 option as selected

<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'initValueText' => '',
'options' => ['placeholder' => 'Search for a Contributor ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => \yii\helpers\Url::to(['data2']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(contributor_id) { return contributor_id.text; }'),
'templateSelection' => new JsExpression('function (contributor_id) { return contributor_id.text; }'),
],
])->label('Contributors');
?>
How to show selected value, now it shows id as a selected.
please anyone help me.
UPDATE
Sorry for late reply didn't notice you need to set the initial text for the select2 as you are using the ajax option so you should use the option initValueText. According to the docs
initValueText : The text to displayed in Select2 widget for the
initial value. This is useful and applicable when you are using the
widget with ajax loaded data AND/OR you are not providing the data.
Check the ajax usage section for an example.
So you need to use it like below add this line inside your controller action and pass it to the view or add it inside the view before the select2
$contributorName = empty($model->contributors) ? '' : Contributors::findOne($model->contributors)->name;
<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'initValueText' => $contributorName, // set the initial display text
'options' => ['placeholder' => 'Search for a Contributor ...'],
'data'=>yii\helpers\ArrayHelper::map(Contributors::find()->all(),'id','name')
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => \yii\helpers\Url::to(['data2']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(contributor_id) { return contributor_id.text; }'),
'templateSelection' => new JsExpression('function (contributor_id) { return contributor_id.text; }'),
],
])->label('Contributors');
?>
You need to provide the data option to the set of values from which the selected value would be shown you want the text to be shown instead of the id, provide the data options in form of an array with key=>value pairs.
Looking at your code you want to show the contributor name against the id in database table so you should use ArrayHelper:map() along with querying your Contributors model, see below and update your field names for the Contributors model/table inside the ArrayHelper::map()
<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'options' => ['placeholder' => 'Search for a Contributor ...'],
'data'=>yii\helpers\ArrayHelper::map(Contributors::find()->all(),'id','name')
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => \yii\helpers\Url::to(['data2']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(contributor_id) { return contributor_id.text; }'),
'templateSelection' => new JsExpression('function (contributor_id) { return contributor_id.text; }'),
],
])->label('Contributors');
?>

How to add error messages for DateValidation?

In my model I use DateValidation
['date_birthday', 'date', 'format' => 'd.m.yy', 'min' => '01.01.1900', 'max' => date('d.m.yy'), 'tooSmall'=>'The date is from past. Try another','tooBig' => 'The date is from future. Try another', 'message' => 'Try to input the date'],
In view I call the widget
<?php echo $form->field($modelForm, 'date_birthday')->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
]
]) ?>
It checks for min and max dates, but show no error message. I think its because of different date formats in model and view. How to fix it?
If you submit form you will see error messages. According to this issue https://github.com/yiisoft/yii2/issues/7745 yii2 have not client-side validations of date
You can enable ajax validation. Add in create and update action before if statement
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
And add use yii\widgets\ActiveForm; on the top of controller class. In your _form.php file enable ajax for whole form
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
]); ?>
, or for the field only
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
...
Also, you can add plugin options for limit date with startDate and endDate (https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#startdate)
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
'startDate' => '01.01.1900',
'endDate' => date('d.m.Y'),
]
]) ?>

Remove Dollar sign from Column value(Indian Currency) Yii2 kartik gridview

Below is the snapshot of my index page in Yii2 with Kartik Gridview widget;
Below is the gridview code for the same.
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
[
'class' => 'kartik\grid\SerialColumn',
'contentOptions' => ['class' => 'kartik-sheet-style'],
'headerOptions' => ['class' => 'kartik-sheet-style'],
],
//'line_id',
'metal_name',
'item',
'unit_name',
'weight',
['attribute' => 'quantity',
'pageSummary' =>(true),
'value' => function ($model) {
if($model){
return $model->quantity;
}
}],
'rate_per_gram',
'making_charges',
[
'attribute' => 'total',
'format'=>'currency',
'pageSummary' =>(true),
'value' => function ($model) {
if($model){
return $model->total;
}
}
],
['class' => 'kartik\grid\ActionColumn'],
],
'responsive'=>true,
'hover'=>true,
'export'=>false,
'showPageSummary' => true,
]); ?>
I have tried lot of stuff to get plain number format with 2 decimals, but i could succeed in one.
How can I Format my Total column with Indian Currency, viz. Rs. 35670.00 or just 35670.00?
One way is to set currency directly:
[
'attribute' => 'total',
'format' => ['currency', 'INR'],
'pageSummary' => true,
],
PS. You don't need to set value key unless you want to replace it with something else in certain case.

Yii2, set default value for select2 widget

use kartik\widgets\Select2;
echo Select2::widget([
'model' => $myModel,
'name' => 'company[]',
'options' => [
'placeholder' => 'Select a company ...',
'multiple' => true,
],
'value' => 6, //doesn't work
'initValueText' => '6', //doesn't work
'pluginOptions' => [
'allowClear' => true,
'ajax' => [
'url' => Url::to(['/company/default/get-company-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {return {results:data.results}; }'),
],
'initSelection' => new JsExpression('function(element, callback) {
$(element).val(6); //doen't work
callback({"text" : "Vendor B", "id" : 6}); // it does only set text, not id
}'),
],
]);
... many many select2 form below too, that named 'company[]'
After form submit, if user come back to this page, I want to set what user selected as default.
How can I set default value for Select2 widget?
When you update the model, it will automatically have the last selected value.
$myModel = new \app\models\myModel;
$myModel->attributes = \Yii::$app->request->post('myModel');

Yii2 kartik typeahead - get number of suggestions

I'm using kartik's typeahead widget for Yii2 in a view:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus"
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
],
]);
How can i get the number of loaded suggestions after the remote dataset is retrieved to execute a javascript function like:
displaynumber(NUMBEROFSUGGESTIONS);
After checking through the source of kartiks widget i came up with the following solution:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus",
'id' => 'serial_product'
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => [
'url' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'ajax' => ['complete' => new JsExpression("function(response)
{
jQuery('#serial_product').removeClass('loading');
checkresult(response.responseText);
}")]
],
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
],
]);
where response.responseText is containing the response from server (json).
function checkresult(response) {
var arr = $.parseJSON(response);
console.log(arr.length);
}
With this function i can get then count of suggestions delivered from server.