Skip to content
Advertisement

How to automatically trim string when persisting a Doctrine entity?

Let’s say I have this entity:

use AppRepositoryCategoryRepository;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass=CategoryRepository::class)
 */
class MyEntity
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     */
    private ?int $id = null;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private ?string $name = null;

    // getter setters ...
}

My controller:

class MyController extends AbstractController
{
    public function __invoke(EntityManagerInterface $em)
    {
        $myEntity = new MyEntity();
        $myEntity->setName('  awesome name  ');
        $em->persist($myEntity);
        $em->flush();
    }
}

I want doctrine to register the name of myEntity as awesome name and not awesome name .

Is there a way to configure doctrine to do this?

Advertisement

Answer

You do not need to “configure doctrine” in any way. Just use PHP and introduce the logic in your entity:

class MyEntity {
    // ... rest of the class implementation

    public function setName(?string $name): void {
        $this->name = $name === null ? $name : trim($name);
    }
}

This way your data will be in a consistent state before you persist it in the database.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement