By oskarg on
Hi,
This is probably really basic, but I have Googled a lot and still can't find a good anwser.
When the user submits a node form for node type A, a second node of type B is programmatically created in a custom validation function. Now I want to set a node reference field in the node to be created (of type A) to point to the newly created node (of type B). What is the best way to do this?
Comments
hi, may be it must be module
hi, may be it must be module "node reference create"? if i remember correct, this module have to create new node, if you didn't reference any another node.
Usually the node would be
Usually the node would be created in the submit function, not the validation function. Otherwise, you will get a new node being created multiple times if validation fails. Is there some reason why you are creating your node in the validation function and not the submission function?
Contact me to contract me for D7 -> D10/11 migrations.
During validation of the
During validation of the submitted form, a credit check is performed based on a VAT identification number that is entered in the node form. If the corresponding company's credit rating is too low, validation fails. Otherwise, credit check information is stored in a node (of type B) for use later.
(This is part of a process where anonymous users can post content and get an account created for them at the same time.)
In that case, I would do
In that case, I would do something like the following. In the form, I would use this:
The container will be filled in the next section:
The above calls a custom node builder function:
The validation function will attempt to build the node. If the node is not properly created, an error is set on whichever field caused the problem, and the user gets sent back to the form with a validation error. If the node is properly created, the created node is inserted into the empty container created in the form definition. It can then be used in the submit function as follows:
You now have the NID of the created node, which can be used in the submit function and attached to the original node. Since you are using nodes, the functions will likely be node functions rather than form definitions you are creating from scratch, but the idea is all the same.
Contact me to contract me for D7 -> D10/11 migrations.
Thanks a lot! I have modified
Thanks a lot! I have modified my code to reflect your advice. There is only one thing I can't wrap my head around, and that is how to actually set the node reference field in my _form_submit function.
I have tried something like
But this has no effect on the newly created node, i.e. the field value of field_proj_creditcheck is not set. At first I thought it was a permissions problem, but it was not.
EDIT:
I managed to set the field value using the following in the validation function
Thanks again!
Your EDIT code worked for me
^ That last code snippet after your EDIT worked for me. Thank you.
Hakuna Matata