yii2 join model as dataProvider - yii2

I've joined 2 tables like following:
$model = SalesEntry::find()
->joinWith('salesItems')
->all();
then in view used DataProvider like following:
GridView::widget([
'dataProvider' => $model,
'columns' => [
'date', // sample field from first table to see if ok
],
]);
and I’ve got following error:
Call to a member function getCount() on a non-object
What am I doing wrong here?

That is because an ActiveQuery instance is not a DataProvider, which the widget expects. You need to wrap it in an ActiveDataProvider for it to work:
GridView::widget([
'dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model]),
' columns' => [
'date', // sample field from first table to see if ok
],
]);

DataProvider in GridView should be an instance of yii\data\DataProviderInterface
See docs.

Related

Yii2: How to use map() to show two fields in a Select2?

I am using a Select2 widget for Yii2. It shows a list with the ids of the users.
I need to show two fields defined in my model called Users: first_name_user and last_name_user. Like this:
Daniel Gates
John Connor
John Doe
Maria Key
But I don't know how use map() to show more than one field.
<?= $form
->field($model, 'id_user')
->widget(\common\widgets\Select2::classname(), [
'items' => \yii\helpers\ArrayHelper::map(\app\models\Users::find()->orderBy('name_user')->all(), 'id_user', 'name_user')
])
?>
Model
Add use app\models\Users; and use yii\helpers\ArrayHelper; at top.
public function userList()
{
$userList = [];
$users = Users::find()->orderBy('first_name_user')->all();
$userList = ArrayHelper::map($users, 'id_user', function ($user) {
return $user->first_name_user.' '.$user->last_name_user;
});
return $userList;
}
_form
<?= $form->field($model, 'id_user')->widget(Select2::className(), [
'data' => $model->userList(),
'options' => ['placeholder' => 'Select User'],
]) ?>
You need to use data option instead of items for Select2.
You need to modify your query to show the concatenated first_name_user and last_name_user as an alias and then return it along with the id column to be used in Select2 by ArrayHelper::map().
It's better to add a function to the model you are using to populate the form and return the results from there to the ArrayHelper::map().
Your query should look like
function userList(){
return \app\models\Users::find()
->select([new \yii\db\Expression('[[id_user]],CONCAT([[first_name_user]]," ",[[last_name_user]]) as full_user_name')])
->orderBy('name_user')
->all();
}
Your form field should look like below
<?=
$form->field($model, 'id_user')->widget(Select2::className(), [
'data' => \yii\helpers\ArrayHelper::map($model->userList(), 'id_user', 'full_user_name'),
'options' => [
'placeholder' => 'Select User',
'id' => 'id_user'
],
'theme' => Select2::THEME_DEFAULT,
'pluginOptions' => [
'allowClear' => true
],
]);
?>

Why my listview not found any record in yii2?

I have a dataprovider to search a world but my listview does not display any record? How can i send this query object to listview?
every thing in my webpage is worked very good but at the output my list view show "not found any result" this mean my list view code is no have problem . problem is in my dataprovider and this query beacuse i customize that
my controller:
$query = new Query();
$dataProvidersearch=new ActiveDataProvider([
'query'=>$query->from('tbl_post')->Where(['like', 'title', $search])-
>andWhere(['like', 'en_title', $search])->andWhere(['like', 'content', $search])->andWhere(['like', 'en_content', $search]),
]);
this is my list view in my view:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
]);
I'm not sure you have enough code here for someone to help. Even something simple like a listview could consist of a view, a controller, and two model files and your code could be failing at any of these points. You may have simply forgot to include the listview library at the top of your view, but we can't see that in your current example.
What I would recommend is using Gii to generate a listview. It is simple to do and once you have it created, you can study the code to see where you went wrong. You can see how to get started generating code with Gii here: http://www.yiiframework.com/doc-2.0/guide-start-gii.html
ANSWER FROM COMMENTS: Replace andWhere with orWhere, no results are found because no record can match 'title' and 'en_title' and 'content' and 'en_content'.
You are submitting $posts as 'dataProvider' while it should be dataProvidersearch
Instead of:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];
Should be:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$dataProvidersearch,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];

How to display names instead of id's in GridView Yii2?

I have a question here. I set the relations between item and sale tables and now my GridView column of Item name is displaying id's of it. But what I need is that it would display Item names instead of ID's. How should I do that?
Here is my GridView column:
[
'attribute' => 'item_id',
'value' =>
],
I was thinking that I should write a function with if statement, but I have a lot of names and it would be very long. Is there an easier way to solve it?
Assuming your relationship is called getItems(), and the field for the item's name is called name:
[
'attribute' => 'items.name'
],
In my case it is company table and products table.
comp_id is is the primary key in the company table and it has related with products table.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'prod_id',
'name',
'description:ntext',
[
'attribute' => 'comp_id',
'value' => 'comp.name' //getComp()
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
//getcomp function the product model page.
public function getComp()
{`enter code here`
return $this->hasOne(Company::className(), ['comp_id' => 'comp_id']);
}

CakePHP 3.0 cannot get 2 items from 1 table

In a football match i have 2 clubs "Home-Club" and "Away-Club" . I have created table "match" and "club" in MySQL. In "match" table has 2 foreign key "home_id" and "away_id". I'm using cakePHP to show list matches, match information contain names of "Home-Club" and "Away-Club". How to get name of "Home-Club" and "Away-Club" in template file ( .ctp file ).
For now I using this code in the template file:
$match->club->name
Code in Controller:
public function index()
{
$this->paginate = [
'contain' => ['Club']
];
$this->set('match', $this->paginate($this->Match));
$this->set('_serialize', ['match']);
}
It always show name of "Away-Club". I don't known how to get name of "Home-Club"
Please tell me how to do it
Thanks very much!
Problem is in definition of belongsTo associations. Try to redefine it this way:
$this->belongsTo('HomeClub', [
'className' => 'Club',
'foreignKey' => 'home_id',
'propertyName' => 'home_club'
]);
$this->belongsTo('AwayClub', [
'className' => 'Club',
'foreignKey' => 'away_id',
'propertyName' => 'away_club'
]);
Names of belongsTo associations have to be unique. Now contain them in the controller
// ...
$this->paginate = [
'contain' => ['HomeClub', 'AwayClub']
];
$this->set('matches', $this->paginate($this->Match));
And then in the template use
<?= $match->home_club->name ?>
<?= $match->away_club->name ?>

Multiple values in one field Yii2

How to display multpiple values in one field.. I Use Select2 Widget. If i use $courses_model[0] it display only one value
Controller
public function actionUpdateteachers($id)
{
$courses_model = ReferenceTeachersCourses::find()->where(['reference_teachers_id' => $id])->all();
.....
}
View
...
<?= $form->field($courses_model[0], 'reference_course_type_id')->widget(Select2::classname(), [
'data' =>ArrayHelper::map($courses,'id','name'),
'options' => ['multiple' => true],
'pluginOptions' => [
'allowClear' => true,
],
]);
...
?>
This widgets works fine - but your $courses_model[0]->reference_course_type_id must have an array of ids as a value if you want to see multiple values selected.