0

Fieldset私は2つの非常によく似たMyFooFieldsetとを持っていMyBarFieldsetます。コードの重複を避けるために、 を作成し、コード全体をそこに移動して、具体的なクラスのメソッドのAbstractMyFieldset違いを処理したいと考えています。init()

AbstractMyFooFieldset

namespace My\Form\Fieldset;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
abstract class AbstractMyFieldset extends Fieldset implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add(
            [
                'type' => 'multi_checkbox',
                'name' => 'my_field',
                'options' => [
                    'label_attributes' => [
                        'class' => '...'
                    ],
                    'value_options' => $this->getValueOptions()
                ]
            ]);
    }
    public function getInputFilterSpecification()
    {
        return [...];
    }
    protected function getValueOptions()
    {
        ...
        return $valueOptions;
    }
}

MyFooServerFieldset

namespace My\Form\Fieldset;
use Zend\Form\Fieldset;
class MyFooServerFieldset extends AbstractMyFieldset
{
    public function init()
    {
        parent::init();
        $this->get('my_field')->setType('radio'); // There is not method Element#setType(...)! How to do this?
        $this->get('my_field')->setAttribute('required', 'required'); // But this works.
    }
}

および属性などtype、要素の およびその他の構成を設定したいと考えています。属性の設定は問題ないようです。少なくとも属性を設定できます。しかし、タイプを設定できません -- がありません。typerequiredrequiredElement#setType(...)

編集された後、typeのを設定する方法は?Zend\Form\Elementadd

4

1 に答える 1

1

各要素には独自の型と要素クラスが定義されているため、要素の型を設定する方法はありません。AbstractMyFieldsetで、 内の「Type」キーを参照してくださいinit()。要素クラスを追加するようにフォームに指示し、MultiCheckboxそのクラスを別のものに変更したいとします。したがって、デフォルトを削除して、その属性とオプションを新しく追加された Zend Form 要素にコピーする必要があります。

別のオプションはZend\Form\Element、属性を上書きして type 属性を設定できる基本クラスを使用することです。->setAttribute('type', 'my_type')しかし、デフォルトの Zend2 フォーム クラスのすべての利点が失われています。特に、またはのデフォルトのInArrayバリデータとして.Zend\Form\Element\RadioZend\Form\Element\MultiCheckbox

または、両方のフィールドセットに対してabstractFieldSetを作成することを検討し、それらが値オプションを取得してそれを再利用する方法を定義する必要があります。お気に入り:

abstract class AbstractFieldSet extends Fieldset {
    public function addMyField($isRadio = false)
    {
        $this->add([
            'type' => $isRadio ? 'radio' : 'multi_checkbox',
            'name' => 'my_field',
            'options' => [
                'value_options' => $this->getValueOptions()
            ]
        ]);
    }

    protected function getValueOptions()
    {
        // ..
        return $valueOptions
    }
}

class fieldSet1 extends AbstractFieldSet {
    public function init()
    {
        $this->addMyField(false);
    }
}

class fieldSet2 extends AbstractFieldSet {
    public function init()
    {
        $this->addMyField(true);
    }
}
于 2016-11-14T15:06:54.123 に答える