ZF2 - FormRow不会生成值

时间:2015-05-01 20:12:01

标签: php forms zend-framework2

我在FieldSet中有一个数量字段。

private function addAmount()
{
    $number = new Number('amount');
    $number->setLabel('Amount');

    // Attributes
    $number->setAttribute('required', TRUE);
    $number->setAttribute('id', 'product-amount');
    $number->setAttribute('class', 'form-control');
    $number->setAttribute('min', 1);
    $number->setAttribute('max', 10);
    $number->setAttribute('step', 1);

    // Label attributes
    $number->setLabelAttributes(array(
        'class' => 'control-label'
    ));

    $number->setValue(1);
    $this->add($number);
}

我将值设置为1,但在使用FormRow生成输入字段后,没有可用的值。

是否有一种漂亮而简洁的方法可以在FieldSet或Form中设置默认值并将它们显示在视图中?

感谢。

- 编辑 -

在表单中,我按照建议设置了数据。

$ this-> setData(array(' product' => array(' amount' => 1))); $这 - > bindValues();

即使在视图中也可以使用数据,但是在视图中它没有在Phprenderer FormNumber中使用。视图看起来只是相关元素:

    <?php
    $form->setAttribute('action', $this->url('product', array('action' => add')));
    $form->setAttribute('class', 'form-horizontal');

    $form->prepare();
    echo $this->form()->openTag($form);

    $product = $form->get('product');
    ?>

    <div class="form-group <?= ($this->formElementErrors($product->get('amount'))) ? 'has-error' : ''; ?>">
    <?php
    echo $this->formRow($product->get('amount')) . PHP_EOL;
    ?>
    </div>

如果我在绑定对象中设置了金额值,则会正确显示。我无法在验证之前填充。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

我从来没有手动破解过这样的表格,我总是用工厂来创建它们。不确定设置是否是一个因素,但这有效:

<强> FORM

namespace Application\Form;

use Zend\Form\Element,
    Zend\Captcha,
    Zend\InputFilter,
    Zend\Form\Element\Text,
    Zend\Form\Form;

class CreditCardForm extends Form
{

    public function init()
    {

        $this->add([
            'name' => 'card-holder-name',
            'type' => Text::class,
            'options' => [
                'label' => _( "Name on Card" ),
            ],
            'attributes' => [
                'maxlength' => 64,
            ],
        ]);
    }
}

INPUT FILTER

namespace Application\InputFilter;

use Zend\Filter\StringTrim;
use Zend\InputFilter\InputFilter;
use Zend\Form\Element;
use Zend\Validator\StringLength;
use Zend\Validator\CreditCard;

class CreditCardInputFilter extends InputFilter
{

    public function init()
    {

        $this->add([
           'name' => 'card-holder-name',
           'required' => true,
           'filters' => [
               ['name' => StringTrim::class],
           ],
        ]);
    }
}

FORM FACTORY

namespace Application\Factory\Form;

use Application\Form\CreditCardForm;
use Application\InputFilter\CreditCardInputFilter;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Hydrator\ClassMethods;

/**
 * Class ServerFormFactory
 */
class CreditCardFormFactory implements FactoryInterface, MutableCreationOptionsInterface
{

    /**
     * @var array
     */
    protected $options;

     /**
     * Set creation options
     *
     * @param  array $options
     * @return void
     */
    public function setCreationOptions( array $options )
    {
        $this->options = $options;
    }


    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /**
         * @var \Zend\Form\FormElementManager       $serviceLocator
         * @var \Zend\ServiceManager\ServiceManager $serviceManager
         */
        $serviceManager = $serviceLocator->getServiceLocator();
        try
        {
            $form      = new CreditCardForm( 'card' );
            $form->setHydrator( new ClassMethods() );
            $form->setInputFilter( $serviceManager->get('InputFilterManager')->get( CreditCardInputFilter::class ) );
        }
        catch( \Exception $x )
        {
            die( $x->getMessage() );
        }


        return $form;
    }
}

在您的配置中一起粘贴,例如:

<强> CONFIG

'service_manager' => [

    'form_elements' => [
        'factories' => [
            CreditCardForm::class => CreditCardFormFactory::class,
        ],
    ],
],

这样可行:

$sm   = $this->getServiceLocator();
$form = $sm->get( 'FormElementManager' )->get( CreditCardForm::class );
$form->get( 'card-holder-name' )->setValue( 'Peter Smith' );
$viewModel->setVariable( 'form', $form );

当您在模板中渲染该表单时(强烈建议在Github上使用Twig和neilime TWBS包),它将按预期填充。我希望这篇文章可以帮到你!

祝你好运! ;)

答案 1 :(得分:0)

感谢大家的回复。当前的解决方案是在相关实体中设置默认值:

     /**
      * Product
      *
      * @ORM\Table(name="products")
      * @ORM\Entity(repositoryClass="\Entities\ProductRepository")
      */
      class Product
      {

       const DEFAULT_AMOUNT = 1;

       public function __construct()
       {
          $this->setAmount($this->getDefaultAmount());
       }

}

这很有效,我确实喜欢上面给出的解决方案,肯定会看看Twig。