RE: [symfony-es] Cómo definir un valor por defecto al crear una entidad

534 views
Skip to first unread message

ogonzalezf

unread,
Sep 7, 2012, 2:20:49 PM9/7/12
to symfo...@googlegroups.com

Bueno puedes hacerlo de la siguiente manera antes persistir la entidad user para hacer el flush puedes poner $user->setUser_type(xxxxxxx) le pasas el user_type que desees y listo después  pones algo como:

            $em->persist($user);

            $em->flush();

 

 

Saludos

 

Osay González Fuentes.

Centro Nacional de Calidad de Software.

La Habana, Cuba.

 

 

 

From: symfo...@googlegroups.com [mailto:symfo...@googlegroups.com] On Behalf Of reiziel
Sent: viernes, 07 de septiembre de 2012 13:32
To: symfo...@googlegroups.com
Subject: [symfony-es] Cómo definir un valor por defecto al crear una entidad

 

Hola amigos,

 

Tengo una duda en symfony 2.1 y solicito su ayuda. Tengo dos entidades, una es User y la otra es UserType y necesito que cuando se cree un User tenga por defecto un UserType. Los tipos de usuario ya están creados, por lo que básicamente necesito que cuando se cree un objeto del tipo User para insertarlo en la bd tenga por defecto un UserType de los que ya están creados en la BD. Agradezco su ayuda.

 

Mi entidad User es:

 

namespace zzz\zzzBundle\Entity;

 

use FOS\UserBundle\Entity\User as BaseUser;

use Doctrine\ORM\Mapping as ORM;

use zzz\zzzBundle\Entity\UserType;

 

/**

 * @ORM\Entity

 * @ORM\Table(name="users")

 */

class User extends BaseUser

{

  ....

  /**

     * @ORM\OneToOne(targetEntity="UserType")

     * @ORM\JoinColumn(name="user_type_id", referencedColumnName="id")

     */

            protected $user_type;

}

 

Y la entidad UserType:

 

namespace zzz\zzzBundle\Entity;

 

use Doctrine\ORM\Mapping as ORM;

 

/**

 * @ORM\Entity

 * @ORM\Table(name="users_type")

 */

class UserType

{

   /**

     * @var integer $id

     *

     * @ORM\Column(name="id", type="integer")

     * @ORM\Id

     * @ORM\GeneratedValue(strategy="AUTO")

     */

    private $id;

           

            /**

     * @ORM\Column(name="type", type="string")

     */

            protected $type;

}

--
Has recibido este mensaje porque estás suscrito al grupo "symfony-es" de Google Groups.
Para publicar en este grupo, envía un email a symfo...@googlegroups.com
Para darte de baja, envía un email a
symfony-es+...@googlegroups.com
El resto de opciones puedes encontrarlas en
http://groups.google.com/group/symfony-es?hl=es

Leonardo Fernandez

unread,
Sep 7, 2012, 3:21:46 PM9/7/12
to symfo...@googlegroups.com
eso lo tendrias que hacer en el metodo constructor?
on incluso 
protected $user_type = "Valor por defecto..."

Leonardo Fernandez

unread,
Sep 7, 2012, 3:47:34 PM9/7/12
to symfo...@googlegroups.com
Buscando un poco encontre esto

Database default values are not "portably" supported. The only way to use database default values is through the columnDefinition mapping attribute where you specify the SQL snippet (DEFAULT cause inclusive) for the column the field is mapped to.

You can use:

<?php
/**
 * @Entity
 */
class myEntity {
    /**
     * @var string
     *
     * @Column(name="myColumn", type="string", length="50")
     */
    private $myColumn = 'myDefaultValue';
    ...
}
http://stackoverflow.com/questions/3376881/default-value-in-doctrine


You should have a service for creating new YourEntity instances. The service will know of to retrieve the default group, or how to create a reference to the default group, and will take care of passing it to the entity's constructor.

For example:

class YourEntityService
{
   
...

   
public function createNewYourEntity()
   
{
        $defaultGroup
= $this->em->getReference('Usergroup', 1);
       
return new YourEntity($defaultGroup);
   
}

   
...
}
http://stackoverflow.com/questions/7301813/doctrine-entity-as-default-value-in-another-entity



Doctrine does not support to set the default values in columns through the “DEFAULT” keyword in SQL. This is not necessary however, you can just use your class properties as default values. These are then used upon insert:
http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/faq.html

Leonardo Fernandez

unread,
Sep 7, 2012, 3:48:34 PM9/7/12
to symfo...@googlegroups.com

Juan Martín Díaz

unread,
Sep 11, 2012, 8:03:42 AM9/11/12
to symfo...@googlegroups.com
Bueno, yo lo que he hecho es, al momento de crear la nueva entidad, recuperar desde la BD la entidad correpondiente (en tu caso el tipo de usuario) y asignarla a la referencia de la entidad que se está creando (en tu caso usuario).
Si lo que necesitas es que al momento de ingresar los datos del usuario en el form, el tipo de usuario ser elegido y que presente un valor por defecto, una alternativa es recuperar desde la BD una instancia del tipo de usuario deseado y asignarselo a la nueva entidad usuario antes de crear el form, así:

public function newAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $type = $em->getRepository('TuBundle:UserType')->find(2);
        
        $entity = new User();
        $entity->setType($type);
        $form   = $this->createForm(new UserForm(), $entity);

        return $this->render('TuBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

De esta manera en el formulario "new" estará seleccionada por defecto el UserType con id = 2.
Saludos.



El viernes, 7 de septiembre de 2012, Leonardo Fernandez escribió:
Esto también: ayuda  https://www.google.com.py/search?q=doctrine+deafault+value+for+entity&sugexp=chrome,mod=13&sourceid=chrome&ie=UTF-8#hl=es&pwst=1&sa=X&ei=WU5KUJL1IYPq9ATaxoHADA&ved=0CB0QvwUoAQ&q=doctrine+default+value+for+entity&spell=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&fp=6d4c6ca7f9647072&biw=1366&bih=624 

El 7 de septiembre de 2012 16:47, Leonardo Fernandez <leod...@gmail.com> escribió:
Buscando un poco encontre esto

Database default values are not "portably" supported. The only way to use database default values is through the columnDefinition mapping attribute where you specify the SQL snippet (DEFAULT cause inclusive) for the column the field is mapped to.

You can use:

<?php
/**
 * @Entity
 */
class myEntity {
    /**
     * @var string
     *
     * @Column(name="myColumn", type="string", length="50")
     */
    private $myColumn = 'myDefaultValue';
    ...
}
http://stackoverflow.com/questions/3376881/default-value-in-doctrine


You should have a service for creating new YourEntity instances. The service will know of to retrieve the default group, or how to create a reference to the default group, and will take care of passing it to the entity's constructor.

For example:

class 

Marcelo Prizmic

unread,
Sep 11, 2012, 8:25:31 AM9/11/12
to symfo...@googlegroups.com
En este caso estás usando el id=2. Sería lo mismo usar directamente un id de UserType.
Me parece que lo mejor es crear el servicio que cree el usuario y que consulte la BD para tomar un UserType de la tabla.
Marcelo
Reply all
Reply to author
Forward
0 new messages