Search code examples
phpformssymfonysecurityslugify

Symfony, generate slug from submitted form


I have this form which I want to modify in order to add a slug field which should be generated from user submitted data.

Like user chosen category (name), and random words from content, and I'm also using Slugify for cleaning up URLs:

Any idea?

 $u = $this->getUser();
 $sl = new Slugify();
 $task = new AdsList();
 $task->setPostXpr(new \DateTime('+1 month'));
 $task->setSlug($ans);
 $task->setPostedBy($u);
 $form = $this->createFormBuilder($task)
     ->add('title', TextType::class)
     ->add('content', TextareaType::class)
     ->add('category', EntityType::class, array(
         // query choices from CategoryAd.Name
         'class' => 'AppBundle:CategoryAd',
         'choice_label' => 'name',
     ))
     ->add('postXpr', DateType::class, array(
         'widget' => 'single_text',
         // this is actually the default format for single_text
         'format' => 'yyyy-MM-dd',
         'label' => 'Post Expire',
     ))
     ->add('save', SubmitType::class, array('label' => 'Create Post'))
        ->getForm();

Solution

  • You just need to add the mapping information to the entity for the slug field but not to the form and then use the cocur/slugify

    Using cocur

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity->setSlug($this->get('cocur_slugify')->slugify($entity->getName()));
        $em->persist($entity);
        $em->flush();
        return $this->redirectToRoute('my_route_to_redirect', array('slug' => $entity->getSlug()));
            }
    

    Or you could use doctrine extensions as @Alexander Br. posted