Попытка отправить форму и загрузить медиа с помощью formType symfony 3.4

Здравствуйте, я работаю над формой, мне нужно загрузить медиа из этой формы, используя FormType. Сейчас я просто хочу напечатать отправленные данные, но я получаю эту ошибку.

Ожидается аргумент типа "Приложение \ Соната \MediaBundle\Entity\Media или null", "Symfony\Component\HttpFoundation\File\UploadedFile"

Ниже мой код

Моя сущность

В этой организации я имею отношение к СМИ.

            <?php

        namespace CMS\DesignsBundle\Entity;

        use CMS\BaseBundle\Entity\BaseEntity;
        use Doctrine\ORM\Mapping as ORM;
        use Symfony\Component\Validator\Constraints as Assert;
        use Symfony\Component\HttpFoundation\File\File;

        /**
         * DesignsFiles
         *
         * @ORM\Table(name="teo_designs_files")
         * @ORM\Entity(repositoryClass="CMS\DesignsBundle\Repository\DesignsFilesRepository")
         */
        class DesignsFiles extends BaseEntity
        {
            /**
             * @var int
             *
             * @ORM\Column(name="id", type="integer")
             * @ORM\Id
             * @ORM\GeneratedValue(strategy="AUTO")
             */
            protected $id;
            /**
             * @var string
             * @Assert\NotBlank()
             * @ORM\Column(name="title", type="string", length=255)
             */
            protected $title;
            /**
             * @ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"})
             * @ORM\JoinColumn(name="media_id", referencedColumnName="id" , onDelete="SET NULL",nullable=true)
             */
            protected $media;

            /**
             * @var int
             * Many Designs have One User.
             * @ORM\ManyToOne(targetEntity="CMS\FrontUserBundle\Entity\FrontUser", inversedBy="designs")
             * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
             */
            protected $userId;

            /**
             * @var bool
             *
             * @ORM\Column(name="is_shortlisted", type="boolean")
             */
            protected $isShortlisted;

            /**
             * @var \DateTime
             *
             * @ORM\Column(name="shortlisted_date", type="date",nullable=true))
             */
            protected $shortlistedDate;


            /**
             * Set title.
             *
             * @param string $title
             *
             * @return DesignsFiles
             */
            public function setTitle($title)
            {
                $this->title = $title;

                return $this;
            }

            /**
             * Get title.
             *
             * @return string
             */
            public function getTitle()
            {
                return $this->title;
            }

            /**
             * Set isShortlisted.
             *
             * @param bool $isShortlisted
             *
             * @return DesignsFiles
             */
            public function setIsShortlisted($isShortlisted)
            {
                $this->isShortlisted = $isShortlisted;

                return $this;
            }

            /**
             * Get isShortlisted.
             *
             * @return bool
             */
            public function getIsShortlisted()
            {
                return $this->isShortlisted;
            }

            /**
             * Set shortlistedDate.
             *
             * @param \DateTime|null $shortlistedDate
             *
             * @return DesignsFiles
             */
            public function setShortlistedDate($shortlistedDate = null)
            {
                $this->shortlistedDate = $shortlistedDate;

                return $this;
            }

            /**
             * Get shortlistedDate.
             *
             * @return \DateTime|null
             */
            public function getShortlistedDate()
            {
                return $this->shortlistedDate;
            }

            /**
             * Set media.
             *
             * @param \Application\Sonata\MediaBundle\Entity\Media|null $media
             *
             * @return DesignsFiles
             */
            public function setMedia(\Application\Sonata\MediaBundle\Entity\Media $media = null)
            {
                $this->media = $media;

                return $this;
            }

            /**
             * Get media.
             *
             * @return \Application\Sonata\MediaBundle\Entity\Media|null
             */
            public function getMedia()
            {
                return $this->media;
            }

            /**
             * Set userId.
             *
             * @param \CMS\FrontUserBundle\Entity\FrontUser|null $userId
             *
             * @return DesignsFiles
             */
            public function setUserId(\CMS\FrontUserBundle\Entity\FrontUser $userId = null)
            {
                $this->userId = $userId;

                return $this;
            }

            /**
             * Get userId.
             *
             * @return \CMS\FrontUserBundle\Entity\FrontUser|null
             */
            public function getUserId()
            {
                return $this->userId;
            }
        }

Мой FormType

            <?php

        namespace CMS\FrontUserBundle\Form;

        use CMS\DesignsBundle\Entity\DesignsFiles;
        use Symfony\Component\Form\AbstractType;
        use Symfony\Component\Form\FormBuilderInterface;
        use Symfony\Component\OptionsResolver\OptionsResolver;
        use Symfony\Component\Form\Extension\Core\Type\SubmitType;
        use Symfony\Component\Form\Extension\Core\Type\FileType;

        class UploadDesignType extends AbstractType {
            /**
             * @param FormBuilderInterface $builder
             * @param array $options
             */
            public function buildForm( FormBuilderInterface $builder, array $options ) {
                $builder
                    ->add( 'title', 'text', array(
                        'label' => 'Title of your design:',
                        'attr'  => array(
                            'class'       => 'form-control',
                            'placeholder' => 'Design Title'
                        ),
                    ) )
                    ->add( 'media', FileType::class, array(
                        'label' => 'Upload File: Max Size: 5MB   Format: PNG,PDF,JPG',
                        'attr'  => array(
                            'class'       => 'form-control btn blackbtn mt-0',
                            'placeholder' => 'Upload Design'
                        ),
                    ) )
                    ->add('save', SubmitType::class, array(
                        'label' => 'Submit',
                        'attr' => array(
                            'class' => 'btn greeninvbtn',
                        ),
                    ))
                ;
            }

            /**
             * @param OptionsResolver $resolver
             */
            public function configureOptions( OptionsResolver $resolver ) {
                $resolver->setDefaults( array(
                    'data_class' => DesignsFiles::class,
                ) );
            }

        }

Мой контроллер

                <?php

            namespace CMS\FrontUserBundle\Controller;
            use CMS\DesignsBundle\Entity\DesignsFiles;
            use CMS\FrontUserBundle\Entity\FrontUser;
            use Symfony\Component\HttpFoundation\Session\Session;
            use Symfony\Bundle\FrameworkBundle\Controller\Controller;
            use CMS\BaseBundle\Controller\BaseController;
            use Symfony\Component\Form\FormError;
            use CMS\FrontUserBundle\Form\UploadDesignType;
            use Symfony\Component\HttpFoundation\Request;
            class DashboardController extends BaseController
            {
                public function UploadDesignsAction(Request $request)
                {
                    $designFile = new DesignsFiles();
                    $form = $this->createForm(UploadDesignType::class, $designFile);
                    $form->handleRequest($request);
                    $data = $form->getData();
                    dump($data);
                    if ($request->getMethod() == "POST" && $form->isSubmitted() && $form->isValid()) {
//Here I will upload media but right now it's not getting inside.
                        $file = $designFile->getMedia();
                        $media = $this->uploadMediaAction($file);
                        dump($media);
                        dump($file);
                        dump($data);
                        die('chk');
                    }

                    $formData = array('page' => '', 'object' => '', 'form' => $form->createView());
                    return $this->render('FrontUserBundle/User/upload_designs.html.twig', $formData);
                }

            }

Функция UploadMediaAction написана в моем BaseController, который

        public function uploadMediaAction($file)
        {
            $MediaErrors = array();
            $MediaErrors['error'] = false;

            if (!$file instanceof UploadedFile) {
                $MediaErrors['message'] = ['Missing file.'];
                $MediaErrors['error'] = true;
            } else {
                $AllowedMimetypesImagesAndFile = array(
                    'image/jpeg',
                    'image/png',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/msword',
                    'application/pdf',
                    'application/x-pdf'
                );
                if (!in_array($file->getMimeType(), $AllowedMimetypesImagesAndFile)) {
                    $MediaErrors['message'] = ['Invalid file/image.'];
                    $MediaErrors['error'] = true;
                }
                if (!$MediaErrors['error']) {
                    $mediaManager = $this->container->get('sonata.media.manager.media');
                    $media = new Media();
                    $media->setBinaryContent($file);
                    $media->setContext('default');
                    $ImagemimeTypes = array('image/jpeg', 'image/png');
                    $FilemimeTypes = array(
                        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                        'application/msword',
                        'application/pdf',
                        'application/x-pdf'
                    );
                    if (in_array($file->getMimeType(), $FilemimeTypes)) {
                        $media->setProviderName('sonata.media.provider.file');
                    }
                    if (in_array($file->getMimeType(), $ImagemimeTypes)) {
                        $media->setProviderName('sonata.media.provider.image');
                    }
                    $media->setEnabled(true);
                    $mediaManager->save($media);
                    $MediaErrors['media'] = $media;
                }
            }

            return $MediaErrors;
        }

Я новичок в Symfony, пожалуйста, помогите мне найти решение.

0 ответов

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