order not working with sortWhitelist - cakephp-3.0

Using CakePHP 3.5.3
Hi,
The below code works works as it should and displays the result set and orders it by the due_date asc.
public $paginate = [
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
public function index()
{
$session = $this->request->session();
// Declare client id 1
$cidOne = null;
$cidOne = $session->read('Cid.one');
// NOTE* DON'T USE ORDER HERE BECAUSE THE SORTS WILL NOT WORK
$query = $this->Activities->find('all')
->where(['cid_1' => $cidOne])
->andWhere(['status' => 1]);
// Send the query to the view.
$this->set('activities', $this->paginate($query));
}
But when I add sortWhitelist as below the initial page load is not sorted by the due_date and no sort arrow is displayed.
public $paginate = [
'sortWhitelist' => [
'due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
Thanks for any help. Z.

There must be consistency between the sortWhitelist array, the order array and the paginator link
so if your field is Activities.due_date your code becomes:
public $paginate = [
'sortWhitelist' => [
'Activities.due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
and in your view
<?= $this->Paginator->sort('Activities.due_date', __('Due Date')) ?>
If there is no ambiguity in the fields names you can omit the Model name and simply use due_date as column name

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

yii2-formwizard change model after select2 selection

I'm trying to implement a multiple models form using the form-wizard widget, with Profile as main model and few others as linked ones. When I select the entity type field for the main model, I would like to change the linked model for the next step, basing on the value of entity type field.
I have tried with this code:
Create Form Code
$modelUrlReletedModelsCreate = Profile::urlRelatedModelCreate();
$urlLinkedProfile = Url::to(['create']);
echo FormWizard::widget([
'formOptions'=>[
'id'=>'profile_form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'validationUrl' => Url::to(['profile-models-validation'])
],
'theme' => FormWizard::THEME_MATERIAL_V,
'steps' => [
//step 1
[
'model' => $model,
'title' => \Yii::t('app', 'Profile'),
'fieldConfig' => [
'only' => ['entity_type_id', 'profile_type_id'],
'entity_type_id' => [
'widget' => Select2::class,
'options' => [
'data' => EntityType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element')],
'pluginEvents' => ['select2:select'=>'function(e){;'
. 'var type = $("#pr-ty-sel").val();'
. 'var profile= "'.($model->profile_id ? : "no").'";'
. '$.ajax({ method: "GET",'
. 'url:"'.$urlLinkedProfile.'",'
. 'data:{ entity_text : e.params.data.text,'
. 'entity_id : e.params.data.id,'
. 'profile_type_id : type,'
. 'profile_id : profile},'
. 'success: function(data){'
. '$("#profile_form").html(data);'
. '}'
. '});}'],
],
],
'profile_type_id' =>[
'widget' => Select2::class,
'options' => [
'data' => \app\models\ProfileType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element'),'id'=>'pr-ty-sel'],
],
]
],
'description' => \Yii::t('app', 'Add Profile Type Data'),
'formInfoText' => \Yii::t('app', 'Fill all fields'),
],
//step 2 I want ot change here $linkedModel
[
'model' => [$model,$linkedModel],
'title' => \Yii::t('app', 'Personal Data'),
'description' => \Yii::t('app', 'Insert Personal Data'),
],
]
]);
Controller Action Create Code
public function actionCreate($profileId = NULL)
{
if($profileId AND $profileId !== 'no'){
$model = $this->findModel($profileId);
}else{
$model = new Profile();
}
$profileLinkedModel = new ProfilePrivate();
$renderMethod = 'render';
if (Yii::$app->request->isAjax) {
$entityText = \Yii::$app->request->get('entity_text');
$entity_id = \Yii::$app->request->get('entity_id');
$profileTypeId = \Yii::$app->request->get('profile_type_id');
$profileId = \Yii::$app->request->get('profile_id');
//Utility function to clean the entity text (remove number and special characters)
$entityTextCleaned = \app\components\Utility::cleanString($entityText);
if ($entityTextCleaned == 'private') {
$profileLinkedModel = new ProfilePrivate();
} elseif ($entityText == 'company') {
$profileLinkedModel = new ProfileCompany();
} else {
//#TODO
return FALSE;
}
$model->entity_type_id = $entity_id;
$model->profile_type_id = $profileTypeId;
$profileLinkedModel->profile_id = $model->profile_id;
Yii::$app->response->format = Response::FORMAT_JSON;
$renderMethod = 'renderAjax';
}
//extra table field used to enable custom rule in model
$model->createFullProfile = TRUE;
if ($model->load(Yii::$app->request->post())) {
return $this->redirect(['view', 'id' => $model->profile_id]);
}
return $this->$renderMethod('create', [
'model' => $model,
'profileLinkedModel' => $profileLinkedModel,
]);
}
When I select a field for entity type field, the server runs the ajax request on select event, but when it ends the other form field is not more selectable. So, in other words, after the ajax request I'm unable to select the profile type field. If I try to select the profile type field before the entity type field I can go to next step, but load always the default model.

Add search to custom query Yii2

I build a custom query to count and sum some of the field and then use gridview to display data.
Here is my query:
$query2 = (new \yii\db\Query())
->select([
'date',
'sum( IF(status = "Passed", 1, 0) ) AS passed',
'sum( IF(status = "Failed", 1, 0) ) AS failed',
'sum( IF(status = "On Hold", 1, 0) ) AS onhold',
'sum( IF(status <> "NULL", 1, 0) ) AS total'
])
->from('qa3d')->where(['week'=>$week])
->groupBy('date');
$dataProvider2 = new ActiveDataProvider([
'query' => $query2,
]);
And my gridview:
<?= GridView::widget([
'dataProvider' => $dataProvider2,
// 'filterModel' => $searchModel,
'headerRowOptions' => ['class' => 'kartik-sheet-style'],
'filterRowOptions' => ['class' => 'kartik-sheet-style'],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Status Report by Analyst - Week to Date',
],
'toolbar' => [
'{toggleData}',
],
'pjax' => true,
'columns' => [
'date',
'passed',
'failed',
[
'attribute' => 'onhold',
'label' => "On Hold",
],
'total',
],
]); ?>
I commented out the filterModel because it's not working. How can I build a search like Gii CRUD generator did for this custom query?
Please help me with this.
Thank you!
Yes you have. You must create search form that point to action of that page then u must decide how will you forward params. You can put it to search model or get it and pass to query you have. IT depends where is your query.
$searchModel = new SomeSearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
or like this and then access array elements.
$post = Yii::$app->request->queryParams;
In your case I supposed you will search for $week = $post['week'];

How to connect 3 tables in yii2 and display in Gridview then make sorting work correctly

I have used the gii tool to create crud application. I have 3 tables the tbl_targetcities, lib_cities, and lib_provinces. I was able to connect lib_cities to tbl_targetciteis but not the lib_provinces. And also the sorting of city / Municipality does not work. It seems that it sorts according ti the ID.
tbl_target_cities
lib_cities
lib_provinces
sample View
So far here is my relation in the model.
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
}
in my view file...
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'city_code',
'value'=>'cityName.city_name'
],
[
'attribute'=>'prov code',
'value'=>'cityName.city_name'
],
'kc_classification',
'cluster',
'grouping',
'priority',
'launch_year',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How to display the prov_name from lib_provinces???
EDIT to answer user2839376 question in the comment box
IN THE SEARCH MODEL CLASS
$query = TblSpBub::find();
$query->joinWith('brgyCode')->joinWith(['cityCode'])->joinWith(['cityCode.provCode']);
$covered= LibAreas::find()->where(['user_id'=>yii::$app->user->identity->id])->all();
$query->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
]);
$dataProvider->sort->attributes['city'] = [
'asc' => ['lib_Cities.city_name' => SORT_ASC],
'desc' => ['lib_Cities.city_name' => SORT_DESC],
];
$dataProvider->sort->attributes['province'] = [
'asc' => ['lib_provinces.prov_name' => SORT_ASC],
'desc' => ['lib_provinces.prov_name' => SORT_DESC],
];
In LibCities model add new relation:
public function getProvince()
{
return $this->hasOne(LibProvince::className(),['prov_code'=>'prov_code']);
}
And change getCityName relation. You should add with() for relation:
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
}
And in view correct your columnto this:
[
'attribute'=>'prov code',
'value'=>'cityName.province.prov_name'
],
You have to use the function relations() in models.
In tbl_target_cities model:
public function relations()
{
return array(
'city' => array(self::HAS_ONE, 'LibCities', 'city_code'),
);
}
In LibCities model :
public function relations()
{
return array(
'province' => array(self::HAS_ONE, 'LibProvinces', 'prov_code'),
'targets' => array(self::HAS_MANY, 'TargetCity', 'city_code',
);
}
This will allowed you to jump throw the LibCities model,
now you can simply acces to prov name like this :
$model->city->province->prov name;
Note : You need to have the 3 models defined.
EDIT
array(
'name' => 'province name',
'value' => $data->city->province->prov_name;
),
Done it, Heres how.
in addition to the above code (original post)
// in Model I added an additional function
public function getTaskowner()
{
return $this->hasOne(Tasks::className(), ['id' => 'task_id'])
->with(
['location','taskowner']
);
}
and in view i did this
....
'columns' => [
....
[
'class' => 'kartik\grid\DataColumn',
'value'=> 'tasks.location.taskowner.name',
.....
],
.....
and it worked
key points. used an array with the 'with->(..)' to include both then in the view added 'tasks.location.taskowner.name', to join them all