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));
Related
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,
]);
How do I get random values from another table? In my employee php I have 3 records, so there is 3 id values. In my ticket.php once I create a ticket it will automatically get the id value from the employee table but it is not randomise how do I do it?
Mine is currently getting the same value from employee whenever I create a ticket.
In the ticketcontroller.php
public function actionCreate()
{
$model = new Ticket();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->time_start = date('y-m-d h:i:s');
$model->status = ('On Going');
$model->employee_respond_id = array_rand('id');
return $this->render('create', [
'model' => $model,
]);
}
}
In the _form.php
<?= $form->field($model, 'employee_respond_id')->dropDownlist(
ArrayHelper::map(Employee::find()->all(), 'id', 'id'),
[
'readOnly' => true,
'style' => 'width:200px'
]
); ?>
Try this way:
public function actionCreate()
{
$model = new Ticket();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$employeeIDs = ArrayHelper::map(Employee::find()->all(), 'id', 'id'),
$model->time_start = date('y-m-d h:i:s');
$model->status = ('On Going');
$model->employee_respond_id = array_rand($employeeIDs);
return $this->render('create', [
'model' => $model,
'employeeIDs' => $employeeIDs
]);
}
}
_form.php
<?= $form->field($model, 'employee_respond_id')->dropDownlist(
$employeeIDs,
[
'readOnly' => true,
'style' => 'width:200px'
]
); ?>
Better use employee name as label and id as value in dropdown, still it will work for random function.
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(),
]);
}
}
I wanna show usernames in timeline index. It show error
Call to a member function getStatusesLabel() on integer
if use this code :
'status' =>$model->data['status']->getStatusesLabel(),
and
'author' => $model->data['author']->getAuthor(),
and another error
Trying to get property of non-object
if use this code :
'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
My Model
namespace common\models;
.....
class Article extends ActiveRecord
{
.....
public function getAuthor()
{
return $this->hasOne(User::className(), ['id' => 'author_id']);
}
public function getUpdater()
{
return $this->hasOne(User::className(), ['id' => 'updater_id']);
}
public function getCategory()
{
return $this->hasOne(ArticleCategory::className(), ['id' => 'category_id']);
}
public function getArticleAttachments()
{
return $this->hasMany(ArticleAttachment::className(), ['article_id' => 'id']);
}
public static function statuses()
{
return [
self::STATUS_PUBLISHED => Yii::t('common', 'Published'),
self::STATUS_DRAFT => Yii::t('common', 'Draft'),
];
}
public function afterCreate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_item',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'created_at' => $this->created_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
public function afterUpdate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_itemU',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'updated_at' => $this->updated_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
}
my controller article:
public function actionCreate()
{
$model = new Article();
$transaction = Yii::$app->db->beginTransaction();
try{
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->afterCreate();
$transaction->commit();
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
'categories' => ArticleCategory::find()->active()->all(),
]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
controller timeline
public function actionIndex()
{
$searchModel = new TimelineEventSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort = [
'defaultOrder'=>['created_at'=>SORT_DESC]
];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
command timeline :
class AddToTimelineCommand extends Object implements SelfHandlingCommand
{
public $category;
public $event;
public $data;
public function handle($command)
{
$model = new TimelineEvent();
$model->application = Yii::$app->id;
$model->category = $command->category;
$model->event = $command->event;
$model->data = json_encode($command->data, JSON_UNESCAPED_UNICODE);
return $model->save(false);
}
}
index timeline:
<ul class="timeline">
<?php foreach($dataProvider->getModels() as $model): ?>
<?php if(!isset($date) || $date != Yii::$app->formatter->asDate($model->created_at)): ?>
<!-- timeline time label -->
<li class="time-label">
<span class="bg-blue">
<?php echo Yii::$app->formatter->asDate($model->created_at) ?>
</span>
</li>
<?php $date = Yii::$app->formatter->asDate($model->created_at) ?>
<?php endif; ?>
<li>
<?php
try {
$viewFile = sprintf('%s/%s', $model->category, $model->event);
echo $this->render($viewFile, ['model' => $model]);
} catch (\yii\base\InvalidParamException $e) {
echo $this->render('_item', ['model' => $model]);
}
?>
</li>
view _item for index:
<div class="timeline-body">
<?php echo Yii::t('backend', 'Updated post <b>({title})</b>, published date : {published_at} ', [
'title' => Html::a($model->data['title'],
Url::to(Yii::$app->urlManager->hostInfo.'/article'.'/') .$model->data['slug'],
['target' => '_blank']),
//'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
//'author' => $model->data['author']->getAuthor(),
'author' => $model->data['author'],
'category' => $model->data['category'],
//'status' =>$model->data['status']->getStatusesLabel(),
'published_at' => Yii::$app->formatter->asDatetime($model->data['published_at']),
'updated_at' => Yii::$app->formatter->asDatetime($model->data['updated_at'])
])//.Html::a($model->data['title'], ["/article/$model->data['title']"]) ?>
</div>
what is wrong with the above code?
i was use in GridView / detailview, there is no errors
how do I fix it?
In a simple view (not based on gridview or detailView widget) that you render using eg:
return $this->render('your_view', [
'model' => $model,
]);
you can use directly the model and the attribute (or the depending function) eg:
'author' => $model->author
If you instead use a
return $this->render('your_view', [
'dataProvider' => $dataProvider,
]);
you can refer to the model instance
'author' => $dataProvider->models[i]['author']
where i is the index for the specific instance
I'm new to Yii and I'm developing a database application that reads tables from MySQL. I needed the user to be able to export data as CSV or PDF, so I downloaded Kartik Yii2 Export Extension. I don't know how am I supposed to configure my settings to run this extension, I read the guide but I didn't understand how to fix this error:
Invalid Configuration – yii\base\InvalidConfigException
The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.
Here is my code:
Models/industrial.php:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Industrial extends ActiveRecord
{
}
controller/IndustrialController.php:
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\industrial;
use yii\data\ActiveDataProvider;
class IndustrialController extends Controller
{
public function actionIndex()
{
$dataProvider=new ActiveDataProvider('Industrial', array(
'pagination'=>array(
'pageSize'=>20,
),
));
$query = industrial::find();
$pagination = new Pagination([
'defaultPageSize' => 20,
'totalCount' => $query->count(),
]);
$industrials = $query->orderBy('Company_Name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'industrials' => $industrials,
'pagination' => $pagination,
'dataProvider'=>$dataProvider,
]);
}
}
views/industrial/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Industrial Companies</h1>
<ul>
<?php
use kartik\export\ExportMenu;
use kartik\grid\GridView;
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
[
'attribute'=>'Name',
'label'=>'Name',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return Html::a($model->Name, '#', []);
},
'format'=>'raw'
],
'Name',
'Location',
'Telephone',
];
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-default'
]
]) . "<hr>\n".
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'export' => [
'fontAwesome' => true,
]
]);
$array = (array) $industrials;
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]) ?>
Please help me.
in the configuration of your activeDataProvider
I see no value assigned to the key 'query' such as follows
$ dataProvider = new ActiveDataProvider ([
'query' => Post :: find (),
'pagination' => [
'pageSize' => 20,
],
]);
test with the following
actionIndex public function ()
{
$ dataProvider = new ActiveDataProvider ('Industrial', array (
'query' => Industrial :: find (),
'pagination' => array (
'pageSize' => 20,
),
));
It seems that there is an error code
you should write:
$ query = Industrial :: find ();
and not
$ query = industrial :: find ();
Industrial class begins with uppercase
Add this under components in config/web.php in Yii2 folder, it will work
'modules' => [
'gridview' => [
'class' => '\kartik\grid\Module',
],
],