Symfony3.4:动态注册表

时间:2018-03-05 13:22:55

标签: php symfony registration symfony-3.4

我对Symfony有点新意,所以我在动态表单上非常努力。 我正在尝试将用户保存在数据库中,并在表单提交时对其地址进行地理编码。

这是我的用户实体:

<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     *
     * @Assert\NotBlank(message="Veuillez inscrire votre prénom.", groups={"Registration", "Profile"})
     * @Assert\Length(
     *     min=3,
     *     max=255,
     *     minMessage="The name is too short.",
     *     maxMessage="The name is too long.",
     *     groups={"Registration", "Profile"}
     * )
     */
    protected $firstname;

    /**
     * @var string
     *
     * @ORM\Column(name="lastname", type="string", length=255,nullable=true)
     */
    protected $lastname;

    /**
     * @var string
     *
     * @ORM\Column(name="address", type="string", length=255, nullable=true)
     */
    protected $address;

    /**
     * @var string
     *
     * @ORM\Column(name="zipcode", type="string", length=10, nullable=true)
     */
    protected $zipcode;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string", length=255, nullable=true)
     */
    protected $city;

    /**
     * @var string
     *
     * @ORM\Column(name="country", type="string", length=255, nullable=true)
     */
    protected $country;

    /**
     * @var string
     *
     * @ORM\Column(name="latitude", type="string", length=255, nullable=true)
     */
    protected $latitude;

    /**
     * @var string
     *
     * @ORM\Column(name="longitude", type="string", length=255, nullable=true)
     */
    protected $longitude;


    public function __construct()
    {
        parent::__construct();

        $this->enabled = false;
        $this->roles = array();
        $this->inscriptiondate = new \Datetime();
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * Set latitude
     *
     * @param string $lat
     *
     * @return User
     */
    public function setLatitude($latitude)
    {
        $this->latitude = $latitude;

        return $this;
    }

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

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

        return $this;
    }

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

这是我的注册表格:

<?php
// src/AppBundle/Form/RegistrationType.php

namespace AppBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use UserBundle\Repository\GenderRepository;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

use Doctrine\ORM\EntityRepository;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('firstname', TextType::class, array(
                'label' => 'First name'))
            ->add('lastname', TextType::class, array(
                'label' => 'Last name'))
            ->add('address')
            ->add('zipcode')
            ->add('city')
            ->add('country');

        $builder->addEventListener(
            FormEvents::SUBMIT,
            function (FormEvent $event) {
                $form = $event->getForm();

                $data = $event->getForm()->getData();

                $address = $data->getAddress();
                $zipcode = $data->getZipCode();
                $city = $data->getCity();
                $country = $data->getCountry();
                $fulladdress = urlencode($address)."+".$zipcode."+".$city."+".$country;
                $geocode = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$fulladdress.'&key=KEY');
                $output = json_decode($geocode);
                $latitude = $output->results[0]->geometry->location->lat;
                $longitude = $output->results[0]->geometry->location->lng;

                dump($fulladdress); // Works fine, I see full address in dump

                $form->add('latitude', HiddenType::class, array('data' => $latitude))
                     ->add('longitude', HiddenType::class, array('data' => $longitude)); // Does not save data in database
            }
        );
    } 

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }
}

对于第一次测试,我在 $ builder-&gt; addEventListener(FormEvents :: PRE_SET_DATA,function(FormEvent $ event)中写了一个静态地址,它再次正常工作,geocode看起来不错。< / p>

当我尝试从表单输入动态获取地址并显示表单时,我得到: 错误:在null

上调用成员函数getAddress()

看起来 $ address = $ data-&gt; getAddress(); 返回NULL,因为我们正在查看 FormEvents :: PRE_SET_DATA ,因为表单尚未提交。我试图玩其他事件,但无法使其工作。

当我尝试将其放入 FormEvents :: PRE_SUBMIT 时,表单显示正常但在提交时我得到: 错误:调用数组

上的成员函数getAddress()

当我尝试将其放入 FormEvents :: SUBMIT 时,表单显示正常,submition正常,没有错误,但数据库中的纬度和经度列为NULL。

我还尝试过 $ address = $ data ['address']; 而不是 $ address = $ data-&gt; getAddress(); ,但不是更好。

这只是我的第二个symfony项目,所以不是专家。 我错过了什么? 任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

问题在于:

            $form = $event->getForm();
            $data = $form ->getData();

您应该从表单加载数据。

您收到的地址错误并不意味着GetAddress()返回null$datanull且您无法访问成员一个null变量。

修改:

与评论中的链接相同的链接:

            // It's important here to fetch $event->getForm()->getData(), as
            // $event->getData() will get you the client data (that is, the ID)
            $sport = $event->getForm()->getData();