1

I have a number field where a user needs to enter two values. Each value should have a custom prefix but that isn't possible within the field settings.

Does anybody know how this can be done? Thanks.

1

That's how you can add prefixes to node output (replace view_mode and field_name to yours):

/**
 * Implements hook_preprocess_field().
 */
function mymodule_preprocess_field(&$vars) {
  if ($vars['element']['#entity_type'] == 'node' &&
      $vars['element']['#view_mode'] == 'full' &&
      $vars['element']['#field_name'] == 'field_number') {

    $vars['items'][0]['#markup'] = '<span>$</span>' . $vars['items'][0]['#markup'];
    $vars['items'][1]['#markup'] = '<span>€</span>' . $vars['items'][1]['#markup'];
  }
}
  • I just tried it and it works great. Thanks a lot for your help and endurance ;-) – ThuleNB Apr 5 '16 at 17:51
1

You can use form_alter function to do it:

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_number'][LANGUAGE_NONE][0]['value']['#prefix'] = '$';
    $form['field_number'][LANGUAGE_NONE][1]['value']['#prefix'] = '€';
  }
}

enter image description here

  • Thanks for your help, that looks great! Where would I need to put this code? I not much of a coder. Should this go into a custom module? – ThuleNB Mar 31 '16 at 6:40
  • 1
    Absolutely, just create a custom module and put this code there. Pay attention: your_module in function name should be replaced by your module's name, form id article_node_form should be replaced by your form id, and field_number - to your field name. This answer can help you to create a custom module: drupal.stackexchange.com/questions/130548/… – skorzh Mar 31 '16 at 6:51
  • Follow up question: the different prefixes are shown correctly in the edit form but they are not displayed in the display mode although "show prefix and suffix" is checked in the appearance settings. Do you know how I can show the prefix in the display mode, too? – ThuleNB Mar 31 '16 at 17:58
  • It depends how you output the node, you have to use preprocess hooks to alter output of fields, if you tell me how you display the node, I will try to help you. – skorzh Apr 4 '16 at 9:05
  • It is a custom content type named "profil". In the appearance settings I am using the "Standard" mode. Besides I use the module "Dispay Suite" to have a layout with two columns. Is this enough information or do you need to know something else? Thanks a lot for your help!!! – ThuleNB Apr 4 '16 at 9:19

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.