KnpLabs / DoctrineBehaviors

Doctrine2 behavior traits that help handling Blameable, Loggable, Sluggable, SoftDeletable, Uuidable, Timestampable, Translatable, Tree behavior
http://knplabs.com
MIT License
911 stars 287 forks source link

Allow empty translations #678

Closed nicolassing closed 2 years ago

nicolassing commented 2 years ago

For some reasons (maybe weird reasons ... ) I have some entities with empty translations (all translatable fields are empty).

https://github.com/KnpLabs/DoctrineBehaviors/blob/302ed95ec17417828ccac1fdcb19e95dac9c72dd/src/Model/Translatable/TranslatableMethodsTrait.php#L139

This bundle do not return an empty translation even if it exists. As a result I get UniqueConstraintViolation from Doctrine :(.

Can i make a PR do remove this check or if it's here for a good reason, I can add an option to bypass this behavior.

What do you think ? Thx !

TomasVotruba commented 2 years ago

Hi, thanks for reporting.

Could you provide failing test case, so we can see the failure message and have it covered for regressions?

MichaelBrauner commented 2 years ago

You can implement your own Trait. This is an example of my implementation.

<?php

declare(strict_types=1);

namespace App\Entity\Trait;

use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait as KnpTranslatableTrait;
use Symfony\Component\PropertyAccess\PropertyAccess;

trait NullableTranslatableTrait
{
    use KnpTranslatableTrait;

     public function mergeNewTranslations(): void
     {
        foreach ($this->getNewTranslations() as $newTranslation) {
            if (! $this->getTranslations()->contains($newTranslation)) {
                $this->addTranslation($newTranslation);
                $this->getNewTranslations()
                    ->removeElement($newTranslation);
            }
        }
    }
}

In my case it was necessary because I use doctrine JoinTable inheritance. And the subclasses are by default empty when they don't contain any additional translated fields apart from the ones declared inside the parent class.

TomasVotruba commented 2 years ago

Thanks @MichaelBrauner for the answer :+1: