4

I am trying to update a value during the validate phase of a node-form, i.e. if the custom validation error is fired, just empty one of the fields.

for the last 30 hours I am trying to make sense of the drupal api, but I am giving up. I just do not seem to get the idea what the different values mean.

the function is: form_set_value($element, $value, &$form_state)

now i understand that the last value is simply the $form_state, that I am having through the validate function. but what about $element and $value?

I was trying a lot and apparently the desired value resides in $form['field_name']['und'][0]['value']['#value'] and only there.

but when I am trying form_set_value($form['field_name']['und'][0]['value']['#value'],'foo',$form_state) it raises

    Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be an array, string given, called in /includes/form.inc on line 2436 and defined in drupal_array_set_nested_value()

and when I am trying:

    $newvalue = $form['field_name']['und'][0]['value'];
    $newvalue['#value']='foo';
    form_set_value($form['field_name']['und'][0]['value'],$newvalue,$form_state);

it raises:

    Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen()

Thanks for any help!

[EDIT]

My complete function is:

    function hook_node_validate($node,$form,&$form_state) {
      if(fancy_stuff){
        form_set_value();
        form_set_error();
      } 
    }

[EDIT2]

    //calls when node is being created
    function eventcheck_node_validate($node,$form,&$form_state) {
      //checks if the node type is applicable
      if($node -> type=='article') {
        //checks if field 'field_event_choose' AND either 'field_event_title' 
        //or 'field_event' is supplied, if so, fire form_set_value() and form_set_error()
        if ((array_key_exists('endpoints',$node -> field_event_choose['und'][0])) && 
        (($node -> field_event_title['und'][0]['value']<>'') || (isset($node -> 
        field_event['und'][0]['value'])))) {

          //fire away
          $form_set_value(???);
          $form_set_error('event_checker_group',t('sorry blabla'));

        }
      }
    }

I hope that helps.

11

After a lot of debugging, I finally managed to make this work. The trick lies inside $form['complete form']. but first things first, how does form_set_value() work and what does it do?

The form_set_value() function

As the documentation suggests:

If you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2').

Now what does that mean? In my case, I had a textfield called 'field_event_title', which is the name I gave it on creation. In $form, all fields have a sub-array in $form['field_name'], which in my case is $form['field_event_title']. This is where the submitted value also is stored. Since it is a textfield, Drupal maintains both the language and the delta [question for editors: is this right?] of the input data. So in fact, the value is not stored in $form['field_name']['value'], but in $form['field_name']['und'][0]['value'] (['und']=language; [0]=delta). Note that "und" is the Drupal key for the default language of the site; if it is in German, then it would be "de"; however, in most cases it should be "und."

To actually change the value using form_set_value(), one is ought to invoke the function by writing:

form_set_value($form['field_name'], array('und' => array(0 => array('value' => 'foo'))), $form_state);

Updating a form to repopulate it with different values than submitted (or clearing them)

Thus far, this was what Krister Andersson suggested, but that did not work in my case, since I wanted to clear fields once a custom validation error has been invoked. One would suspect that the form repopulates itself using the values inside $form_state['values'] (which is actually the place where the values are stored, the actual place that gets updated when using form_set_value() and the place which generates the $form later), but that is not the case: It uses the values inside $form_state['complete form'], which is a 'copy' of $form (notice that it is spelled 'complete form', with a space, not an underscore).

Using $form_state['complete form']['field_name']['und'][0]['value']['#value'] = 'foo'; is what updates the values that actually repopulate the form on a validation error. (Note: you can, as do I in my usecase, set it to =NULL to simply empty the field.)

Summary

Where is the difference between $form['field_name'] (e.g. updating through form_set_value()) and $form['complete form']? Well, the former updates the actual value, which then gets stored inside the database; the latter is being used to repopulate a form when it failed a validation.

  • 1
    Thank you Alex for a great write up! I've been trying to get this working for hours on an entity reference field. – Bryan Jiencke Dec 4 '12 at 1:15
  • Cross linking drupal.org/node/1377784 – Elijah Lynn Jul 16 '13 at 22:45
  • Just a FYI, while a new value for a custom field that gets passed to form_set_value() might need to be placed in a specially constructed array, for a non-custom field like the node title, you need to set a placeholder value using $form['title']['#value'] = NULL; in the form_alter phase as discussed in this comment on api.drupal.org. If you don't you've continually get a "Title field is required" message. – alexkb Feb 6 '15 at 5:52
  • I was able to set the value for a required Entity Reference field in the validation function by doing form_set_value($form_state['complete form']['FIELD_NAME'][LANGUAGE_NONE][0], array('target_id' => $my_entity_id), $form_state); This used the ['#parents'] value on this element to correctly store the entity ID in this field. It seems to be working for me, but is this correct? – thirdender Jun 13 '16 at 15:58
1

I managed to get it working by doing this:

// hook_form_alter, check so it's the correct form and attach a validate function
function sample_form_alter(&$form,&$form_state,$form_id) {
  if ($form_id == "sample_dummy_node_form") {
    $form['#submit']['#validate'] = 'sample_dummy_node_form_validate';
  }
}

// validate function, wich just sets the `title` field to `tjoohooo` using `form_set_value`
function sample_dummy_node_form_validate($form, &$form_state) {
  $form['title']['#parents'] = array('title');
  form_set_value($form['title'],t('tjoohooo'), $form_state);
}

If you haven't done so already, you should have a look at the documentation form_set_value

* EDIT *

In you example I guess the code in your validate method should be:

function hook_node_validate($node,$form,&$form_state) {
  if (fancy_stuff){
    $form['field_name']['#parents'] = array('field_name');
    form_set_value($form['field_name'],t('foo'),$form_state);
  } 
}

From the documentation for the parameters:

$element: The form element that should have its value updated; in most cases you can just pass in the element from the $form array, although the only component that is actually used is '#parents'. If constructing yourself, set $element['#parents'] to be an array giving the path through the form array's keys to the element whose value you want to update. For instance, if you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2').

  • thanks for your reply, but either that still does not work, or I still have no clue. why should I declare $form['title']['#parents'] = array('title');? and in your case, it still angers about the new value being a string, not array. maybe I should have explained more in detail in what context i am calling form_set_value, please see for the edited part of my question. thanks! – alex Dec 19 '11 at 20:59
  • I didn't mean that you should use title you should use $form['your_field']['#parent'] = array('your_field') where your_field is the name of the field whose value you would like to modify. – Cyclonecode Dec 19 '11 at 21:20
  • Also, it isn't the form_set_value() method that complains, but the drupal_array_set_nested_value() method wich is called from form_set_value() and the second parameter to that method is $element['#parents']. – Cyclonecode Dec 19 '11 at 21:35
  • thanks for your time krister! but now I have two new errors: Warning: array_values() expects parameter 1 to be array, string given in _field_filter_items() - Warning: Invalid argument supplied for foreach() in text_field_validate() – alex Dec 19 '11 at 23:18
  • my main problem is still the meaning of "For instance, if you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2')." where would I set $element['#parents']? before the call? like so: $element['#parents']=array('field_name' => ['und'] = > [0] = > ['value'] = > ['#value'] = > 'foo');? and then? form_set_value($form['field_name'],$element['#parents'],$form_state);? I'm so sorry, but this is a mystery to me. :) – alex Dec 20 '11 at 10:04

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.