0

I have a content type with these fields, among others:

  • field_address – required
  • field_entrance – not required
  • field_apartment_number – not required (or actually required if a previous field meets a certain criteria, otherwise not shown at all)

With the Automatic Entity Label modul I can use tokens to save the node title using this pattern:

[node:field_address] [node:field_entrence] [node:field_apartment_number]

If any of the non required fields are left blank there's no value from those fields saved to the node title. However, the whitespace between the tokens is still saved, and I don't want that. I'm not good at PHP but this I what I have, copy-pasted from various sources:

<?php

$address = field_get_items('node', $node, 'field_address');
$entrance = field_get_items('node', $node, 'field_entrence');
$apartment_number = field_get_items('node', $node, 'field_apartment_number');

print $address['value'];

if ($entrance) {
   print ' ' . $entrance['value'];
}

if ($apartment_number) {
   print ' ' . $apartment_number['value'];
}

?>

But it doesn't work. Instead, no title is saved at all. How do I correct my code?

1 Answer 1

1

As far as I remember, field_get_items() returns an array of items. In your case something like:

    if (count($address)) {
       print $address[0]['value'];

       if (count($entrance)) {
          print ' ' . $entrance[0]['value'];
       }

      if (count($apartment_number)) {
         print ' ' . $apartment_number[0]['value'];
      }
   }

should work.

2
  • Apologies for the delayed response. Your code works great when I omit the $address part, so it's a completely correct answer to my original question. It took me several hours to find out what kept it from working for me and then several more to find out why, but now I realise it's because $address is actually a select list, not a text field. What I don't realise, however, is how to retrieve the label of the selected item. I've tried googling, cutting and pasting but my programming skills just don't hold up. Anyway, that's a whole other question.
    – Johanna
    Commented Dec 10, 2016 at 22:58
  • I made a whole new question: drupal.stackexchange.com/questions/222683/…
    – Johanna
    Commented Dec 10, 2016 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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