Yii2 DateControl: How to set default value (date) - yii2

I have in views/example/_form.php the following date field:
use yii\widgets\ActiveForm;
use kartik\datecontrol\DateControl;
...
$form = ActiveForm::begin();
...
echo $form->field($model, 'date')->widget(DateControl::className(), [
'type' => DateControl::FORMAT_DATE,
// 'value' => date('Y-m-d'),
// 'value' => date('d.m.Y'),
// 'value' => time(),
// 'value' => '02.12.2015',
// 'value' => '2015-12-02',
// 'value' => '2015-12-02 00:00:00 0000',
// 'value' => date('Y-M-d'),
// 'value' => date('d.M.Y'),
// 'value' => date('dd.MM.yyyy'),
]);
...
ActiveForm::end();
None of my attempts to set the default date was successfull (see the commented lines above). I have always received no error message and no default value. The resulting HTML input field looks always the same (the 'value' is empty):
<input type="text" id="yiiversion-date-disp" class="form-control" name="date-yiiversion-date" value="" data-krajee-datecontrol="datecontrol_1e107159" data-datepicker-source="yiiversion- date-disp-kvdate" data-datepicker-type="2" data-krajee-kvdatepicker="kvDatepicker_0aa71c62">
Configuration in config/main.php looks like this:
'modules' => [
'datecontrol' => [
'class' => 'kartik\datecontrol\Module',
'autoWidget' => true,
'autoWidgetSettings' => [
'date' => [
'pluginOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'todayBtn' => true,
],
],
],
],
],
The dates are displayed as 01.01.2015 ('dd.MM.yyyy') and saved as 2015-01-01 ('Y-M-d') - MySQL datatype DATE.
More information:
https://github.com/kartik-v/yii2-datecontrol
http://demos.krajee.com/datecontrol

As suggested by InsaneSkull the solution is quite simple. I had to add to the correspondig controller only: $model->date = date('Y-m-d');
The resulting action could look e.g. like this:
public function actionCreate()
{
$model = new YiiTask();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->date = date('Y-m-d');
return $this->render('create', [
'model' => $model,
]);
}
}

Related

loop logic for storing multi record in laravel?

public function store(Request $request)
{
$productId = $request->id;
$request->validate([
'name' => 'required',
'quantity' => 'required|integer|gt:0',
'fmcode',
'fmcodes',
'area',
'naoffm','glno'
]);
for ($i = 0; $i<=$request->GLNO; $i++){
$product = Product::updateOrCreate(
[
'id' => $productId
],
[
'id'=>$productId,
'name' => $request->name,
'quantity' => $request->quantity,
'fmcode' => $request->FMCODE,
'fmcodes' => $request->FMCODES,
'area' => $request->AREA,
'naoffm' => $request->NAOFFM,
'id'=>$request->GLNO[$i],
'glno'=>$request->GLNO[$i],
]
);
}
return Response()->json($product);
}
selected dropdown of glno values have to store multiple records with glno dropdownlist
and required loop logic to store request data so required solutions for this
You can do multiple insertions using Query Builder. Sample;
DB:table('table_name')->insert(
[
'id' => 1,
'name' => 'mkeremcansev'
],
[
'id' => 2,
'name' => 'John Doe'
]
);

Listview pagination and GET parameters on the next page

I have this UrlManager rule:
'<pageSlug>-pa<pageId:\d+>' => 'page/page',
Then I have page with url like this domain.com/blog-pa54
In this example I have
pageSlug = blog and pageId = 54
In my view I have ListView with my blog posts.
I set my dataprovider like this:
$dataProvider = new ActiveDataProvider([
'query' => BlogPost::find()
->where([
'active' => 1
]),
'pagination' => [
'defaultPageSize' => 3,
//'params' => [], when I set this, it only shows get param "page"
'pageParam' => 'page',
'route' => $pageURL, // this variable is equal to "blog-pa54"
],
]);
My route is current url slug - blog-pa54
When I go to next page I recieve this url: blog-pa54?pageSlug=blog&pageId=54&page=2
How can I remove $_GET params pageSlug and pageId from url?
I try to set pagination > params = [] and it remove this get param, but when I go to other page it doesn't change items in my ListView
Here is also my ListView and LinkPager
<div class="blog-post-wrapper">
<?= ListView::widget([
'dataProvider' => $blogPostsDataprovider,
'itemOptions' => ['tag' => null],
'options' => [
'tag' => false,
],
'layout' => "{summary}<div class='row'>{items}</div>",
'itemView' => function ($model, $key, $index, $widget) use ($page) {
return $this->render('//blog-post/_blogPostList', [
'page' => $page,
'model' => $model
]);
},
]); ?>
</div>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $blogPostsDataprovider->pagination,
'linkContainerOptions' => [
'class' => 'page-item',
],
'linkOptions' => [
'class' => 'page-link',
],
]); ?>
Okay, I figured it out.
params attribute must not be empty.
You can set it like this:
'params' => [
'page' => isset($_GET['page']) ? $_GET['page'] : 1,
]
Or if you have another get params like get filters:
$getParams = [];
if(isset($_GET)){
foreach($_GET as $getKey => $getValue){
if(in_array($getKey, ['pageSlug', 'pageId'])){ //here I skip my params from UrlManager rule
continue;
}
$getParams[$getKey] = $getValue;
}
}
.....
'params' => $getParams

Is there a way to dynamically change maximumSelectionLength on kartik/select2 in yii2?

I am trying to update through javascript the maximumSelectionLength parameter of a select2 field (listeProduits) based on the value of a second select2 (nom_id) when it is changed.
I'm first storing the maxChildren values in a js table before loading the form so that I can access it on the client side when a new nom_id is selected.
The below approach doesn't work though as it messes up the listeProduits select2.
<script>
var nomMaxChildren = <?= json_encode(ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'max_children')); ?>;
alert(nomMaxChildren[1]);
</script>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'nom_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'nom'),
'options' => ['placeholder' => Yii::t('app','Select a name...')],
'pluginEvents' => [
"select2:select" => "function() {
$('select[name =\"listeProduits[]\"]').select2({
maximumSelectionLength: nomMaxChildren[\$(this).val()]
});
}",
]
]);?>
<label class="control-label"><?= Yii::t('app', 'Produits')?></label>';
<?= Select2::widget([
'attribute' => 'listeProduits',
'name' => 'listeProduits',
'data' => ArrayHelper::map(Produit::find()->asArray()->where(['statut_id' => 2])->andWhere(['boite_id' => null])->orWhere(['boite_id' => $model->id])->all(), 'id', 'numero_de_serie'),
'value' => (is_null($model->id)) ? null : ArrayHelper::map(Produit::find()->asArray()->where(['boite_id' => $model->id])->all(), 'id', 'id'),
'options' => ['placeholder' => Yii::t('app','Select products')],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
'maximumSelectionLength' => (isset($model->nom)) ? $model->nom->max_children : null,
],
'showToggleAll' => false,
]);?>
Also if you have any idea on how to validate the fact that the maximumSelectionLength is ok on client side, it would be great :D
set maximumSelectionLength property dynamically :
$('#demo-select').select2({ maximumSelectionLength: 1 });

Yii2- How to restrict a user from viewing others data in index page

I am working on yii2 in my project, I have users and their roles. Each role is given access to a Module and a Sub Menu. There is a sub-menu named SIM List in which all the SIM records can be viewed. There is a field named issued_to which tells us that which SIM has been issued to which user.
Unless a SIM is issued to any user, the issued_to field will remain empty. Once issued the name of the user will appear on the SIM List.
Now I want to manage it in such a way that only a specific user can see the list. For example 5 Sims have been issued to a user named U. Now the user U should only see that SIM records which are issued to him, otherwise the list should be empty.
In my Index controller I am getting issued_to field name which is empty by default.
public function actionIndex()
{
$searchModel = new SimsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
By doing like below I can get issued_to user id
$model = $dataProvider->getModels()[0];
$user_id = $model['issued_to'];
var_dump($user_id);
exit();
Now in this controller, I want to add a check of user_id which gives me only the records which are of that specific user.
Index View
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'imsi',
'sim_number',
'operator_name',
'data_details',
'sms_details',
'monthly_bill',
//'created_by',
[
'label' => 'Created By',
'value' => function ($data) {
if (is_object($data))
return $data->created->name;
return ' - ';
},
//'filter' => Html::activeDropDownList($searchModel, 'created_by', \app\models\User::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']),
],
'created_at',
// 'updated_at',
'status',
// 'updated_by',
//'sim_stauts',
[
'label'=>'SIM Status',
'value'=>function($a){
return $a->getStatusvalue();
}
],
//'issued_to',
[
'label' => 'Issued To',
'value' => function ($d) {
if(is_object($d->user))
//return $d->user->name;
return $d->issued_to == '' ? '' : $d->user->username;
return ' - ';
// return $d->user->name;
},
'filter' => Html::activeDropDownList($searchModel, 'issued_to', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),
],
//'returned_by',
[
'label' => 'Returned By',
'value' => function ($d) {
if(is_object($d->user2))
//return $d->user->name;
return $d->returned_by == '' ? '' : $d->user->username;
return ' - ';
// return $d->user->name;
},
'filter' => Html::activeDropDownList($searchModel, 'returned_by', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),
],
'historic',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Update 1
My search model is below
public function search($params)
{
$query = Sims::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'created_by' => $this->created_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'updated_by' => $this->updated_by,
'sim_stauts' => $this->sim_stauts,
'issued_to' => $this->issued_to,
'returned_by' => $this->returned_by,
'historic' => $this->historic,
]);
$query->andFilterWhere(['like', 'imsi', $this->imsi])
->andFilterWhere(['like', 'sim_number', $this->sim_number])
->andFilterWhere(['like', 'operator_name', $this->operator_name])
->andFilterWhere(['like', 'data_details', $this->data_details])
->andFilterWhere(['like', 'sms_details', $this->sms_details])
->andFilterWhere(['like', 'monthly_bill', $this->monthly_bill])
->andFilterWhere(['like', 'status', $this->status]);
return $dataProvider;
}
How can I achieve it? Any help would be highly appreciated.
As per your description, you have the user_id saved inside the issued_to field and you need to only fetch the results that have the current logged in user_id saved in the field issued_to.
I assume that your search in the grid view is visible to only logged-in users.
You should set the issued_to param manually by first getting the queryParams array from the request object Yii::$app->request->queryParams; which has the array in the same format as the POST has i.e ['ModelName']['field_name'] so you need to infact set the issued_to as
$arrayParams['SimSearch']['issued_to']=Yii:$app->user->id;
Your actionIndex should look like below
public function actionIndex()
{
$searchModel = new SimsSearch();
$queryParams=Yii::$app->request->queryParams;
//check if user or one of the managers
$isAdmin=in_array(Yii::$app->user->identity->user_role,[1,6]);
//set params if normal user
if(!$isAdmin){
$queryParams['SimsSearch']['issued_to']=Yii::$app->user->id;
}
$dataProvider = $searchModel->search($queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Hope this helps you out.

Yii2 captcha always incorrect

Whan I add 'on' => 'create' in my rule my captcha always incorrect
Off that work good why?
I try to let it to other controller support/captcha but still incorrect
MyView
<?= Captcha::widget([
'id' => 'captcha',
'model' => $model,
'attribute' => 'verifyCode',
'options' => ['class' => 'form-control',
'data-v-rule' => '',
'captchaAction' => 'support/captcha',
'data-v-msg' => $i18n->t('please.input.verify.code'),
'placeholder' => $i18n->t('please.input.verify.code', '', false)]
]); ?>
Myrule
...
[['verifyCode'], 'captcha', 'message' => $i18n->t('error.verifyCode'),'captchaAction' => 'support/captcha' , 'on' => 'create'],
...
I get seesion
$_SESSION = [
'__flash' => [],
'__captcha/site/captcha' => 'nnbioo',
'__captcha/site/captchacount' => 1,
'__captcha/support/captcha' => 'cacijq',
'__captcha/support/captchacount' => 1,
];
Mycontroller
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => CaptchaAction::className(),
],
];
}
$customerServiceModel->load($post) is not working, because attribute verifyCode is not safe in this case. Your rule is specified with 'on' => 'create' - so it means, it's save on scenario create. You didn't assigned this scenario to the model so there's 2 solutions:
Remove 'on' => 'create' from rule
Assign create scenario to model by $customerServiceModel->scenario = 'create'; before using load().