Reputation: 513
I created an application that allows admins to save slider content to the database and now I want to include the slider on the home page. I have a Slides controller with a slider function that just send the slides content to the slider view.
Here is that controller function:
public function slider()
{
$slides = $this->Slides->find('all');
$this->set('slides', $slides);
$this->set('_serialize', ['slides']);
}
The view for that function only has the following in it:
<?= $this->element('slider'); ?>
I then created an element file called slider and process the slides there. When I go to url /slides/slider the slider is working, but when I go to the root or home page, the slider is empty. It doesn't seem to be keeping the $slides variable in the element.
On the home page:
<?= $this->element('slider'); ?> // then the rest of the home page follows this.
So how do I keep the variable or make it so that I can have the slider view on the home page as well?
Upvotes: 2
Views: 4965
Reputation: 3141
The best practice in your case is to use Cells:
View cells are small mini-controllers that can invoke view logic and render out templates. They provide a light-weight modular replacement to requestAction().
cd bin
from the consolecake bake cell Slider
from the consolesrc/View/Cell/SliderCell.php
.as the following
public function display()
{
$this->loadModel('Slides');
$slides= $this->Slides->find('all');
$this->set('slides', $slides);
}
src/Template/Cell/Slides/display.ctp
, and play with $slides
in the tepmlate.<?= $this->cell('Slider') ?>
Upvotes: 3
Reputation: 1477
The variables are not sent from the Controller to an element, but from a view.
What you can do is set variables in your controller like this :
$this->set('myvariable','any value');
And, according to cakephp 3 documentation, in the view you can pass the parameter like this:
echo $this->element('helpbox', [
"varToElement" => $myvariable
]);
Source : https://book.cakephp.org/3.0/en/views.html#passing-variables-into-an-element
Upvotes: 2