0

I save the $form_sate['values'] in a data base. When my users come back to the form I want to show the values that they put before. Something like:

function my_form($form, &$form_sate) {
  $form_state_saved = get_form_state_values_from_db();

  $form['my_field'] = array(
    ...
    '#default_value' = $form_state_saved['my_field'];
    ...
  );

  return $form;
}

With a textfield seems that works fine, but I have some custom fields. Is there a way to set the default_value from db? Or should I implement the default_value independently for each field?

  • I think you've answered yourself the question. Every element in your form could be filled with the default value. – Rufein Oct 31 '13 at 20:47
  • You should implement default_value independently for each field. – Jayendra Kainthola Nov 1 '13 at 9:00
1

Use Form default value:

'#default_value' => variable_get('sitename_textfield', ''),

If you use system_settings_form() you don't need to manually save your variables using a custom form submit function. Note: The variable must have the same name as the form item.

Function details: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_settings_form/7

/**
 * Creates/returns a form to configure the variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function sitename_custom_form($form, &$form_state) {
  $form['sitename_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Textfield'),
    '#default_value' => variable_get('sitename_textfield', ''),
  );

  // Use system_settings_form() to automate saving configuration variables.
  return system_settings_form($form);
}
0

You need to use variable_set() if you only want to set the previous value There is no harm in storing independent values for each fiels element using variable_set()

  function my_form($form, &$form_sate) {
      $form['my_field'] = array(
        ...
        '#default_value' = variable_get('my_field','');
        ...
      );

  return $form;
}
function my_form_submit($form, &$form_sate) {

      variable_set('my_field',  $form['my_field']['#default_value']);




}
0

Finally, what my colleague did was a combination of field_default_form and field_form_set_state.

$field_state = array(
  'field' => $field,
  'instance' => $instance,
  'items_count' => $count,
  'array_parents' => array(),
  'errors' => array(),
);
field_form_set_state($parents, $field_name, $language, $form_state, $field_state);

$items is an array with the form values stored in a database.

$form_field = field_default_form('node', NULL, $field, $instance, $language, $items, $form, $form_state);

$form[$field_name] = $form_field[$field_name];

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.