2

I am doing an ajax form submit,

Issue #1 : I am facing problem while submitting the form, The form have a submit and a validate function. In the validate function it is checking whether the username entered is 'King Kong', If it is then it will then it will show an error message. After changing the name to a different one, the error message is still showing up. Also on submit I am displaying a sample text below the form.

Issue #2 : When I submit the form I am getting the form that is filled with the values i have entered in the previous form submit. I have got this link(Form API : display the same form again with AJAX, but with different values, on submit) regarding the Issue #2 ,but no luck, If some one could direct me the right way, I would be really great full.

Here is my code.

function app_form($node) {
  $form['form']['#prefix'] = '<div id = "wrapper">';
  $form['form']['item'] = array(
    '#title' => t('Item'),
    '#type' => 'textfield',
    '#description' => t('Enter an item.'),
    '#required' => TRUE,
  );
  $form['form']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
    'callback' => 'app_form_submit',
    'wrapper' => 'wrapper',
    'effect' => 'fade',
    'name' => 'submit',
  ),
    '#suffix' => '<div id = "after_div">Something can be inserted after this</div>
     <div id="after_status">After Command Status: Unknown</div>',
    '#value' => t('Submit'),
  );
  $form['form']['#suffix'] = '</div>';
  return $form;
}

/**
 * Custom function for submit.
 */ 
function app_form_submit($form, $form_state) {
  ctools_include('object-cache'); 
  if (!form_get_errors()) {
    $new_values[] = array(
      'item' => $form_state['values']['item'],
    ); 
    $selector = '#after_div';
    $commands = array();
    $commands[] = ajax_command_after($selector, "$new_values");
    $commands[] = ajax_command_replace("#after_status", 
      "<div id='after_status'>
      Updated after_command_example " . date('r') . "
      </div>"
    );
    return array('#type' => 'ajax', '#commands' => $commands);
 }
 elseif (form_get_errors()) {
   $element = $form['form'];
   return $element;
 }
}
/**
 * Validate the form.
 */
 function app_form_validate($form, &$form_state) {
   if ($form_state['values']['user_name'] == 'King Kong') {
     form_set_error('user_name',
     t('King Kong is not allowed to use this form.'));
   }
 }
0

Try to rebuild your form with $form_state['rebuild'] = TRUE. Most of the times when I use ajax in forms I have to rebuild the form on callback. More info can be found on https://www.drupal.org/node/1850410

| improve this answer | |

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.