PHP code example of braunstetter / valid-form-event

1. Go to this page and download the library: Download braunstetter/valid-form-event library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

braunstetter / valid-form-event example snippets

 



namespace App\Form\Paragraph;

use Braunstetter\MediaBundle\Manager\FilesystemManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Image;
use Braunstetter\ValidFormEvent\Form\Event\ValidFormEvent;
use App\Entity\MyCustomPageBlock;

class MyPageBlockType extends AbstractType
{

    private FilesystemManager $filesystemManager;

    public function __construct(FilesystemManager $filesystemManager)
    {
        $this->filesystemManager = $filesystemManager->setFolder('/uploads/images/page_blocks');
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('image', FileType::class, [
                'constraints' => [
                    new Image(['maxSize' => '5M'])
                ]
            ])
            ->add('description')

            // Here is the important part.
            // Inside the 'valid' event you can do whatever you want to.
            ->addEventListener(ValidFormEvent::NAME, function (ValidFormEvent $event) {
                $form = $event->getCurrentForm() ?? $event->getForm();

                if ($image = $form->get('image')->getData()) {
                    $this->filesystemManager->upload($image);
                }
            });

    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => MyCustomPageBlock::class,
        ]);
    }
}