장바구니 지우기 | Symfony로 장바구니 만들기
장바구니의 제거 버튼과 같은 방법으로 장바구니의 지우기 버튼을 관리하기 위해 폼 이벤트를 사용할 것입니다.
이벤트 구독자 만들기
Create a ClearCartListener
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 ClearCartListener implements EventSubscriberInterface
{
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [FormEvents::POST_SUBMIT => 'postSubmit'];
}
/**
* Removes all items from the cart when the clear button is clicked.
*
* @param FormEvent $event
*/
public function postSubmit(FormEvent $event): void
{
$form = $event->getForm();
$cart = $form->getData();
if (!$cart instanceof Order) {
return;
}
// Is the clear button clicked?
if (!$form->get('clear')->isClicked()) {
return;
}
// Clears the cart
$cart->removeItems();
}
}
The current cart is available from the main form by using the FormEvent::getData()
method. It should be an instance of an Order
entity.
If the Clear button has been clicked, we remove all items from the cart. In other words, we clear the cart.
이벤트 가입자 등록
To register the CleartCartListener
subscriber to the CartType
form, use the addEventListener
method using the form builder:
<?php
namespace App\Form;
use App\Entity\Order;
use App\Form\EventListener\ClearCartListener;
use App\Form\EventListener\RemoveItemListener;
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 RemoveItemListener());
$builder->addEventSubscriber(new ClearCartListener());
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Order::class,
]);
}
}
Of course, you can merge the two listeners into one but the goal was to show you how to use the form events to dynamically modify form data.
At this point, we have managed all the cart features, but there is still some work to be done. Let's go to the next step, it's almost done.
Reference
이 문제에 관하여(장바구니 지우기 | Symfony로 장바구니 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/qferrer/clearing-the-cart-building-a-shopping-cart-with-symfony-3o90텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)