장바구니에서 제품 제거 | Symfony로 장바구니 만들기

  • Creating the Event Subscriber
  • Registering the Event Subscriber



  • 지금까지는 제거 버튼이 효과가 없습니다. 제출 버튼이 여러 개 있고 기본 버튼이 저장이므로 제거 버튼이 클릭되었는지 확인하고 사용자가 장바구니에서 제거하려는 제품을 제거하여 장바구니를 다시 주문해야 합니다.

    제출된 데이터를 기반으로 양식 데이터(이 경우 Order 엔터티)를 수정하려면 Form Events 을 사용하는 것이 가장 좋습니다. 그렇게 하려면 이벤트 구독자 클래스를 만들고 FormEvents::POST_SUBMIT 이벤트를 구독하고 장바구니를 재정렬해야 합니다.

    이벤트 구독자 만들기

    Create a RemoveCartItemListener subscriber and subscribe to the FormEvents::POST_SUBMIT event:

    <?php
    
    namespace App\Form\EventListener;
    
    use App\Entity\Order;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\Form\FormEvent;
    use Symfony\Component\Form\FormEvents;
    
    /**
     * Class RemoveCartItemListener
     * @package App\Form\EventListener
     */
    class RemoveCartItemListener implements EventSubscriberInterface
    {
        /**
         * @inheritDoc
         */
        public static function getSubscribedEvents(): array
        {
            return [FormEvents::POST_SUBMIT => 'postSubmit'];
        }
    
        /**
         * Removes items from the cart based on the data sent from the user.
         *
         * @param FormEvent $event
         */
        public function postSubmit(FormEvent $event): void
        {
            $form = $event->getForm();
            $cart = $form->getData();
    
            if (!$cart instanceof Order) {
                return;
            }
    
            // Removes items from the cart
            foreach ($form->get('items')->all() as $child) {
                if ($child->get('remove')->isClicked()) {
                    $cart->removeItem($child->getData());
                    break;
                }
            }
        }
    }
    
    

    The postSubmit() method will be invoked after the form is submitted. This will allow us to manipulate the form data mapped with the submitted data.

    The current cart is available from the main form by using the FormEvent::getData() method. It should be an instance of an Order entity.

    For each item field, we check if a Remove button has been clicked by the user with the button's isClicked() method. If so, we get the OrderItem entity by using the form field's getData() method and remove it from the current cart.

    Now, we need to register this event subscriber to the CartType form.

    이벤트 가입자 등록

    To register the RemoveCartItemListener subscriber to the CartType form, use the addEventListener method of the builder in the form type class:

    <?php
    
    namespace App\Form;
    
    use App\Entity\Order;
    use App\Form\EventListener\RemoveCartItemListener;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    
    class CartType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('items', CollectionType::class, [
                    'entry_type' => CartItemType::class
                ])
                ->add('save', SubmitType::class)
                ->add('clear', SubmitType::class);
    
            $builder->addEventSubscriber(new RemoveCartItemListener());
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'data_class' => Order::class,
            ]);
        }
    }
    

    That's all. Nothing to do in the CartController because we added the logic in the form. Now you are familiar with the form events, let's do the same to clear the cart.

    좋은 웹페이지 즐겨찾기