Symfony,从提交的表单生成 slug
Symfony, generate slug from submitted form
我有这个表单,我想修改它以添加一个 slug 字段,该字段应该从用户提交的数据中生成。
喜欢用户选择的类别(名称)和内容中的随机词,我还使用 Slugify 清理网址:
有什么想法吗?
$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();
您只需将映射信息添加到 slug 字段的实体而不是表单,然后使用 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()));
}
或者您可以像@Alexander Br 一样使用学说扩展。已发布
我有这个表单,我想修改它以添加一个 slug 字段,该字段应该从用户提交的数据中生成。
喜欢用户选择的类别(名称)和内容中的随机词,我还使用 Slugify 清理网址:
有什么想法吗?
$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();
您只需将映射信息添加到 slug 字段的实体而不是表单,然后使用 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()));
}
或者您可以像@Alexander Br 一样使用学说扩展。已发布