Moylin
Moylin

Reputation: 787

Symfony2.3 Required entity property, not requird in form, how do I default the property dynamically?

In Symfony2.3, I'm trying to configure an entity to do as follows

Example is a basic page entity.

I have two properties.

/**
 *@ORM\Column(type="string",length=255)
 *@Assert\NotBlank()
 */
protected $slug;

/**
*set slug
*@return Campaign
*/
protected $slug;

and

public function setSlug($slug)
{
    // if slug is false or empty, use the title instead
    if ($slug == '' || $slug == false)
    {
        $slug = $this->getTitle();
    }
    $slug = preg_replace('/[\s-]+/', '-', trim($slug," -\t\n\r\0\x0B"));
    $slug = preg_replace('/[^a-z0-9-]/', '', strtolower($slug) );
    $this->slug = $slug;
    return $this;
}

Although Slug Is required in the entity, it's not required in the form. I don't want it to be required in the form as it should default to the title if not filled in. Other than manually checking for it and calling this in the controller if it's not filled in, is there a better more automated way form the form configuration?

Upvotes: 0

Views: 104

Answers (2)

Moylin
Moylin

Reputation: 787

Found what appears to be the most organized way to do this is an event subscriber. After form binding, call the set slug method if the slug is false. This will allow it to validate correctly on the entity but allow the form to process without the field being required.

Upvotes: 0

Udan
Udan

Reputation: 5599

For this feature I use Doctrine Extensions.

Find more abowt how to implement them here: http://symfony.com/doc/current/cookbook/doctrine/common_extensions.html

WIth this approach, thw only thing you need to do for the slug to be generated is define a property as sluggable in youe entity.

Upvotes: 1

Related Questions