دروپال: ajax form

گام اول: تعرین ajax callback در فرم

$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Post'),
    '#ajax' => array(
      'callback' => 'status_reply_form_ajax_callback',
      'wrapper' => 'status-reply-form-' . $status->sid . '-wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  $form['#prefix'] = '<div id="status-reply-form-' . $status->sid . '-wrapper">';
  $form['#suffix'] = '</div>';

گام دوم: نوشتن submit handler

function status_reply_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

گام سوم: نوشتن ajax callback

function status_reply_form_ajax_callback($form, &$form_state) {
  drupal_validate_form('status_reply_form', $form, $form_state);
  // if there are errors, return the form to display the error messages
  if (form_get_errors()) {
    $form_state['rebuild'] = TRUE;
    return $form;
  }

  $status_reply = $form_state['status_reply'];
  foreach ($status_reply as $key => $value) {
    if (isset($form_state['values'][$key])) {
      $status_reply->$key = $form_state['values'][$key];
    }
  }
  if ($status_reply->srid) {
    status_reply_update($status_reply);
  } else {
    status_reply_insert($status_reply);
  }

  $commands = array();
  $status_reply_view = status_reply_view($status_reply);
  $commands[] = ajax_command_append('.status-replies-' . $status_reply->sid, render($status_reply_view));
  $commands[] = ajax_command_invoke("#status-reply-form-{$status_reply->sid}-wrapper textarea", 'val', array(''));
  return array('#type' => 'ajax', '#commands' => $commands);
}

افزودن نظر جدید