在CakePHP中将变量从元素传递到视图

时间:2015-08-26 08:13:12

标签: cakephp

我有一个庞大的数组,在几个视图中使用,所以我将它存储在一个元素文件中并在需要时获取它:

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')
    )
);

我将其加入profiles/add.ctp

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

但变量未通过。我想知道如何从元素中传递它?

1 个答案:

答案 0 :(得分:5)

元素不是正确的方法。元素用于在多个视图中多次呈现或显示相似的片段。您可以将变量从View传递给Element,但不能相反。

我建议将数组放入AppController,如下所示:

<?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);
        }
    }

?>