表单元素的默认类

时间:2012-03-22 22:03:11

标签: php zend-framework

我有一个自定义表单类,它扩展了基础Zend_Form并指定了表单本身和元素的装饰器。

现在我陷入困境 - 如何为每个输入元素添加一些特定的HTML类?

我唯一能想到的是覆盖addElement(),但我愿意接受更好的解决方案。

4 个答案:

答案 0 :(得分:2)

只是另一种解决方案:

class My_Form extends Zend_Form
{ 
    public function render(Zend_View_Interface $view = null) 
    { 
        foreach ($this->getElements() as $element) { 
            $element->setAttrib('class', 'default'); 
        }

        return parent::render($view); 
    }
}

答案 1 :(得分:1)

听起来你想要一种方法来自动为每个元素分配一个唯一的类。

扩展 b.b3rn4rd 给出的答案,尝试类似:

class My_Form extends Zend_Form
{ 
    public function render(Zend_View_Interface $view = null) 
    { 
        foreach ($this->getElements() as $element) { 
            //assign the class as some unique identifier that is part of the element
            //each element requires a unique name so it's a good place to start
            $element->setAttrib('class', $element->getName()); 
        }

        return parent::render($view); 
}

}

答案 2 :(得分:1)

我不喜欢继承Zend_Form的解决方案,所以我设计了另一种方法来做到这一点。

<?php

abstract class Application_Style
{

    private $_object;


    function __construct ($object = null)
    {
        if (isset ($object))
        {
            $this->apply ($object);
        }
    }


    function apply ($object)
    {
        $this->setObject ($object);
        if ($this->filter ())
        {
            $this->onApply ();
        }

        return $object;
    }


    function __call ($method, $arguments)
    {
        return call_user_func_array (array (
            $this->getObject (),
            $method
        ), $arguments);
    }


    abstract protected function onApply ();


    protected function filter ()
    {
        return true;
    }


    function setObject ($_object)
    {
        $this->_object = $_object;
    }


    function getObject ()
    {
        return $this->_object;
    }
}




class Application_Style_ElementClass extends Application_Style
{


    function onApply ()
    {
        foreach ($this->getObject ()
            ->getElements () as $element)
        {
            $element->setOptions (array (
                'class' => 'test-class'
            ));
        }
    }


    function filter ()
    {
        return $this->getObject () instanceof Zend_Form;
    }
}


$form = new Zend_Form ();
$form->addElement ('text', 'name');
new Application_Style_ElementClass ($form);  // apply the class name
echo $form;

通过这种方式,您可以按任何顺序应用任何表单所需的所有样式。

答案 3 :(得分:0)

向元素添加HTML类属性就像这样

$element->setAttrib('class', 'text'):
or directly 
$element->class = 'text;