OroCommerce - Symfony: как переопределить сущность (пользовательская учетная запись для регистрации клиентов)

Пытаюсь сделать индивидуальная форма регистрации клиентов

И для этого я должен переопределить эти два файла:

CustomerBundle \ Layout \ DataProvider \ FrontendCustomerUserRegistrationFormProvider.php
и
CustomerBundle \ Form \ Type \ FrontendCustomerUserRegistrationType.php

Итак, я поместил этот код в config / config.yml, и он работает, как ожидалось:

services:
    oro_customer.provider.frontend_customer_user_registration_form:
        class: 'My_Code\Bundle\CustomerBundle\Layout\DataProvider\FrontendCustomerUserRegistrationFormProvider'
        arguments:
            - "@form.factory"
            - "@doctrine"
            - "@oro_config.manager"
            - "@oro_website.manager"
            - "@oro_user.manager"
            - '@router'
        tags:
            - { name: layout.data_provider, alias: oro_customer_frontend_customer_user_register }

    oro_customer.form.type.frontend.customer_user.register:
        class: 'My_Code\Bundle\CustomerBundle\Form\Type\FrontendCustomerUserRegistrationType'
        arguments:
            - '@oro_config.manager'
            - '@oro_user.manager'
        calls:
            - [setDataClass, ['%oro_customer.entity.customer_user.class%']]
        tags:
            - { name: form.type, alias: oro_customer_frontend_customer_user_register }

Но мне также нужно переопределить объект, чтобы он отобразил новый столбец в форме регистрации клиентов.

Я заметил, что у FrontendCustomerUserRegistrationType есть этот код:

calls:
            - [setDataClass, ['%oro_customer.entity.customer_user.class%']]

Так что у CustomerBundle \ Resources \ config \ services.yml это тоже есть:

parameters:
           oro_customer.entity.customer_user.class: Oro\Bundle\CustomerBundle\Entity\CustomerUser

Поэтому я переопределил его с помощью config / config.yml:

parameters:
    oro_customer.entity.customer_user.class: My_Code\Bundle\CustomerBundle\Entity\CustomerUser

Но не работает, выдает ошибку:

The form’s view data is expected to be an instance of class My_Code\Bundle\CustomerBundle\Entity\CustomerUser, but is an instance of class Oro\Bundle\CustomerBundle\Entity\CustomerUser. You can avoid this error by setting the “data_class” option to null or by adding a view transformer that transforms an instance of class Oro\Bundle\CustomerBundle\Entity\CustomerUser to an instance of My_Code\Bundle\CustomerBundle\Entity\CustomerUser.

Я думаю, что из-за этого переопределение FrontendCustomerUserRegistrationType пошло не так и не удалось.

Вот мой переопределенный FrontendCustomerUserRegistrationType.php:

<?php

namespace My_Code\Bundle\CustomerBundle\Form\Type;

use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\CustomerBundle\Entity\CustomerUser;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\UserBundle\Entity\UserManager;
use Symfony\Component\Form\AbstractType;
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\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
use Oro\Bundle\CustomerBundle\Form\Type\FrontendCustomerUserRegistrationType as OroFrontendCustomerUserRegistrationType;

class FrontendCustomerUserRegistrationType extends OroFrontendCustomerUserRegistrationType
{

    /**
     * @var ConfigManager
     */
    protected $configManager;

    /**
     * @param ConfigManager $configManager
     * @param UserManager $userManager
     */
    public function __construct(ConfigManager $configManager, UserManager $userManager)
    {
        parent::__construct($configManager, $userManager);
        $this->configManager = $configManager;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($this->isCompanyNameFieldEnabled()) {
            $builder->add(
                'companyName',
                TextType::class,
                [
                    'required' => true,
                    'mapped' => false,
                    'label' => 'oro.customer.customeruser.profile.company_name',
                    'constraints' => [
                        new Assert\NotBlank(),
                        new Assert\Length(['max' => 255])
                    ],
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.company_name']
                ]
            );
        }

        $builder
            ->add(
                'firstName',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.first_name.label',
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.first_name']
                ]
            )
            ->add(
                'lastName',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.last_name.label',
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.last_name']
                ]
            )
            ->add(
                'email',
                EmailType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.email.label',
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.email']
                ]
            )
            ->add(
                'test',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'Test Label',
                    'attr' => ['placeholder' => 'Test Place Holder']
                ]
            )
            ->add(
                'test2',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'Test2 Label',
                    'attr' => ['placeholder' => 'Test2 Place Holder']
                ]
            )
            ;

        $builder->add(
            'plainPassword',
            RepeatedType::class,
            [
                'type' => PasswordType::class,
                'first_options' => [
                    'label' => 'oro.customer.customeruser.password.label',
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.password']
                ],
                'second_options' => [
                    'label' => 'oro.customer.customeruser.password_confirmation.label',
                    'attr' => ['placeholder' => 'oro.customer.customeruser.placeholder.password_confirmation']
                ],
                'invalid_message' => 'oro.customer.message.password_mismatch',
                'required' => true,
                'validation_groups' => ['create']
            ]
        );

        $this->addBuilderListeners($builder);
    }

    /**
     * @return bool
     */
    private function isCompanyNameFieldEnabled()
    {
        return (bool) $this->configManager->get('oro_customer.company_name_field_enabled');
    }
}

О, и я также создал столбцы успеха 2 «test» и «test2» в таблице «oro_customer_user», используя oro: миграции.

Просто спросите, когда вам нужно проверить еще файл, спасибо за помощь :)

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
0
0
331
1

Ответы 1

Вам также необходимо переопределить метод configureOptions на вашем data_class:

public function configureOptions(OptionsResolver $resolver)
{

    parent::configureOptions($resolver);
    $resolver->setDefault('data_class',  \My_Code\Bundle\CustomerBundle\Entity\CustomerUser::class);
}

Привет, спасибо за ответ, я попробовал это решение и работал drive.google.com/open?id=1JLRrnoMOAbGMvTX33_Xh8vN-xxyb2kNV

fudu 14.11.2018 03:40

привет, ты можешь мне помочь с этим? stackoverflow.com/questions/53373313/…

fudu 19.11.2018 12:17

Другие вопросы по теме