tirenweb
tirenweb

Reputation: 31749

symfony2: storing an object in the database

When I try to execute the action below I'm getting this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category_id' cannot be null (500 Internal Server Error)

As you can see in the action I'm setting the field category_id (setCategoryId()), so what's the reason of the error?

Note: as you can see I'm trying to save in the database a proposal (propuesta) and tags associated to it.

public function savePropuestaAction() {

    $em = $this->get('doctrine.orm.entity_manager');
    $propuesta = new Propuestas();

    //retrieve the values inserted in the form.    
    $form = $this->getRequest()->request->get('form');
    $propuestaContent = $form['propuesta'];
    $propuestaCategory = $form['Categoría'][0];     

    $propuesta->setTitulo('$propuestaCategory');
    $propuesta->setContenido($propuestaContent);
    $propuesta->setCategoryId(1);

    //retrieve the tags inserted in the form...
    $tags = array();
    foreach($form as $key => $field)
    {
      if(substr($key, 0, 3) == 'tag')
      {
        $tagsName[] = $field;
      }
    }

    // ...and then store them and associate them to the proposal.
    if(count($tagsName))
    {                  
      foreach($tagsName as $tagName)
      { 
        $tag = new TagPropuesta();
        $tag->setName($tagName);
        $em->persist($tag);
        $em->flush();

        $propuesta->addTagPropuesta($tag);
        $em->persist($propuesta);
        $em->flush();
      }
    }              

    return new Response();
}

EDIT: after a couple of answers I've tried it replacing the line

$propuesta->setCategoryId(1);

with

$repository = $this->getDoctrine()->getRepository('JanderJanderBundle:PropuestasCategory');
$category = $repository->find(1);
//die(get_class($category)); 
$propuesta->setCategory($category);

but the error message is the same..

Here you have also the .yml file and the entity Propuesta (I didn't modify Propuesta class at all, I just generated it using generate:entities task):

Jander\JanderBundle\Entity\Propuestas:
  type: entity
  table: propuestas
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
    category_id:
      type: integer
      nullable: true
    user_id:
      type: integer
      nullable: true
    titulo:
      type: string
      length: 230
      fixed: false
    contenido:
      type: string
      length: 230
      fixed: false
    tema:
      type: string
      length: 40
      fixed: false
      nullable: true
    eliminado:
      type: boolean
      nullable: true
    created:
      type: date
      gedmo:
        timestampable:
          on: create
    votes_up:
      type: integer
      nullable: true
    votes_down:
      type: integer
      nullable: true
  manyToOne:
    category:
      targetEntity: PropuestasCategory
      inversedBy: propuestas
      joinColumn:
        name: category_id
        referencedColumnName: id  
    usuario:
      targetEntity: Usuario
      inversedBy: propuestas
      joinColumn:
        name: user_id
        referencedColumnName: id
  manyToMany:
    tags:
      targetEntity: TagPropuesta
      inversedBy: propuestas    
  lifecycleCallbacks: {  }



<?php

namespace Jander\JanderBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Jander\JanderBundle\Entity\Propuestas
 */
class Propuestas
{
    /**
     * @var integer $id
     */
    private $id;

    /**
     * @var string $contenido
     */
    private $contenido;

    /**
     * @var string $tema
     */
    private $tema;

    /**
     * @var boolean $eliminado
     */
    private $eliminado;

    /**
     * @var date $created
     */
    private $created;

    /**
     * @var integer $votes
     */
    private $votes;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set contenido
     *
     * @param string $contenido
     */
    public function setContenido($contenido)
    {
        $this->contenido = $contenido;
    }

    /**
     * Get contenido
     *
     * @return string 
     */
    public function getContenido()
    {
        return $this->contenido;
    }

    /**
     * Set tema
     *
     * @param string $tema
     */
    public function setTema($tema)
    {
        $this->tema = $tema;
    }

    /**
     * Get tema
     *
     * @return string 
     */
    public function getTema()
    {
        return $this->tema;
    }

    /**
     * Set eliminado
     *
     * @param boolean $eliminado
     */
    public function setEliminado($eliminado)
    {
        $this->eliminado = $eliminado;
    }

    /**
     * Get eliminado
     *
     * @return boolean 
     */
    public function getEliminado()
    {
        return $this->eliminado;
    }

    /**
     * Set created
     *
     * @param date $created
     */
    public function setCreated($created)
    {
        $this->created = $created;
    }

    /**
     * Get created
     *
     * @return date 
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set votes
     *
     * @param integer $votes
     */
    public function setVotes($votes)
    {
        $this->votes = $votes;
    }

    /**
     * Get votes
     *
     * @return integer 
     */
    public function getVotes()
    {
        return $this->votes;
    }
    /**
     * @var integer $category_id
     */
    private $category_id;

    /**
     * @var Jander\JanderBundle\Entity\PropuestasCategory
     */
    private $category;


    /**
     * Set category_id
     *
     * @param integer $categoryId
     */
    public function setCategoryId($categoryId)
    {
        $this->category_id = $categoryId;
    }

    /**
     * Get category_id
     *
     * @return integer 
     */
    public function getCategoryId()
    {
        return $this->category_id;
    }

    /**
     * Set category
     *
     * @param Jander\JanderBundle\Entity\PropuestasCategory $category
     */
    public function setCategory(\Jander\JanderBundle\Entity\PropuestasCategory $category)
    {
        $this->category = $category;
    }

    /**
     * Get category
     *
     * @return Jander\JanderBundle\Entity\PropuestasCategory 
     */
    public function getCategory()
    {
        return $this->category;
    }
    /**
     * @var Jander\JanderBundle\Entity\TagPropuesta
     */
    private $tags;

    public function __construct()
    {
        $this->tags = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add tags
     *
     * @param Jander\JanderBundle\Entity\TagPropuesta $tags
     */
    public function addTagPropuesta(\Jander\JanderBundle\Entity\TagPropuesta $tags)
    {
        $this->tags[] = $tags;
    }

    /**
     * Get tags
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getTags()
    {
        return $this->tags;
    }
    /**
     * @var integer $user_id
     */
    private $user_id;

    /**
     * @var Jander\JanderBundle\Entity\Usuario
     */
    private $usuario;


    /**
     * Set user_id
     *
     * @param integer $userId
     */
    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    /**
     * Get user_id
     *
     * @return integer 
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    /**
     * Set usuario
     *
     * @param Jander\JanderBundle\Entity\Usuario $usuario
     */
    public function setUsuario(\Jander\JanderBundle\Entity\Usuario $usuario)
    {
        $this->usuario = $usuario;
    }

    /**
     * Get usuario
     *
     * @return Jander\JanderBundle\Entity\Usuario 
     */
    public function getUsuario()
    {
        if($this->usuario == null)
        {
            return "anonimo";  
        }else{
            return $this->usuario;
        }

    }
    /**
     * @var integer $jander
     */
    private $jander;


    /**
     * Set jander
     *
     * @param integer $jander
     */
    public function setJander($jander)
    {
        $this->jander = $jander;
    }

    /**
     * Get jander
     *
     * @return integer 
     */
    public function getJander()
    {
        return $this->jander;
    }
    /**
     * @var integer $votes_up
     */
    private $votes_up;

    /**
     * @var integer $votes_down
     */
    private $votes_down;


    /**
     * Set votes_up
     *
     * @param integer $votesUp
     */
    public function setVotesUp($votesUp)
    {
        $this->votes_up = $votesUp;
    }

    /**
     * Get votes_up
     *
     * @return integer 
     */
    public function getVotesUp()
    {
        if($this->votes_up == null)
        {
          return 0;
        }
        else
        {
          return $this->votes_up;
        }    
    }

    /**
     * Set votes_down
     *
     * @param integer $votesDown
     */
    public function setVotesDown($votesDown)
    {
        $this->votes_down = $votesDown;
    }

    /**
     * Get votes_down
     *
     * @return integer 
     */
    public function getVotesDown()
    {
        if($this->votes_down == null)
        {
          return 0;
        }
        else
        {
          return $this->votes_down;
        }    


    }

    public function getTotalVotes()
    {
        return ($this->getVotesDown()+$this->getVotesUp());
    }
    /**
     * @var string $titulo
     */
    private $titulo;


    /**
     * Set titulo
     *
     * @param string $titulo
     */
    public function setTitulo($titulo)
    {
        $this->titulo = $titulo;
    }

    /**
     * Get titulo
     *
     * @return string 
     */
    public function getTitulo()
    {
        return $this->titulo;
    }
}

Javi

Upvotes: 0

Views: 2756

Answers (2)

Asish AP
Asish AP

Reputation: 4441

I think in your db table named 'propuesta' have a foreignkey category_id,right? Then in your entity must have a field category not category_id and its set and get function are setCategory() and getCategory(),not setCategoryId(). For a foreignkey related field must have expected its object. So in your case

$category=$em->getDoctrine()->getEnitityManager()->getRepository('YourBundleName:Category')->find($id);
$propuesta->setCategory($category);//here category is an object.

so first check your entity of propuesta and its yml file.

updated

1. Change your yml like this

    Jander\JanderBundle\Entity\Propuestas:
      type: entity
      table: propuestas
      fields:
        id:
          id: true
          type: integer
          unsigned: false
          nullable: false
          generator:
            strategy: IDENTITY
        user_id:
          type: integer
          nullable: true
        titulo:
          type: string
          length: 230
          fixed: false
        contenido:
          type: string
          length: 230
          fixed: false
        tema:
          type: string
          length: 40
          fixed: false
          nullable: true
        eliminado:
          type: boolean
          nullable: true
        created:
          type: date
          gedmo:
            timestampable:
              on: create
        votes_up:
          type: integer
          nullable: true
        votes_down:
          type: integer
          nullable: true
      manyToOne:
        category:
          targetEntity: PropuestasCategory
          inversedBy: propuestas
          joinColumn:
            name: category_id
            referencedColumnName: id  
        usuario:
          targetEntity: Usuario
          inversedBy: propuestas
          joinColumn:
            name: user_id
            referencedColumnName: id
      manyToMany:
        tags:
          targetEntity: TagPropuesta
          inversedBy: propuestas    
      lifecycleCallbacks: {  }

You do'nt need to specify the category_id in your yml file,just specify the relation.

  1. Change your entity file also

    remove the field categoryid its setCategoryId() and getCategoryId() function.

  2. You must change all your yml file of other table and give the relation as the above.Also change their entity files.

Just go through how to write yml file and its relation,then use generate:enitites command of symfony2.

If you don't know how to write yml and its entity Another one good method is reverse process 1. First create your db and its tables, give its foreignkey relations as you need in your msql.

  1. set your database connections in parameters.ini file of your project.(hopes you know,just give dbname,username,password(if any)).

  2. Delete all your yml file in res/config/doctrine/ and Entity files.

4.open your terminal just give the following commands.These below commands generate automatically all your entity files and yml files with correct relations as you specify in your db.

a).php app/console doctrine:mapping:convert yml ./src/Acme/BlogBundle/Resources/config/doctrine --from-database --force //Acme/BlogBundle/ is namespace

Symfony2 generate entity from Database
b).php app/console doctrine:mapping:import AcmeBlogBundle yml //AcmeBlogBundle is bundle name c).php app/console doctrine:generate:entities AcmeBlogBundle

if you have any doubts refer this linkClick here

Hope this helps you

Upvotes: 2

Cerad
Cerad

Reputation: 48893

Need to thinks objects, not ids';

$category = $em=>getReference('Category',1);
$propuesta->setCategory($category);

I'm assuming that you did define a relation between propuesta and category.

Upvotes: 0

Related Questions