0

I was wondering how to do this with drupal. You probably wonder why I don't just use the unlimited amount of values setting. That's because I want to require the user to fill in the amount of values related to the integer value.

For example, you want to create a group (node) for a specific category (node). A category which contains an integer field (field_members). Now lets say you also have a node reference field (field_category) at those group node its fields, which refers to a specific category (in this case field_members). Then the user must add the amount of users related to the category its field_members value.

  • are you able to code? – Andre Baumeier Sep 1 '14 at 16:04
  • @Andre-B Sure :D – Fleuv Sep 2 '14 at 8:03
  • see my answer then ;) – Andre Baumeier Sep 2 '14 at 11:51
0

You will probably have to setup some way of two step process to enable the reference between both nodes (maybe entityreference). The field you are using will have to be an unlimited multi value field.

with this peace of code you will be able to reduce the items of that field (including the add button). Feel free to provide any other logic for looking up the settings node / proding a default limit etc.

<?php
function mymodule_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  if ($entity_type == 'node' && $entity->type == 'my_content_type') {
    $multi_values = array();
    foreach ($form['field_myfield'][LANGUAGE_NONE] as $key => $value) {
      if (is_numeric($key)) {
        $multi_values[$key] = $value;
      }
    }

    if (count($multi_values) > 1) {
      $multi_value_keys = array_keys($multi_values);
      foreach ($multi_value_keys as $key) {
        unset($form['field_myfield'][LANGUAGE_NONE][$key]);
      }

      // get the count of the asociated node, maybe using entity reference?
      $settings_node = node_load($entity->field_settings_node[0][LANGUAGE_NONE]['target_id']);
      if ($settings_node) {
        $limit = $settings_node->field_limiting_field[LANGUAGE_NONE][0]['value']; // e.g. textfield..
        if ($limit) {
          $i = 0;
          // add all the fields that are allowed, cut of the once that are too much (and remove the add button)
          while ($i < $limit && $i < count($multi_values)) {
            $form['field_myfield'][LANGUAGE_NONE][$i] = array_shift($multi_values);
            $i++;
          }
        }
      }
    }
  }
}

You might also want to look at How to dynamically set the maximum cardinality for a multi value field? for another example (setting the access attribute for those fields)

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.