Foros del Web » Programando para Internet » PHP » Symfony »

[SOLUCIONADO] Validando tipo file con Assert

Estas en el tema de Validando tipo file con Assert en el foro de Symfony en Foros del Web. Hola Tengo una Entidad "UpFile" para subir imágenes. Todo me funciona bien, los datos se persisten en la Base de datos al momento de subir ...
  #1 (permalink)  
Antiguo 04/01/2015, 16:52
 
Fecha de Ingreso: febrero-2014
Ubicación: Edo. México
Mensajes: 85
Antigüedad: 10 años, 2 meses
Puntos: 0
Validando tipo file con Assert

Hola

Tengo una Entidad "UpFile" para subir imágenes. Todo me funciona bien, los datos se persisten en la Base de datos al momento de subir una imagen. Lo único que no logro es validar estos archivos con los Assert. Es la primera vez que manejo Assert asi que puedo estar haciendo algo mal. Les pongo a continuación lo que tengo:

Entidad "UpFile"
Código PHP:
use SymfonyComponentValidatorConstraints as Assert;
use 
SymfonyComponentHttpFoundationFileFile;
/**
     * @Assert\Image(
     *     maxSize="2M",
     *     minWidth = 100,
     *     maxWidth = 470,
     *     minHeight = 100,
     *     maxHeight = 470,
     *     mimeTypes = {"image/png", "image/gif", "image/jpg", "image/jpeg"},
     *     mimeTypesMessage = "Por favor suba un .JPG .PNG ó .GIFF"
     * )
     */
    
protected $file;

/**
     * Sets file.
     *
     * @param File $file
     */
    
public function setFile(File $file null)
    {
         ......
    }

    
/**
     * Get file.
     *
     * @return File
     */
    
public function getFile()
    {     ......
    } 
"ImagenesType"
Código PHP:
->add('file'null , array(                        
                        
'attr' => array('class' => 'fileUPstyle'),                        
                        
'label' => false,
                        
'required' => false
                        
)) 
Me olvidaba del config.yml
Código PHP:
framework:
    
validation: { enable_annotationstrue 

Al subir el formulario no me marca ningún error, pero la validación la ignora y subo .exe , .pdf , archivos con 20Mb de tamaño etc.
Alguna idea de que me puede estar fallando?

Saludos y muchas gracias por la atención

Última edición por Esdras_mtz; 04/01/2015 a las 16:58 Razón: Falto una parte
  #2 (permalink)  
Antiguo 05/01/2015, 09:19
Avatar de hhs
hhs
Colaborador
 
Fecha de Ingreso: junio-2013
Ubicación: México
Mensajes: 2.995
Antigüedad: 10 años, 10 meses
Puntos: 379
Respuesta: Validando tipo file con Assert

Puedes publicar la parte del controlador donde recibes y guardas las imagenes
__________________
Saludos
About me
Laraveles
A class should have only one reason to change.
  #3 (permalink)  
Antiguo 05/01/2015, 12:03
 
Fecha de Ingreso: febrero-2014
Ubicación: Edo. México
Mensajes: 85
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Validando tipo file con Assert

Todo lo manejo desde la Entidad "UpFile"

Código PHP:
...
use 
SymfonyComponentValidatorConstraints as Assert;
use 
SymfonyComponentHttpFoundationFileFile;

/**
 * UpFile
 *
 * @ORM\Table(name="UpFile")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class UpFile
{
    
    
/**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    
private $path;
    
    
/**
     * @Assert\Image(
     *     maxSize="100k"
        .....
     * )
     */
    
protected $file;
    
    
/**
     * @var \RCV
     *
     * @ORM\ManyToOne(targetEntity="RCV", inversedBy="Ilustrarxy", cascade={"persist"})
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="Id_RCV", referencedColumnName="Id")
     * })
     */
    
private $IdRCV;    
    
    
    private 
$temp;
    
    
/**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    
public function preUpload()
    {
        if (
null !== $this->getFile()) {
            
$this->path $this->getFile()->guessExtension();
        }
    }

    
/**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    
public function upload()
    {
        if (
null === $this->getFile()) {
            return;
        }

        
// check if we have an old image
        
if (isset($this->temp)) {
            
// delete the old image
            
unlink($this->temp);
            
// clear the temp image path
            
$this->temp null;
        }

        
// you must throw an exception here if the file cannot be moved
        // so that the entity is not persisted to the database
        // which the UploadedFile move() method does
        
$this->getFile()->move(
            
$this->getUploadRootDir(),
            
$this->Id.'.'.$this->getFile()->guessExtension()
        );

        
$this->setFile(null);
    }

    
/**
     * @ORM\PreRemove()
     */
    
public function storeFilenameForRemove()
    {
        
$this->temp $this->getAbsolutePath();
    }

    
/**
     * @ORM\PostRemove()
     */
    
public function removeUpload()
    {
        if (isset(
$this->temp)) {
            
unlink($this->temp);
        }
    }

    
/**
     * Sets file.
     *
     * @param File $file
     */
    
public function setFile(File $file null)
    {
        
$this->file $file;
        
// check if we have an old image path
        
if (is_file($this->getAbsolutePath())) {
            
// store the old name to delete after the update
            
$this->temp $this->getAbsolutePath();
        } else {
            
$this->path 'initial';
        }
    }

    
/**
     * Get file.
     *
     * @return File
     */
    
public function getFile()
    {
        return 
$this->file;
    }

    

    public function 
getAbsolutePath()
    {
        return 
null === $this->path
            
null
            
$this->getUploadRootDir().'/'.$this->Id.'.'.$this->path;
    }

    public function 
getWebPath()
    {
        return 
null === $this->path
            
null
            
$this->getUploadDir().'/'.$this->path;
    }

    protected function 
getUploadRootDir()
    {
        return 
__DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function 
getUploadDir()
    {
        return 
'file/Ilustraciones';
    } 
    
  
// Todos los  SETy GET
      
....

En el controlador lo pongo asi
Código PHP:
       $Cuento=new RCV();
        
// La entidad "UpFile" es uno o varios <input type="file"> embebidos en RCV()
        
$Cuento->addIlustrarxy(new UpFile());
       
$form$this->createForm(new CuentoType(), $Cuento);

       
$form->handleRequest($request);
        if (
$form->isValid()){            
            
$em $this->getDoctrine()->getManager();
            
$Cuento->setIdUser($this->getUser());            

            
$em->persist($Cuento);
            
$em->flush();            
           ....         
        }
       ... 
  #4 (permalink)  
Antiguo 05/01/2015, 14:06
Avatar de hhs
hhs
Colaborador
 
Fecha de Ingreso: junio-2013
Ubicación: México
Mensajes: 2.995
Antigüedad: 10 años, 10 meses
Puntos: 379
Respuesta: Validando tipo file con Assert

Ok al parecer todo esta bien, solo una pregunta mas el formulario CuentoType usa el tipo collection para almacenar los input file ???
__________________
Saludos
About me
Laraveles
A class should have only one reason to change.
  #5 (permalink)  
Antiguo 05/01/2015, 16:09
 
Fecha de Ingreso: febrero-2014
Ubicación: Edo. México
Mensajes: 85
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Validando tipo file con Assert

Sip lo tengo asi

Código PHP:
->add('Ilustrarxy''collection', array(
                    
'type' => new ImagenesType(),
                    
'allow_add'    => true,
                    
'by_reference' => false,
                    
'allow_delete' => true,
                    
'delete_empty' => true,
                    
'required'=>false,                                     
                    )) 
Es muy extraño, todo lo hace bien. Persiste las dos entidades y almacena el archivo donde debe. Pero sencillamente la validación del Assert en el $file, la ignora :/

Estoy con Symfony 2.6.1
  #6 (permalink)  
Antiguo 05/01/2015, 18:06
Avatar de hhs
hhs
Colaborador
 
Fecha de Ingreso: junio-2013
Ubicación: México
Mensajes: 2.995
Antigüedad: 10 años, 10 meses
Puntos: 379
Respuesta: Validando tipo file con Assert

Quiero suponer que CuentoType tiene asociada una Entidad esta entidad tiene mediante la propiedad Ilustrarxy una asociacion con Upfile pero cuando haces la validación no le estas diciendo a la entidad que tiene que delegar la validación a Upfile, esto lo haces mediante el Assert Valid: http://symfony.com/doc/current/refer...nts/Valid.html
__________________
Saludos
About me
Laraveles
A class should have only one reason to change.
  #7 (permalink)  
Antiguo 06/01/2015, 12:34
 
Fecha de Ingreso: febrero-2014
Ubicación: Edo. México
Mensajes: 85
Antigüedad: 10 años, 2 meses
Puntos: 0
Respuesta: Validando tipo file con Assert

hhs me has vuelto a salvar. Precisamente era eso lo que me faltaba. Delegar la validación a Upfile. Muchas gracias

Saludos.

Etiquetas: file, tipo
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:25.