草庐IT

php - ZF2 Form 将所有选择选项设置为在绑定(bind)时选择

coder 2024-04-07 原文

我的 ZF2 表单元素(选择)有问题。当我将我的学说实体绑定(bind)到此表单时,我所有的选择选项都会获得选定的属性,而不仅仅是应该的属性。实体刚刚获得一个连接的对象,Hydrator 也设置在 for 中。

这是我的一些代码。希望我只是错过了一些小东西。

AddressEntity.php

<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;
use ZF2Core\Entity\AbstractEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="`address`")
 */
class Address extends AbstractEntity
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="bigint", options={"unsigned":true})
     */
    protected $addressId;

    /**
     * @ORM\ManyToOne(targetEntity="SNOrganisation\Entity\Organisation", inversedBy="organisationId")
     * @ORM\JoinColumn(name="organisationId", referencedColumnName="organisationId", nullable=false)
     */
    protected $organisation;

    /**
     * @ORM\ManyToOne(targetEntity="AddressType")
     * @ORM\JoinColumn(name="addressTypeId", referencedColumnName="addressTypeId", nullable=false)
     */
    protected $addressType;

    /** @ORM\Column(type="string", nullable=true) */
    protected $otys;

    /** @ORM\Column(type="string") */
    protected $address;

    /** @ORM\Column(type="string", nullable=true) */
    protected $postalcode;

    /** @ORM\Column(type="string") */
    protected $city;

    /** @ORM\Column(type="string", nullable=true) */
    protected $email;

    /**
     * @ORM\ManyToOne(targetEntity="ZF2Country\Entity\Country")
     * @ORM\JoinColumn(name="countryId", referencedColumnName="countryId", nullable=false)
     */
    protected $country;

    /** @ORM\Column(type="datetime") */
    protected $created;

    /** @ORM\Column(type="datetime", nullable=true) */
    protected $deleted;

    public function getAddressId()
    {
        return $this->addressId;
    }

    public function getOrganisation()
    {
        return $this->organisation;
    }

    public function getAddressType()
    {
        return $this->addressType;
    }

    public function getOtys()
    {
        return $this->otys;
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function getPostalcode()
    {
        return $this->postalcode;
    }

    public function getCity()
    {
        return $this->city;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getCreated()
    {
        return $this->created;
    }

    public function getDeleted()
    {
        return $this->deleted;
    }

    public function setAddressId($addressId)
    {
        $this->addressId = $addressId;
        return $this;
    }

    public function setOrganisation($organisation)
    {
        $this->organisation = $organisation;
        return $this;
    }

    public function setAddressType($addressType)
    {
        $this->addressType = $addressType;
        return $this;
    }

    public function setOtys($otys)
    {
        $this->otys = $otys;
        return $this;
    }

    public function setAddress($address)
    {
        $this->address = $address;
        return $this;
    }

    public function setPostalcode($postalcode)
    {
        $this->postalcode = $postalcode;
        return $this;
    }

    public function setCity($city)
    {
        $this->city = $city;
        return $this;
    }

    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }

    public function setCreated($created)
    {
        $this->created = $created;
        return $this;
    }

    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;
        return $this;
    }

    public function getCountry()
    {
        return $this->country;
    }

    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

}

AddressForm.php

<?php

namespace SNOrganisation\Form;

use Zend\Form\Form;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Application\Entity\Address;
use Zend\ServiceManager\ServiceManager;

class AddressForm extends Form
{

    public function __construct($name = null, $entityManager, ServiceManager $serviceManager)
    {
        parent::__construct($name);

        $this->setAttribute('method', 'post');
        $this->setAttribute('class', 'form-horizontal');

        $this->setHydrator(new DoctrineHydrator($entityManager, 'Application\Entity\Address'));
        $this->setObject(new Address());

        $this->add(array(
            'name'       => 'addressType',
            'type'       => 'select',
            'options'    => array(
                'label'              => _('Type'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
                'value_options' => $this->getAddressTypeOptions($serviceManager),
            ),
            'attributes' => array(
                'class'      => 'form-control',
            ),
        ));

        $this->add(array(
            'name'       => 'address',
            'type'       => 'text',
            'options'    => array(
                'label'              => _('Address'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
            ),
            'attributes' => array(
                'class'          => 'form-control',
                'placeholder'    => 'Abbey Road 1',
            ),
        ));

        $this->add(array(
            'name'       => 'postalcode',
            'type'       => 'text',
            'options'    => array(
                'label'              => _('Postalcode'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
            ),
            'attributes' => array(
                'class'      => 'form-control',
                'placeholder'    => '1234 AB',
            ),
        ));

        $this->add(array(
            'name'       => 'city',
            'type'       => 'text',
            'options'    => array(
                'label'              => _('City'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
            ),
            'attributes' => array(
                'class'      => 'form-control',
                'placeholder'    => 'Amsterdam',
            ),
        ));

        $this->add(array(
            'name'       => 'country',
            'type'       => 'select',
            'options'    => array(
                'label'              => _('Country'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
                'value_options' => $this->getCountryOptions($serviceManager),
            ),
            'attributes' => array(
                'class'      => 'form-control',
            ),
        ));

        $this->add(array(
            'name'       => 'email',
            'type'       => 'email',
            'options'    => array(
                'label'              => _('Email'),
                'label_attributes'   => array(
                    'class' => 'col-lg-2 control-label'
                ),
            ),
            'attributes' => array(
                'class'      => 'form-control',
                'placeholder'    => 'name@domain.tld',
            ),
        ));
        $this->add(array(
            'name'       => 'submit',
            'type'       => 'submit',
            'options'    => array(
                'label' => _('Save'),
            ),
            'attributes' => array(
                'class' => 'btn btn-large btn-primary',
            ),
        ));
    }

    protected function getAddressTypeOptions($serviceManager)
    {
        $data = array();
        $addressTypeService = $serviceManager->get('application_service_addresstype');
        $addressTypeCollection = $addressTypeService->getAddressTypes()->getResult();

        foreach($addressTypeCollection as $addressType)
        {
            $data[$addressType->getAddressTypeId()] = $addressType->getName();
        }
        return $data;
    }

    protected function getCountryOptions($serviceManager)
    {
        $data = array();
        $countryService = $serviceManager->get('zf2country_service_country');
        $countryCollection = $countryService->getCountries()->getResult();

        foreach($countryCollection as $country)
        {
            $data[$country->getCountryId()] = $country->getName();
        }
        return $data;
    }
}

AddressController.php

<?php

namespace SNOrganisation\Controller;

use ZF2Core\Controller\AbstractController;
use Zend\View\Model\ViewModel;
use Application\Entity\Address;

class AddressController extends AbstractController
{
    public function editAction()
    {
        $organisationId = (int)$this->params()->fromRoute('id');
        $addressId = (int)$this->params()->fromRoute('addressId');
        $request = $this->getRequest();
        $address = $this->getEntityManager()->getRepository('Application\Entity\Address')->find($addressId);

        if ($address)
        {
            $addressForm = $this->getServiceLocator()->get('snorganisation_form_address');
            $addressForm->bind($address);
        }
        else
        {
            $this->resultMessenger()->addFatalMessage($this->getTranslator()->translate('The address could not be found'));
            $this->redirect()->toRoute('organisation');
        }

            return new ViewModel(array(
            'addressForm' => $addressForm,
        ));
    }
}

实体转储

<?php
object(Application\Entity\Address)[700]
  protected 'addressId' => string '487956' (length=6)
  protected 'organisation' => 
    object(DoctrineORMModule\Proxy\__CG__\SenetOrganisation\Entity\Organisation)[701]
      public '__initializer__' => 
        object(Closure)[583]
      public '__cloner__' => 
        object(Closure)[584]
      public '__isInitialized__' => boolean false
      protected 'organisationId' => string '412705' (length=6)
      protected 'ownerPerson' => null
      protected 'otys' => null
      protected 'name' => null
      protected 'paymentInterval' => null
      protected 'vatNumber' => null
      protected 'debtor' => null
      protected 'invoiceByEmail' => null
      protected 'active' => null
      protected 'reasonInactive' => null
      protected 'created' => null
      protected 'addressCollection' => null
      protected 'personCollection' => null
      protected 'orderCollection' => null
      protected 'serviceManager' => null
  protected 'addressType' => 
    object(DoctrineORMModule\Proxy\__CG__\Application\Entity\AddressType)[714]
      public '__initializer__' => 
        object(Closure)[704]
      public '__cloner__' => 
        object(Closure)[705]
      public '__isInitialized__' => boolean false
      protected 'addressTypeId' => string '2' (length=1)
      protected 'name' => null
      protected 'serviceManager' => null
  protected 'otys' => null
  protected 'address' => string 'Langebrug 87 b' (length=14)
  protected 'postalcode' => string '2311 TJ' (length=7)
  protected 'city' => string 'Leiden' (length=6)
  protected 'email' => null
  protected 'country' => 
    object(DoctrineORMModule\Proxy\__CG__\ZF2Country\Entity\Country)[724]
      public '__initializer__' => 
        object(Closure)[711]
      public '__cloner__' => 
        object(Closure)[710]
      public '__isInitialized__' => boolean false
      protected 'countryId' => string '157' (length=3)
      protected 'nameIso' => null
      protected 'name' => null
      protected 'iso' => null
      protected 'iso3' => null
      protected 'serviceManager' => null
  protected 'created' => 
    object(DateTime)[698]
      public 'date' => string '2014-03-22 16:05:49' (length=19)
      public 'timezone_type' => int 3
      public 'timezone' => string 'Europe/Amsterdam' (length=16)
  protected 'deleted' => null
  protected 'serviceManager' => null

最佳答案

让我调查一下,是什么原因。有时使用 Zend\Form\Select 元素而不是 Doctrine 元素会很方便。但是 Zend element 有时不能处理 doctrine Entities。原因在 Zend\Form\View\Helper\FormSelect.php 文件的以下代码中,方法 renderOptions

if (ArrayUtils::inArray($value, $selectedOptions)) {
    $selected = true;
}

这段代码使每个选项都被选中。但是$selectedOptions不是实体id,它是实体对象。此对象通过魔术方法转换为数组,因此我们有错误的 $selectedOptions

所以我决定将表单元素类型从“Select”更改为 DoctrineModule\Form\Element\ObjectSelect 并注入(inject) entityManager。

'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
    'object_manager' => $entityManager,
    'target_class' => 'Telecom\Entity\Name',
)

我不知道,为什么有时它不是问题。可能我应该看看由 Doctrine 生成的 Proxy 对象。如果我明白了什么,我会更新答案。

关于php - ZF2 Form 将所有选择选项设置为在绑定(bind)时选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22805539/

有关php - ZF2 Form 将所有选择选项设置为在绑定(bind)时选择的更多相关文章

  1. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  2. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  3. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  4. ruby - Rails 3 的 RGB 颜色选择器 - 2

    状态:我正在构建一个应用程序,其中需要一个可供用户选择颜色的字段,该字段将包含RGB颜色代码字符串。我已经测试了一个看起来很漂亮但效果不佳的。它是“挑剔的颜色”,并托管在此存储库中:https://github.com/Astorsoft/picky-color.在这里我打开一个关于它的一些问题的问题。问题:请建议我在Rails3应用程序中使用一些颜色选择器。 最佳答案 也许页面上的列表jQueryUIDevelopment:ColorPicker为您提供开箱即用的产品。原因是jQuery现在包含在Rails3应用程序中,因此使用基

  5. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  6. ruby - 我正在学习编程并选择了 Ruby。我应该升级到 Ruby 1.9 吗? - 2

    我完全不是程序员,正在学习使用Ruby和Rails框架进行编程。我目前正在使用Ruby1.8.7和Rails3.0.3,但我想知道我是否应该升级到Ruby1.9,因为我真的没有任何升级的“遗留”成本。缺点是什么?我是否会遇到与普通gem的兼容性问题,或者甚至其他我不太了解甚至无法预料的问题? 最佳答案 你应该升级。不要坚持从1.8.7开始。如果您发现不支持1.9.2的gem,请避免使用它们(因为它们很可能不被维护)。如果您对gem是否兼容1.9.2有任何疑问,您可以在以下位置查看:http://www.railsplugins.or

  7. ruby-on-rails - Rails 单选按钮 - 模型中多列的一种选择 - 2

    我希望用户从一个模型的三个选项中选择一个。即我有一个模型视频,可以被评为正面/负面/未知目前我有三列bool值(pos/neg/unknown)。这是处理这种情况的最佳方式吗?为此,表单应该是什么样的?目前我有类似的东西但显然它允许多项选择,而我试图将它限制为只有一个..怎么办? 最佳答案 如果要使用字符串列,让我们说rating。然后在你的表单中:#...#...它只允许一个选择编辑完全相同但使用radio_button_tag: 关于ruby-on-rails-Rails单选按钮-模

  8. ruby-on-rails - CarrierWave - PDF - 只选择第一页 - 2

    我的Rails应用程序中安装了carrierwave。但是,当用户上传多页pdf时,我只希望应用程序获取文档中的第一页并将其转换为jpeg。这可能吗?用什么命令?这是我的uploader。#encoding:utf-8classImageUploader[200,300]##defscale(width,height)##dosomething#end#Createdifferentversionsofyouruploadedfiles:version:thumbdoprocess:resize_to_fill=>[150,210]process:convert=>:jpgdefful

  9. ruby-on-rails - ActiveAdmin 自定义选择过滤器下拉名称 - 2

    对于用户模型,我有一个过滤器来检查用户的预订状态,该状态由整数值(0、1或2)表示。UserActiveAdmin索引页上的过滤器是通过以下代码实现的:filter:booking_status,as::select然而,这会导致下拉选项为0、1或2。当管理员用户从下拉列表中选择它们时,我更愿意自己将它们命名为“未完成”、“待定”和“已确认”之类的名称。有没有办法在不改变booking_status在模型中的表示方式的情况下做到这一点? 最佳答案 假设booking_status是模型中的枚举字段,您可以使用:过滤器:booking

  10. ruby-on-rails - 多次选择一个随机数,但绝不会两次选择相同的随机数 - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:HowdoIgeneratealistofnuniquerandomnumbersinRuby?我想做的事:Random.rand(0..10).timesdoputsRandom.rand(0..10)end但如果随机数已经显示过,则无法再次显示。如何最轻松地做到这一点?

随机推荐