0

I'm here still learning with drupal 7 but now I have a new question about a node create programmatically,I hope you can help me.

I want to generate all node fields names programmatically and then set a lavue on each one.

To store each field from node I generate the names of the field witn an array with each name, this is because I want to make function to indicate the names of the fields of the node that I want to fill.

The problem is that my code is not working to fill the nodes, maybe because my fields names are bad generated. I generate and fill them this way:

    $nodefields = array('areaid', 'areaname');

    foreach ($nodefields as $fieldname) {
            $node->$fieldname['und'][0]['value'] = $row->$fieldname;
            }
    node_save($node);

The rows are obtained by a query to a external db (column has the same name as the field), that's fine, the records are ok, if I fill them manually like:

$node->areaname['und'][0]['value'] = $row->$areaname;

Works ok, but I can't make it work with a loop to generalize that part.

  • maybe because my fields are bad generated The code you showed here does not generate any fields. Can you include that code too? – Neograph734 Jul 27 '17 at 11:58
  • Thanks for your answer, I believe that was my mistake in my question, I mean that, when you want to save a node field value programatically you do somethink like this: $node->areaname['und'][0]['value'] = $row->$areaname; but now, I have an array with the names of the fields, to loop and save the value on each one with this: $node->$field['und'][0]['value'] = $row->$field; – Elros Romeo Jul 27 '17 at 12:01
1

Your problem is that below code does not work as you probably expect.

$node->$fieldname['und'][0]['value'] = $row->$fieldname;

You expect this to work like this:

$fieldname = 'name'; 
$node->name['und'][0]['value'] = $row->name;

but PHP will probably do something like this:

$fieldname = 'name'; 
$fieldname['und'][0]['value'] = $row->name;
$node->$row->name;

Instead, try to wrap your variable name in curly brackets to have it replaced first:

$node->{$fieldname}['und'][0]['value'] = $row->$fieldname;
  • 1
    Thanks for your answer, I'll check it later and as I guess I'll mark your answer as the correct one. – Elros Romeo Jul 27 '17 at 12:08
0

I think you might be missing brackets


$nodefields = array('areaid', 'areaname');
foreach ($nodefields as $fieldname) {
  $node->{$fieldname}['und'][0]['value'] = $row->{$fieldname};
}
node_save($node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.