来自自定义字段的symfony2 FOSUserBundle数据不会写入数据库

时间:2015-03-04 10:37:56

标签: php symfony fosuserbundle

我阅读了很多次覆盖的文档,但我仍然不知道为什么这段代码不起作用。自定义字段 - 包工作但数据不保存在数据库中。

公司\ UserBundle \表格\型号\ RegistrationFormType.php

namespace Company\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\EntityRepository;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('phoneNumber', 'text', array('label' => 'Numer telefonu(opcjonalnie)', 'required' => false))
            ->add('package', 'integer', array('label' => 'Pakiet', 'required' => false ));

    }

    public function getParent()
    {
        return 'fos_user_registration';
    }

    public function getName()
    {
        return 'company_user_registration';
    }
}

注册控制器是默认的。

<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register m-signup--form">
        <h2>Zarejestruj się</h2>
        <ul class="errorLog">
        <div class="field">
            <label for="fos_user_registration_form_email">Email</label>
            {{ form_widget(form.email) }}
        </div>
        <div class="field">
            <label for="fos_user_registration_form_username">Login</label>
            {{ form_widget(form.username) }}
        </div>
        <div class="field">
            {{ form_widget(form.plainPassword) }}
        </div>
        <div class="field">
            <label for="fos_user_registration_form_phoneNumber">Numer telefonu <span>(opcjonalnie)</span></label>
            {{ form_widget(form.phoneNumber) }}
        </div>
        <div class="field">
            <label for="fos_user_registration_form_package">Pakiet</label>
            {{ form_widget(form.package) }}
        </div>
            <span>{{ form_widget(form) }}</span>
        <input type="submit" class="btn btn-dark" style="font-weight: bold;" value="Zarejestruj się" />
    </form>

我会感激任何帮助。

公司\ UserBundle \实体\ user.php的

namespace Company\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="company_user")
 */
class User extends BaseUser
{

/**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @ORM\Column(type="integer", name="phone_number", nullable = true)
     */
    public $phoneNumber;

    /**
     * @ORM\Column(type="integer", name="package")
     */
    public $package;

    /**
     * @return mixed
     */
    public function getPackage()
    {
        return $this->package;
    }

    /**
     * @param mixed $package
     */
    public function setPackage($package)
    {
        $this->package = $package;
    }

    /**
     * @return mixed
     */
    public function getPhoneNumber()
    {
        return $this->phoneNumber;
    }

    /**
     * @param mixed $phoneNumber
     */
    public function setPhoneNumber($phoneNumber)
    {
        $this->phoneNumber = $phoneNumber;
    }

     ...

应用\设置\ config.yml

fos_user:
    db_driver: orm 
    firewall_name: main
    user_class: Company\UserBundle\Entity\User
    registration:
        confirmation:
            enabled: true
        form:
            type: company_user_registration

公司\ UserBundle \资源\配置\ services.yml

services:
    company_user.password_resetting:
        class: Company\UserBundle\EventListener\RegistrationCompleteListener
        arguments: [@router, @doctrine.orm.entity_manager, @templating]
        tags:
            - { name: kernel.event_subscriber }
    company_user.registration.form.type:
            class: Company\UserBundle\Form\Type\RegistrationFormType
            tags:
                - { name: form.type, alias: company_user_registration }

RegistrationController.php

class RegistrationController extends Controller
{
    public function registerAction(Request $request)
    {
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

            $user = $userManager->createUser();
            $user->setEnabled(true);

            $event = new GetResponseUserEvent($user, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

            if (null !== $event->getResponse()) {
                return $event->getResponse();
            }

            $form = $formFactory->createForm();
            $form->setData($user);
            $form->handleRequest($request);

            if ($request->getMethod() == 'POST') {
                $form->bind($request);

                if ($form->isValid()) {
                    $event = new FormEvent($form, $request);
                    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

                    $userManager->updateUser($user);

                    if (null === $response = $event->getResponse()) {

                        $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
                        $response = new RedirectResponse($url);
                    }

                    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                    return $response;
                } else {
                    header('Content-Type: application/json');
                    $errors = array();
                    $errors = $this->getErrorMessages($form);
                    $errors["status"] = "error";
                    return new Response(json_encode($errors));
                }
            }
            return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.' . $this->getEngine(), array(
                'form' => $form->createView(),
            ));

        }
        //Listowanie błędów
        private function getErrorMessages(\Symfony\Component\Form\Form $form) {
            $errors = array();
            foreach ($form->getErrors() as $key => $error) {
                $template = $error->getMessageTemplate();
                $parameters = $error->getMessageParameters();

                foreach ($parameters as $var => $value) {
                    $template = str_replace($var, $value, $template);
                }

                $errors[$key] = $template;
            }
            if ($form->count()) {
                foreach ($form as $child) {
                    if (!$child->isValid()) {
                        $errors[$child->getName()] = $this->getErrorMessages($child);
                    }
                }
            }
            return $errors;
        }

        /**
         * Tell the user to check his email provider
         */
        public function checkEmailAction()
        {

            $email = $this->container->get('session')->get('fos_user_send_confirmation_email/email');
            $this->container->get('session')->remove('fos_user_send_confirmation_email/email');
            $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);

            if (null === $user) {
                throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
            }

            return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:checkEmail.html.' . $this->getEngine(), array(
                'user' => $user,
            ));
        }

        /**
         * Receive the confirmation token from user email provider, login the user
         */
        public function confirmAction(Request $request, $token)
        {
            /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
            $userManager = $this->container->get('fos_user.user_manager');

            $user = $userManager->findUserByConfirmationToken($token);

            if (null === $user) {
                throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
            }

            /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
            $dispatcher = $this->container->get('event_dispatcher');

            $user->setConfirmationToken(null);
            $user->setEnabled(true);

            $event = new GetResponseUserEvent($user, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

            $userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
                $response = new RedirectResponse($url);
            }

            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

            return $response;
        }

        /**
         * Tell the user his account is now confirmed
         */
        public function confirmedAction()
        {
            $user = $this->container->get('security.context')->getToken()->getUser();
            if (!is_object($user) || !$user instanceof UserInterface) {
                throw new AccessDeniedException('This user does not have access to this section.');
            }

            $url = $this->container->get('router')->generate('static_user_add_first');
            $response = new RedirectResponse($url);

            return $response;
        }

        protected function getEngine()
        {
            return $this->container->getParameter('fos_user.template.engine');
        }
    }

2 个答案:

答案 0 :(得分:0)

你有没有configure FOSUser(config.yml)?

# app/config/config.yml
fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: YourApp\UserBundle\Entity\User #path to your custom User entity

此外,您的表单是否包含以下方法?

public function getParent()
{
    return 'fos_user_registration';
}

public function getName()
{
    return 'yourapp_user_registration';
}

您构建表单的方式为我提供了有关错误配置的提示。您正在尝试添加FOSUser提供的注册表单中已存在的字段。

您的buildForm方法更可能如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder->add('phoneNumber', 'text',  array('label' => 'Numer telefonu(opcjonalnie)', 'required' => false))
        ->add('package', 'text', array('label' => 'Pakiet', 'required' => false ));
}

要完成这项工作,您必须将表单设为服务:

services:
    yourapp_user.registration.form.type:
        class: Path\To\Your\RegistrationFormType
        tags:
            - { name: form.type, alias: yourapp_user_registration }

将config.yml链接到所述服务:

fos_user:
    # ...
    registration:
        form:
            type: yourapp_user_registration 

答案 1 :(得分:0)

万岁!!我终于找到了! 问题出在Listener中的onRegistrationSuccess函数中。以前的程序员在那里调用带有静态值的setPackage函数。当我删除它都开始工作。

GrégoryElhaimer非常感谢您的参与和帮助。你很棒!