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

Problema con formulario y clave foranea

Estas en el tema de Problema con formulario y clave foranea en el foro de Symfony en Foros del Web. Hola, tengo un formulario que funciona correctamente en el que tengo dos campos que son claves foráneas (1 el id del artículo y 2 el ...
  #1 (permalink)  
Antiguo 21/10/2012, 12:40
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Pregunta Problema con formulario y clave foranea

Hola,

tengo un formulario que funciona correctamente en el que tengo dos campos que son claves foráneas (1 el id del artículo y 2 el id de usuario). Estos dos datos no los tengo en el formulario por que los defino yo por defecto.

El problema es que si después (antes de guardar el formulario en la base de datos) pongo $opinion->setArticulo($articulo); me da el siguiente error:

Código:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`symfony`.`opinion`, CONSTRAINT `FK_64BF89BB2DBC2FC9` FOREIGN KEY (`articulo_id`) REFERENCES `Articulo` (`id`))
Así que no se que hacer, no se si hay alguna forma de ponerlo en el formulario de forma que este oculta para el usuario. No se cual es la forma correcta de hacer esto pero supongo que será un problema común.

Saludos,
  #2 (permalink)  
Antiguo 21/10/2012, 13:37
Avatar de carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Respuesta: Problema con formulario y clave foranea

Yo creo que es que no esta encontrando el id por llamarlo de algún modo del artículo que estas guardando, estas seguro que lo estas setteando correctamente correctamente??
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way
  #3 (permalink)  
Antiguo 21/10/2012, 22:55
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Si, en $articulo contengo un objeto artículo. He hecho un print_r y esta correcto.
  #4 (permalink)  
Antiguo 22/10/2012, 04:33
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Respuesta: Problema con formulario y clave foranea

El hecho de que el objeto PHP tenga los valores correctos no implica necesariamente que existan en la base de datos. La base de datos y la aplicación son entidades separadas, Cada una con sus reglas de consistencia.
En ese caso lo que indica es que se está pretendiendo dar de alta a un registro en una tabla, donde un campo hace referencia al ID de la tabla artículo, sin haber dado de alta el artículo en su tabla previamente.
Es un problema de dependencia de FK/PK.
Da de alta el articulo, recupera su PK y usala para el registro de la otra tabla.

Si el problema persiste, postea el problema en el foro de BBDD, con la estructura de tablas y query usada por la aplicación para poder resolver el problema específico de BBDD, que es off-topic en este.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #5 (permalink)  
Antiguo 22/10/2012, 05:31
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

A ver, en este formulario yo no estoy dando de alta un artículo. Estoy dando de alta un comentario para el artículo. Así que el artículo ya esta creado simplemente necesito añadir la id en la tabla del comentario para saber a que artículo corresponde.
  #6 (permalink)  
Antiguo 22/10/2012, 06:20
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Respuesta: Problema con formulario y clave foranea

Cita:
Así que el artículo ya esta creado simplemente necesito añadir la id en la tabla del comentario para saber a que artículo corresponde.
Perfecto, pero ¿en qué momento recuperas y cómo pasas ese ID al comentario?
El problema esencial es que el ID que estás poniendo en el comentario no corresponde a ningún articulo que exista en tu base de datos. De modo que puede ser:
- El valor no está llegando al objeto que usas luego para crear la sentencia de INSERT.
- Estás tomando el valor siguiente al mayor id del articulo por usar una función incorrecta o a destiempo (error usual en algunas ocasiones).
- Hay error en la incializacion de la variable y llega cero (0) o NULL
- Intentas usar insert_id() luego de haber usado una query intermedia entre el insert del articulo y el del comentario.
Estos son algunos de los casos en que se puede generar un error de valor en el ID de la FK.

POstea las partes del código que tengan que ver con la recuperación de ese ID antes de insertar el comentario,.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #7 (permalink)  
Antiguo 22/10/2012, 06:32
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Es un tema de Doctrine, postea las entidades tal cual las tengas y el código que estas utilizando para persistirlas.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #8 (permalink)  
Antiguo 22/10/2012, 13:00
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Aqui os dejo el código. El $opinion->setArticulo($articulo); he probado a ponerlo también justo después del new Opinion(); y también me da error. El $articulo contiene un objeto articulo 100% seguro ya que lo muestro por pantalla mientras se comenta.

La variable $articulo_id la obtengo por la URL.

Código PHP:
Ver original
  1. $em = $this->getDoctrine()->getEntityManager();
  2.        
  3.         // Articulo Actual
  4.         $articulo  = $em->getRepository('ArticuloBundle:Articulo')->findOneById($articulo_id);
  5.         $marca = $articulo->getMarcaId(); // Obtenemos los datos de la marca
  6.         // Usuario actual
  7.         $usuario = $this->get('security.context')->getToken()->getUser();
  8.  
  9.         $opinion = new Opinion();
  10.  
  11.         $form = $this->createFormBuilder($opinion)
  12.                 ->add('opinion', 'textarea',array('label' => 'Opinión extensa sobre el producto'))
  13.                 ->add('sabor', 'integer')
  14.                 ->add('calidadprecio', 'integer',array('label' => 'Calidad/Precio'))
  15.                 ->add('efectividad', 'integer')
  16.                 ->add('probado', 'choice' ,array(
  17.                         'choices' => array('0' => 'No', '1' => 'Si'),
  18.                         'required' => true,
  19.                         'label' => '¿Has probado el producto?'
  20.                     ))
  21.                 ->add('pros', 'entity', array(
  22.                         'expanded' => false,
  23.                         'class' => 'OpinionesBundle:Pros',
  24.                         'query_builder' => function(EntityRepository $er) {
  25.                             return $er->createQueryBuilder('pc')
  26.                                    ->orderBy('pc.descripcion', 'ASC');
  27.                         },
  28.                         'multiple' => true,
  29.                         'property' => 'descripcion',
  30.                         'label' => 'Beneficios'
  31.                     ))
  32.                 ->add('contras', 'entity', array(
  33.                         'expanded' => false,
  34.                         'class' => 'OpinionesBundle:Contras',
  35.                         'query_builder' => function(EntityRepository $er) {
  36.                             return $er->createQueryBuilder('pc')
  37.                                    ->orderBy('pc.descripcion', 'ASC');
  38.                         },
  39.                         'multiple' => true,
  40.                         'property' => 'descripcion',
  41.                         'label' => 'Contras'
  42.                     ))
  43.                 ->getForm();
  44.  
  45.         if ($request->getMethod() == 'POST') {
  46.             $form->bindRequest($request);
  47.  
  48.             if($form->isValid()) {
  49.  
  50.                 $opinion->setArticulo($articulo);
  51.  
  52.                 $em->persist($opinion);
  53.                 $em->flush();
  54.  
  55.                 return $this->redirect($this->generateUrl('portada'));
  56.  
  57.             } else {
  58.                 // Formulario no valido
  59.             }
  60.         }

Gracias por vuestra ayuda a ver si conseguimos resolver esto. :)
  #9 (permalink)  
Antiguo 22/10/2012, 13:13
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Hola Victoor, falta el código de las entidades(Articulo y Opinion).

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #10 (permalink)  
Antiguo 22/10/2012, 14:33
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Opinion.php
Código PHP:
Ver original
  1. <?php
  2.  
  3. namespace BestSup\OpinionesBundle\Entity;
  4.  
  5. use Doctrine\ORM\Mapping as ORM;
  6. use Symfony\Component\Validator\Constraints as Assert;
  7.  
  8. /**
  9.  * BestSup\OpinionesBundle\Entity\Opinion
  10.  *
  11.  * @ORM\Table()
  12.  * @ORM\Entity
  13.  */
  14. class Opinion
  15. {
  16.     /**
  17.      * @var integer $id
  18.      *
  19.      * @ORM\Column(name="id", type="integer")
  20.      * @ORM\Id
  21.      * @ORM\GeneratedValue(strategy="AUTO")
  22.      */
  23.     private $id;
  24.  
  25.     /**
  26.      * @var integer $articulo
  27.      *
  28.      * @ORM\ManyToOne(targetEntity="BestSup\ArticuloBundle\Entity\Articulo")
  29.      */
  30.     private $articulo;
  31.  
  32.     /**
  33.      * @var integer $usuario
  34.      *
  35.      * @ORM\ManyToOne(targetEntity="BestSup\UserBundle\Entity\User")
  36.      */
  37.     private $usuario;
  38.  
  39.     /**
  40.      * @var text $opinion
  41.      *
  42.      * @Assert\MinLength(limit=400, message="La opinión es demasiado corta. (Al menos 400 caracteres).")
  43.      *
  44.      * @ORM\Column(name="opinion", type="text")
  45.      */
  46.     private $opinion;
  47.  
  48.     /**
  49.      * @var integer $sabor
  50.      *
  51.      * @Assert\Max(limit = 10, message = "Debe ser un valor entre 0 y 10.")
  52.      * @Assert\min(limit = 0, message = "Debe ser un valor entre 0 y 10.")
  53.      *
  54.      * @ORM\Column(name="sabor", type="integer")
  55.      */
  56.     private $sabor;
  57.  
  58.     /**
  59.      * @var integer $calidadprecio
  60.      *
  61.      * @Assert\Max(limit = 10, message = "Debe ser un valor entre 0 y 10.")
  62.      * @Assert\min(limit = 0, message = "Debe ser un valor entre 0 y 10.")
  63.      *
  64.      * @ORM\Column(name="calidadprecio", type="integer")
  65.      */
  66.     private $calidadprecio;
  67.  
  68.     /**
  69.      * @var integer $efectividad
  70.      *
  71.      * @Assert\Max(limit = 10, message = "Debe ser un valor entre 0 y 10.")
  72.      * @Assert\min(limit = 0, message = "Debe ser un valor entre 0 y 10.")
  73.      *
  74.      * @ORM\Column(name="efectividad", type="integer")
  75.      */
  76.     private $efectividad;
  77.  
  78.     /**
  79.      * @var integer $probado
  80.      *
  81.      * @ORM\Column(name="probado", type="integer")
  82.      */
  83.     private $probado;
  84.  
  85.     /**
  86.      * @var integer $pros
  87.      *
  88.      * @ORM\ManyToMany(targetEntity="BestSup\OpinionesBundle\Entity\Pros", cascade={"persist"})
  89.      */
  90.     private $pros;
  91.  
  92.     /**
  93.      * @var integer $contras
  94.      *
  95.      * @ORM\ManyToMany(targetEntity="BestSup\OpinionesBundle\Entity\Contras", cascade={"persist"})
  96.      */
  97.     private $contras;
  98.  
  99.  
  100.     /**
  101.      * Get id
  102.      *
  103.      * @return integer
  104.      */
  105.     public function getId()
  106.     {
  107.         return $this->id;
  108.     }
  109.  
  110.     /**
  111.      * Set articulo
  112.      *
  113.      * @param integer $articulo
  114.      */
  115.     public function setArticulo($articulo)
  116.     {
  117.         $this->articulo = $articulo;
  118.     }
  119.  
  120.     /**
  121.      * Get articulo
  122.      *
  123.      * @return integer
  124.      */
  125.     public function getArticulo()
  126.     {
  127.         return $this->articulo;
  128.     }
  129.  
  130.     /**
  131.      * Set usuario
  132.      *
  133.      * @param integer $usuario
  134.      */
  135.     public function setUsuario($usuario)
  136.     {
  137.         $this->usuario = $usuario;
  138.     }
  139.  
  140.     /**
  141.      * Get usuario
  142.      *
  143.      * @return integer
  144.      */
  145.     public function getUsuario()
  146.     {
  147.         return $this->usuario;
  148.     }
  149.  
  150.     /**
  151.      * Set opinion
  152.      *
  153.      * @param text $opinion
  154.      */
  155.     public function setOpinion($opinion)
  156.     {
  157.         $this->opinion = $opinion;
  158.     }
  159.  
  160.     /**
  161.      * Get opinion
  162.      *
  163.      * @return text
  164.      */
  165.     public function getOpinion()
  166.     {
  167.         return $this->opinion;
  168.     }
  169.  
  170.     /**
  171.      * Set sabor
  172.      *
  173.      * @param integer $sabor
  174.      */
  175.     public function setSabor($sabor)
  176.     {
  177.         $this->sabor = $sabor;
  178.     }
  179.  
  180.     /**
  181.      * Get sabor
  182.      *
  183.      * @return integer
  184.      */
  185.     public function getSabor()
  186.     {
  187.         return $this->sabor;
  188.     }
  189.  
  190.     /**
  191.      * Set calidadprecio
  192.      *
  193.      * @param integer $calidadprecio
  194.      */
  195.     public function setCalidadPrecio($calidadprecio)
  196.     {
  197.         $this->calidadprecio = $calidadprecio;
  198.     }
  199.  
  200.     /**
  201.      * Get calidadprecio
  202.      *
  203.      * @return integer
  204.      */
  205.     public function getCalidadPrecio()
  206.     {
  207.         return $this->calidadprecio;
  208.     }
  209.  
  210.     /**
  211.      * Set efectividad
  212.      *
  213.      * @param integer $efectividad
  214.      */
  215.     public function setEfectividad($efectividad)
  216.     {
  217.         $this->efectividad = $efectividad;
  218.     }
  219.  
  220.     /**
  221.      * Get efectividad
  222.      *
  223.      * @return integer
  224.      */
  225.     public function getEfectividad()
  226.     {
  227.         return $this->efectividad;
  228.     }
  229.  
  230.     /**
  231.      * Set probado
  232.      *
  233.      * @param integer $probado
  234.      */
  235.     public function setProbado($probado)
  236.     {
  237.         $this->probado = $probado;
  238.     }
  239.  
  240.     /**
  241.      * Get probado
  242.      *
  243.      * @return integer
  244.      */
  245.     public function getProbado()
  246.     {
  247.         return $this->probado;
  248.     }
  249.  
  250.     /**
  251.      * Set pros
  252.      *
  253.      * @param integer $pros
  254.      */
  255.     public function setPros($pros)
  256.     {
  257.         $this->pros = $pros;
  258.     }
  259.  
  260.     /**
  261.      * Get pros
  262.      *
  263.      * @return integer
  264.      */
  265.     public function getPros()
  266.     {
  267.         return $this->pros;
  268.     }
  269.     public function __construct()
  270.     {
  271.         $this->pros = new \Doctrine\Common\Collections\ArrayCollection();
  272.     }
  273.    
  274.     /**
  275.      * Add pros
  276.      *
  277.      * @param BestSup\OpinionesBundle\Entity\Pros $pros
  278.      */
  279.     public function addPros(\BestSup\OpinionesBundle\Entity\Pros $pros)
  280.     {
  281.         $this->pros[] = $pros;
  282.     }
  283.  
  284.     /**
  285.      * Set contras
  286.      *
  287.      * @param integer $contras
  288.      */
  289.     public function setContras($contras)
  290.     {
  291.         $this->contras = $contras;
  292.     }
  293.  
  294.     /**
  295.      * Get contras
  296.      *
  297.      * @return integer
  298.      */
  299.     public function getContras()
  300.     {
  301.         return $this->contras;
  302.     }
  303.    
  304.     /**
  305.      * Add contras
  306.      *
  307.      * @param BestSup\OpinionesBundle\Entity\Contras $contras
  308.      */
  309.     public function addContras(\BestSup\OpinionesBundle\Entity\Contras $contras)
  310.     {
  311.         $this->contras[] = $contras;
  312.     }
  313. }
  #11 (permalink)  
Antiguo 22/10/2012, 14:34
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Articulos.php
Código PHP:
Ver original
  1. <?php
  2.  
  3. namespace BestSup\ArticuloBundle\Entity;
  4.  
  5. use Doctrine\ORM\Mapping as ORM;
  6. use BestSup\ArticuloBundle\Util\Util;
  7.  
  8. /**
  9.  * BestSup\ArticuloBundle\Entity\Articulo
  10.  *
  11.  * @ORM\Table()
  12.  * @ORM\Entity
  13.  */
  14. class Articulo
  15. {
  16.     /**
  17.      * @var integer $id
  18.      *
  19.      * @ORM\Column(name="id", type="integer")
  20.      * @ORM\Id
  21.      * @ORM\GeneratedValue(strategy="AUTO")
  22.      */
  23.     private $id;
  24.  
  25.     /**
  26.      * @var string $nombre
  27.      *
  28.      * @ORM\Column(name="nombre", type="string", length=255)
  29.      */
  30.     private $nombre;
  31.  
  32.     /**
  33.      * @var text $descripcion
  34.      *
  35.      * @ORM\Column(name="descripcion", type="text")
  36.      */
  37.     private $descripcion;
  38.  
  39.     /**
  40.      * @var string $imagen
  41.      *
  42.      * @ORM\Column(name="imagen", type="string", length=255)
  43.      */
  44.     private $imagen;
  45.  
  46.     /**
  47.      * @var string $slug
  48.      *
  49.      * @ORM\Column(name="slug", type="string", length=255)
  50.      */
  51.     private $slug;
  52.  
  53.     /**
  54.      * @var datetime $fecha_alta
  55.      *
  56.      * @ORM\Column(name="fecha_alta", type="datetime")
  57.      */
  58.     private $fecha_alta;
  59.  
  60.     /**
  61.      * @var datetime $fecha_modificacion
  62.      *
  63.      * @ORM\Column(name="fecha_modificacion", type="datetime")
  64.      */
  65.     private $fecha_modificacion;
  66.  
  67.     /**
  68.      * @var float $nota
  69.      *
  70.      * @ORM\Column(name="nota", type="float")
  71.      */
  72.     private $nota;
  73.  
  74.     /**
  75.      * @var integer $categoria
  76.      *
  77.      * @ORM\ManyToOne(targetEntity="BestSup\ArticuloBundle\Entity\Categoria")
  78.      */
  79.     private $categoria;
  80.  
  81.     /**
  82.      * @var integer $marca
  83.      *
  84.      * @ORM\ManyToOne(targetEntity="BestSup\ArticuloBundle\Entity\Marca")
  85.      */
  86.     private $marca;
  87.  
  88.  
  89.     /**
  90.      * Get id
  91.      *
  92.      * @return integer
  93.      */
  94.     public function getId()
  95.     {
  96.         return $this->id;
  97.     }
  98.  
  99.     /**
  100.      * Set nombre
  101.      *
  102.      * @param string $nombre
  103.      */
  104.     public function setNombre($nombre)
  105.     {
  106.         $this->nombre = $nombre;
  107.         $this->slug = Util::getSlug($nombre);
  108.     }
  109.  
  110.     /**
  111.      * Get nombre
  112.      *
  113.      * @return string
  114.      */
  115.     public function getNombre()
  116.     {
  117.         return $this->nombre;
  118.     }
  119.  
  120.     /**
  121.      * Set descripcion
  122.      *
  123.      * @param text $descripcion
  124.      */
  125.     public function setDescripcion($descripcion)
  126.     {
  127.         $this->descripcion = $descripcion;
  128.     }
  129.  
  130.     /**
  131.      * Get descripcion
  132.      *
  133.      * @return text
  134.      */
  135.     public function getDescripcion()
  136.     {
  137.         return $this->descripcion;
  138.     }
  139.  
  140.     /**
  141.      * Set imagen
  142.      *
  143.      * @param string $imagen
  144.      */
  145.     public function setImagen($imagen)
  146.     {
  147.         $this->imagen = $imagen;
  148.     }
  149.  
  150.     /**
  151.      * Get imagen
  152.      *
  153.      * @return string
  154.      */
  155.     public function getImagen()
  156.     {
  157.         return $this->imagen;
  158.     }
  159.  
  160.     /**
  161.      * Set slug
  162.      *
  163.      * @param string $slug
  164.      */
  165.     public function setSlug($slug)
  166.     {
  167.         $this->slug = $slug;
  168.     }
  169.  
  170.     /**
  171.      * Get slug
  172.      *
  173.      * @return string
  174.      */
  175.     public function getSlug()
  176.     {
  177.         return $this->slug;
  178.     }
  179.  
  180.     /**
  181.      * Set fecha_alta
  182.      *
  183.      * @param datetime $fechaAlta
  184.      */
  185.     public function setFechaAlta($fechaAlta)
  186.     {
  187.         $this->fecha_alta = $fechaAlta;
  188.     }
  189.  
  190.     /**
  191.      * Get fecha_alta
  192.      *
  193.      * @return datetime
  194.      */
  195.     public function getFechaAlta()
  196.     {
  197.         return $this->fecha_alta;
  198.     }
  199.  
  200.     /**
  201.      * Set fecha_modificacion
  202.      *
  203.      * @param datetime $fechaModificacion
  204.      */
  205.     public function setFechaModificacion($fechaModificacion)
  206.     {
  207.         $this->fecha_modificacion = $fechaModificacion;
  208.     }
  209.  
  210.     /**
  211.      * Get fecha_modificacion
  212.      *
  213.      * @return datetime
  214.      */
  215.     public function getFechaModificacion()
  216.     {
  217.         return $this->fecha_modificacion;
  218.     }
  219.  
  220.     /**
  221.      * Set nota
  222.      *
  223.      * @param float $nota
  224.      */
  225.     public function setNota($nota)
  226.     {
  227.         $this->nota = $nota;
  228.     }
  229.  
  230.     /**
  231.      * Get nota
  232.      *
  233.      * @return float
  234.      */
  235.     public function getNota()
  236.     {
  237.         return $this->nota;
  238.     }
  239.  
  240.     /**
  241.      * Set categoria
  242.      *
  243.      * @param integer $categoriaId
  244.      */
  245.     public function setCategoriaId(\BestSup\ArticuloBundle\Entity\Categoria $categoriaId)
  246.  
  247.     {
  248.         $this->categoria = $categoriaId;
  249.     }
  250.  
  251.     /**
  252.      * Get categoria
  253.      *
  254.      * @return integer
  255.      */
  256.     public function getCategoriaId()
  257.     {
  258.         return $this->categoria;
  259.     }
  260.  
  261.     /**
  262.      * Set marca
  263.      *
  264.      * @param integer $marcaId
  265.      */
  266.     public function setMarcaId(\BestSup\ArticuloBundle\Entity\Marca $marcaId)
  267.     {
  268.         $this->marca = $marcaId;
  269.     }
  270.  
  271.     /**
  272.      * Get marca
  273.      *
  274.      * @return integer
  275.      */
  276.     public function getMarcaId()
  277.     {
  278.         return $this->marca;
  279.     }
  280. }
  #12 (permalink)  
Antiguo 22/10/2012, 15:39
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Estas seguro que el articulo es valido ?, donde lo validas ?, de todas formas modifica el setter a

Código PHP:
Ver original
  1. public funtion setArticulo(Articulo $articulo)
  2. {
  3.     $this->articulo = $articulo;
  4. }
__________________
http://es.phptherightway.com/
thats us riders :)
  #13 (permalink)  
Antiguo 24/10/2012, 12:59
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Ahora que he cambiado lo que comentas el error es

Catchable Fatal Error: Argument 1 passed to BestSup\OpinionesBundle\Entity\Opinion::setArticul o() must be an instance of
BestSup\OpinionesBundle\Entity\Articulo, instance of BestSup\ArticuloBundle\Entity\Articulo given, called in
/Users/victoor89/Sites/Symfony/src/BestSup/OpinionesBundle/Controller/DefaultController.php on line 68 and defined in
/Users/victoor89/Sites/Symfony/src/BestSup/OpinionesBundle/Entity/Opinion.php line 115

Y si parece que en la variable $articulo no hay un artículo, pero en la base de datos tengo un artículo con id 11 (valor de $articulo_id) y la consulta está correcta así que realmente no se que pasa……
  #14 (permalink)  
Antiguo 24/10/2012, 13:21
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: Problema con formulario y clave foranea

Pues si te fijas, el problema no es ese, si no más bien que la entidad no es correcta:
Catchable Fatal Error: Argument 1 passed to BestSup\OpinionesBundle\Entity\Opinion::setArticul o() must be an instance of
BestSup\OpinionesBundle\Entity\Articulo, instance of BestSup\ArticuloBundle\Entity\Articulo given, called in
/Users/victoor89/Sites/Symfony/src/BestSup/OpinionesBundle/Controller/DefaultController.php on line 68 and defined in
/Users/victoor89/Sites/Symfony/src/BestSup/OpinionesBundle/Entity/Opinion.php line 115

Es decir, doctrine espera un Articulo de OpinionesBundle, y le estas pasando uno de ArticuloBundle, es por eso que te esta marcando el error, porque son dos entidades diferentes.
  #15 (permalink)  
Antiguo 24/10/2012, 13:22
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Tienes que hacer el import de la clase BestSup\ArticuloBundle\Entity\Articulo en la clase BestSup\OpinionesBundle\Entity\Opinion, debería funciona, tienes algún listener para el persist ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #16 (permalink)  
Antiguo 27/10/2012, 03:51
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Cita:
Iniciado por masterpuppet Ver Mensaje
Tienes que hacer el import de la clase BestSup\ArticuloBundle\Entity\Articulo en la clase BestSup\OpinionesBundle\Entity\Opinion, debería funciona, tienes algún listener para el persist ?

No entiendo nada… :S ¿Que debo hacer?
  #17 (permalink)  
Antiguo 27/10/2012, 06:50
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Tienes que importar la clase o bien en setArticulo pasar el FQCN.

importar
Código PHP:
Ver original
  1. namespace BestSup\OpinionesBundle\Entity;
  2.  
  3. use BestSup\ArticuloBundle\Entity\Articulo;
  4.  
  5. class Opinion
  6. {
  7.     public function setArticulo(Articulo $articulo)
  8.     {...}
  9. }

fqnc
Código PHP:
Ver original
  1. namespace BestSup\OpinionesBundle\Entity;
  2.  
  3. class Opinion
  4. {
  5.     public function setArticulo(\BestSup\ArticuloBundle\Entity\Articulo $articulo)
  6.     {...}
  7. }

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #18 (permalink)  
Antiguo 27/10/2012, 10:15
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Los dos son la entidad Opinion?
  #19 (permalink)  
Antiguo 27/10/2012, 21:09
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problema con formulario y clave foranea

Victoor, me estas matando, son dos formas de hacer lo mismo, importa la clase o utiliza el FQCN.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #20 (permalink)  
Antiguo 30/10/2012, 15:01
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 16 años, 8 meses
Puntos: 0
Respuesta: Problema con formulario y clave foranea

Vale, muchas gracias. He conseguido arreglarlo y no se muy bien como, pero funciona.

¡Muchas gracias!

Etiquetas: formulario, key, symfony2, foreignkey
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 08:17.