0

public function createGalleryAction(Request $request) {

    $gallery = new Gallery;
    $gallery_form = $this->createFormBuilder($gallery)
            ->add('galleryName', TextType::class, array('label' => 'Gallery Name'))
            ->add('Add', SubmitType::class, array('label' => 'Add', 'attr' => array('class' => 'btn btn-primary')))
            ->getForm();
    $gallery_form->handleRequest($request);
    if ($gallery_form->isValid() && $gallery_form->isSubmitted()) {

        $galleryName = $gallery_form['galleryName']->getData();
        $gallery->setGalleryName($galleryName);

        $em = $this->getDoctrine()->getManager();
        $em->persist($gallery);
        $em->flush();
    }

    return $this->render('admin/addgallery.html.twig', [
                'gallery_form' => $gallery_form->createView()
    ]);
}`**enter code here**`

Please mention where to put the validation code, I'm new to the Symfony..

Pranan Subba
  • 186
  • 3
  • 10

2 Answers2

0
//Entity Gallery

use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity
* @UniqueEntity("galleryName")
*/
class Gallery
{
/**
 *
 * @ORM\Column(name="galleryName", type="string", length=255, unique=true)
 */
protected $galleryName;

// ...
}

https://symfony.com/doc/current/reference/constraints/UniqueEntity.html

if you want to use doctrine:

$galleryName = $gallery_form['galleryName']->getData();

$galleryExist = $em->getRepsitory('AppBundle:Gallery')->findOneByGalleryName($galleryName);
  if($galleryExisty){
   // do something
  }
hous
  • 2,577
  • 2
  • 27
  • 66
0

It actually depends on your database schema. If gallery name is defined as unique (which you should btw, since you want to avoid duplicate names), the $em->flush() would raise an error. Hence, you should encapsulate your code with a try catch statement:

try {
  // add your logic here, ex:
  ...
  ...
  $em->persist($gallery);

} catch(\Exception $ex) {

 // do whatever you want with your error here, ex:
 $session->getFlashBag()->add('error', 'Gallery already exists');
 return $this->render('admin/addgallery.html.twig', [
            'gallery_form' => $gallery_form->createView()
 ]);

}
billias
  • 775
  • 7
  • 17