Battousai
Battousai

Reputation: 513

How to send variables to an element in CakePHP 3.x from a controller and keep variables when using element in a different view?

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

Answers (2)

Eymen Elkum
Eymen Elkum

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().

  1. From the base App dir run cd bin from the console
  2. then run cake bake cell Slider from the console
  3. Go to src/View/Cell/SliderCell.php.
  4. edit the display function,

as the following

public function display()
{
    $this->loadModel('Slides');
    $slides= $this->Slides->find('all');
    $this->set('slides', $slides);
}
  1. Now go to the src/Template/Cell/Slides/display.ctp, and play with $slides in the tepmlate.
  2. To render the Cell anywhere just use this: <?= $this->cell('Slider') ?>

Upvotes: 3

Mehdi
Mehdi

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

Related Questions