Symfony - Orocommerce: ожидается, что данные представления формы будут экземпляром Entity

Я пытаюсь переопределить форму / тип в Symfony-Orocommerce, и сначала я получил эту ошибку:

Cannot read index "namePrefix" from object of type "Oro\CustomerBundle\Entity\CustomerUser" because it doesn't implement \ArrayAccess.

И после того, как я следил за эта почта, у меня появилась еще одна ошибка, которую я не могу решить :(

The form's view data is expected to be an instance of class MyCode\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 ...

Вот мой код:

MyCode\Bundle\CustomerBundle\Controller\CustomerUserController.php

<?php

namespace MyCode\Bundle\CustomerBundle\Controller;

use Oro\Bundle\CustomerBundle\Entity\CustomerUser;
use MyCode\Bundle\CustomerBundle\Entity\CustomerUser as MyCodeCustomerUser;
use Oro\Bundle\CustomerBundle\Form\Handler\CustomerUserHandler;
use Oro\Bundle\CustomerBundle\Form\Type\CustomerUserType;
use MyCode\Bundle\CustomerBundle\Form\Type\CustomerUserType as MyCodeCustomerUserType;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\SecurityBundle\Annotation\Acl;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Oro\Bundle\CustomerBundle\Controller\CustomerUserController as OroCustomerUserController;
use Doctrine\ORM\EntityManager;
use Psr\Log\LoggerInterface;

class CustomerUserController extends Controller
{
   //some code
   /**
     * Edit customer user form
     *
     * @Route("/update/{id}", name = "oro_customer_customer_user_update", requirements = {"id" = "\d+"})
     * @Template
     * @Acl(
     *      id = "oro_customer_customer_user_update",
     *      type = "entity",
     *      class = "OroCustomerBundle:CustomerUser",
     *      permission = "EDIT"
     * )
     * @param CustomerUser $customerUser
     * @param Request     $request
     * @return array|RedirectResponse
     */
    public function updateAction(CustomerUser $customerUser, Request $request)
    {
        return $this->update($customerUser, $request);
    }

    /**
     * @param CustomerUser $customerUser
     * @param Request     $request
     * @return array|RedirectResponse
     */
    protected function update(CustomerUser $customerUser, Request $request)
    {
        $form = $this->createForm(MyCodeCustomerUserType::class, $customerUser);
        $handler = new CustomerUserHandler(
            $form,
            $request,
            $this->get('oro_customer_user.manager'),
            $this->get('oro_security.token_accessor'),
            $this->get('translator'),
            $this->get('logger')
        );

        $result = $this->get('oro_form.model.update_handler')->handleUpdate(
            $customerUser,
            $form,
            function (CustomerUser $customerUser) {
                return [
                    'route'      => 'oro_customer_customer_user_update',
                    'parameters' => ['id' => $customerUser->getId()]
                ];
            },
            function (CustomerUser $customerUser) {
                return [
                    'route'      => 'oro_customer_customer_user_view',
                    'parameters' => ['id' => $customerUser->getId()]
                ];
            },
            $this->get('translator')->trans('oro.customer.controller.customeruser.saved.message'),
            $handler
        );

        return $result;
    }
}

Здесь я изменил CustomerUserType на MyCodeCustomerUserType, вот и все.

CustomerBundle\Resources\config\services.yml

parameters:
  mycode_customer.entity.customer_user.class: MyCode\Bundle\CustomerBundle\Entity\CustomerUser

services:
  mycode.form.type.customer_user:
      class: 'MyCode\Bundle\CustomerBundle\Form\Type\CustomerUserType'
      arguments:
            - '@security.authorization_checker'
            - '@oro_security.token_accessor'
      calls:
            - [setDataClass, ['%mycode_customer.entity.customer_user.class%']]
            - [setAddressClass, ['%oro_customer.entity.customer_user_address.class%']]
      tags:
            - { name: form.type, alias: mycode_customer_customer_user }

MyCode\Bundle\CustomerBundle\Form\Type\CustomerUserType.php

<?php

namespace MyCode\Bundle\CustomerBundle\Form\Type;

use Oro\Bundle\AddressBundle\Form\Type\AddressCollectionType;
use MyCode\Bundle\CustomerBundle\Entity\CustomerUser as MyCodeCustomerUser;
use Oro\Bundle\CustomerBundle\Entity\Repository\CustomerUserRoleRepository;
use Oro\Bundle\FormBundle\Form\Type\OroDateType;
use Oro\Bundle\SecurityBundle\Authentication\TokenAccessorInterface;
use Oro\Bundle\CustomerBundle\Form\Type\CustomerSelectType;
use Oro\Bundle\UserBundle\Form\Type\UserMultiSelectType;
use Oro\Bundle\CustomerBundle\Form\Type\CustomerUserTypedAddressType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
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\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Oro\Bundle\CustomerBundle\Form\Type\CustomerUserType as OroCustomerUserType;

class CustomerUserType extends OroCustomerUserType
{
    /**
     * @param FormBuilderInterface $builder
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function addEntityFields(FormBuilderInterface $builder)
    {
        $builder
            ->add(
                'namePrefix',
                TextType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.name_prefix.label'
                ]
            )
            ->add(
                'firstName',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.first_name.label'
                ]
            )
            ->add(
                'middleName',
                TextType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.middle_name.label'
                ]
            )
            ->add(
                'lastName',
                TextType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.last_name.label'
                ]
            )
            ->add(
                'nameSuffix',
                TextType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.name_suffix.label'
                ]
            )
            ->add(
                'email',
                EmailType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.email.label'
                ]
            )
            ->add(
                'customer',
                CustomerSelectType::class,
                [
                    'required' => true,
                    'label' => 'oro.customer.customeruser.customer.label'
                ]
            )
            ->add(
                'enabled',
                CheckboxType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.enabled.label',
                ]
            )
            ->add(
                'birthday',
                OroDateType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.birthday.label',
                ]
            )
            ->add(
                'salesRepresentatives',
                UserMultiSelectType::class,
                [
                    'label' => 'oro.customer.customer.sales_representatives.label',
                ]
            )
            ->add(
                'isGuest',
                CheckboxType::class,
                [
                    'required' => false,
                    'label' => 'oro.customer.customeruser.is_guest.label',
                ]
            );


        if ($this->authorizationChecker->isGranted('oro_customer_customer_user_role_view')) {
            $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'preSetData']);
            $builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmit']);
        }

        if ($this->authorizationChecker->isGranted('oro_customer_customer_user_address_update')) {
            $options = [
                'label' => 'oro.customer.customeruser.addresses.label',
                'entry_type' => CustomerUserTypedAddressType::class,
                'required' => false,
                'entry_options' => [
                    'data_class' => $this->addressClass,
                    'single_form' => false,
                ],
            ];

            if (!$this->authorizationChecker->isGranted('oro_customer_customer_user_address_create')) {
                $options['allow_add'] = false;
            }

            if (!$this->authorizationChecker->isGranted('oro_customer_customer_user_address_remove')) {
                $options['allow_delete'] = false;
            }

            $builder
                ->add(
                    'addresses',
                    AddressCollectionType::class,
                    $options
                );
        }

        $builder->add(
                    'test',
                    TextType::class, 
                    [
                        'mapped' => false,
                        'required'  => false,
                        'label'     => 'Test',
                        'attr' => ['placeholder' => 'Test']
                    ]
                );

Спасибо за чтение, хорошего дня :)

Стоит ли изучать 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 и хотите разрабатывать...
1
0
493
1

Ответы 1

Я думаю, что нашел решение, я не заметил, что updateAction () в контроллере использует (CustomerUser $ customerUser) вместо (MyCodeCustomerUser $ customerUser), поэтому это вызывает проблему, а после исправления это вызывает другую проблему.
Пожалуйста, проверьте эта ссылка для получения дополнительной информации.

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