By ajits on
I am working on a task which requires adding of a node (with only title field) programmatically. This can be easily achievable, and I have did it already by using:
$node = new stdClass();
$node->type = "node_type";
// Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
node_object_prepare($node);
// Set the title of the node.
$node->title = $title; // $title is supplied to the function.
// Or e.g. 'en' if locale is enabled
$node->language = $lang_code; // $lang_code is supplied to the function.
// Making user 1 as the author of the node.
$node->uid = 1;
// (1 or 0): published or not
$node->status = 1;
// (1 or 0): promoted to front page
$node->promote = 0;
// Set the source translation node.
$node->tnid = $node->nid;
// Save the node.
node_save($node);
However, I am struggling with the part where I could add the translations (same title) to it. I am using i18n module and node translation in it. Any pointers would be appreciated.
Comments
I've never done it, but I can
I've never done it, but I can maybe point you in the right direction.
First, remove this:
It's not doing it the right way, and $node->nid will not be set, so it doesn't do anything anyways.
In Drupal, translated nodes are actually different nodes, linked together through the 'tnid' column in {node} table in the database. The tnid of the translated node is the nid of the original node.
So to create a translation, you would need to create two nodes.
Look at this line of your code:
After
node_save()has been called,$node->nidwill be set (if the node was successfully saved). This becomes the tnid of the translated node. So after your code above, you could do something like this (continues on from your code):Contact me to contract me for D7 -> D10/11 migrations.
After saving the first node
After saving the first node (referring to the above example) and before creating the secont one you have to set the tnid of the first node, so replacing the above code:
This step, while not crucial,
This step, while not crucial, is actually quite important if you want your site to be aware of the source language of a node as well as having translations showing up correctly on the Edit Node → Translate page.
However, the translations will work without.