Thomas K
Thomas K

Reputation: 6206

Set slug using associated entity field

I'm using DoctrineExtensionsto get sluggable behavior for my entities. One one of my entities I would like to use the city field of the related address entity for the slug. However, I don't know how to access it:

/**
 * @var Foo\SiteBundle\Entity\Address
 *
 * @ORM\ManyToOne(targetEntity="Foo\SiteBundle\Entity\Address", cascade={"persist"})
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="address_id", referencedColumnName="id")
 * })
 */
private $address;

/**
 * @Gedmo\Slug(fields={"address->city", "name"})
 * @ORM\Column(length=128, unique=true)
 */
private $slug;

How can I make this work?

Upvotes: 3

Views: 2500

Answers (2)

Sybio
Sybio

Reputation: 8645

You could perform it: https://github.com/l3pp4rd/DoctrineExtensions/issues/86

But here https://github.com/l3pp4rd/DoctrineExtensions:

2012-02-26

Removed slug handlers, this functionality brought complucations which could not be maintained.

Unfortunately this functionnality was removed !

So I think you have to change your logical: for example, you can use a route containing the slug of the address and the current entity and load the entity in response:

@Route("/user/{slugUser}/{slugAddress}.html", requirements={"slugUser"="^[a-z0-9-]+", "slugAddress"="^[a-z0-9-]+"})

Or perhaps a solution, try to set it manually... and automatically with lifecycles, but i'm not sure if it works:

/**
 * @Gedmo\Slug(fields={})
 * @ORM\Column(length=128, unique=true)
 */
private $slug;

/**
 * @ORM\PrePersist
 */
public function updateSlug()
{
    $this->setSlug($this->name.$this->address->getCity());
}

Upvotes: 1

Carlos Granados
Carlos Granados

Reputation: 11351

You cannot do this directly as the sluggable extension can only use a direct field of the entity. The only way I can think of, though it is a bit clumsy, is to add a field which tracks the city of the address. Something like:

/**
 * @ORM\Column(length=128)
 */
private $city;

/**
 * @Gedmo\Slug(fields={"city", "name"})
 * @ORM\Column(length=128, unique=true)
 */
private $slug;

//setter for Address
public function setAddress($address) {
    $this->address= $address;
    $this->city = $address->getCity();
}

I am not really sure if city needs to be persisted to the database (i.e. if you need to use @ORM\Column with it) or if the extension can work with a property which is not persisted, just try it without the @ORM annotation and see if it works.

Upvotes: 0

Related Questions