需要slug字段值作为JDoe(对于John Doe)的学说

时间:2018-05-27 22:35:12

标签: symfony doctrine-orm slug

如何将slug字段设置为JDoe(名字的J-First字符,Doe - 完整的姓氏);

/**
 * @var string
 *
 * @Gedmo\Slug(fields={"firstName", "lastName"}, separator="??")
 * @ORM\Column(name="slug", type="string", length=20, unique=true)
 */

谢谢!

1 个答案:

答案 0 :(得分:1)

方法1

我没有尝试过以下内容,但它可能是您正在寻找的代码段。试一试,让我知道它是否有效:

class SomeEntity
{
    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"getFirstNameSlugged", "lastName"}, separator="??")
     * @ORM\Column(name="slug", type="string", length=20, unique=true)
     */
    private $slug;

    private function getFirstNameFirstLetter()
    {
        return substr ($this->firstName, 0 , 1);
    }

    private function getFirstNameSlugged()
    {
        return ucfirst (getFirstNameFirstLetter());
    }

}

方法2

实体中的

使用setSlug()方法:

class SomeEntity
{
    const SEPERATOR = '??';

    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"firstName", "lastName"}, separator="??")
     * @ORM\Column(name="slug", type="string", length=20, unique=true)
     */
    private $slug;

    private function getFirstNameFirstLetter()
    {
        return substr ($this->firstName, 0 , 1);
    }

    private function getFirstNameSlugged()
    {
        return ucfirst (getFirstNameFirstLetter());
    }

    private function getLastNameSlugged()
    {
        return ucfirst ($this->getLastName());
    }

    public function setSlug()
    {
        $this->slug = $this->getFirstNameSlugged() . self::SEPERATOR . $this->getLastNameSlugged();

        return $this->slug;
    }
}

并在控制器

$entity = new SomeEntity;
$entity->setSlug();

$em->persist($entity);
$em->flush();

方法3

实体中,创建一个方法并将其设置在控制器中:

class SomeEntity
{
    /**
     * @var string
     *
     * @Gedmo\Slug(fields={"firstName", "lastName"}, separator="??")
     * @ORM\Column(name="slug", type="string", length=20, unique=true)
     */
    private $slug;

    private function getFirstNameFirstLetter()
    {
        return substr ($this->firstName, 0 , 1);
    }

    private function getFirstNameSlugged()
    {
        return ucfirst (getFirstNameFirstLetter());
    }

    private function getLastNameSlugged()
    {
        return ucfirst ($this->getLastName());
    }

    public generateSlug()
    {
        $slug = $this->getFirstNameSlugged() . self::SEPERATOR . $this->getLastNameSlugged();

        return $slug;
    } 
}

并在控制器

$entity = new SomeEntity;

$callable = array('AppBundle\Entity\SomeEntity', 'generateSlug');
$sluggableListener = new \Gedmo\Sluggable\SluggableListener();
$sluggableListener->setTransliterator($callable);

$em->persist($entity);
$em->flush();