0

I'm using doctrine and sf2 and i have a question about the slug extension : Is there any way to generate it before the flush ?

Let say i have a Brand Entity:

/**
 * Brand
 *
 * @ORM\Table(indexes={@ORM\Index(name="name_idx", columns={"name"})})
 * @ORM\Entity(repositoryClass="Shoesalley\Bundle\CoreBundle\Entity\BrandRepository")
 */
class Brand
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @var string
 *
 * @Gedmo\Slug(fields={"name"})
 * @ORM\Column(length=128, unique=true)
 */
private $slug;
}
// getters and setters ...

if i do this i get 2 differents slugs : test and test_1

$brand=new Brand();
$brand->setName('test');
$em->persist($brand);
$brand2=new Brand();
$brand2->setName('Test');
$em->persist($brand2);    

The goal would be to find that the target slug allready exist and only have 1 DB Entry.

I can't use find() without a generated slug, so does anyone have an idea ?

The main idea is something like that, but i don't know how to implement it :

$brand=new Brand();
$brand->setName('test');
$slug = $brand->getSlug();
if( $oBrand = $em->getRepository("DemoBundle:Brand")->findOneBySlug($slug)){
    $brand = $oBrand;
}
$em->persist($brand);   

Thanks a lot for your help.

1 Answers1

-1

You are using the right logic in your solution i think; there are probalbly a few glitches you need to take care of though :

$brand = new Brand();

$brand->setName('test');
$slug = $brand->getSlug(); 
// Is getSlug() going to work before persist ? 
// If not, you'll have to "simulate" the generation of a slug 
// to obtain a string equivalent to that slug

$obrand = $em->getRepository("DemoBundle:Brand")->findOneBySlug($slug);

if(empty($obrand) { // empty, or is_null, depends on what your orm returns when it finds nothing
    $em->persist(brand);
} else {
    echo('Slug ' . $brand->getSlug() . ' is already in use !');
}
np87
  • 543
  • 5
  • 14
  • Exactly, the main problem is still how to simulate the generation of the slug ? – Cyril Souillard Apr 16 '14 at 20:04
  • You should be able to find the logic somewhere in Doctrine doc, it'll still be kind of hackish though. For example [this](https://github.com/guilhermeblanco/Doctrine2-Sluggable-Functional-Behavior/blob/master/lib/DoctrineExtensions/Sluggable/SlugGenerator.php) – np87 Apr 18 '14 at 11:34