0

I need to show a specific amount of multivalued fields on a comment depending on the value of the node (field_optionsamount) that the comment is attached to. There are modules that allow to set the number of fields shown (e.g. https://www.drupal.org/project/multivalue_extras) but the limit is the same for all fields and does not depend on the node.

The code below removes the add more fields button and provides the amount of fields that need to be shown. I don't know how to show x fields though.

function customisations_form_comment_form_alter(&$form,&$form_state,$form_id) {
     $parentNode = $form['nid']['#value'];
     $node_data = node_load($parentNode);
     $amountOptions = $node_data->field_optionsamount['und'][0]['value'];
     drupal_set_message("Amount: ". $amountOptions);
     unset($form['field_toinvest']['und']['add_more']); //hides the add more button
}
0

Don't know what the proper way is to handle answers where the solution comes from another posting. So I only make the reference here: https://drupal.stackexchange.com/a/140861/24957

The code below works perfectly and only shows $amountOptions fields.

if (!isset($form_state['build_info']['args'][0]->field_toinvest[LANGUAGE_NONE][0]['value']) && !isset($form_state['default_fields'])) {
for ($i = 0; $i < $amountOptions; $i++) {
// First field is already in form.
  if ($i > 0) {
    $form['field_toinvest'][LANGUAGE_NONE][$i] = $form['field_toinvest'][LANGUAGE_NONE][0];
  }

  // Set form values
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#default_value'] = 0;
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#value'] = 0;

  // Set row weight
 $form['field_toinvest'][LANGUAGE_NONE][$i]['_weight'] = array(
  '#type' => 'weight',
  '#title' => t('Weight for row ' . ($i + 1)),
  '#title_display' => 'invisible',
  '#delta' => $i,
  '#default_value' => $i,
  '#weight' => 100,
 );
}
$form_state['default_fields'] = 1;
$form_state['field']['field_toinvest'][LANGUAGE_NONE]['items_count'] = amountOptions - 1;
}

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.