In my current project, I decided to create only one translatable File entity and reuse it for all image/document properties I have. For the translations, I uses Knp Doctrine Behaviors Translatable. So here is the code.
The file class:
class File
{
use ORMBehaviors\Translatable\Translatable;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __toString()
{
return (string)$this->id;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
The translatable file class:
class FileTranslation
{
use ORMBehaviors\Translatable\Translation;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $name;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* @Assert\File()
*/
private $file;
/*
* Non tracked parameter
*/
public $folder;
/**
* Set name.
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path.
*
* @param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Get path.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Set folder
*
* @param string $folder
*
* @return File
*/
public function setFolder($folder)
{
$this->folder = $folder;
return $this;
}
/**
* Get folder
*
* @return File
*/
public function getFolder()
{
return $this->folder;
}
}
And then an example of how it's used in another entity (User) to create an image property:
class User
{
/**
* @ORM\OneToOne(targetEntity="File", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="image_id", referencedColumnName="id", nullable=true)
* @Assert\Valid()
*/
private $image;
}
Nothing new. I just followed Symfony/Knp documentation and it works fine. However, now I want to add different validation rules each time I create a new property like $image for different entities. What is the best strategy here?
Each time I try to add a validation rule related to file in the $image property, for instance, it says it cannot find a file.
you can have specific validator for each entity:
For those who have the same problem, I finally did what @sylvain said and I created my custom validators:
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
This is a great tutorial, btw:
https://knpuniversity.com/screencast/question-answer-day/custom-validation-property-path
It works fine. However, I still think the @valid constraint should have worked and I don't understand why it didn't.