I want to share my own solution for this issue:
The problem became when i set file(or image, like max width, max height, etc) constrains for a file property in a entity, and also a NotNull constrain. In other words, i want to check for a file to be like i want to be, and also to make the file required. Im using Vich Uploadable Bundle.
The problem is when any file constrain fail, the file is not loaded in the entity and Admin Generator Bundle crash displaying the file again when the form is redisplayed.
What i do: Do not use NotNull constrain.
In my file entity i create a new property: requiredFile as private, not persistent to DB. Also i create a callback constrain: validateRequiredFile. In the constructor set the requiredFile = true and voila!
The final entity looks like this:
/** * @Vich\Uploadable * @ORM\Table(name="table_name") * @Assert\Callback(methods={"validateRequiredFile"}) * @ORM\Entity(repositoryClass="repo/path") */ class Product{ ...
/**
* Non persistent, just to determinate if file is required
* @var string
*/
private $requiredFile;
...
/**
* Constructor
*/
public function __construct()
{
$this->requiredFile = true;
}
...
/**
* This function is to validate the requires files
*
* How to use:
* In the contructor of the entity who inherit from BaseFile, set requiredFile property as true, Ex:
* public function __construct()
* {
* ...
* $this->requiredFile = true;
* parent::__construct();
* }
*
* @param \Symfony\Component\Validator\ExecutionContextInterface $context
*/
public function validateRequiredFile(ExecutionContextInterface $context){
//get the validated object
$object = $context->getValue();
//to know if is a creation or a update
$newObject = $object->getId() == null;
//validation
if ($newObject && empty($this->file) && $this->requiredFile === true ) {
$context->addViolationAt('file', "The file is required", array(), null);
$this->fileName = Constants::RELATIVE_NOT_VALID_IMAGE_PATH;
}
//in case we dont want to validate file as required, and no file was updated, clean property "fileName" who was setted in constructor
if ($newObject && empty($this->file) && empty($this->requiredFile)) {
$this->fileName = null;
}
}
PS: I create a custom image to use for display in case the validation fails. I put it in the web folder to be accessible for all the site. The path to that image is saved in Constants::RELATIVE_NOT_VALID_IMAGE_PATH;
PS1: The function validateRequiredFile is oriented to be in a BaseFile entity (a @ORM\MappedSuperclass ) where i put all the common properties for a entity with a file. In that way is even easy to use this functionality.
I hove this help somebody, it cost me some time :(