0

I have a "general" layout template, in which I would like to define a general set of options to pass to all the forms I'm creating in the specialized templates the contain the blocks I'm fetching:

<?php

$formOptions = [
    'id' => 'page-content-form',
    'name' => 'page-content-form',
];

echo $this->fetch('h4');

echo $this->fetch('form-start');

echo $this->fetch('form-fields');

I have multiple templates like this one, all with slight differences in the blocks (that are not relevant to this question):

<?php

$this->extend('/element/layout/page_content_form');

$this->append('h4');
echo $this->Html->tag('h4', 'Title');
$this->end();

$this->append('form-start');
echo $this->Form->create($pageContent, $formOptions);
$this->end();

$this->append('form-fields');
// more code here...
$this->end();

However, this gives me a Undefined variable $formOptions warning and a [TypeError] Bootstrap4\View\Helper\FormHelper::create(): Argument #2 ($options) must be of type array, null given error.

I have tried adding $this->set('formOptions', $formOptions) to the layout template, but that didn't fix the issue.

What's the way of correctly passing or sharing variables between different blocks of my view?

mrodo
  • 565
  • 5
  • 21

1 Answers1

0

The layout is not called until after the view template (and any related elements) are rendered. If you need these options in all views, you'd maybe want to do the $this->set('formOptions', $formOptions) call in a beforeRender function of your AppController.

Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
  • Meh, ok... I didn't want to involve the controller in this, but if there's no other way, I guess I'll have to. – mrodo Jul 06 '23 at 16:16
  • There's likely other ways. Trying to do it from the layout is NOT one of those ways. The controller method seems easiest to me. If you put it in your base controller class, you only have to do it once. – Greg Schmidt Jul 06 '23 at 18:44