Yii2 pagination - php

is it possible to use post id in pagination instead of page number
example instead of :
&page=2
it will be
&id=63
Pagination code is :
function actionIndex()
{
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count()]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
view :
foreach ($models as $model) {
// display $model here
}
// display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);

Related

Cakephp Error: The Categories association is not defined on Carts

You can see I have used $this->loadModel('Categories'); in my Cart controller function.
public function home($cat_id=null, $subcat_id=null)
{
// Set leftmenu
$this->loadModel('Categories');
$query = $this->Categories->find('all', [
'contain' => ['SubCategories']
]);
$this->set('categories', $query);
// Set conditions
$conditions = array();
if (!empty($cat_id)) {
$conditions['Products.category_id'] = $cat_id;
}
if (!empty($subcat_id)) {
$conditions['Products.sub_category_id'] = $subcat_id;
}
$this->paginate = [
'conditions' => $conditions,
'contain' => ['Categories', 'SubCategories', 'Discounts' => function ($q) {
return $q
->where(['Discounts.start_at <' => date('Y-m-d H:i:s'), 'Discounts.end_at >' => date('Y-m-d H:i:s')])
->limit(1);
}]
];
$this->set('products', $this->paginate($this->Products));
$this->set('_serialize', ['products']);
}
When I add the items in the cart and click the cart button to view the items then I get this error.

Create new record using 2amigos SelectizeDropDownList in Yii2

I am trying to implement the 2amigos SelectizeDropDownList widget in a form to add new values to a table directly within the dropdown.
I am using the model Book and the Model Author so basically want to be able to add a new author in the book form.
This is the book controller at the update function:
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}
This is the form:
<?=
$form->field($model, 'author_id')->widget(SelectizeDropDownList::className(), [
// calls an action that returns a JSON object with matched
// tags
'loadUrl' => ['author/list'],
'value' => $authors,
'items' => \yii\helpers\ArrayHelper::map(\common\models\author::find()->orderBy('name')->asArray()->all(), 'id', 'name'),
'options' => [
'class' => 'form-control',
'id' => 'id'
],
'clientOptions' => [
'valueField' => 'id',
'labelField' => 'name',
'searchField' => ['name'],
'autosearch' => ['on'],
'create' => true,
'maxItems' => 1,
],
])
?>
And this is the function author controller:
public function actionList($query) {
$models = Author::findAllByName($query);
$items = [];
foreach ($models as $model) {
$items[] = ['id' => $model->id, 'name' => $model->name];
}
Yii::$app->response->format = \Yii::$app->response->format = 'json';
return $items;
}
The form works fine to load, filter, search and add new items.
But it is not inserting the new typed attribute in the author table.
Do I need to add something in the book controller?
How can I check if it is a new value or a change of an existing author?
Thanks a lot
I made it work with the following code, not sure the most elegant because i am checking the if the author_id is a number or a string.
In my case the author won't be a number anyway.
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$x = Yii::$app->request->post('Book');
$new_author = $x['author_id'];
if (!is_numeric($new_author)) {
$author = new Author();
$author->name = $new_author;
$author->save();
$model->author_id = $author->id;
}
if ($model->save()) {
return $this->redirect(['index']);
}
} else {
return $this->render('update', [
'model' => $model,
'categories' => BookCategory::find()->active()->all(),
'publishers' => Publisher::find()->all(),
'copirights' => Copiright::find()->all(),
'authors' => Author::find()->all(),
]);
}
}

Site and its behaviors do not have a method or closure named "orderBy"

while i am fetching this records then getting this error how to solve it ?
public function actionIndex()
{
$query = Site::model();
$pagination = new CPagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);
$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('view', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
you should distinguish between yii1 and yii2.from your codes,you used yii1 and yii2 together.

Yii2 - Query with Pagination

I have a Category model that has a relation with the Products model.
I am doing the following query:
$model = Category::find()->where(['slug' => $slug])->with('products')->one();
And in the view I can retrieve all the products that belong to that Category with:
foreach ($model->products as $value)...
Now I want to do the pagination in the products but I can not find how to do it in the "with" part of the query.
Try this
In Controller:
...
$pages = new Pagination(['totalCount' => $model->products->count()]);
return $this->render('index', [
'model' => $model,
'pages' => $pages,
]);
In View:
foreach ($model->products as $value) {
// display $model here
}
// display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);

Yii Framework Undefined Variable model

I tried my best to solve this , but I can't seem to figure out where the problem is. Here is my code:
views/supermarkets/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<?php
$array = (array) $supermarkets;
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'supermarkets-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'name',
'location',
'telephone',
'fax',
'website'
),
));
function build_table($array){
// start table
$html = '<table class="altrowstable" id="alternatecolor">';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
Supermarkets.php:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Supermarkets extends ActiveRecord
{
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('name',$this->Name,true);
$criteria->compare('location',$this->Location,true);
$criteria->compare('telephone',$this->Telephone,true);
$criteria->compare('fax',$this->Fax,true);
$criteria->compare('website',$this->Website,true);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'name ASC',
),
'pagination'=>array(
'pageSize'=>20
),
));
}
SupermarketsController.php:
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Supermarkets;
class SupermarketsController extends Controller
{
public function actionIndex()
{
$query = supermarkets::find();
$pagination = new Pagination([
'defaultPageSize' => 20,
'totalCount' => $query->count(),
]);
$supermarkets = $query->orderBy('Name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'supermarkets' => $supermarkets,
'pagination' => $pagination,
]);
$model =new Supermarkets('search');
if(isset($_GET['Supermarkets']))
$model->attributes =$_GET['Supermarkets'];
return $this->render('index', array('model'=>$model));
}
public function actionName(){
$model = new Supermarkets();
$this->render('index', array('model'=>$model));
}
}
This is the error I'm getting:
Undefined variable: model in index.php at ('dataProvider' => $model->search() )
I am trying to add Search and filter criteria based on the following question How to add Search and Filter Criteria in Yii
Could you please help me?
in your SupermarketsController.php: you have a mistake:
you have rendered this
return $this->render('index', [
'supermarkets' => $supermarkets,
'pagination' => $pagination,
]);
which doesn't have any model named variable,
and later you have
$model =new Supermarkets('search');
if(isset($_GET['Supermarkets']))
$model->attributes =$_GET['Supermarkets'];
return $this->render('index', array('model'=>$model));
which will be useless, because you are returning before that,
so you can grab that variable and render it along with the first render
This will work. You have rendered 2 time index view. mergethem into one
public function actionIndex()
{
$query = supermarkets::find();
$pagination = new Pagination([
'defaultPageSize' => 20,
'totalCount' => $query->count(),
]);
$supermarkets = $query->orderBy('Name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
$model =new Supermarkets('search');
if(isset($_GET['Supermarkets']))
$model->attributes =$_GET['Supermarkets'];
return $this->render('index', array(
'model' => $model,
'supermarkets' => $supermarkets,
'pagination' => $pagination,
));
}
You have rendered two time in your controller,
$model =new Supermarkets('search');
if(isset($_GET['Supermarkets']))
$model->attributes =$_GET['Supermarkets'];
return $this->render('index', array(
'model' => $model,
'supermarkets' => $supermarkets,
'pagination' => $pagination,
));
Please above code by replacing below code
return $this->render('index', [
'supermarkets' => $supermarkets,
'pagination' => $pagination,
]);
$model =new Supermarkets('search');
if(isset($_GET['Supermarkets']))
$model->attributes =$_GET['Supermarkets'];
return $this->render('index', array('model'=>$model));

Categories