I’m trying to create a node (B type) & assign it to a A type node’s CCK nodereference field using node_save() method.
$node_type_A = node_load($some_nid);
$node_type_A->field_type_B_node_ref[]['nid'] = $node_type_B_nid;
$node_type_A = node_submit($node_type_A);
node_save($node_type_A);
As the result, a new B type node will be created, but no reference will be assigned to the A type node. any help would be appreciated.
GApple is right, the format is correct, but there are couple of things that you might want to care about.
Delta Value
First you need to know the delta value of the latest node reference attached to
$node_type_A, the delta is actually a partial index, when combined withvidfield of the$node_type_A, they become the index for node reference table in the database. In other words, its a count for$node_type_Bwhich are referenced in$node_type_A, ok?GApple is right again, you have to exactly say where to add the new reference. When you got that delta value you can exactly say where to append (delta+1) the new reference. Here it is:
Adding the new reference
We got delta! so we can attach the new
$node_type_Bnode to our$node_type_Anode:Resaving the updated node
Optionally call
node_submit()to populate some essential fields in the node object and save it by utilizingnode_save(). After all, you need to callcontent_insert()to make the node completely saved asidelong with its CCK fields:Flushing the content cache
Probably the most important part, this was killin’ me for couple of days. CCK has a cache table in the database called
cache_content(take a look at its structure), after resaving the updated node, you will notice that nothing has changed in the$node_type_Atheme output even though that the tables are updated. We have to remove a record from that content cache table, this will force Drupal to show the latest snapshot of the data. You can define the following as a function:Hope it helps 😉