2014-01-15 2 views
0

У меня есть объект, который является иерархическим с использованием расширения Gedmo Tree Doctrine в Symfony 2. Код для Категория объекта является:Редактирование Slug с помощью Gedmo TreeSlugHandler

<?php 

namespace MD\Entity; 

use Doctrine\Common\Collections\ArrayCollection; 
use Symfony\Component\Validator\Constraints as Assert; 

use Doctrine\ORM\Mapping as ORM; 

use Gedmo\Mapping\Annotation as Gedmo; 

use MD\Entity\Extension\Treeable; 

/** 
* Category 
* 
* @ORM\Entity(repositoryClass="MD\Entity\Repository\CategoryRepository") 
* 
* @Gedmo\Tree(type="nested") 
*/ 
class Category 
{ 
    /** 
    * Entity Extensions 
    */ 
    use Treeable; 


    /** 
    * The ID of the category 
    * 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * The title of the category 
    * 
    * @var string 
    * 
    * @ORM\Column(type="string", length=255) 
    * 
    * @Assert\NotBlank(message="category.title.not_blank") 
    * @Assert\Length(
    *  max=255, 
    *  maxMessage="category.title.length.max" 
    *) 
    */ 
    protected $title; 

    /** 
    * The description of the category 
    * 
    * @var string 
    * 
    * @ORM\Column(type="text") 
    * 
    * @Assert\NotBlank(message="category.description.not_blank") 
    */ 
    protected $description; 

    /** 
    * The parent of the category 
    * 
    * @var Category 
    * 
    * @ORM\ManyToOne(targetEntity="Category", inversedBy="children") 
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE") 
    * 
    * @Gedmo\TreeParent 
    */ 
    protected $parent; 

    /** 
    * The children of the category 
    * 
    * @var ArrayCollection 
    * 
    * @ORM\OneToMany(targetEntity="Category", mappedBy="parent", cascade={"persist"}) 
    * @ORM\OrderBy({"left" = "ASC"}) 
    */ 
    protected $children; 

    /** 
    * The slug of the category 
    * 
    * @var string 
    * 
    * @ORM\Column(type="string", length=255, unique=true) 
    * 
    * @Gedmo\Slug(handlers={ 
    *  @Gedmo\SlugHandler(class="Gedmo\Sluggable\Handler\TreeSlugHandler", options={ 
    *   @Gedmo\SlugHandlerOption(name="parentRelationField", value="parent"), 
    *   @Gedmo\SlugHandlerOption(name="separator", value="/") 
    *  }) 
    * }, fields={"title"}) 
    */ 
    protected $slug; 



    /** 
    * Constructor 
    */ 
    public function __construct() 
    { 
     $this->children = new ArrayCollection(); 
    } 

    /** 
    * Get the ID of the category 
    * 
    * @return integer 
    */ 
    public function getId() 
    { 
     return $this->id; 
    } 

    /** 
    * Set the title of the category 
    * 
    * @param string $title 
    * 
    * @return $this 
    */ 
    public function setTitle($title) 
    { 
     $this->title = $title; 

     return $this; 
    } 

    /** 
    * Get the title of the category 
    * 
    * @return string 
    */ 
    public function getTitle() 
    { 
     return $this->title; 
    } 

    /** 
    * Set the description of the category 
    * 
    * @param string $description 
    * 
    * @return $this 
    */ 
    public function setDescription($description) 
    { 
     $this->description = $description; 

     return $this; 
    } 

    /** 
    * Get the description of the category 
    * 
    * @return string 
    */ 
    public function getDescription() 
    { 
     return $this->description; 
    } 

    /** 
    * Set the parent of the category 
    * 
    * @param Category $parent 
    * 
    * @return $this 
    */ 
    public function setParent(Category $parent = null) 
    { 
     $this->parent = $parent; 

     if (null !== $parent) { 
      $parent->addChild($this); 
     } 

     return $this; 
    } 

    /** 
    * Get the parent of the category 
    * 
    * @return Category 
    */ 
    public function getParent() 
    { 
     return $this->parent; 
    } 

    /** 
    * Add a child to the category 
    * 
    * @param Category $child 
    * 
    * @return $this 
    */ 
    public function addChild(Category $child = null) 
    { 
     if (!$this->children->contains($child)) { 
      $this->children->add($child); 
      $child->setParent($this); 
     } 

     return $this; 
    } 

    /** 
    * Get the children of the category 
    * 
    * @return ArrayCollection 
    */ 
    public function getChildren() 
    { 
     return $this->children; 
    } 

    /** 
    * Set the slug of the category 
    * 
    * @param string $slug 
    * 
    * @return $this 
    */ 
    public function setSlug($slug) 
    { 
     $this->slug = $slug; 

     return $this; 
    } 

    /** 
    * Get the slug of the category 
    * 
    * @return string 
    */ 
    public function getSlug() 
    { 
     return $this->slug; 
    } 



    /** Magic Methods */ 

    /** 
    * Return a string representation of the category 
    * 
    * @return string 
    */ 
    public function __toString() 
    { 
     return $this->getTitle(); 
    } 
} 

Учитывая категорию с названием Bands и а подкатегория с названием Rock, последняя категория, при создании, имеет пулю bands/rock. Это работает так, как ожидалось.

Когда я добавляю поле слива в форму, однако, когда я редактирую объект, я сначала получаю bands/rock, добавленный в поле формы. Если я изменю это на bands/rock-and-roll и отправлю форму, слизь обновится до bands/bands-rock-and-roll, а не bands/rock-and-roll, как я ожидал.

Если я отредактирую категорию и задаю поле слива rock-and-roll, то отправьте форму, слизь обновится до bands/rock-and-roll. Я ожидаю, что после обновления будет rock-and-roll.

Что нужно сделать, чтобы исправить это поведение? Я по существу хочу, чтобы slug был автоматически сгенерирован с обработчиком, если он не предоставлен, но должен быть установлен точно, что я предоставляю, если я его предоставил.

Благодаря

+0

Вы когда-нибудь находили решение этого вопроса? – Stephen

ответ

0

глядя на документы в Gedmo Tree Doctrine extension и это относительный код, это не неправильное поведение, потому что пробкового соответственно состоит в способе = parentFieldName/поле-You-Have- «TreeSlugHandler» Вставлено (это происходит при каждом редактировании пули).

Если вам нужно в тот же момент пули для определенной категории и другого, что следует за деревом категории, вы можете добавить другое свойство (например: cat_slug) с помощью простой аннотации: @Gedmo \ Slug (fields = {" fieldYouWantToSlug "}).

Помните, что каждый раз (используя метод TreeSlugHandler) вы редактируете slug (изменяете прецедент), каждая подкатегория будет обновляться с новым slug.

Я надеюсь, что мне было полезно

Смежные вопросы