class ShipmentForm in Commerce Shipping 8.2
Defines the shipment add/edit form.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\commerce_shipping\Form\ShipmentForm
- class \Drupal\Core\Entity\ContentEntityForm implements ContentEntityFormInterface
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of ShipmentForm
File
- src/
Form/ ShipmentForm.php, line 22
Namespace
Drupal\commerce_shipping\FormView source
class ShipmentForm extends ContentEntityForm {
/**
* The package type manager.
*
* @var \Drupal\commerce_shipping\PackageTypeManagerInterface
*/
protected $packageTypeManager;
/**
* Constructs a new ShipmentForm object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time.
* @param \Drupal\commerce_shipping\PackageTypeManagerInterface $package_type_manager
* The package type manager.
*/
public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, PackageTypeManagerInterface $package_type_manager) {
parent::__construct($entity_repository, $entity_type_bundle_info, $time);
$this->packageTypeManager = $package_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('entity.repository'), $container
->get('entity_type.bundle.info'), $container
->get('datetime.time'), $container
->get('plugin.manager.commerce_package_type'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $this->entity;
$order_id = $shipment
->get('order_id')->target_id;
if (!$order_id) {
$order_id = $this
->getRouteMatch()
->getRawParameter('commerce_order');
$shipment
->set('order_id', $order_id);
}
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $shipment
->getOrder();
/** @var \Drupal\profile\Entity\ProfileInterface $shipping_profile */
$shipping_profile = $shipment
->getShippingProfile();
if (!$shipping_profile) {
/** @var \Drupal\commerce_shipping\Entity\ShipmentTypeInterface $shipment_type */
$shipment_type = $this->entityTypeManager
->getStorage('commerce_shipment_type')
->load($shipment
->bundle());
/** @var \Drupal\profile\Entity\ProfileInterface $shipping_profile */
$shipping_profile = $this->entityTypeManager
->getStorage('profile')
->create([
'type' => $shipment_type
->getProfileTypeId(),
'uid' => 0,
]);
$address = [
'#type' => 'address',
'#default_value' => [],
];
$shipping_profile
->set('address', $address);
$shipment
->setShippingProfile($shipping_profile);
}
// Store the original amount for ShipmentForm::save().
$form_state
->set('original_amount', $shipment
->getAmount());
$form = parent::form($form, $form_state);
// The ShippingProfileWidget doesn't output a fieldset because that makes
// sense in a checkout context, but on the admin form it is clearer for
// profile fields to be visually grouped.
$form['shipping_profile']['widget'][0]['#type'] = 'fieldset';
// Fixes illegal choice has been detected message upon AJAX reload.
if (empty($form['shipping_method']['widget'][0]['#options'])) {
$form['shipping_method']['#access'] = FALSE;
}
// Prepare the form for ajax.
// Not using Html::getUniqueId() on the wrapper ID to avoid #2675688.
$form['#wrapper_id'] = 'shipping-information-wrapper';
$form['#prefix'] = '<div id="' . $form['#wrapper_id'] . '">';
$form['#suffix'] = '</div>';
$package_types = $this->packageTypeManager
->getDefinitions();
$package_type_options = [];
foreach ($package_types as $package_type) {
$unit = ' ' . array_pop($package_type['dimensions']);
$dimensions = ' (' . implode(' x ', $package_type['dimensions']) . $unit . ')';
$package_type_options[$package_type['id']] = $package_type['label'] . $dimensions;
}
$package_type = $shipment
->getPackageType();
$form['package_type'] = [
'#type' => 'select',
'#title' => $this
->t('Package Type'),
'#options' => $package_type_options,
'#default_value' => $package_type ? $package_type
->getId() : '',
'#access' => count($package_types) > 1,
];
$order_items = $order
->getItems();
/** @var \Drupal\commerce_shipping\ShipmentStorageInterface $shipment_storage */
$shipment_storage = $this->entityTypeManager
->getStorage('commerce_shipment');
// Get all of the shipments for the current order.
$order_shipments = $shipment_storage
->loadMultipleByOrder($order);
// Store order_items that are already tied to shipments on this order.
$already_on_shipment = [];
foreach ($order_shipments as $order_shipment) {
if ($order_shipment
->id() != $shipment
->id()) {
$shipment_items = $order_shipment
->getItems();
foreach ($shipment_items as $shipment_item) {
$order_item_id = $shipment_item
->getOrderItemId();
$already_on_shipment[$order_item_id] = $order_item_id;
}
}
}
$shipment_item_options = [];
// Populates the default values by looking at the items already in this
// shipment.
$shipment_item_defaults = [];
$shipment_items = $shipment
->getItems();
/** @var \Drupal\commerce_shipping\ShipmentItem $shipment_item */
foreach ($shipment_items as $shipment_item) {
$shipment_item_id = $shipment_item
->getOrderItemId();
$shipment_item_defaults[$shipment_item_id] = $shipment_item_id;
$shipment_item_options[$shipment_item_id] = $shipment_item
->getTitle();
}
/** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
foreach ($order_items as $order_item) {
// Skip shipment items that are already on this shipment.
if (isset($shipment_item_options[$order_item
->id()]) || !$order_item
->hasField('purchased_entity') || in_array($order_item
->id(), $already_on_shipment, TRUE)) {
continue;
}
// Only allow items that aren't already on a shipment
// have a purchasable entity and implement the shippable trait.
$purchasable_entity = $order_item
->getPurchasedEntity();
if (!empty($purchasable_entity) && $purchasable_entity
->hasField('weight')) {
$shipment_item_options[$order_item
->id()] = $order_item
->label();
}
}
$form['shipment_items'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Shipment items'),
'#options' => $shipment_item_options,
'#default_value' => $shipment_item_defaults,
'#required' => TRUE,
'#weight' => 48,
];
$form['recalculate_shipping'] = [
'#type' => 'button',
'#value' => $this
->t('Recalculate shipping'),
'#recalculate' => TRUE,
'#ajax' => [
'callback' => [
get_class($this),
'ajaxRefresh',
],
'wrapper' => $form['#wrapper_id'],
],
// The calculation process only needs a valid shipping profile.
'#limit_validation_errors' => [
array_merge($form['#parents'], [
'shipping_profile',
]),
],
'#weight' => 49,
'#after_build' => [
[
static::class,
'clearValues',
],
],
];
return $form;
}
/**
* Ajax callback.
*/
public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
$parents = array_slice($triggering_element['#parents'], 0, -1);
return NestedArray::getValue($form, $parents);
}
/**
* Clears user input of selected shipping rates if recalculation occured.
*
* This is required to prevent invalid options being selected is a shipping
* rate is no longer available.
*
* @param array $element
* The element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The element.
*/
public static function clearValues(array $element, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
if (!$triggering_element) {
return $element;
}
$triggering_element_name = end($triggering_element['#parents']);
if ($triggering_element_name === 'recalculate_shipping') {
$user_input =& $form_state
->getUserInput();
unset($user_input['shipping_method']);
}
return $element;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$triggering_element = $form_state
->getTriggeringElement();
$recalculate = !empty($triggering_element['#recalculate']);
if ($recalculate) {
$form_state
->set('recalculate_shipping', TRUE);
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $this->entity;
$shipment
->setTitle($form_state
->getValue('title'));
$base_form_key = [
'shipping_profile',
'0',
'profile',
];
$selected_profile_key = array_merge($base_form_key, [
'select_address',
]);
$selected_profile_id = $form_state
->getValue($selected_profile_key);
$address_key = array_merge($base_form_key, [
'address',
'0',
'address',
]);
$address = $form_state
->getValue($address_key);
// If an address was input, use that as an address override.
if ($address !== NULL) {
$shipment
->getShippingProfile()
->get('address')
->setValue($address);
}
elseif ($selected_profile_id !== '_original') {
$profile_storage = $this->entityTypeManager
->getStorage('profile');
$selected_profile = $profile_storage
->load($selected_profile_id);
assert($selected_profile instanceof ProfileInterface);
$shipment
->getShippingProfile()
->set('address', $selected_profile
->get('address'));
}
// Add the shipping items.
$this
->addShippingItems($form, $form_state);
if (empty($form_state
->getValue('package_type'))) {
return;
}
$package_type = $this->packageTypeManager
->createInstance($form_state
->getValue('package_type'));
$shipment
->setPackageType($package_type);
}
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $this
->getEntity();
$this
->addShippingItems($form, $form_state);
$shipment
->setData('owned_by_packer', FALSE);
$shipment
->save();
// Make sure the shipment gets added to the order.
$order = $shipment
->getOrder();
$order_shipments = $order
->get('shipments');
$shipment_exists = FALSE;
$save_order = FALSE;
// Loop over the order shipments to make sure this
// shipment exists.
foreach ($order_shipments
->getValue() as $order_shipment) {
if ($order_shipment['target_id'] == $shipment
->id()) {
$shipment_exists = TRUE;
}
}
// Check if the shipment amount has changed, if so we need to trigger
// an order refresh so that the shipping adjustment gets adjusted.
if ($form_state
->get('original_amount') != $shipment
->getAmount()) {
$order
->setRefreshState(OrderInterface::REFRESH_ON_SAVE);
$save_order = TRUE;
}
// Add the shipment to the order if it doesn't exist.
if (!$shipment_exists) {
$order_shipments
->appendItem($shipment);
$save_order = TRUE;
}
// Save the parent order if the shipment amount has changed or if the
// shipment was appended to the order.
if ($save_order) {
$order
->save();
}
$this
->messenger()
->addMessage($this
->t('Shipment for order @order created.', [
'@order' => $order
->getOrderNumber(),
]));
$form_state
->setRedirect('entity.commerce_shipment.collection', [
'commerce_order' => $order
->id(),
]);
}
/**
* Creates new shipping items from the form and adds them to the shipment.
*
* @param array $form
* A nested array of form elements comprising the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function addShippingItems(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $this->entity;
// Clear the shipping items to make sure the list is fresh when we add them.
$shipment
->setItems([]);
/** @var \Drupal\commerce_shipping\ShipmentItem $shipment_item */
foreach ($form_state
->getValue('shipment_items') as $key => $value) {
if ($value == 0) {
// The item was not included in the shipment.
continue;
}
/** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
$order_item = $this->entityTypeManager
->getStorage('commerce_order_item')
->load($key);
$quantity = $order_item
->getQuantity();
$purchased_entity = $order_item
->getPurchasedEntity();
if ($purchased_entity
->get('weight')
->isEmpty()) {
$weight = new Weight(1, WeightUnit::GRAM);
}
else {
/** @var \Drupal\physical\Plugin\Field\FieldType\MeasurementItem $weight_item */
$weight_item = $purchased_entity
->get('weight')
->first();
$weight = $weight_item
->toMeasurement();
}
$shipment_item = new ShipmentItem([
'order_item_id' => $order_item
->id(),
'title' => $purchased_entity
->label(),
'quantity' => $quantity,
'weight' => $weight
->multiply($quantity),
'declared_value' => $order_item
->getTotalPrice(),
]);
$shipment
->addItem($shipment_item);
}
}
}
Members
Name![]() |
Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ContentEntityForm:: |
protected | property |
The entity being used by this form. Overrides EntityForm:: |
9 |
ContentEntityForm:: |
protected | property | The entity repository service. | |
ContentEntityForm:: |
protected | property | The entity type bundle info service. | |
ContentEntityForm:: |
protected | property | The time service. | |
ContentEntityForm:: |
protected | function | Add revision form fields if the entity enabled the UI. | |
ContentEntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityForm:: |
3 |
ContentEntityForm:: |
protected | function |
Copies top-level form values to entity properties Overrides EntityForm:: |
|
ContentEntityForm:: |
protected | function | Flags violations for the current form. | 4 |
ContentEntityForm:: |
protected | function | Returns the bundle entity of the entity, or NULL if there is none. | |
ContentEntityForm:: |
protected | function | Gets the names of all fields edited in the form. | 4 |
ContentEntityForm:: |
public | function |
Gets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
public | function |
Gets the code identifying the active form language. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Should new revisions created on default. | |
ContentEntityForm:: |
protected | function |
Initializes the form state and the entity before the first form build. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
protected | function | Initializes form language code values. | |
ContentEntityForm:: |
public | function |
Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function |
Prepares the entity object before the form is built first. Overrides EntityForm:: |
1 |
ContentEntityForm:: |
public | function |
Sets the form display. Overrides ContentEntityFormInterface:: |
|
ContentEntityForm:: |
protected | function | Checks whether the revision form fields should be added to the form. | |
ContentEntityForm:: |
public | function |
This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state… Overrides EntityForm:: |
3 |
ContentEntityForm:: |
public | function | Updates the changed time of the entity. | |
ContentEntityForm:: |
public | function | Updates the form language to reflect any change to the entity language. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns an array of supported actions for the current entity form. | 29 |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
ShipmentForm:: |
protected | property | The package type manager. | |
ShipmentForm:: |
protected | function | Creates new shipping items from the form and adds them to the shipment. | |
ShipmentForm:: |
public static | function | Ajax callback. | |
ShipmentForm:: |
public static | function | Clears user input of selected shipping rates if recalculation occured. | |
ShipmentForm:: |
public static | function |
Instantiates a new instance of this class. Overrides ContentEntityForm:: |
|
ShipmentForm:: |
public | function |
Gets the actual form array to be built. Overrides ContentEntityForm:: |
|
ShipmentForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
ShipmentForm:: |
public | function |
Button-level validation handlers are highly discouraged for entity forms,
as they will prevent entity validation from running. If the entity is going
to be saved during the form submission, this method should be manually
invoked from the button-level… Overrides ContentEntityForm:: |
|
ShipmentForm:: |
public | function |
Constructs a new ShipmentForm object. Overrides ContentEntityForm:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |