php - CakePHP use Model & Controller on different Template
I have folowed the documentation where you create the Table, Entity, Controller and then the template to display the data. On my /articles site I want to display User data now. So my User data will be on /articles and not on /users.
In /templates/Articles/index.php I can use $articles
now, but not $users
.
How do make use of another controller in my page?
Answer
Solution:
My goal is to add a row with the user email who published the article.
ArticlesController.php
public function index(){
$articles = $this->Paginator->paginate($this->Articles->find());
$users = $this->Articles->Users->find('')->all()->first();
$this->set('users', $users);
$this->set(compact('articles'));
}
My templates/Articles/index.php
<?php foreach ($articles as $article): ?>
<tr>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
</td>
<td>
a
</td>
<td>
<?php echo $article->$users ?>
</td>
<td>
<?= $this->Html->link('Edit', ['action' => 'edit', $article->slug]) ?>
</td>
<td>
<?= $this->Form->postLink(
'Delete',
['action' => 'delete', $article->slug],
['confirm' => 'Are you sure?']) ?>
</td>
</tr>
<?php endforeach; ?>
My ArticlesTable.php
class ArticlesTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp');
$this->belongsToMany('Tags');
$this->hasOne('Users');
}
public function beforeSave(EventInterface $event, $entity, $options)
{
if ($entity->isNew() && !$entity->slug) {
$sluggedTitle = Text::slug($entity->title);
// trim slug to maximum length defined in schema
$entity->slug = substr($sluggedTitle, 0, 191);
}
}
}
Source