Symfony3 Doctrine2 Column cannot be null - sql

[PROBLEM SOLVED]
Hey folks I need your help on a symfony project.
I have two entities, "article" and "image", article can have several images so I made a relationship OneToMany on the article side and ManyToOne on the image side. Doctrine generates for me an "article_id" column on the image table.
I made a form to create an article with one or more images... however when I execute it I have an error that is thrown :
An exception occurred while executing 'INSERT INTO image (url, alt, article_id) VALUES (?,?,?) 'with params ["jpeg", "untitled.jpg", null]: SQLSTATE [23000]: Integrity constraint violation: 1048 Column' article_id 'can not be null.
When I look to the profiler logs debug, I can see that I have an "INSERT INTO article[...]" (so the article is created with an ID ?) and just after this I have the famous "INSERT INTO image[...]" where the error occurs.
Thank you for your help.
EDIT In bold you will find the lines I added to solve this problem.
I added into the ArticleType form, in the images collection options this :
'by_reference' => false
And I added to the addImage method into the Article entity this :
$image->setArticle($this);
$this->images->add($image);

This is a very common question but surprisingly difficult to search for. In fact the first ten or so search results had incorrect answers.
In any event, you need to make sure that image is linked to the article.
class Article
public function addImage($image) {
$this->images[] = $image;
$image->setArticle($this); // ADD THIS

I think #Cerad's answer is very wrong, although I can't blame him because OP hasn't posted enough code, don't be shy with it, we're here to help. It also helps to briefly mention if you're just starting out (as I suspect you are) as it will help us gauge whether its a novice problem or something deeper.
Since I'm assuming it's a novice problem here is the novice solution.
With they way you've mapped (which I believe is correct) you are basically telling Doctrine to Tell your RDBMS (MySql/MariaDB/PostgreSQL) that an article CAN have many images, but an image MUST belong to an article.
This means that if you attempt to save an image without specifying the owning article, it will throw an error.
This is what I think you are doing evident in the line
(url, alt, article_id) VALUES (?,?,?) 'with params ["jpeg", "untitled.jpg", null]
the value "null" is where the issue is coming about because you are not specifying the owning article.
You have 2 options
1.) When saving image, if you have the article object at hand just do
$image->setArticle($article);
2.) When saving the image, if you have the article_id at hand just do
$image->setArticle($em->getReference('AppBundle\Entity\Articles', $article_id));
You must follow one of the above when saving an image directly.
My general experience has been that Doctrine does a really good job of generating entities from command line that you really don't need to change much unless adding some advanced functionality like second_level_cache or MySQL point type.
Cheers.

The problem is that when you submit your form, the first image is attached to the article but the others are not, so you get an SQL error.
You have to do a "foreach loop" for every image and attched the article to each one.
Look here at the addAction function
https://github.com/ismail1432/TheGoodLoc/blob/master/Symfony/src/VTC/AnnonceBundle/Controller/AdvertController.php

Related

Postgres INSERT returning 'invalid input syntax' for json

Problem: Attempting to insert a JSON string into a Postgres table column of json datatype intermittently returns this error for some record insertion attempts but not others.
I confirmed using multiple third party 'JSON validator' apps that the JSON I am inserting is indeed valid, and I have confirmed that any single ' quote characters have been escaped with the double '' technique, and the issue persists.
What are some additional troubleshooting steps to consider?
Here is a scrubbed sample JSON I have attempted:
{"id": "jf4ba72kFNQ","publishedAt": "2012-09-02T06:07:28Z","channelId": "UCrbUQCaozffv1soNdfDROXQ","title": "Scout vs. Witch: a tale of boy meets ghoul (Official Version)","tags": ["L4D","TF2","SFM","animation","zombies","Valve","video game"],"description": "Howdy folks (he''s alive!). I made a new SFM video (October 2015), called \"Nick in a Hotel Room\". Please check it out: https://www.youtube.com/watch?v=FOCTgwBIun0\n\nAlso check out some early behind the scenes of Scout vs. Witch:\nhttps://www.youtube.com/watch?v=73tQEBgD09I\n\nYou can find links to my stuff on my website: http://nailbiter.net\n\n-----\n\nhey gang,\nI''m the animator who made this cartoon. Hope you like it.\n\nThis is my little mash-up of a bunch of stuff I like. What happens when the Scout from Valve''s Team Fortress 2 video-game walks into the wrong neighborhood (Left 4 Dead). Hilarity (and a bodycount) ensues. It was created using Source Film Maker (for all the dialog stuff and the montage at the beginning), and with TF2/Source SDK for the entire 300 alley-run sequence. I had already completed that part before SFM was released. The big zombie horde scenes and a couple others were shot in Left 4 Dead. I hope you get a kick out of it.\n\nStuff I did:\nI animated all of the characters (using Maya) except for the big crowd scenes and parts of the headcrab zombie (the crawling and the legs). The faces in the dialog scenes were animated in SFM.\n\nAlso did additional mapping, particles, motion graphics, zombie maya rigging, and created blendshapes for the Witch''s face to enable her to talk/emote. I didn''t do a full set, just the phonemes I needed for this performance. Inspiration for her performance was based on Meg Mucklebones (if you''ve ever seen Legend) mixed with the demon ladies in Army of Darkness. I have a feeling Valve had seen those movies too when they designed her..\n\nthanks for watching."}
I am answering this question by enumerating all the other troubleshooting steps I have found so far, either 'working knowledge' that 'field workers' will have, or a little more obscure (or buried in postgres docs which, while thorough, are esoteric) insights I have found thru my own trial & error
Steps
Make sure you have escaped any single quote ' characters by double-escaping with like ''
Make sure your JSON string is actually a single line string - JSON is very easy to copy as a multiline string, and postgres JSON columns will not accept this (easy as hitting backspace on any newline)
Most obscure I've found: even when encapsulated in a JSON string field, the ? question mark weirdly enough breaks the JSON syntax for postgres. Something like {"url": "myurl.com?queryParam=someId"} will return as invalid. Solve this by escaping the question mark like: {"url": "myurl.com\?queryParam=someId"}

Avoid duplicates in the destination schema

I have a little problem. I want to map every detail line to one OrderInfo. The destination schema can not have any duplicate OrderInfo. All the detail lines should be in the destination orderInfo, but the SuppliersOrderNo and BuyersOrderNo should not be twice.
Any ideas how to do this, is it possible to use XSL or inline script?
<inv:OrderInfo>
<inv:SuppliersOrderNo>123456</inv:SuppliersOrderNo>
<inv:BuyersOrderNo>6789</inv:BuyersOrderNo>
<inv:DetailLines>
<inv:DetailLine>
<inv:InvoiceDetailLineNo>1</inv:InvoiceDetailLineNo>
<inv:Item>
<inv:SuppliersArticleNo>article2</inv:SuppliersArticleNo>
<inv:SuppliersDescription>BestArticle</inv:SuppliersDescription>
</inv:Item>
</inv:DetailLine>
<inv:DetailLine>
<inv:InvoiceDetailLineNo>2</inv:InvoiceDetailLineNo>
<inv:Item>
<inv:SuppliersArticleNo>article3</inv:SuppliersArticleNo>
<inv:SuppliersDescription>AlmostBestArticle</inv:SuppliersDescription>
</inv:Item>
</inv:DetailLine>
</inv:DetailLines>
</inv:OrderInfo>
<inv:OrderInfo>
<inv:SuppliersOrderNo>123456</inv:SuppliersOrderNo>
<inv:BuyersOrderNo>6789</inv:BuyersOrderNo>
<inv:DetailLines>
<inv:DetailLine>
<inv:InvoiceDetailLineNo>1</inv:InvoiceDetailLineNo>
<inv:Item>
<inv:SuppliersArticleNo>article1337</inv:SuppliersArticleNo>
<inv:SuppliersDescription>WOW</inv:SuppliersDescription>
</inv:Item>
</inv:DetailLine>
</inv:DetailLines>
</inv:OrderInfo>
If you want to do this purely in XSLT, you'll have to use Muenchian gruoping. I wrote a blog that links to some other blogs on how to do this in BizTalk a little while back: https://blog.tallan.com/2014/12/09/muenchian-grouping-in-biztalk-while-keeping-mapper-functionality/
To summarize the blog: if you pursue this, you'll need a map that's completely custom XSLT somewhere, but you could put it into a custom pipeline component if you still want to be able to use "regular" maps functionality without any other caveats (in my blog I describe a method of doing that in a pipeline component so that a "regular" BizTalk map can still be used on the preprocessed output). There are lots of resources on Muenchian grouping out there (including on StackOverflow), so I'm not rehashing all of that in this answer.
You could also try to serialize the message in a C# component and use some LINQ methods to group/sort/order/etc, or if you're inserting the content into SQL at some point you could do it in SQL (which would be able to handle this kind of task more naturally).

How to fix TypeError: transform(...) is null

Another individual said this error is generally caused by "a widget template that is referencing a property via ${...} that doesn't actually exist in the widget."
I've researched and can't seem to find a way to resolve this error. Any advice or leads to help solve this issue? How do you FIND this bit of code to correct the issue?
Got some assistance from SitePen.
Here's the trace Stack -
**string.substitute/<()string.js (line 147) string.substitute()string.js
(line 141) ._updatePaginationStatus()Pagination.js (line 395)
.gotoPage/
return transform(value, key).toString();
instrum...tion.js (line 20)**
The Pagination was failing - potentially trying to pull data before it was actually there.
"Code is trying to do a string.substitute call, but the transformation you're trying to do isn't valid. It looks like the Pagination extension is failing on this. Given the number of steps related to Deferreds, it looks like something is trying to parse data before that data is available. For example, you have an async call, but are treating the data synchronously.
That said, when using the Pagination extension, I think you use the normal Grid rather than the OnDemandGrid."
I switched from OnDemandGrid to Grid - left pagination. Error still there. Switched back to OnDemandGrid - eliminated Pagination. Error Gone.
Also found this little note that I had overlooked in documentation: "Note that the Pagination extension is incompatible with OnDemandGrid, since each has its own way of dealing with collection ranges. Pagination should be mixed into Grid, not OnDemandGrid."
http://dgrid.io/tutorials/0.4/grids_and_stores/
thankyousitepen

Documentation with Diagram "Hyperlinks" in Enterprise Architect?

I'm struggling to get all the required (and only the required) information into the documentation of my Enterprise Architect Project. Precisely: we have modelled various requirements and displayed the source "standards" for these requirements in our diagrams by using the "hyperlink"-element out of the common toolbox. (This allows us to capture a title, the website where the documentation is found and a description of this documentation).
Now this element is visible on the diagram, but not in the package-view of our model and it does not get generated in our word (docx) documentation.
I can see that it should be possible to get this in the documentation, because a "Model Report" which basically prints everything does print the hyperlinks. But I can't find what I have to select in my template (in the package-tree view, as a package field, element field or diagram field) in order to get this printed. I can't just use the model report since this basically dumps the whole database in the document and reverse-engineering this model report has proven too difficult for me. Actually I would expect this to be in some kind of documentation for EA, but could not find such a thing with this level of detail... is there, is there a reproducible way of finding such things out in further cases? (btw I'm using EA 11.0)
[sorry there were illustrations here, but I'm not allowed to upload them...]
As Geert has already noted, there is a difference between "proper" elements and diagram-only elements. This is actually reflected in the document template editor, where there is an "Element" section inside the "Diagram" section. This will produce output for all elements in the diagram, whether or not they are also in the project browser.
Here's an example of the information you can pull out of your hyperlinks. Given a diagram with a hyperlink:
... and a template which outputs name, alias and hyperlink for each element in the diagram:
... EA will generate a document will the following contents:
So if you want the hyperlink to result in a hyperlink in the document, use the HyperlinkAlias field.
What might be a bit confusing is the fact that in addition to the Hyperlink element type in the Common diagram toolbox, EA allows you to create hyperlinks in regular elements (in the Element Properties dialog, Related tab: Files, which can be local files or web addresses).
In fact, I would recommend that you use those in your Requirement elements rather than diagram-only Hyperlinks if traceability is a priority in your model. The diagram-only Hyperlinks, on the other hand, give you a clearer visual.
Selecting a subset of the elements in a diagram ("only the required information") is a little more involved and depends on how your model is structured. Template fragments will get the job done, but you might be able to achieve your desired result by just using the filters in the document generation dialog.
The hyperlink is an element that is stored in the same package as the diagram it is used on, it is just not visible in the project browser (similar to a note element).
There's a good chance that it doesn't have a name, so make sure you don't omit nameless elements.
So if you print all the element of the package containing the diagram then you should be able to print the hyperlink as well.
In case that fails you might want to consider creating a template fragment based on an SQL query or a script. Those offer lots of flexibility to print whatever you need, even if it is located in a different package.
[Edited on 04.05.15 to reflect the comment by Uffe and provide a final solution]
Ok, based on Geerts answer, using the following custom query fragment in the diagram section:
select
t_object.ea_guid as CLASSGUID,
t_object.Object_Type as CLASSTYPE,
t_object.Object_Id as OBJECTID,
t_object.name as HL_Name,
t_object.Stereotype as HL_Stereotype,
t_object.object_type as HL_Type,
t_object.Alias as HL_Alias,
Note as Notes
--,t_object.*
from t_object
left join t_diagramobjects on (t_object.Object_ID = t_diagramobjects.Object_ID)
left join t_diagram on (t_diagram.Diagram_ID = t_diagramobjects.Diagram_ID)
where t_diagram.Diagram_ID = '#DIAGRAMID#'
and t_object.Object_Type='Text'
I was able to get a list of the hyperlinks following the diagram, this is the fragment:
custom >
{HL_Alias}: {HL_Name}
{Notes}
< custom
The "Notes" can be printed by getting the attribute directly out of the t_object table. Don't get confused as I was at first: the auto-completion on t_object and the results (t_object.*) DO NOT SHOW a Note-Attribute, but it does exist an when you write it into the query, it gets generated in the document.

“A cycle was detected in the set of changes” with Linq to SQL

I am currently developing an application in which i experience the exception "A cycle was detected in the set of changes" when calling DataContext.SubmitChanges(). I know why this exception is thrown but i have not been able to find a fix for my situation. Let me explain the situation. I have a database with a table as shown below which i access with LINQ to SQL so it gets mapped to classes in vb.net.
Device
-------
ID
DefaultGatewayID
The DefaultGatewayID is a Device an can even be the same object or another Device. The user uses a GUI with a DataGrid to alter and add new records. The updating records is no problem. The ID already exists and the DefaultGatewayObject is attached to the record (the ID is stored in database).
However when i try to add a new record and set the DefaultGatewayObject in the same transaction i get the 'Cycle detected in set of changes'-exception. I suspect this is caused by LINQ to SQL because it does not know which record to add first, although it is the same item in this case.
I do not have the option to break the insertion into two parts, one for the Device and then adding the DefaultGateway because my submit button is bound to a XAML Command which executes the SubmitChanges.
Ideally i would have some option to specify which object is to be created first, or something like that. I think it's an option to remove the connection to itself and just set the ID in this field, but i'd rather find a fix within LINQ to SQL.
I hope SO has an answer to this. I could only find this related post "Cycle detected while adding Circularly linked list"
You can break the insertion into two parts ans still have one transaction if you wrap your code in a TransactionScope.
Using trans As New TransactionScope()
'Code that generates a new ID in the database
dc.SubmitChanges()
'Code that uses the new ID value.
dc.SubmitChanges()
trans.Complete()
End Using
This is the only way to avoid the exception. If this is impossible because of architectural decisions ("my submit button is bound to a XAML Command") you need to change the architecture. I think a UI command should never be so close to the data access layer anyway. You better call a service method from XAML.