Pass variables from item to view in CakePHP

I have a massive array that is used in several views, so I store it in the element file and retrieve it if necessary:

element/select.ctp:

$districts = array(
    __('Region A') => array(
        __('district 1') => __('district 1'),
        __('district 2') => __('district 1'),
        __('district 3') => __('district 1')
    ),
    __('Region B') => array(
        __('district 4') => __('district 4'),
        __('district 5') => __('district 5'),
        __('district 6') => __('district 6')
    )
);

And I include it in profiles/add.ctp:

echo $this->element('select');
echo $this->Form->Create('Profile');
echo $this->Form->input('district', array(
    'options' => $districts
);

But the variable is not passed. I wonder how can I pass this from an element?

+4
source share
1 answer

Elements are the wrong way to do this. Elements are used to visualize or display similar fragments several times in several views. You can pass variables from view to element, but not vice versa.

I would recommend placing the array in your AppController as follows:

<?php

    namespace App\Controller;

    use Cake\Controller\Controller;
    use Cake\Event\Event;

    class AppController extends Controller
    {
        public function beforeFilter(Event $event) {
            $this->set('districts', array(
                __('Region A') => array(
                    __('district 1') => __('district 1'),
                    __('district 2') => __('district 1'),
                    __('district 3') => __('district 1')
                ),
                __('Region B') => array(
                    __('district 4') => __('district 4'),
                    __('district 5') => __('district 5'),
                    __('district 6') => __('district 6')
                )
            ));
        }
    }

?>

, $districts, .

, AppController:

<?php

    namespace App\Controller;

    use Cake\Controller\Controller;
    use Cake\Event\Event;

    class AppController extends Controller
    {
        public function beforeFilter(Event $event) {
            $this->districts = array(
                __('Region A') => array(
                    __('district 1') => __('district 1'),
                    __('district 2') => __('district 1'),
                    __('district 3') => __('district 1')
                ),
                __('Region B') => array(
                    __('district 4') => __('district 4'),
                    __('district 5') => __('district 5'),
                    __('district 6') => __('district 6')
                )
            );
        }
    }

?>

, :

<?php

    namespace App\Controller;

    class SomeController extends AppController
    {
        public function index() {
            $this->set('districts', $this->districts);
        }
    }

?>
+4

All Articles