I would like to have an url like this one:
www.mysite.com/my-super-blog-post
Instead of this one:
www.mysite.com/7
Where '7' is the id property of my News object.
When I see at the Symfony documentation I think I need to use this line of code:
$this->generateUrl('blog_show', array('slug' => 'my-blog-post'), UrlGeneratorInterface::ABSOLUTE_URL);
Is it right ? What I do not understand is where do I need to use that line of code ? In my NewsController.php file ?
Or maybe you can give me a link to read about a solution.
Edit I use Symfony 3.2
Ok I've found the solution by my self. Here it is what I did.
Firstly read this from the symfony doc. Use ConvertParamater It is really easy to implement http://symfony.com/doc/current/best_practices/controllers.html#using-the-paramconverter
After you have implemented it:
Install StofDoctrineExtensionBundle
in composer.json
"require": { "stof/doctrine-extensions-bundle": "~1.1" }
Don't forget to update the appKernel.php file
<?php
// app/AppKernel.php
public function registerBundles()
{
return array(
// …
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
// …
);
}
Then I configure the config.yml file:
# app/config/config.yml
# Stof\DoctrineExtensionsBundle configuration
stof_doctrine_extensions:
orm:
default:
sluggable: true
Then I add a slug property to my News Entity:
private $slug;
Then I update my News.orm.yml file slug: type: string length: 255 unique: false gedmo: slug: separator: _ style: camel fields: - title
Then I do
doctrine:generate:entites myBundle:News
And also `doctrine:schema:update --force
This created a slug field in my News table. Because this field may not be null, I have manually entered some value so each row of my News table has a valid slug
Then in my NewsController I use this line of code:
$this->generateUrl('myroute_news_show_one_by_id', array('slug' => $news->getSlug()), UrlGeneratorInterface::ABSOLUTE_URL);
return $this->render('MyBundle:News:single_post.html.twig', [
'news' => $news,
'tags' => $arrTagNames
]);`
And in my Twig template I create link like to show one news:
<a href="{{ path('myroute_show_one_by_id', {'slug': news.slug}) }}">{{news.title}}</a>
I hope this could help someone else
In case anyone is using this old post as a reference for adding slugs to URLs, this functionality is baked into Symfony 4. This post Symfony 4 routing from DB shows how to do it simply using
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
/**
* @Route("/page/{slug}")
* @ParamConverter("page")
*/
public function showAction(Page $page)
{
}
It's working beautifully in my test project. Hope this helps someone!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With