![Antiguo](http://static.forosdelweb.com/fdwtheme/images/statusicon/post_old.gif)
21/11/2014, 11:23
|
![Avatar de Dundee](http://static.forosdelweb.com/customavatars/avatar21929_9.gif) | | | Fecha de Ingreso: junio-2002 Ubicación: El Médano
Mensajes: 1.310
Antigüedad: 22 años, 2 meses Puntos: 8 | |
Respuesta: Warning: spl_object_hash() expects parameter 1 to be object, integer given No obstante ese problema parece estar ya resuelto al haber cambiado el tipo de dato a "entity" , pero ahora al guardar los datos en la db tengo un nuevo problema , porque los intenta guardar como null.
Para evitar más confusiones voy a pegar el código (con motivo de aprender buenas prácticas, he creado el form en una clase aparte para poder reutilizarlo cuando lo necesite).
Error:
Código:
An exception occurred while executing 'INSERT INTO Book (phrase, creator_uid, parent_branch) VALUES (?, ?, ?)' with params [null, null, null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'creator_uid' cannot be null
DefaultController.php
Código:
<?php
namespace Book\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Book\MainBundle\Entity\Book;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Book\MainBundle\Form\Phrase\NewPhrase;
class DefaultController extends Controller
{
public function indexAction($book)
{
$book = new Book();
$book->setPhrase('erase una vez 3..');
$book->setParentBranch(1);
$book->setCreatorUid(1);
$em = $this->getDoctrine()->getManager();
$em->persist($book);
$em->flush();
return $this->render('BookMainBundle:Default:index.html.twig', array('book' => $book));
}
public function createAction(Request $request){
$em = $this->getDoctrine()->getManager();
// crea una task y le asigna algunos datos ficticios para este ejemplo
$parent_book = new Book();
$parent_book->setId(2);
//guardas parent
$em->persist($parent_book);
$book = new Book();
$book->setPhrase('Write a blog post');
$book->setParentBranch($parent_book->getId());
// $book->setDueDate(new \DateTime('tomorrow'));
$book->setCreatorUid(1);
/*
$form = $this->createFormBuilder($book)
// ->setAction($this->generateUrl('task_success'))
// ->setMethod('GET')
->add('phrase', 'textarea', array('label' => 'My phrase', 'max_length' => 500))
->add('parentBranch', 'integer')
->add('creatorUid', 'integer')
// ->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
*/
$form = $this->createForm(new NewPhrase(), $book);
$form->handleRequest($request);
if ($form->isValid()) {
// guardar la tarea en la base de datos
var_dump($book);
$em = $this->getDoctrine()->getManager();
$em->persist($book);
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
}
// Default view.
return $this->render('BookMainBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
public function successAction(){
return new Response('Formulario enviado correctamente');
}
}
Book.php (la entidad)
Código:
<?php
namespace Book\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Book
* @ORM\Table()
* @ORM\Entity(repositoryClass="Book\MainBundle\Entity\BookRepository")
*/
class Book
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @Assert\NotBlank()
* @Assert\Length(
* min = 10,
* max = 500,
* minMessage = "Your phrase must be at least {{ limit }} characters long",
* maxMessage = "Your phrase cannot be longer than {{ limit }} characters long"
* )
* @ORM\Column(name="phrase", type="string", length=255)
*/
private $phrase;
/**
* @var integer
* @Assert\NotBlank()
* @ORM\OneToOne(targetEntity="Book")
* @ORM\JoinColumn(name="parent_branch", referencedColumnName="id")
*/
private $parentBranch;
/**
* @var integer
* @Assert\NotBlank()
* @ORM\Column(name="creator_uid", type="integer")
*/
private $creatorUid;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* @return integer
*/
public function setId($id)
{
$this->id = $id;
return $this->id;
}
/**
* Set phrase
*
* @param string $phrase
* @return Book
*/
public function setPhrase($phrase)
{
$this->phrase = $phrase;
return $this;
}
/**
* Get phrase
*
* @return string
*/
public function getPhrase()
{
return $this->phrase;
}
/**
* Set parentBranch
*
* @param integer $parentBranch
* @return Book
*/
public function setParentBranch($parentBranch)
{
$this->parentBranch = $parentBranch;
return $this;
}
/**
* Get parentBranch
*
* @return integer
*/
public function getParentBranch()
{
return $this->parentBranch;
}
/**
* Set creatorUid
*
* @param integer $creatorUid
* @return Book
*/
public function setCreatorUid($creatorUid)
{
$this->creatorUid = $creatorUid;
return $this;
}
/**
* Get creatorUid
*
* @return integer
*/
public function getCreatorUid()
{
return $this->creatorUid;
}
public function __toString()
{
return $this->phrase;
}
}
Y por último la famosa clase NewPhrase.php
Código:
<?php
// src/Acme/TaskBundle/Form/Type/TaskType.php
namespace Book\MainBundle\Form\Phrase;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class NewPhrase extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('phrase', 'text', array('label' => 'My phrase', 'max_length' => 500))
->add('parentBranch', 'entity', array(
'class' => 'BookMainBundle:Book',
))
->add('creatorUid', 'integer')
->add('save', 'submit');
}
// unique identifier for this form.
public function getName()
{
return 'phrase';
}
}
|