예제 #1
1
  /**
   * Calls a method on an entity queue and reloads the listing page.
   *
   * @param \Drupal\entityqueue\EntityQueueInterface $entity_queue
   *   The view being acted upon.
   * @param string $op
   *   The operation to perform, e.g., 'enable' or 'disable'.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Either returns a rebuilt listing page as an AJAX response, or redirects
   *   back to the listing page.
   */
  public function ajaxOperation(EntityQueueInterface $entity_queue, $op, Request $request) {
    // Perform the operation.
    $entity_queue->$op()->save();

    // If the request is via AJAX, return the rendered list as JSON.
    if ($request->request->get('js')) {
      $list = $this->entityManager()->getListBuilder('entity_queue')->render();
      $response = new AjaxResponse();
      $response->addCommand(new ReplaceCommand('#entity-queue-list', $list));
      return $response;
    }

    // Otherwise, redirect back to the page.
    return $this->redirect('entity.entity_queue.collection');
  }
 /**
  * Ajax callback to validate the email field.
  */
 public function submitEmailAjax(array &$form, FormStateInterface $form_state)
 {
     $valid = $this->validateEmail($form, $form_state);
     $response = new AjaxResponse();
     if ($valid) {
         $css = ['border' => '1px solid green'];
         $message = $this->t('Email ok.');
     } else {
         $css = ['border' => '1px solid red'];
         $message = $this->t('Email not valid.');
     }
     // $response->addCommand(new CssCommand('#edit-email', $css));.
     $response->addCommand(new OpenModalDialogCommand('Alert', 'hello', array('width' => '700')));
     return $response;
 }
예제 #3
1
 /**
  * Ajax callback to render a sample of the input date format.
  *
  * @param array $form
  *   Form API array structure.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Form state information.
  *
  * @return AjaxResponse
  *   Ajax response with the rendered sample date using the given format. If
  *   the given format cannot be identified or was empty, the response will
  *   be empty as well.
  */
 public static function ajaxSample(array $form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     $format_value = NestedArray::getValue($form_state->getValues(), $form_state->getTriggeringElement()['#array_parents']);
     if (!empty($format_value)) {
         // Format the date with a custom date format with the given pattern.
         // The object is not instantiated in an Ajax context, so $this->t()
         // cannot be used here.
         $format = t('Displayed as %date_format', array('%date_format' => \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', $format_value)));
         // Return a command instead of a string, since the Ajax framework
         // automatically prepends an additional empty DIV element for a string,
         // which breaks the layout.
         $response->addCommand(new ReplaceCommand('#edit-date-format-suffix', '<small id="edit-date-format-suffix">' . $format . '</small>'));
     }
     return $response;
 }
 public function ajaxSubmit(array &$form, FormStateInterface $form_state)
 {
     //---------------------------------------------------------------
     //            get the own attributes values of the swap
     //---------------------------------------------------------------
     //get all the swaps plugins
     $manager = \Drupal::service('plugin.manager.swaps');
     $swaps = $manager->getDefinitions();
     $swap = $swaps['column'];
     $input = $form_state->getUserInput();
     $settings = array();
     $settings['size'] = $input['swaps_column_size'];
     $settings['number'] = $input['swaps_column_number'];
     //---------------------------------------------------------------
     // get the default attributes values of the swap (required for visual help)
     //---------------------------------------------------------------
     $settings['swapId'] = $swap['id'];
     $settings['swapName'] = $swap['name'];
     $settings['container'] = $swap['container'];
     SwapDefaultAttributes::getDefaultFormElementsValues($settings, $input);
     //---------------------------------------------------------------
     //            create the ajax response
     //---------------------------------------------------------------
     $visualSettings = array('visualContentLayout' => array('attributes' => $settings));
     $response = new AjaxResponse();
     $response->addCommand(new CloseModalDialogCommand());
     $response->addCommand(new SettingsCommand($visualSettings, FALSE));
     return $response;
 }
예제 #5
0
파일: Callbacks.php 프로젝트: frankcr/sftw8
 /**
  * Ajax callback triggered by checkbox.
  */
 function checkboxCallback($form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax_checkbox_value', (int) $form_state->getValue('checkbox')));
     $response->addCommand(new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $form_state->getValue('checkbox')));
     return $response;
 }
예제 #6
0
 /**
  * AJAX callback.
  */
 public function ajaxCallback($form, FormStateInterface $form_state)
 {
     $item = ['#type' => 'item', '#title' => $this->t('Ajax value'), '#markup' => microtime()];
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax-value', $item));
     return $response;
 }
 public function validateEmailAjax(array &$form, FormStateInterface $form_state)
 {
     $httpClient = \Drupal::httpClient();
     $configuration = $this->config('gestiondenuncias.configuration');
     $pwd = $configuration->get('contrasena_verifyemail');
     $usr = $configuration->get('nombre_ususario_verifyemail');
     $email = $form_state->getValues('denunciante')['email'];
     $serverResponse = json_decode($httpClient->request('POST', "http://api.verify-email.org/api.php?usr={$usr}&pwd={$pwd}&check={$email}")->getBody()->getContents());
     $response = new AjaxResponse();
     if ($serverResponse->authentication_status != 1) {
         \Drupal::logger('gestiondenuncias.verify-email')->error('Los parametros de conexion a verify-email son incorrectos');
     } else {
         if ($serverResponse->limit_status) {
             \Drupal::logger('gestiondenuncias.verify-email')->error('Se llego al limite de consultas de verify-email');
         } else {
             if ($serverResponse->verify_status) {
                 $css = ['border' => '1px solid green'];
                 $message = $this->t('Email válido');
             } else {
                 $css = ['border' => '1px solid red'];
                 $message = $this->t('Email parece ser inválido');
             }
             $message = $message . $form_state->getValues()['denunciante']['email'];
             $response->addCommand(new CssCommand('#edit-email', $css));
             $response->addCommand(new HtmlCommand('.email-valid-message', $message));
         }
     }
     return $response;
 }
예제 #8
0
 /**
  * Ajax callback triggered by checkbox.
  */
 function checkboxCallback($form, $form_state)
 {
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax_checkbox_value', (int) $form_state['values']['checkbox']));
     $response->addCommand(new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $form_state['values']['checkbox']));
     return $response;
 }
예제 #9
0
 /**
  * Catches a form AJAX exception and build a response from it.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  *   The event to process.
  */
 public function onException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $request = $event->getRequest();
     // Render a nice error message in case we have a file upload which exceeds
     // the configured upload limit.
     if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
         $this->drupalSetMessage($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]), 'error');
         $response = new AjaxResponse();
         $status_messages = ['#type' => 'status_messages'];
         $response->addCommand(new ReplaceCommand(NULL, $status_messages));
         $response->headers->set('X-Status-Code', 200);
         $event->setResponse($response);
         return;
     }
     // Extract the form AJAX exception (it may have been passed to another
     // exception before reaching here).
     if ($exception = $this->getFormAjaxException($exception)) {
         $request = $event->getRequest();
         $form = $exception->getForm();
         $form_state = $exception->getFormState();
         // Set the build ID from the request as the old build ID on the form.
         $form['#build_id_old'] = $request->get('form_build_id');
         try {
             $response = $this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, []);
             // Since this response is being set in place of an exception, explicitly
             // mark this as a 200 status.
             $response->headers->set('X-Status-Code', 200);
             $event->setResponse($response);
         } catch (\Exception $e) {
             // Otherwise, replace the existing exception with the new one.
             $event->setException($e);
         }
     }
 }
예제 #10
0
 /**
  * Custom ajax form submission handler.
  *
  * @param array $form
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  */
 public function add(array &$form, FormStateInterface $form_state)
 {
     $context = $form_state->getValue('contexts');
     $content = \Drupal::formBuilder()->getForm($this->getContextClass(), $context, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }
예제 #11
0
 /**
  * Returns an Ajax response to render a text field without transformation filters.
  *
  * @param \Drupal\Core\Entity\EntityInterface $entity
  *   The entity of which a formatted text field is being rerendered.
  * @param string $field_name
  *   The name of the (formatted text) field that that is being rerendered
  * @param string $langcode
  *   The name of the language for which the formatted text field is being
  *   rerendered.
  * @param string $view_mode_id
  *   The view mode the formatted text field should be rerendered in.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   The Ajax response.
  */
 public function getUntransformedText(EntityInterface $entity, $field_name, $langcode, $view_mode_id)
 {
     $response = new AjaxResponse();
     // Direct text editing is only supported for single-valued fields.
     $field = $entity->getTranslation($langcode)->{$field_name};
     $editable_text = check_markup($field->value, $field->format, $langcode, array(FilterInterface::TYPE_TRANSFORM_REVERSIBLE, FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE));
     $response->addCommand(new GetUntransformedTextCommand($editable_text));
     return $response;
 }
예제 #12
0
 public function ajaxFormCallback(array &$form, FormStateInterface $form_state)
 {
     dd('callback');
     //dd(array_keys($form['ajax_wrapper']));
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax_wrapper', $form['ajax_wrapper']));
     $status_messages = ['#type' => 'status_messages'];
     $response->addCommand(new HtmlCommand('.highlighted aside .region', $status_messages));
     return $response;
 }
예제 #13
0
 /**
  * Tests the support for IE specific headers in file uploads.
  *
  * @cover ::prepareResponse
  */
 public function testPrepareResponseForIeFormRequestsWithFileUpload()
 {
     $request = Request::create('/example', 'POST');
     $request->headers->set('Accept', 'text/html');
     $response = new AjaxResponse([]);
     $response->headers->set('Content-Type', 'application/json; charset=utf-8');
     $response->prepare($request);
     $this->assertEquals('text/html; charset=utf-8', $response->headers->get('Content-Type'));
     $this->assertEquals($response->getContent(), '<textarea>[]</textarea>');
 }
예제 #14
0
 /**
  * Returns an node through JSON.
  *
  * @param Request $request
  *  The global request object.
  * @param string $entityType
  *  The type of the requested entity.
  * @param string $entityId
  *  The id of the requested entity.
  * @param string $viewMode
  *  The view mode you wish to render for the requested entity.
  *
  * @return array
  *   The Views fields report page.
  */
 public function switchViewMode(Request $request, $entityType, $entityId, $viewMode)
 {
     $response = new AjaxResponse();
     $entity = entity_load($entityType, $entityId);
     if ($entity->access('view')) {
         $element = entity_view($entity, $viewMode);
         $content = \Drupal::service('renderer')->render($element, FALSE);
         $response->addCommand(new ReplaceCommand('.' . $request->get('selector'), $content));
     }
     return $response;
 }
 public function add(array &$form, FormStateInterface $form_state)
 {
     $condition = $form_state->getValue('conditions');
     $content = \Drupal::formBuilder()->getForm($this->getConditionClass(), $condition, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     list(, $route_parameters) = $this->getOperationsRouteInfo($this->machine_name, $form_state->getValue('conditions'));
     $content['submit']['#attached']['drupalSettings']['ajax'][$content['submit']['#id']]['url'] = $this->url($this->getAddRoute(), $route_parameters, ['query' => [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]]);
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }
예제 #16
0
 /**
  * Returns an Ajax response to generate preview of embedded items.
  *
  * Expects the the HTML element as GET parameter.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object.
  * @param \Drupal\filter\FilterFormatInterface $filter_format
  *   The filter format.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Throws an exception if 'value' parameter is not found in the request.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The preview of the embedded item specified by the data attributes.
  */
 public function preview(Request $request, FilterFormatInterface $filter_format)
 {
     $text = $request->get('value');
     if ($text == '') {
         throw new NotFoundHttpException();
     }
     $output = check_markup($text, $filter_format->id());
     $response = new AjaxResponse();
     $response->addCommand(new EmbedInsertCommand($output));
     return $response;
 }
예제 #17
0
 /**
  * Tests the support for IE specific headers in file uploads.
  *
  * @cover ::prepareResponse
  */
 public function testPrepareResponseForIeFormRequestsWithFileUpload()
 {
     $request = Request::create('/example', 'POST');
     $request->headers->set('Accept', 'text/html');
     $response = new AjaxResponse([]);
     $response->headers->set('Content-Type', 'application/json; charset=utf-8');
     $ajax_response_attachments_processor = $this->getMock('\\Drupal\\Core\\Render\\AttachmentsResponseProcessorInterface');
     $subscriber = new AjaxResponseSubscriber($ajax_response_attachments_processor);
     $event = new FilterResponseEvent($this->getMock('\\Symfony\\Component\\HttpKernel\\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST, $response);
     $subscriber->onResponse($event);
     $this->assertEquals('text/html; charset=utf-8', $response->headers->get('Content-Type'));
     $this->assertEquals($response->getContent(), '<textarea>[]</textarea>');
 }
 function er_browser_widget_search_content(array &$form, FormStateInterface $form_state)
 {
     $form = \Drupal::formBuilder()->getForm('Drupal\\er_browser_widget\\Form\\EntityReferenceBrowserWidgetForm');
     $response = new AjaxResponse();
     $title = $this->t('Entity Search and Reference.');
     $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response->setAttachments($form['#attached']);
     $content = views_embed_view('entity_reference_browser_widget');
     $options = array('dialogClass' => 'test-dialog', 'width' => '75%');
     $modal = new OpenModalDialogCommand($title, $form, $options);
     $response->addCommand($modal);
     return $response;
 }
예제 #19
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $form));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
예제 #20
0
 /**
  * Util to render dialog in ajax callback.
  *
  * @param bool $is_modal
  *   (optional) TRUE if modal, FALSE if plain dialog. Defaults to FALSE.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An ajax response object.
  */
 protected function dialog($is_modal = FALSE)
 {
     $content = ajax_test_dialog_contents();
     $response = new AjaxResponse();
     $title = $this->t('AJAX Dialog contents');
     $html = drupal_render($content);
     if ($is_modal) {
         $response->addCommand(new OpenModalDialogCommand($title, $html));
     } else {
         $selector = '#ajax-test-dialog-wrapper-1';
         $response->addCommand(new OpenDialogCommand($selector, $title, $html));
     }
     return $response;
 }
 /**
  * Processes AJAX file uploads and deletions.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An AjaxResponse object.
  */
 public function upload(Request $request)
 {
     $form_parents = explode('/', $request->query->get('element_parents'));
     $form_build_id = $request->query->get('form_build_id');
     $request_form_build_id = $request->request->get('form_build_id');
     if (empty($request_form_build_id) || $form_build_id !== $request_form_build_id) {
         // Invalid request.
         drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
         $response = new AjaxResponse();
         $status_messages = array('#theme' => 'status_messages');
         return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages)));
     }
     try {
         /** @var $ajaxForm \Drupal\system\FileAjaxForm */
         $ajaxForm = $this->getForm($request);
         $form = $ajaxForm->getForm();
         $form_state = $ajaxForm->getFormState();
         $commands = $ajaxForm->getCommands();
     } catch (HttpExceptionInterface $e) {
         // Invalid form_build_id.
         drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
         $response = new AjaxResponse();
         $status_messages = array('#theme' => 'status_messages');
         return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages)));
     }
     // Get the current element and count the number of files.
     $current_element = NestedArray::getValue($form, $form_parents);
     $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
     // Process user input. $form and $form_state are modified in the process.
     drupal_process_form($form['#form_id'], $form, $form_state);
     // Retrieve the element to be rendered.
     $form = NestedArray::getValue($form, $form_parents);
     // Add the special Ajax class if a new file was added.
     if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
         $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
     } else {
         $form['#suffix'] .= '<span class="ajax-new-content"></span>';
     }
     $status_messages = array('#theme' => 'status_messages');
     $form['#prefix'] .= drupal_render($status_messages);
     $output = drupal_render($form);
     drupal_process_attached($form);
     $js = _drupal_add_js();
     $settings = drupal_merge_js_settings($js['settings']['data']);
     $response = new AjaxResponse();
     foreach ($commands as $command) {
         $response->addCommand($command, TRUE);
     }
     return $response->addCommand(new ReplaceCommand(NULL, $output, $settings));
 }
예제 #22
0
 /**
  * Assign this task to the current user and reloads the listing page.
  *
  * @param \Drupal\tmgmt_local\LocalTaskInterface $tmgmt_local_task
  *   The task being acted upon.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
  *   Either returns a rebuilt listing page as an AJAX response, or redirects
  *   back to the listing page.
  */
 public function assignToMe(LocalTaskInterface $tmgmt_local_task, Request $request)
 {
     $tmgmt_local_task->assign(\Drupal::currentUser());
     $tmgmt_local_task->save();
     drupal_set_message(t('The task has been assigned to you.'));
     // If the request is via AJAX, return the rendered list as JSON.
     if ($request->request->get('js')) {
         $list = $this->entityTypeManager()->getListBuilder('view')->render();
         $response = new AjaxResponse();
         $response->addCommand(new ReplaceCommand('#views-entity-list', $list));
         return $response;
     }
     // Otherwise, redirect back to the page.
     return $this->redirect('<current>');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $status_messages = array('#theme' => 'status_messages');
         $output = drupal_render($form);
         $output = '<div>' . drupal_render($status_messages) . $output . '</div>';
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $output));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
예제 #24
0
 /**
  * Util to render dialog in ajax callback.
  *
  * @param bool $is_modal
  *   (optional) TRUE if modal, FALSE if plain dialog. Defaults to FALSE.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An ajax response object.
  */
 protected function dialog($is_modal = FALSE)
 {
     $content = AjaxTestController::dialogContents();
     $response = new AjaxResponse();
     $title = $this->t('AJAX Dialog contents');
     // Attach the library necessary for using the Open(Modal)DialogCommand and
     // set the attachments for this Ajax response.
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     if ($is_modal) {
         $response->addCommand(new OpenModalDialogCommand($title, $content));
     } else {
         $selector = '#ajax-test-dialog-wrapper-1';
         $response->addCommand(new OpenDialogCommand($selector, $title, $content));
     }
     return $response;
 }
예제 #25
0
 /**
  * {@inheritdoc}
  */
 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match)
 {
     $response = new AjaxResponse();
     // First render the main content, because it might provide a title.
     $content = $this->renderer->renderRoot($main_content);
     // Attach the library necessary for using the OpenOffCanvasDialogCommand and
     // set the attachments for this Ajax response.
     $main_content['#attached']['library'][] = 'outside_in/drupal.off_canvas';
     $response->setAttachments($main_content['#attached']);
     // If the main content doesn't provide a title, use the title resolver.
     $title = isset($main_content['#title']) ? $main_content['#title'] : $this->titleResolver->getTitle($request, $route_match->getRouteObject());
     // Determine the title: use the title provided by the main content if any,
     // otherwise get it from the routing information.
     $options = $request->request->get('dialogOptions', []);
     $response->addCommand(new OpenOffCanvasDialogCommand($title, $content, $options));
     return $response;
 }
 public function addEmailCallback(array &$form, FormStateInterface $form_state)
 {
     $email = $form_state->getValue('new_email');
     if (\Drupal::service('email.validator')->isValid($email)) {
         $config = \Drupal::service('config.factory')->getEditable('registration_role_with_approval.settings');
         $mailing_list = $config->get('mailing_list');
         $mailing_list .= " " . $email;
         $config->set('mailing_list', $mailing_list);
         $config->save();
         $form['custom_mail']['mailing_list']['#default_value'] = $mailing_list;
         $ajax_response = new AjaxResponse();
         $ajax_response->addCommand(new InvokeCommand('#edit-mailing-list', 'val', $mailing_list));
         $ajax_response->addCommand(new ChangedCommand('#edit-mailing-list', '#edit-mailing-list'));
         $ajax_response->addCommand(new InvokeCommand('#edit-mailing-list', 'change'));
         //return $form['custom_mail']['mailing_list'];
         return $ajax_response;
     }
 }
예제 #27
0
 /**
  * {@inheritdoc}
  */
 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match)
 {
     $response = new AjaxResponse();
     // First render the main content, because it might provide a title.
     $content = drupal_render_root($main_content);
     // Attach the library necessary for using the OpenDialogCommand and set the
     // attachments for this Ajax response.
     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response->setAttachments($main_content['#attached']);
     // Determine the title: use the title provided by the main content if any,
     // otherwise get it from the routing information.
     $title = isset($main_content['#title']) ? $main_content['#title'] : $this->titleResolver->getTitle($request, $route_match->getRouteObject());
     // Determine the dialog options and the target for the OpenDialogCommand.
     $options = $request->request->get('dialogOptions', array());
     $target = $this->determineTargetSelector($options, $route_match);
     $response->addCommand(new OpenDialogCommand($target, $title, $content, $options));
     return $response;
 }
 /**
  * Displays modal form for input the attributes of the swap
  */
 public function displayModalAttributesForm($swap)
 {
     //get the list of all modules
     $modules = \Drupal::moduleHandler()->getModuleList();
     //search the swap form in all modules
     foreach (array_keys($modules) as $name) {
         $namespace = "Drupal\\" . $name . "\\Form\\" . $swap . "AttributesForm";
         //validate the namespace have the form
         if (class_exists($namespace)) {
             $form = \Drupal::formBuilder()->getForm($namespace);
             break;
         }
     }
     $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
     //create the ajax response
     $response = new AjaxResponse();
     $modalOptions = array('width' => '1428', 'height' => 'auto');
     $response->addCommand(new OpenModalDialogCommand("Swap Settings", $form, $modalOptions));
     return $response;
 }
예제 #29
0
 /**
  * Implements the sumbit handler for the ajax call.
  *
  * @param array $form
  *   Render array representing from.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Current form state.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   Array of ajax commands to execute on submit of the modal form.
  */
 public function ajaxSubmitForm(array &$form, FormStateInterface $form_state)
 {
     // At this point the submit handler has fired.
     // Clear the message set by the submit handler.
     drupal_get_messages();
     // We begin building a new ajax reponse.
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix']);
         unset($form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#fapi-example-modal-form', $form));
     } else {
         $title = $form_state->getValue('title');
         $message = t('You specified a title of %title.', ['%title' => $title]);
         $content = ['#type' => 'html_tag', '#tag' => 'p', '#value' => $message];
         $response->addCommand(new HtmlCommand('#fapi-example-message', $content));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }
예제 #30
0
 /**
  * Converts the output of a controller into an Ajax response object.
  *
  * @var mixed $content
  *   The return value of a controller, for example a string, a render array, a
  *   HtmlFragment object, a Response object or even an AjaxResponse itself.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An Ajax response containing the controller result.
  */
 public function render($content)
 {
     // If there is already a Response object, return it without manipulation.
     if ($content instanceof Response && $content->isOk()) {
         return $content;
     }
     // Allow controllers to return an HtmlFragment directly.
     if ($content instanceof HtmlFragment) {
         $content = $content->getContent();
     }
     // Most controllers return a render array, but some return a string.
     if (!is_array($content)) {
         $content = array('#markup' => $content);
     }
     $response = new AjaxResponse();
     if (isset($content['#type']) && $content['#type'] == 'ajax') {
         // Complex Ajax callbacks can return a result that contains an error
         // message or a specific set of commands to send to the browser.
         $content += $this->elementInfo('ajax');
         $error = $content['#error'];
         if (!empty($error)) {
             // Fall back to some default message otherwise use the specific one.
             if (!is_string($error)) {
                 $error = 'An error occurred while handling the request: The server received invalid input.';
             }
             $response->addCommand(new AlertCommand($error));
         }
     }
     $html = $this->drupalRender($content);
     // The selector for the insert command is NULL as the new content will
     // replace the element making the Ajax call. The default 'replaceWith'
     // behavior can be changed with #ajax['method'].
     $response->addCommand(new InsertCommand(NULL, $html));
     $status_messages = array('#theme' => 'status_messages');
     $output = $this->drupalRender($status_messages);
     if (!empty($output)) {
         $response->addCommand(new PrependCommand(NULL, $output));
     }
     return $response;
 }