开发者

CakePHP $this->element correct usage?

I'm trying to make a reusable component (a weekday dropdown box, simple as pie) and 开发者_如何学JAVAam following the advice in http://book.cakephp.org/view/1081/Elements.

According to that page, I should make a blah.ctp file in app/views/elements, and it will be magically accessible in my view code as $this->element('blah').

So I did it. I'm passing the form and field name to my element in the view code:

$this->element(
    'weekday_input', 
    array('form'=>$this->Form, 'fieldname'=>'weekday')
);

Earlier I created a form using $this->Form->create, so I figured I need to pass it to the element explicitly.

And my element code, in weekday_input.ctp:

echo $form->input(
    $fieldname, 
    array(
        'options', 
        array('Sunday'=>'Sunday',...,'Saturday'=>'Saturday')
    )
);

(Weekdays in between omitted for brevity.)

Am I using $this->element properly? Is there something more clean available?


You don't have to pass the Form object. Form, Html and other helpers are available in elements (just as in view). Whether or not you want to pass fieldname depends: Do you need to change it?


An element is a bit too simple I expect. Also it is not very testable. Would focus on Helpers, which is a more advanced way of developing this. But there is another solution I would prefer even more:

For this kind of issues it might be more appropriate to extend the formhelper itself. You can see a simple example here:

http://blog.nlware.com/2012/02/07/cakephp-2-0-how-to-extend-the-formhelper/

A full example can be found for example here:

https://github.com/slywalker/cakephp-plugin-boost_cake/blob/master/View/Helper/BoostCakeFormHelper.php

As you asked for a clean solution think about creating a plugin (or check out existing plugins). That will separate the code out of your project more clean. And it will be available for re-use without much issues.

you can find all files needed for a plugin in the same project: https://github.com/slywalker/cakephp-plugin-boost_cake

And the documentation here: http://book.cakephp.org/2.0/en/plugins.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜