2

In Drupal, when you create a field, you can specify the default value for a field. For example, if you have a field called price, you can set the default value to be 400. When the user creates a new node, 400 is the default value, but s/he can change it to whatever s/he wants.

Is there a way to link this default value to a node field value.

For example, lets say on node/12 I have a field called "price default". If the user enters 500 on this field (on node/12), the default value of the price field (for all new nodes) will change from 400 to 500.

3 Answers 3

5

Ahmed was close, but to take it all the way you need to fetch the field's value:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {  
  if ($form_id = 'YOUR_FORM_ID_HERE') {
    // Fetch node that has default value
    $node = node_load($nid);
    // Fetch the value from price field
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $field_val = $node_wrapper->field_price->value();
    // Set fetched value as default
    $form['field_price'][LANGUAGE_NONE][0]["value"]['#default_value'] = $field_val;
  }
}
  • I am itching for a clean way to avoid having ['und'][0] in there, as these values can change with localisation, but this would still work.
2
  • 1
    Use of the LANGUAGE_NONE constant over 'und' is preferred.
    – Christian
    Nov 13, 2013 at 5:54
  • 1
    Yes sir. This is indeed best practice. Corrected the answer with your suggestion, thanks friend. Nov 13, 2013 at 21:41
0

You can use hook_form_alter to set default value of your field by select the last value of it

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    $form['account']['status']['#default_value'] = '0';
}
0

You actually can. Before setting the price field's default value, do a node_load($nid) (You must know the node's id), it should return the complete node object inclusive of the fields. You can find the value of price_default from that and set the default value of price field accordingly.

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.