[Postgres][Doctrine][Symfony 3] boolean and nullable issue - postgresql

I'm stuck with the following problem :
I'm setting a new boolean parameter into my entity,
/**
* #var boolean
*
* #ORM\Column(type="boolean", nullable=false)
*/
private $tester = false;
here, the tester has to be set to false,
but I get the following error when I try the -f :
[PDOException]
SQLSTATE[23502]: Not null violation: 7 ERREUR: « tester » column got NULL values
Thank you very much for your help.

Hi The New boolean field can't be null so you have to make a default value true or false
so change your code to
/**
* #var boolean
*
* #ORM\Column(type="boolean", nullable=false,options={"default":false})
*/
private $tester;

Related

Column cannot be null, but it is filled

This error is happening below, but I am passing a value to the column.
An exception occurred while executing 'INSERT INTO tbevt_votacaostatusopcao (clvotacaostatusopcao_idintegracao, clvotacaostatusopcao_idopcao, clvotacaosta
tusopcao_nome) VALUES (?, ?, ?)' with params [null, "23094", "Sim"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'clvotacaostatusopcao_idintegracao' cannot be null
My Entity:
/**
* #var VotacaoIntegracao
* #ORM\ManyToOne(targetEntity="Evento\Entity\VotacaoIntegracao", fetch="EAGER")
* #ORM\JoinColumn(name="clvotacaostatus_idintegracao", referencedColumnName="clvotacaointegracao_idintegracao")
*/
protected $integracao;
/**
* #var VotacaoStatusOpcao
* #ORM\OneToMany(targetEntity="Evento\Entity\VotacaoStatusOpcao", mappedBy="opcao")
*/
protected $votacaoStatusOpcao;
/**
* #ORM\Column(name="clvotacaostatus_idintegracao", type="integer")
*/
protected $idIntegracao;
/**
* #ORM\Column(name="clvotacaostatus_idstatus", type="integer")
*/
protected $idStatus;
My Service:
$this->entityManager->persist($votacaoStatus);
$votacaoStatus->setIdIntegracao($idIntegracao);
$votacaoStatus->setIdStatus($situacaoVotacao);
$this->entityManager->flush($votacaoStatus);
$this->entityManager->commit();
If I comment on the protected $integracao variable, the insert works, but I need this link. But I know the error is here.
Please, help me.
Both $integracao and idIntegracao are mapped to the same column clvotacaostatus_idintegracao. This looks like a mistake, probably you are setting one field and not another and later down the line Doctrine tries to save null value that comes from one of the fields

Invalid text representation: 7 ERROR: invalid input syntax for uuid: "test"

I'm using Symfony 3.2 with doctrine and postgresql.
I've created an entity with a uuid as primary key.
My entity definition:
/**
* Booking
*
* #ORM\Table(name="booking")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BookingRepository")
* #ORM\EntityListeners({"AppBundle\EventListener\BookingListener"})
*/
class Booking {
/**
* #var string
*
* #ORM\Column(type="guid")
* #ORM\Id
* #ORM\GeneratedValue(strategy="UUID")
*/
private $id;
}
In my controller I have a show action like this:
/**
* #Route("booking/{id}", name="booking_show")
* #Method({"GET"})
*/
public function showAction(Request $request, Booking $booking) {
...
}
Everything seems to work fine, but when I try to load a route putting an wrong value as an ID (i.e. /booking/hello123), I receive a:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for uuid: "hello123"
Instead I would expect a 404.
Is there a way to capture this exception and redirect to a 404 page?
You can make use of Route Requirements - you can specify what conditions your parameter need to match to "qualify" to a certain route. This requirement is a regex, so all you need to do is to write a regex for an UUID
/**
* #Route("booking/{id}", name="booking_show", requirements={"id": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"})
* #Method({"GET"})
*/
public function showAction(Request $request, Booking $booking) {
...
}
NOTE: Regex used above is just first result I found in Google for UUID regex, I didn't verify if it works
In the end if your id does not match regex, it does not match route and you should get 404.
you need to change the showaction
/**
* #Route("booking/{id}", name="booking_show")
* #Method({"GET"})
*/
public function showAction(Request $request,$bookingID) {
$em = $this->getDoctrine()->getManager();
$booking = $em->getRepository('AppBundle:Entity')->find(bookingID);
if(!$booking)
$this->createNotFoundException('No entity found with id :'.$bookingID);
...
}

Persisting a document suddenly stops returning next identifier value (ALNUM strategry)

I have Symfony 2.6 application and using doctrine-odm-bundle 3.0.2 (doctrine-odm: 1.1.2, mongodb: 1.4.0).
My document has referenceMany and referenceOne in attributes and when I create new instance of it, fill fields and persist - it goes fine in the begining. I can create few nearly empty documents, with referenced document(s) or without and it works fine. At some point I am trying to add new item in the database and getting an error:
E11000 duplicate key error collection: test.Product index: _id_ dup key: { : 0 }
The message is clear - I can see that there was a document added to the collection with id = 0, therefore second one can't go -> duplicate entry. But why it suddenly starts to return "0" for id? Even though, I checked doctrine_increment_ids collection - counter for id is being incremented. But $product->getId() becomes "0" after persist.
If I drop the database and start all over - it works, I can still add new products in the collection. Let's say I successfully created 12 products. Creating 13th resulting a document with id=0 being persisted in the collection. 14th fails with duplicate error.
Can you please help to troubleshoot or suggest an idea where does it go wrong?
P.S> I am not considering an upgrade of Symfony2 (at this point) neither as doctrine-odm-bundle (it depends on newer Symfony2 as well) - migration efforts are quite high and I am not sure it will fix the issue. First I want to find out the root cause.
// Document Product
/**
* #MongoDB\Document
* #MongoDB\HasLifecycleCallbacks
*/
class Product
{
/** #MongoDB\Id(strategy="ALNUM", type="int") */
protected $id;
/**
* #Gedmo\ReferenceOne(type="entity", class="Entity\User", inversedBy="products", identifier="userId")
*/
protected $user;
/**
* #MongoDB\Field(name="user_id", type="int")
*/
protected $userId;
/**
* #MongoDB\ReferenceMany(
* targetDocument="Picture",
* discriminatorMap={"file" = "File", "picture" = "Picture"},
* discriminatorField="discr",
* defaultDiscriminatorValue="picture"
* )
* #Assert\Valid
*/
protected $pictures;
...
}
// Entity User
/**
* User entity
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var ArrayCollection $textures
*
* #Gedmo\ReferenceMany(type="document", class="Document\Product", mappedBy="user")
*/
protected $products;
...
}
// Document Picture
/**
* #MongoDB\Document
* #MongoDB\InheritanceType("SINGLE_COLLECTION")
* #MongoDB\DiscriminatorField("discr")
* #MongoDB\DiscriminatorMap({"file" = "File", "picture" = "Picture"})
* #MongoDB\DefaultDiscriminatorValue("picture")
* #MongoDB\HasLifecycleCallbacks
*/
class Picture
{
/**
*
* #MongoDB\Id(strategy="ALNUM", type="int")
*/
protected $id;
/**
* #MongoDB\ReferenceOne(targetDocument="Product")
*
* #var Product $product
*/
protected $product;
...
}
Documentation reading always helps (generation strategies). Basically, strategy="ALNUM" and type="int" just can't go together :)
Change strategy to INCREMENT and remove type="int" if you want to have integers in your _id.
Or you can change type to string to continue with _id being an alphanumeric string.

Symfony2 valid constraint on form element does not show custom error message

I am constructing a form for users to submit a DMCA complaint, and one of the design requirements is to allow them to enter one or more URLs. To that end, I've created an entity (DMCAComplaint), and a child entity (DMCAComplaintURL) which is joined to DMCAComplaint in a Doctrine OneToMany relationship.
In order to validate the URL entries via regex, I have the following assertion set up:
// src: Bundle/Event/DMCAComplaintURL.php
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255, nullable=false)
* #Assert\Regex(
* pattern="/(https?:\/\/)?([\w].)*example.com(\/.*)?/"),
* message="Please enter a URL within our site"
* )
*/
protected $url;
And in the complaint:
// src: Bundle/Entity/DMCAComplaint.php
/**
* #var \DMCAComplaintURL
*
* #ORM\OneToMany(targetEntity="DMCAComplaintURL", mappedBy="dmcaComplaint", cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id", referencedColumnName="dmca_complaint_id")
* })
* #Assert\Valid
*/
protected $urls;
While the assertion works, it only gives the following error: This value is not valid. I would like it to have a custom message, as outlined in the DMCAComplaintUrl $url property. Is there a way to make this bubble up to the Valid assertion? or can I use something else to get what I need?
Set error_bubbling to true on your form field:
http://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling

Troubleshooting "[Syntax Error] Expected PlainValue, got ')'"

I am getting this error in my annotations docblock for Doctrine 2:
Doctrine\Common\Annotations\AnnotationException: [Syntax Error] Expected PlainValue, got ')'
After looking for an answer I found this reference Stackoverflow Question 3500125 which in essence says to put quotes around all values in annotations.
With the annotation block I have this does not seem possible. here is my example that is throwing the error.
/**
* #var tags
*
* #ManyToMany(targetEntity="namespace\to\tag")
* #JoinTable(name="content_tag",
* joinColumns={
* #JoinColumn(name="content_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #JoinColumn(name="tag_id", referencedColumnName="id")
* }
* ) // This is the line indicated by the error
*/
private $tags;
If I follow the advice of the answer I found in stack overflow which is to quote out the values, my code will be like this:
/**
* #var tags
*
* #ManyToMany(targetEntity="namespace\to\tag")
* #JoinTable(name="content_tag",
* joinColumns="{
* #JoinColumn(name="content_id", referencedColumnName="id")
* }",
* inverseJoinColumns="{
* #JoinColumn(name="tag_id", referencedColumnName="id")
* }" // Note the extra quotation marks
* )
*/
private $tags;
Which is not right at all.
For people who have come here but not because of doctrine, my mistake was using single quotes instead of double quotes in the #Routes annotation.
WRONG:
/**
* #Route('/home')
*/
RIGHT
/**
* #Route("/home")
*/
It was a silly mistake, the error string was not very helpful as it pointed to the line i showed in my question as the line that the error was on. The fact was that this entity was extending a parent object, the parent had the #Entity tag but the child did not, i moved it and everything works fine.
I Just had the same kind of error by using an assert for an entity :
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* mode = 'strict',
* normalizer = 'trim'
* )
Turning it into
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* mode = "strict",
* normalizer = "trim"
* )
Fixed it :)