没有JavaScript的Symfony表单呈现CollectionType

时间:2017-12-01 07:59:27

标签: javascript php jquery forms symfony

我正在使用Symfony 3.3并希望使用CollectionType创建表单。只需将所有内容配置为here并且工作正常。

现在我想只渲染一组集合类型(参考示例,它将是一个“标记”,但没有JavaScript / jQuery / Prototype。仍然尝试使用

{{ form_start(form) }} {{ form_widget(form.tags.vars.prototype.name)|e }} {{ form_end(form) }}

{{ form_start(form) }} {{ form_widget(form.tags.vars.prototype.name)|raw }} {{ form_end(form) }}

返回表单字段,但在提交后未处理(未进行验证,“值”丢失。 还添加了replace({'__name__': '1'}),但不会更改结果。

我想创建一个付款流程,用户只需输入一个“帐单邮寄地址”(在示例中会引用“代码”)。付款流程中的基本功能必须在没有JavaScript的情况下运行,以确保即使在禁用JavaScript时用户也可以付费,无论出于何种原因。

如何在不使用JavaScript的情况下呈现一组“标签”表单字段?

谢谢,最好!

实体/用户:

class User extends EntitySuperclass implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\Column(type="string")
     */
    private $username;

    /**
     *
     * @Assert\Length(max=4096,groups={"account_complete","account_password","user"})
     * @Assert\Length(min = 8,groups={"account_complete","account_password","user"}, minMessage="user.password_length")
     */
    private $plainPassword;

    /**
     * The below length depends on the "algorithm" you use for encoding
     * the password, but this works well with bcrypt.
     *
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank(groups={"account_register","user"})
     * @Assert\Email(
     *      groups = {"account_register", "account","user"},
     *      strict = true,
     *      checkMX = true
     * )
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $emailNew = '';

    /**
     * @ORM\ManyToOne(targetEntity="Salutation")
     * 
     */
    private $salutation;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(groups={"account_complete","user"})
     * @Assert\Regex(pattern = "/^[a-zA-ZäöüÄÖÜß0-9 ]+$/",groups={"account_complete","user"}, message="user.first_name.regex")
     */
    private $firstName;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(groups={"account_complete","user"})
     * @Assert\Regex(pattern = "/^[a-zA-ZäöüÄÖÜß0-9 ]+$/",groups={"account_complete","user"}, message="user.last_name.regex")
     */
    private $lastName;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive = false;

    /**
     * @ORM\Column(name="email_confirmed", type="boolean")
     */
    private $emailConfirmed = false;

    /**
     * @ORM\Column(type="integer")
     */
    private $shibbolethState = 0;

    /**
     * @ORM\Column(type="string")
     */
    private $shibbolethHash = '';

    /**
     * @ORM\Column(type="string")
     */
    private $shibbolethPersistentId = '';

    /**
     * @ORM\ManyToMany(targetEntity="UserGroup")
     * @ORM\JoinTable(name="User_UserGroup",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
     *      )
     */
    private $userGroups;

    /**
     * @ORM\Column(type="integer")
     */
    private $confirmationEmailSend;

    /**
     * @ORM\Column(type="integer")
     */
    private $lastLogin = 0;

    /**
     * @ORM\Column(type="integer")
     */
    protected $expires = 0;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $sessionId = '';

    /**
     * @ORM\ManyToMany(targetEntity="BankDetails", cascade={"persist"})
     * @ORM\JoinTable(name="User_BankDetails",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="bank_details_id", referencedColumnName="id")}
     * )
     */
    private $bankDetails;

    /**
     * @ORM\ManyToMany(targetEntity="Address", cascade={"persist"})
     * @ORM\JoinTable(name="User_BillingAddress",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="billing_address_id", referencedColumnName="id")}
     * )
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "user.billing_addresses.min",
     *      groups={"test"}
     * )
     * @Assert\Valid
     */
    private $billingAddresses;

    public function __construct()
    {
        parent::__construct();
        $this->isActive = true;
        $this->confirmationEmailSend = 0;
        $this->userGroups = new ArrayCollection();
        $this->bankDetails = new ArrayCollection();
        $this->billingAddresses = new ArrayCollection();
        // may not be needed, see section on salt below
        // $this->salt = md5(uniqid(null, true));
    }

    /**
     * @ORM\PrePersist
     */
    public function prePersist()
    {
        $currentTimestamp = time();

        if($this->getConfirmationEmailSend() == NULL)
            $this->setConfirmationEmailSend(0);

   }

    public function getUsername()
    {
        //return $this->username;
        return $this->email;
    }

    public function getSalt()
    {
        // The bcrypt algorithm doesn't require a separate salt.
        return null;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getRoles()
    {
        $roles = array();
        $userGroups = $this->getUserGroups();
        if(!empty($userGroups)) {
            foreach($userGroups as $userGroup) {
                $role = $userGroup->getRole();
                $roles[] = 'ROLE_'.strtoupper($role);
            }
        }
        return $roles;
    }

    public function isGranted($role)
    {
        return in_array($role, $this->getRoles());
    }

    public function eraseCredentials()
    {
    }

    public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    public function isEnabled()
    {
        return $this->isActive;
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            // see section on salt below
            // $this->salt,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            // see section on salt below
            // $this->salt
        ) = unserialize($serialized);
    }

    /**
     * Set username
     *
     * @param string $username
     *
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    public function setPlainPassword($password)
    {
        $this->plainPassword = $password;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;
        $this->setUsername($email);

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     *
     * @return User
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Add userGroup
     *
     * @param \AppBundle\Entity\UserGroup $userGroup
     *
     * @return User
     */
    public function addUserGroup(\AppBundle\Entity\UserGroup $userGroup)
    {
        $this->userGroups[] = $userGroup;

        return $this;
    }

    /**
     * Remove userGroup
     *
     * @param \AppBundle\Entity\UserGroup $userGroup
     */
    public function removeUserGroup(\AppBundle\Entity\UserGroup $userGroup)
    {
        $this->userGroups->removeElement($userGroup);
    }

    /**
     * Get userGroups
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUserGroups()
    {
        return $this->userGroups;
    }

    /**
     * Set shibbolethPersistentId
     *
     * @param string $shibbolethPersistentId
     *
     * @return User
     */
    public function setShibbolethPersistentId($shibbolethPersistentId)
    {
        $this->shibbolethPersistentId = $shibbolethPersistentId;

        return $this;
    }

    /**
     * Get shibbolethPersistentId
     *
     * @return string
     */
    public function getShibbolethPersistentId()
    {
        return $this->shibbolethPersistentId;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set emailConfirmed
     *
     * @param boolean $emailConfirmed
     *
     * @return User
     */
    public function setEmailConfirmed($emailConfirmed)
    {
        $this->emailConfirmed = $emailConfirmed;

        return $this;
    }

    /**
     * Get emailConfirmed
     *
     * @return boolean
     */
    public function getEmailConfirmed()
    {
        return $this->emailConfirmed;
    }

    public function removeAllUserGroups() {
        $userGroups = $this->getUserGroups();
        foreach($userGroups as $userGroup) {
           $this->removeUserGroup($userGroup);
        }
    }

    public function hasUserGroup($userGroupId) {
        foreach($this->getUserGroups() as $userGroup) {
            if($userGroup->getId() == $userGroupId)
                return true;
        }
        return false;
    }

    /**
     * Set lastLogin
     *
     * @param integer $lastLogin
     *
     * @return User
     */
    public function setLastLogin($lastLogin)
    {
        $this->lastLogin = $lastLogin;

        return $this;
    }

    /**
     * Get lastLogin
     *
     * @return integer
     */
    public function getLastLogin()
    {
        return $this->lastLogin;
    }

    /**
     * Set confirmationEmailSend
     *
     * @param integer $confirmationEmailSend
     *
     * @return User
     */
    public function setConfirmationEmailSend($confirmationEmailSend)
    {
        $this->confirmationEmailSend = $confirmationEmailSend;

        return $this;
    }

    /**
     * Get confirmationEmailSend
     *
     * @return integer
     */
    public function getConfirmationEmailSend()
    {
        return $this->confirmationEmailSend;
    }

    /**
     * Set validTill
     *
     * @param integer $validTill
     *
     * @return User
     */
    public function setValidTill($validTill)
    {
        $this->validTill = $validTill;

        return $this;
    }

    /**
     * Get validTill
     *
     * @return integer
     */
    public function getValidTill()
    {
        return $this->validTill;
    }

    /**
     * Set shibbolethValid
     *
     * @param integer $shibbolethValid
     *
     * @return User
     */
    public function setShibbolethValid($shibbolethValid)
    {
        $this->shibbolethValid = $shibbolethValid;

        return $this;
    }

    /**
     * Get shibbolethValid
     *
     * @return integer
     */
    public function getShibbolethValid()
    {
        return $this->shibbolethValid;
    }

    /**
     * Set shibbolethHash
     *
     * @param string $shibbolethHash
     *
     * @return User
     */
    public function setShibbolethHash($shibbolethHash)
    {
        $this->shibbolethHash = $shibbolethHash;

        return $this;
    }

    /**
     * Get shibbolethHash
     *
     * @return string
     */
    public function getShibbolethHash()
    {
        return $this->shibbolethHash;
    }

    /**
     * Set shibbolethState
     *
     * @param integer $shibbolethState
     *
     * @return User
     */
    public function setShibbolethState($shibbolethState)
    {
        $this->shibbolethState = $shibbolethState;

        return $this;
    }

    /**
     * Get shibbolethState
     *
     * @return integer
     */
    public function getShibbolethState()
    {
        return $this->shibbolethState;
    }

    /**
     * Set expires
     *
     * @param integer $expires
     *
     * @return User
     */
    public function setExpires($expires)
    {
        $this->expires = $expires;

        return $this;
    }

    /**
     * Get expires
     *
     * @return integer
     */
    public function getExpires()
    {
        return $this->expires;
    }

    /**
     * Set emailNew
     *
     * @param string $emailNew
     *
     * @return User
     */
    public function setEmailNew($emailNew)
    {
        $this->emailNew = $emailNew;

        return $this;
    }

    /**
     * Get emailNew
     *
     * @return string
     */
    public function getEmailNew()
    {
        return $this->emailNew;
    }

    /**
     * Set passwordHash
     *
     * @param string $passwordHash
     *
     * @return User
     */
    public function setPasswordHash($passwordHash)
    {
        $this->passwordHash = $passwordHash;

        return $this;
    }

    /**
     * Get passwordHash
     *
     * @return string
     */
    public function getPasswordHash()
    {
        return $this->passwordHash;
    }

    /**
     * Set sessionId
     *
     * @param string $sessionId
     *
     * @return User
     */
    public function setSessionId($sessionId)
    {
        $this->sessionId = $sessionId;

        return $this;
    }

    /**
     * Get sessionId
     *
     * @return string
     */
    public function getSessionId()
    {
        return $this->sessionId;
    }

    /**
     * Set salutation
     *
     * @param \AppBundle\Entity\Salutation $salutation
     *
     * @return User
     */
    public function setSalutation(\AppBundle\Entity\Salutation $salutation = null)
    {
        $this->salutation = $salutation;

        return $this;
    }

    /**
     * Get salutation
     *
     * @return \AppBundle\Entity\Salutation
     */
    public function getSalutation()
    {
        return $this->salutation;
    }

    /**
     * Add bankDetail
     *
     * @param \AppBundle\Entity\BankDetails $bankDetail
     *
     * @return User
     */
    public function addBankDetail(\AppBundle\Entity\BankDetails $bankDetail)
    {
        $this->bankDetails[] = $bankDetail;

        return $this;
    }

    /**
     * Remove bankDetail
     *
     * @param \AppBundle\Entity\BankDetails $bankDetail
     */
    public function removeBankDetail(\AppBundle\Entity\BankDetails $bankDetail)
    {
        $this->bankDetails->removeElement($bankDetail);
    }

    /**
     * Get bankDetails
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBankDetails()
    {
        return $this->bankDetails;
    }

    /**
     * Add billingAddress
     *
     * @param \AppBundle\Entity\Address $billingAddress
     *
     * @return User
     */
    public function addBillingAddress(\AppBundle\Entity\Address $billingAddress)
    {
        $this->billingAddresses[] = $billingAddress;

        return $this;
    }

    /**
     * Remove billingAddress
     *
     * @param \AppBundle\Entity\Address $billingAddress
     */
    public function removeBillingAddress(\AppBundle\Entity\Address $billingAddress)
    {
        $this->billingAddresses->removeElement($billingAddress);
    }

    /**
     * Set billingAddresses
     *
     * @param \AppBundle\Entity\Address $billingAddresses
     *
     * @return User
     * 
     */
    public function setBillingAddresses(\AppBundle\Entity\Address $billingAddress)
    {
        if($this->billingAddresses !== NULL and $this->billingAddresses->contains($billingAddress)){
            return false;
        }
        $this->addBillingAddress($billingAddress);
        return $this;
    }

    /**
     * Get billingAddresses
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBillingAddresses()
    {
        return $this->billingAddresses;
    }
}

实体/地址:

class Address extends EntitySuperclass
{

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

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

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(groups={"user","document_access_new_step_3"})
     */
    private $line1;

    /**
     * @ORM\Column(type="string")
     */
    private $line2;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(groups={"user","document_access_new_step_3"})
     */
    private $city;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(groups={"user","document_access_new_step_3"})
     */
    private $postalCode;

    /**
     * @ORM\ManyToOne(targetEntity="Country")
     * @Assert\NotBlank(groups={"user","document_access_new_step_3"})
     */
    private $country;

    public function __construct()
    {
        parent::__construct();
        $this->country = NULL;
    }


    /**
     * Set firstName
     *
     * @param string $firstName
     *
     * @return Address
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     *
     * @return Address
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set line1
     *
     * @param string $line1
     *
     * @return Address
     */
    public function setLine1($line1)
    {
        $this->line1 = $line1;

        return $this;
    }

    /**
     * Get line1
     *
     * @return string
     */
    public function getLine1()
    {
        return $this->line1;
    }

    /**
     * Set line2
     *
     * @param string $line2
     *
     * @return Address
     */
    public function setLine2($line2)
    {
        $this->line2 = $line2;

        return $this;
    }

    /**
     * Get line2
     *
     * @return string
     */
    public function getLine2()
    {
        return $this->line2;
    }

    /**
     * Set city
     *
     * @param string $city
     *
     * @return Address
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set postalCode
     *
     * @param string $postalCode
     *
     * @return Address
     */
    public function setPostalCode($postalCode)
    {
        $this->postalCode = $postalCode;

        return $this;
    }

    /**
     * Get postalCode
     *
     * @return string
     */
    public function getPostalCode()
    {
        return $this->postalCode;
    }

    /**
     * Set country
     *
     * @param \AppBundle\Entity\Country $country
     *
     * @return Address
     */
    public function setCountry(\AppBundle\Entity\Country $country = null)
    {
        $this->country = $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return \AppBundle\Entity\Country
     */
    public function getCountry()
    {
        return $this->country;
    }
}

FormType \用户

class UserFinancialTransactionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('billingAddresses', AddressType::class, array(
            ))
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
            'translation_domain' => 'forms',
        ));
    }
}

FormType \地址

class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $countryChoices = $options['country_choices'];
        $builder
            ->add('firstName', TextType::class, array(
                'label' => 'address.first_name',
                'required' => false,
            ))
            ->add('lastName', TextType::class, array(
                'label' => 'address.last_name',
                'required' => false,
            ))
            ->add('line1', TextType::class, array(
                'label' => 'address.line1',
            ))
            ->add('line2', TextType::class, array(
                'label' => 'address.line2'
            ))
            ->add('city', TextType::class, array(
                'label' => 'address.city'
            ))
            ->add('postalCode', TextType::class, array(
                'label' => 'address.postal_code'
            ))
            ->add('country', EntityType::class, array(
                'label' => 'address.country',
                'class' => 'AppBundle:Country',
                'choices' => $countryChoices,
                'choice_label' => 'shortDe',
                'query_builder' => function (EntityRepository $entityRepository) {
                    return $entityRepository->createQueryBuilder('c')
                    ->orderBy('c.shortDe', 'ASC');
                },
            ))
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Address::class,
            'translation_domain' => 'forms',
            'country_choices' => null,
        ));
    }
}

Twig模板:

{{ form_errors(form) }}

        {{ form_start(form) }}
            {{ form_row(form.payment.user.billingAddresses) }}
{{ form_end(form) }}

1 个答案:

答案 0 :(得分:0)

如果集合中只需要一个元素,则无需拥有集合。而不是在表单中使用集合类型,而是直接使用表单类型,并将关系更改为ManyToOne或OneToOne

$builder->add('myEntityProperty', MyNestedType::class);

修改

如果你真的需要一个集合,那么编辑你的setBillingAddresses以接受billingAddresses实例,然后将其作为集合的第一个元素,或者将其推送到数组中

在您的实体中:

...
public function setBillingAddresses(MyBundle\BillingAddresses $billingAddress){
    if($this->billingAddresses->contains($billingAddress)){
      return false;
    }
    $this->billingAddresses[] = $billingAddress;
    /*if this function is on the OneToMany side, or on a ManyToMany mappedBy field,
      you have to call the BillingAddresses function to set or add the current entity*/
}

修改

//User

//...
/**
 * @ORM\OneToMany(targetEntity="Address", mappedBy="user", cascade={"persist", "remove"}, orphanRemoval=true)
 * @Assert\Count(
 *      min = 1,
 *      minMessage = "user.billing_addresses.min",
 *      groups={"test"}
 * )
 * @Assert\Valid
 */
private $billingAddresses;
//...

public function __construct()
{
    //...
    $this->billingAddresses = new ArrayCollection();
    //...
}


/**
 * Add billingAddress
 *
 * @param \AppBundle\Entity\Address $billingAddress
 *
 * @return User
 */
public function addBillingAddress(\AppBundle\Entity\Address $billingAddress)
{
    if($this->billingAddresses->contains($billingAddress)){
        return false;
    }
    $this->billingAddresses[] = $billingAddress;
    $billingAddress->setUser($this);

    return $this;
}

/**
 * Remove billingAddress
 *
 * @param \AppBundle\Entity\Address $billingAddress
 */
public function removeBillingAddress(\AppBundle\Entity\Address $billingAddress)
{
    $this->billingAddresses->removeElement($billingAddress);
}

/**
 * Set billingAddresses
 *
 * @param \AppBundle\Entity\Address $billingAddresses
 *
 * @return User
 * 
 */
public function setBillingAddresses(\AppBundle\Entity\Address $billingAddress)
{

    $this->addBillingAddress($billingAddress);
}

/**
 * Get billingAddresses
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getBillingAddresses()
{
    return $this->billingAddresses;
}
//Address

//...
/**
 * @ORM\ManyToOne(targetEntity="User", mappedBy="billingAddresses")
 */
private $user;
//...

//...
public function setUser(\AppBundle\Entity\User $user)
{

    $this->user = $user;
}

public function getUser()
{
    return $this->user;
}
//...