CakePHP 3.0 cannot get 2 items from 1 table - cakephp-3.0

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 ?>

Related

Setting a default value on join table from another table when model is edited or created

Hoping someone may be able to point me in the right direction.
I have a app that consists of (among other things) Recommendations and Assessments. They are joined with a join table that includes extra fields that I would like to update but am struggling to figure out how.
As you can see above, when I create a Reccommendation, I set the following fields:
default_user_impact
default_business_impact
default_deployment_complexity
default_criticality
Now when I create a new Assessment or edit one that has not got any Recommendations linked the Assessment saves fine because nothing is needing to be written to the join table.
When I try to edit an Assessment to include one or more Recommendations, the app tries to write the link to the join table and fails because the user_impact, business_impact, deployment_complexity and criticality fields aren't specified - perfectly normal because I have set the fields to required in MySQL right? The error I get in CakePHP is
SQLSTATE[HY000]: General error: 1364 Field 'user_impact' doesn't have a default value
What I want to be able to do is at the time of editing or creating an Assessment is to use the values in the Recommendations table to populate the corresponding join table entries. Any ideas how to go about this?
So as an example:
user_impact = default_user_impact
business_impact = default_business_impact
deployment_complexity = default_deployment_complexity
criticality = default_criticality
The reason I want to do this is so that I can have the Recommendations set with values for those fields, and then if a user wants to run an assessment and they want to adjust the values just for their own assessment then it won't impact others etc.
Here is my AssessmentsTable association.
$this->belongsToMany('Recommendations', [
'foreignKey' => 'assessment_id',
'targetForeignKey' => 'recommendation_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my RecommendationsTable association.
$this->belongsToMany('Assessments', [
'foreignKey' => 'recommendation_id',
'targetForeignKey' => 'assessment_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my AssessmentsRecommendations association:
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
This is what my AssessmentsController edit function looks like:
public function edit($id = null)
{
$assessment = $this->Assessments->get($id, [
'contain' => ['Recommendations'],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$assessment = $this->Assessments->patchEntity($assessment, $this->request->getData(), ['associated'=>['Recommendations._joinData']]);
if ($this->Assessments->save($assessment, ['associated' => ['Recommendations._joinData']])) {
$this->Flash->success(__('The assessment has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The assessment could not be saved. Please, try again.'));
}
$clients = $this->Assessments->Clients->find('list', ['limit' => 200]);
$recommendations = $this->Assessments->Recommendations->find('list', ['limit' => 200]);
$this->set(compact('assessment', 'clients', 'recommendations'));
}
Now when I've added the beforeSave function to the AssessmentsRecommendationsTable I see the following error:
Argument 2 passed to App\Model\Table\AssessmentsRecommendationsTable::beforeSave() must be an instance of App\Model\Table\EntityInterface, instance of Cake\ORM\Entity given, called in /var/www/html/csa-portal/vendor/cakephp/cakephp/src/Event/EventManager.php on line 310
Any help would be much appreciated.
First, the associations you are using are wrong. It should be like this
For AssessmentsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'assessment_id'
]);
For RecommendationsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'recommendation_id'
]);
For AssessmentsRecommendationsTable
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
Now for the default values, you have to user beforeSave in you AssessmentsRecommendationsTable.php file.You can modify your data as per your need here before the save.
public function beforeSave(Event $event, EntityInterface $entity, \ArrayObject $options)
{
if ($entity->isNew()) { // Returns true when you add new record
$recommendation = TableRegistry::getTableLocator()->get('Recommendations')->get($entity->recommendation_id);
$entity->user_impact = $recommendation->default_user_impact;
$entity->business_impact = $recommendation->default_business_impact;
$entity->deployment_complexity = $recommendation->default_deployment_complexity;
$entity->criticality = $recommendation->default_criticality;
}
}
I have never used belongsToMany, if the associations works for you then ignore the association part.
Have you considered writing a Rule to handle this?
https://book.cakephp.org/3/en/orm/validation.html#applying-application-rules

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
],
]);
?>

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']);
}

Multiple categories in Url

I want to create links something like that:
http://example.com/cat1/itemname-1
http://example.com/cat1/cat2/itemname-2
http://example.com/cat1/cat2/cat3/itemname-3
http://example.com/cat1/cat2/cat3/[..]/cat9/itemname-9
How rule looks like in yii2 UrlManager and how to create links for this?
Url::to([
'param1' => 'cat1',
'param2' => 'cat2',
'param3' => 'cat3',
'slug' => 'itemname',
'id' => 3
]);
Above code is really bad for multiple category params.
I add that important is only last param it means ID.
Controller looks like that:
public function actionProduct($id)
{
echo $id;
}
The below url rule would to this trick but you have to build the "slug" with the categories within your controller:
'rules' => [
['route' => 'module/controller/product', 'pattern' => '<slug:(.*)+>/<id:\d+>', 'encodeParams' => false],
]
Generate the Url:
yii\helpers\Url::toRoute(['/module/controller/product', 'slug' => 'cat1/cat2/cat3', 'id' => 1])
The output would be:
example.com/cat1/cat2/cat3/1

CakePHP HABTM Association not working

I've been trying to find an answer to my problem for hours. I am currently working with cakePHP 2.4.
I have two models, Users and Groups. I have created the following associations for each:
(User.php)
public $hasAndBelongsToMany = array(
'Group' =>
array(
'className' => 'Group',
'joinTable' => 'groups_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id',
'unique' => true,
)
);
and (Group.php):
public $hasAndBelongsToMany = array(
'GroupUser' =>
array(
'className' => 'User',
'joinTable' => 'groups_users',
'foreignKey' => 'group_id',
'associationForeignKey' => 'user_id',
'unique' => true,
)
);
The reason I use GroupUser and not "User" is I get an error because I have already used "User for some other relation.
My form looks like this:
echo $this->Form->create('Group', array('controller' => 'group','action' => 'add'));
echo $this->Form->input('User.id', array('type' => 'hidden', 'value' => $authUser['id']);
echo $this->Form->input('Group.address');
echo $this->Form->end(__('Save', true));
I also have a table called groups_users with "id", "user_id" and "group_id"
When I submit the form, it created the new Group and saves the data, but the association is not created.
I tried manually filling a groups_users record with an existing user_id and group_id but still, when I use find(All), it doesn't find the expected association like it should according to the books.
I debugged the array that is being saved and it looks like this:
Array
(
[User] => Array
(
[user_id] => 39
)
[Group] => Array
(
[address] => asdasd, San Antonio, Texas 78233, EE. UU.
)
)
This is the code in my GroupsController add function:
if ($this->Group->save($this->request->data)) {
// redirect or do something
}
I have tried changing the array to work with saveAll like in the books, still only created new record but no association. And as I said, I mannually created a record and tried finding it and it wouldn't find it anyway.
I solved it apparently, I think it was because I hadn't created the GroupsUser.php model file. Not rreally sure because I changed a bunch of stuff! But maybe it helps someone.