Let's say I have this entity:
use App\Repository\CategoryRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=CategoryRepository::class)
*/
class MyEntity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private ?int $id = null;
/**
* @ORM\Column(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?
CodePudding user response:
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.