Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By peterk900 on
I have a custom form which creates nodes. The form is re-displayed with the original values after submission or if I include $form_state['rebuild'] = TRUE; the re-display has all the fields empty.
I want to be able to change the fields that are re-displayed - for example setting some to "" and leaving others at their previous value.
I have tried various options - some do nothing whereas others break the form.
Here is the code for the submit function:
function fe4_form_submit($form, &$form_state) {
global $user;
$values = array(
'type' => 'prices',
'uid' => $user->uid,
'status' => 1,
'comment' => 1,
'promote' => 0,
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('My E Title');
$entity->field_product_name[LANGUAGE_NONE][0] = array('value' => $form_state['values']['product_name'] );
$entity->field_price[LANGUAGE_NONE][0] = array('value' => $form_state['values']['price'] );
$ewrapper->save(TRUE);
drupal_set_message( "Node with nid " . $ewrapper->getIdentifier() . " saved!\n");
$newvalue = 9934.09;
//---none of these work
//form_set_value($form['field_product_name'], array(0 => array('value' => $newvalue)), $form_state);
//$form_state['values']['price'] = $newvalue;
//$form['price'][#default_value] = $newvalue;
//$form['price'] = array ( 'value' => $newvalue);
//$form_state['values']['price'][LANGUAGE_NONE][0]['value'] = $newvalue;
//$form_state['values']['price'][0]['value'] = $newvalue;
//$form_state['rebuild'] = TRUE;
}
I am obviously missing something important in my understanding of the Form API. I hope someone can point out what it is ! Thanks.
Comments
function some_form($form, &
This should get you started. After submission, the value of field_1 will be the value entered into field_1. The value of field_2 will be "You entered [value of field 2]".
Thank you..
Here is the module code - but unfortunately it makes no changes to the form fields on submit as indicated by the form_set_value line.
Have I misunderstood something ?
No, I gave you bad code! I
No, I gave you bad code! I didn't realize you can't use form_set_value() in a submit handler.
Change this:
To this:
And actually, you can remove #default_value from both form inputs.
is there any updated way to
is there any updated way to do this? *Exception has occurred: Cannot use object of type FormState as array
I understand that you can use the -> to access properties
***Edit: found a different solution using normal button with ajax commands: AppendCommand and RemoveCommand
This code is for Drupal 7, it
This code is for Drupal 7, it won't work in Drupal 8.
Alternative for this code in Drupal 8 and Drupal 9
In submit function for unsetting field values after submission of form
unset($form_state->getUserInput()['field_1']);