Question

I'm using symfony2.3 and admin generator bundle. I have a entity with a file field. I want in to mark that field as required. I have try several ways but nothing work as expected.

This is my file field iin the entity:

/**
 * @Assert\NotNull()
 * @Assert\Image(
 *     maxSize="50k",
 *     maxSizeMessage = "El tamaño maximo de la imagen es de {{ limit }}kb",
 *     minWidth = 237,
 *     maxWidth = 237,
 *     minHeight = 170,
 *     maxHeight = 170,
 *     minWidthMessage = "La imagen debe tener {{ min_width }}px de ancho.",
 *     minHeightMessage = "La imagen debe tener {{ min_height }}px de alto.",
 *     maxWidthMessage = "La imagen debe tener {{ max_width }}px de ancho.",
 *     maxHeightMessage = "La imagen debe tener {{ max_height }}px de alto."
 * )
 * @Vich\UploadableField(mapping="product_mapping", fileNameProperty="fileName")
 *
 * @var File $file
 */
protected $file; 

/**
 * @var string $fileName
 * 
 * @ORM\Column(name="fileName", type="string", length=255, nullable = false)
 */
protected $fileName;   

Note @Assert\NotNull() and nullable = false.

With this configuration i'm able to validate the creation of a new entity(if i let the file field empty the admin generator bundle show me a message: the field can't be null...), but when i edit(update) the created entity, the validation for NotNull is raised(with an entity previously created with a valid file). I'm force to upload again a file to be able to update the entity.

This is the configuration for admin generator (entity-generator.yml)

file:
    label:            Imagen
    formType:         single_upload
    dbType:           string        
    addFormOptions:
        #required:  true               ## this launch a exception
        previewFilter:  150x150_outbound_thumnail
        help:     "La imagen del producto debe tener 237px de ancho y 170px de alto, y no debe exceder los 50kb."   

Thanks in advance

Was it helpful?

Solution 2

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 :(

OTHER TIPS

single_upload is not supported, you will have troubles using it. Few months ago this project changed its form types to AvocodeFormExtension - but only mentioned it in change log. Why bother to edit documentation?

If you still want to use single_upload, try to validate file presence in controller. If you mark this field required, you will have to upload it every time, even editing object with attached file. Required means that form send from browser to server has to contain file, not an object! (I use FormType or templates to pass required on newActions, and no required on editActions)

Good Luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top