commerce_shipping-8.x-2.0-rc2/src/Form/ShipmentAddModalForm.php
src/Form/ShipmentAddModalForm.php
<?php
namespace Drupal\commerce_shipping\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Defines the add shipment modal form.
*/
class ShipmentAddModalForm extends ShipmentForm {
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = parent::actions($form, $form_state);
$actions['submit']['#ajax'] = [
'callback' => '::ajaxSubmit',
];
$order = $this->entity->getOrder();
$actions['cancel'] = [
'#type' => 'link',
'#title' => $this->t('Cancel'),
'#url' => $order->toUrl(),
'#attributes' => [
'class' => ['button', 'button--danger', 'dialog-cancel'],
],
];
return $actions;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$return = parent::save($form, $form_state);
$order = $this->entity->getOrder();
$form_state->setRedirectUrl($order->toUrl());
return $return;
}
/**
* Submit form dialog #ajax callback.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* An AJAX response that display validation error messages or represents a
* successful submission.
*/
public function ajaxSubmit(array $form, FormStateInterface $form_state) {
if ($form_state->hasAnyErrors()) {
$response = self::ajaxRefreshForm($form, $form_state);
}
else {
$response = new AjaxResponse();
$url = Url::fromRoute('<front>');
$order = $this->entity->getOrder();
if ($order) {
$url = $order->toUrl();
}
$response->addCommand(new RedirectCommand($url->toString()));
}
return $response;
}
}
