0

I have a form field which uses the #ajax element. When a user interacts with this field a function is called and a new form element is added to the form and then the new form is displayed to the user.

However, if validation fails the added element disappears? Of course, I want it to remain.

How do I solve this problem?

  • 1
    you can add your code here that you have tried so that the question becomes more meaningful. – shrish Jun 26 '14 at 15:53
1

Generally it's not good to create the elements in the ajax callback. What I usually do is add the form elements to the main form, but wrap them in the if statement, and then in the ajax callback just refresh the container of that element or the whole form if it's small.

function SOMETHING_form($form, &$form_state) {

  $form['nominee'] => array(
    '#type' => 'checkbox', 
    '#title' => t('I am nominating someone else'),
    '#ajax' => array(
      'callback' => 'return_nominee_email_element',
      'wrapper' => 'nominee-email-wrapper',
      'progress' => array('type' => 'none'),
    ),
  ),

  if(isset($form_state['values']) && $form_state['values']['contact_details']['nominee'] == TRUE) {
    $form['nominee_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
      '#prefix' => '<div id="nominee-email-wrapper">',
      '#suffix' => '</div>',
    );
  } else {
    $form['nominee_email'] = array(
      '#prefix' => '<div id="nominee-email-wrapper">',
      '#suffix' => '</div>',
    );
  }

 return $form; 
}

function return_nominee_email_element($form, &$form_state) {
  return $form;
}

See if something like that works for you.

0

The mistake I made was assuming that $form_state['values'] always contains all the values the user has input so far. It doesn't, but $form_state['input'] appears to. So, if you want to render a form element according to the current state of the form: test the contents of $form_state['input'], not $form_state['values']. If the form is rebuilt (due to an custom ajax callback, or file upload, for example) $form_state['values'] will change and can't be relied upon.

Edit: Be careful using $form_state['input'] as it contains untrustworthy, raw input from the user.

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.