diff -u b/modules/checkout/src/Plugin/Commerce/CheckoutPane/BillingInformation.php b/modules/checkout/src/Plugin/Commerce/CheckoutPane/BillingInformation.php
--- b/modules/checkout/src/Plugin/Commerce/CheckoutPane/BillingInformation.php
+++ b/modules/checkout/src/Plugin/Commerce/CheckoutPane/BillingInformation.php
@@ -37,8 +37,7 @@
$pane_form['profile'] = [
'#type' => 'commerce_profile_select',
'#title' => $this->t('Select an address'),
- '#create_title' => t('+ Enter a new address'),
- '#profile' => $this->order->getBillingProfile(),
+ '#profile' => $this->getBillingProfile(),
'#profile_type' => 'customer',
'#profile_uid' => $this->order->getCustomerId(),
'#default_country' => $store->getAddress()->getCountryCode(),
@@ -57,2 +56,20 @@
+
+ /**
+ * Gets the billing profile.
+ *
+ * @return \Drupal\profile\Entity\ProfileInterface
+ * The billing profile.
+ */
+ protected function getBillingProfile() {
+ if ($billing_profile = $this->order->getBillingProfile()) {
+ return $billing_profile;
+ }
+ $billing_profile = $this->entityTypeManager->getStorage('profile')->create([
+ 'type' => 'customer',
+ 'uid' => $this->order->getCustomerId(),
+ ]);
+ return $billing_profile;
+ }
+
}
interdiff impossible; taking evasive action
reverted:
--- b/modules/order/src/Element/ProfileSelect.php
+++ a/modules/order/src/Element/ProfileSelect.php
@@ -3,10 +3,7 @@
namespace Drupal\commerce_order\Element;
use Drupal\commerce\Element\CommerceElementTrait;
-use Drupal\Component\Utility\Html;
-use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
-use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\RenderElement;
use Drupal\profile\Entity\ProfileInterface;
@@ -18,9 +15,7 @@
* @code
* $form['billing_profile'] = [
* '#type' => 'commerce_profile_select',
+ * '#default_value' => $profile,
- * '#profile' => $profile,
- * '#profile_type' => 'customer',
- * '#profile_uid' => \Drupal::currentUser()->id(),
* '#default_country' => 'FR',
* '#available_countries' => ['US', 'FR'],
* ];
@@ -29,10 +24,6 @@
* $form['billing_profile']['#profile']. Due to Drupal core limitations the
* profile can't be accessed via $form_state->getValue('billing_profile').
*
- * Note:
- * This element always behaves as required. For optional behavior add
- * a checkbox above the element that hides it on #ajax.
- *
* @RenderElement("commerce_profile_select")
*/
class ProfileSelect extends RenderElement {
@@ -45,54 +36,51 @@
public function getInfo() {
$class = get_class($this);
return [
- '#tree' => TRUE,
- '#title' => t('Select a profile'),
- '#create_title' => t('+ Enter a new profile'),
- // The element doesn't use #default_value / #value. Use #profile instead.
- '#default_value' => NULL,
- // The preselected profile. A profile entity, or NULL.
- '#profile' => NULL,
- // Needed for creating new profiles, since #profile is not always given.
- '#profile_type' => NULL,
- '#profile_uid' => 0,
- // Whether profiles should always be loaded in the latest revision.
- // Disable when editing historical data, such as placed orders.
- '#profile_latest_revision' => TRUE,
// The country to select if the address widget doesn't have a default.
'#default_country' => NULL,
// A list of country codes. If empty, all countries will be available.
'#available_countries' => [],
+ // The profile entity operated on. Required.
+ '#default_value' => NULL,
'#process' => [
[$class, 'attachElementSubmit'],
+ [$class, 'processForm'],
- [$class, 'processElement'],
],
'#element_validate' => [
[$class, 'validateElementSubmit'],
[$class, 'validateForm'],
],
+ '#commerce_element_submit' => [
+ [$class, 'submitForm'],
+ ],
'#theme_wrappers' => ['container'],
];
}
/**
+ * Builds the element form.
- * Validates the element properties.
*
* @param array $element
+ * The form element being processed.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ * The current state of the form.
+ * @param array $complete_form
+ * The complete form structure.
- * The form element.
*
* @throws \InvalidArgumentException
+ * Thrown when #default_value is empty or not an entity, or when
+ * #available_countries is not an array of country codes.
+ *
+ * @return array
+ * The processed form element.
- * Thrown if an element property is invalid, or empty but required.
*/
+ public static function processForm(array $element, FormStateInterface $form_state, array &$complete_form) {
+ if (empty($element['#default_value'])) {
+ throw new \InvalidArgumentException('The commerce_profile_select element requires the #default_value property.');
- public static function validateElementProperties(array $element) {
- if (empty($element['#profile_type'])) {
- throw new \InvalidArgumentException('The commerce_profile_select #profile_type property must be provided.');
}
+ elseif (isset($element['#default_value']) && !($element['#default_value'] instanceof ProfileInterface)) {
+ throw new \InvalidArgumentException('The commerce_profile_select #default_value property must be a profile entity.');
- if (isset($element['#profile']) && !($element['#profile'] instanceof ProfileInterface)) {
- throw new \InvalidArgumentException('The commerce_profile_select #profile property must be a profile entity.');
- }
- if (!empty($element['#profile_uid']) && !is_numeric($element['#profile_uid'])) {
- throw new \InvalidArgumentException('The commerce_profile_select #profile_uid property must be a numeric entity ID.');
}
if (!is_array($element['#available_countries'])) {
throw new \InvalidArgumentException('The commerce_profile_select #available_countries property must be an array.');
@@ -103,209 +91,24 @@
$element['#default_country'] = NULL;
}
}
- }
+ $element['#profile'] = $element['#default_value'];
+ $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
+ $form_display->buildForm($element['#profile'], $element, $form_state);
+ if (!empty($element['address']['widget'][0])) {
+ $widget_element = &$element['address']['widget'][0];
+ // Remove the details wrapper from the address widget.
+ $widget_element['#type'] = 'container';
+ // Provide a default country.
+ if (!empty($element['#default_country']) && empty($widget_element['address']['#default_value']['country_code'])) {
+ $widget_element['address']['#default_value']['country_code'] = $element['#default_country'];
- /**
- * Builds the element form.
- *
- * @param array $element
- * The form element being processed.
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- * @param array $complete_form
- * The complete form structure.
- *
- * @return array
- * The processed form element.
- */
- public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {
- self::validateElementProperties($element);
-
- $element_state = self::getElementState($element['#parents'], $form_state);
- // If the provided profile is in a previous revision, make sure it stays
- // available as an option when $element['#profile'] gets changed.
- if (empty($element['#profile_latest_revision']) && empty($element_state['fixed_option'])) {
- if (!empty($element['#profile']) && !$element['#profile']->isDefaultRevision()) {
- $element_state['fixed_option'] = [
- 'id' => self::buildOptionId($element['#profile'], $element['#profile_latest_revision']),
- 'label' => $element['#profile']->label() . ' ' . t('(Original)'),
- ];
- }
- }
-
- /** @var \Drupal\profile\ProfileStorageInterface $profile_storage */
- $profile_storage = \Drupal::entityTypeManager()->getStorage('profile');
- $user_storage = \Drupal::entityTypeManager()->getStorage('user');
- $user = $element['#profile_uid'] ? $user_storage->load($element['#profile_uid']) : NULL;
- $profiles = [];
- if ($user) {
- $profiles = $profile_storage->loadMultipleByUser($user, $element['#profile_type'], TRUE);
- }
- elseif ($profile = $form_state->get('profile')) {
- $profiles[] = $profile;
- }
- $profile_options = [];
- foreach ($profiles as $profile) {
- $option_id = self::buildOptionId($profile, $element['#profile_latest_revision']);
- $profile_options[$option_id] = $profile->label();
- }
- if (!empty($element_state['fixed_option'])) {
- $option_id = $element_state['fixed_option']['id'];
- $profile_options[$option_id] = $element_state['fixed_option']['label'];
- }
-
- $user_input = $form_state->getUserInput();
- $selected_option = NestedArray::getValue($user_input, array_merge($element['#parents'], ['profile_selection']));
- if (!empty($selected_option)) {
- // Keep the last selection in element state, so that the element knows
- // where to return the customer upon cancelling form mode.
- $element_state['selected_option'] = $selected_option;
- }
- elseif (!empty($element_state['selected_option']) && !$form_state->get('return_to_view')) {
- $selected_option = $element_state['selected_option'];
- }
- else {
- $selected_option = '_new';
- if ($default_profile = self::selectDefaultProfile($element, $profiles)) {
- $selected_option = self::buildOptionId($default_profile, $element['#profile_latest_revision']);
- }
- }
-
- if ($selected_option == '_new') {
- $element['#profile'] = $profile_storage->create([
- 'type' => $element['#profile_type'],
- 'uid' => $element['#profile_uid'],
- ]);
- $element_state['mode'] = 'form';
- }
- else {
- $id_parts = explode('-', $selected_option);
- if (!empty($id_parts[1])) {
- $element['#profile'] = $profile_storage->loadRevision($id_parts[1]);
- }
- else {
- $element['#profile'] = $profile_storage->load($id_parts[0]);
- }
- }
- $form_state->set('return_to_view', FALSE);
-
- $id_prefix = implode('-', $element['#parents']);
- $wrapper_id = Html::getUniqueId($id_prefix . '-ajax-wrapper');
- $element = [
- '#prefix' => '
',
- '#suffix' => '
',
- // Pass the id along to other methods.
- '#wrapper_id' => $wrapper_id,
- ] + $element;
-
- if ($element_state['mode'] == 'view') {
- $element['profile_selection'] = [
- '#type' => 'select',
- '#title' => $element['#title'],
- '#options' => $profile_options,
- '#default_value' => $selected_option,
- '#ajax' => [
- 'callback' => [get_called_class(), 'ajaxRefresh'],
- 'wrapper' => $wrapper_id,
- ],
- '#limit_validation_errors' => [],
- '#weight' => -1,
- '#access' => !empty($profile_options),
- ];
- if (\Drupal::currentUser()->isAuthenticated()) {
- $element['profile_selection']['#options'] += ['_new' => $element['#create_title']];
}
+ // Limit the available countries.
+ if (!empty($element['#available_countries'])) {
+ $widget_element['address']['#available_countries'] = $element['#available_countries'];
-
- $view_builder = \Drupal::entityTypeManager()->getViewBuilder('profile');
- $element['profile'] = $view_builder->view($element['#profile'], 'default');
-
- $element['edit_button'] = [
- '#type' => 'button',
- '#value' => t('Edit'),
- '#limit_validation_errors' => [],
- '#ajax' => [
- 'callback' => [get_called_class(), 'ajaxRefresh'],
- 'wrapper' => $wrapper_id,
- ],
- '#submit' => [[get_called_class(), 'ajaxSubmit']],
- '#name' => implode('_', $element['#parents']) . '_edit',
- '#element_mode' => 'form',
- // When given a historical profile, don't allow it to be edited.
- '#access' => $element['#profile_latest_revision'] || $element['#profile']->isDefaultRevision(),
- ];
- }
- else {
- $element['form'] = [
- '#parents' => array_merge($element['#parents'], ['form']),
- ];
- $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
- $form_display->buildForm($element['#profile'], $element['form'], $form_state);
- if (!empty($element['form']['address']['widget'][0])) {
- $widget_element = &$element['form']['address']['widget'][0];
- // Remove the details wrapper from the address widget.
- $widget_element['#type'] = 'container';
- // Provide a default country.
- if (!empty($element['#default_country']) && empty($widget_element['address']['#default_value']['country_code'])) {
- $widget_element['address']['#default_value']['country_code'] = $element['#default_country'];
- }
- // Limit the available countries.
- if (!empty($element['#available_countries'])) {
- $widget_element['address']['#available_countries'] = $element['#available_countries'];
- }
}
- // Create a dummy button so the triggering element is not a button that
- // has real significance. See FormBuilder->doBuildForm logic around
- // support for IE and setTriggeringElement.
- $element['dummy'] = [
- '#type' => 'button',
- '#value' => t('Dummy'),
- '#attributes' => ['class' => ['visually-hidden']],
- '#limit_validation_errors' => [],
- '#ajax' => [
- 'callback' => [get_called_class(), 'ajaxRefresh'],
- 'wrapper' => $wrapper_id,
- ],
- '#submit' => [
- [get_called_class(), 'ajaxSubmit'],
- ],
- ];
- $element['submit'] = [
- '#type' => 'submit',
- '#value' => t('Save'),
- '#ajax' => [
- 'callback' => [get_called_class(), 'ajaxRefresh'],
- 'wrapper' => $wrapper_id,
- ],
- '#submit' => [
- [get_called_class(), 'ajaxSubmit'],
- ],
- '#name' => implode('_', $element['#parents']) . '_submit',
- '#element_mode' => 'view',
- '#save_profile' => TRUE,
- '#button_type' => 'primary',
- ];
- $element['cancel_button'] = [
- '#type' => 'submit',
- '#value' => t('Cancel'),
- '#limit_validation_errors' => [],
- '#ajax' => [
- 'callback' => [get_called_class(), 'ajaxRefresh'],
- 'wrapper' => $wrapper_id,
- ],
- '#submit' => [
- [get_called_class(), 'ajaxSubmit'],
- ],
- '#name' => implode('_', $element['#parents']) . '_cancel',
- '#element_mode' => 'view',
- '#cancel' => TRUE,
- '#access' => !empty($profiles),
- '#button_type' => 'danger',
- ];
}
- // Persist any changes made to $element_state.
- self::setElementState($element['#parents'], $form_state, $element_state);
-
return $element;
}
@@ -322,91 +125,9 @@
* form, as a protection against buggy behavior.
*/
public static function validateForm(array &$element, FormStateInterface $form_state) {
+ $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
+ $form_display->extractFormValues($element['#profile'], $element, $form_state);
+ $form_display->validateFormValues($element['#profile'], $element, $form_state);
- self::getElementMode($form_state);
- $triggering_element = $form_state->getTriggeringElement();
- $form_state->set('save_profile', FALSE);
- $form_state->set('cancel_profile', FALSE);
- if (!empty($triggering_element['#save_profile']) && !empty($element['form'])) {
- $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
- $form_display->extractFormValues($element['#profile'], $element['form'], $form_state);
- $form_display->validateFormValues($element['#profile'], $element['form'], $form_state);
- if (!FormState::hasAnyErrors() && $element['#profile']->hasTranslationChanges()) {
- $foo = $element['#profile']->save();
- $form_state->set('return_to_view', TRUE);
- $form_state->set('profile', $element['#profile']);
- }
- }
- if (!empty($triggering_element['#cancel'])) {
- $form_state->set('return_to_view', TRUE);
- }
- }
-
- /**
- * Builds the option ID for the given profile.
- *
- * @param \Drupal\profile\Entity\ProfileInterface $profile
- * The profile.
- * @param bool $use_latest_revision
- * (optional) Use the latest revision, defaults to TRUE.
- *
- * @return string
- * The option ID.
- */
- public static function buildOptionId(ProfileInterface $profile, $use_latest_revision = TRUE) {
- $option_id = $profile->id();
- if (!$use_latest_revision) {
- $option_id .= '-' . $profile->getRevisionId();
- }
- return $option_id;
- }
-
- /**
- * Selects the default profile for the given element.
- *
- * @param array $element
- * The element.
- * @param array $profiles
- * The available profiles.
- *
- * @return \Drupal\profile\Entity\ProfileInterface|null
- * The default profile, or NULL if none found.
- */
- public static function selectDefaultProfile(array $element, array $profiles) {
- $default_profile = NULL;
- if (!empty($element['#profile'])) {
- $default_profile = $element['#profile'];
- }
- elseif (!empty($profiles)) {
- $default_profile = reset($profiles);
- foreach ($profiles as $profile) {
- if ($profile->isDefault()) {
- $default_profile = $profile;
- break;
- }
- }
- }
-
- return $default_profile;
- }
-
- /**
- * Ajax callback.
- */
- public static function ajaxRefresh(array &$form, FormStateInterface $form_state) {
- $triggering_element = $form_state->getTriggeringElement();
- $element = NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -1));
- return $element;
- }
-
- /**
- * Ajax submit callback.
- */
- public static function ajaxSubmit(array &$form, FormStateInterface $form_state) {
- $triggering_element = $form_state->getTriggeringElement();
- $element = NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -1));
- $element_state = self::getElementState($element['#parents'], $form_state);
- self::setElementState($element['#parents'], $form_state, $element_state);
- $form_state->setRebuild();
}
/**
@@ -417,56 +138,10 @@
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
+ public static function submitForm(array &$element, FormStateInterface $form_state) {
+ $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
+ $form_display->extractFormValues($element['#profile'], $element, $form_state);
+ $element['#profile']->save();
- public static function submitForm(array &$element, FormStateInterface $form_state) {}
-
- /**
- * Gets the element state.
- *
- * @param array $parents
- * The element parents.
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- *
- * @return array
- * The element state.
- */
- public static function getElementState(array $parents, FormStateInterface $form_state) {
- $parents = array_merge(['element_state', '#parents'], $parents);
- $element_state = (array) NestedArray::getValue($form_state->getStorage(), $parents);
- $element_state['mode'] = self::getElementMode($form_state);
- return $element_state;
- }
-
- /**
- * Get the element mode.
- *
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- *
- * @return string
- * The element mode.
- */
- public static function getElementMode(FormStateInterface $form_state) {
- $triggering_element = $form_state->getTriggeringElement();
- if (!empty($triggering_element['#element_mode'])) {
- $form_state->set('element_mode', $triggering_element['#element_mode']);
- }
- return $form_state->get('element_mode') ?: 'view';
- }
-
- /**
- * Sets the element state.
- *
- * @param array $parents
- * The element parents.
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- * @param array $element_state
- * The element state.
- */
- public static function setElementState(array $parents, FormStateInterface $form_state, array $element_state) {
- $parents = array_merge(['element_state', '#parents'], $parents);
- NestedArray::setValue($form_state->getStorage(), $parents, $element_state);
}
}
unchanged:
--- a/modules/order/src/Element/ProfileSelect.php
+++ b/modules/order/src/Element/ProfileSelect.php
@@ -3,9 +3,12 @@
namespace Drupal\commerce_order\Element;
use Drupal\commerce\Element\CommerceElementTrait;
+use Drupal\Component\Utility\Html;
+use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\RenderElement;
+use Drupal\Core\Url;
use Drupal\profile\Entity\ProfileInterface;
/**
@@ -15,7 +18,9 @@
* @code
* $form['billing_profile'] = [
* '#type' => 'commerce_profile_select',
- * '#default_value' => $profile,
+ * '#profile' => $profile,
+ * '#profile_type' => 'customer',
+ * '#profile_uid' => \Drupal::currentUser()->id(),
* '#default_country' => 'FR',
* '#available_countries' => ['US', 'FR'],
* ];
@@ -24,6 +29,10 @@
* $form['billing_profile']['#profile']. Due to Drupal core limitations the
* profile can't be accessed via $form_state->getValue('billing_profile').
*
+ * Note:
+ * This element always behaves as required. For optional behavior add
+ * a checkbox above the element that hides it on #ajax.
+ *
* @RenderElement("commerce_profile_select")
*/
class ProfileSelect extends RenderElement {
@@ -36,20 +45,29 @@ class ProfileSelect extends RenderElement {
public function getInfo() {
$class = get_class($this);
return [
+ '#tree' => TRUE,
+ '#title' => t('Select a profile'),
+ // The element doesn't use #default_value / #value. Use #profile instead.
+ '#default_value' => NULL,
+ // The preselected profile. A profile entity, or NULL.
+ '#profile' => NULL,
+ // Needed for creating new profiles, since #profile is not always given.
+ '#profile_type' => NULL,
+ '#profile_uid' => 0,
+ // Whether profiles should always be loaded in the latest revision.
+ // Disable when editing historical data, such as placed orders.
+ '#profile_latest_revision' => TRUE,
// The country to select if the address widget doesn't have a default.
'#default_country' => NULL,
// A list of country codes. If empty, all countries will be available.
'#available_countries' => [],
- // The profile entity operated on. Required.
- '#default_value' => NULL,
'#process' => [
[$class, 'attachElementSubmit'],
- [$class, 'processForm'],
+ [$class, 'processElement'],
],
'#element_validate' => [
[$class, 'validateElementSubmit'],
- [$class, 'validateForm'],
],
'#commerce_element_submit' => [
[$class, 'submitForm'],
@@ -59,28 +77,23 @@ public function getInfo() {
}
/**
- * Builds the element form.
+ * Validates the element properties.
*
* @param array $element
- * The form element being processed.
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- * @param array $complete_form
- * The complete form structure.
+ * The form element.
*
* @throws \InvalidArgumentException
- * Thrown when #default_value is empty or not an entity, or when
- * #available_countries is not an array of country codes.
- *
- * @return array
- * The processed form element.
+ * Thrown if an element property is invalid, or empty but required.
*/
- public static function processForm(array $element, FormStateInterface $form_state, array &$complete_form) {
- if (empty($element['#default_value'])) {
- throw new \InvalidArgumentException('The commerce_profile_select element requires the #default_value property.');
+ public static function validateElementProperties(array $element) {
+ if (empty($element['#profile_type'])) {
+ throw new \InvalidArgumentException('The commerce_profile_select #profile_type property must be provided.');
}
- elseif (isset($element['#default_value']) && !($element['#default_value'] instanceof ProfileInterface)) {
- throw new \InvalidArgumentException('The commerce_profile_select #default_value property must be a profile entity.');
+ if (isset($element['#profile']) && !($element['#profile'] instanceof ProfileInterface)) {
+ throw new \InvalidArgumentException('The commerce_profile_select #profile property must be a profile entity.');
+ }
+ if (!empty($element['#profile_uid']) && !is_numeric($element['#profile_uid'])) {
+ throw new \InvalidArgumentException('The commerce_profile_select #profile_uid property must be a numeric entity ID.');
}
if (!is_array($element['#available_countries'])) {
throw new \InvalidArgumentException('The commerce_profile_select #available_countries property must be an array.');
@@ -91,46 +104,131 @@ public static function processForm(array $element, FormStateInterface $form_stat
$element['#default_country'] = NULL;
}
}
+ }
- $element['#profile'] = $element['#default_value'];
- $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
- $form_display->buildForm($element['#profile'], $element, $form_state);
- if (!empty($element['address']['widget'][0])) {
- $widget_element = &$element['address']['widget'][0];
- // Remove the details wrapper from the address widget.
- $widget_element['#type'] = 'container';
- // Provide a default country.
- if (!empty($element['#default_country']) && empty($widget_element['address']['#default_value']['country_code'])) {
- $widget_element['address']['#default_value']['country_code'] = $element['#default_country'];
- }
- // Limit the available countries.
- if (!empty($element['#available_countries'])) {
- $widget_element['address']['#available_countries'] = $element['#available_countries'];
+ /**
+ * Builds the element form.
+ *
+ * @param array $element
+ * The form element being processed.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ * The current state of the form.
+ * @param array $complete_form
+ * The complete form structure.
+ *
+ * @return array
+ * The processed form element.
+ */
+ public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {
+ self::validateElementProperties($element);
+ $element_state = self::getElementState($element['#parents'], $form_state);
+ // If the provided profile is in a previous revision, make sure it stays
+ // available as an option when $element['#profile'] gets changed.
+ if (empty($element['#profile_latest_revision']) && empty($element_state['fixed_option'])) {
+ if (!empty($element['#profile']) && !$element['#profile']->isDefaultRevision()) {
+ $element_state['fixed_option'] = [
+ 'id' => self::buildOptionId($element['#profile'], $element['#profile_latest_revision']),
+ 'label' => $element['#profile']->label() . ' ' . t('(Original)'),
+ ];
}
}
-
+ /** @var \Drupal\profile\ProfileStorageInterface $profile_storage */
+ $profile_storage = \Drupal::entityTypeManager()->getStorage('profile');
+ $user_storage = \Drupal::entityTypeManager()->getStorage('user');
+ $user = $element['#profile_uid'] ? $user_storage->load($element['#profile_uid']) : NULL;
+ $profiles = [];
+ if ($user) {
+ $profiles = $profile_storage->loadMultipleByUser($user, $element['#profile_type'], TRUE);
+ }
+ $profile_options = [];
+ foreach ($profiles as $profile) {
+ $option_id = self::buildOptionId($profile, $element['#profile_latest_revision']);
+ $profile_options[$option_id] = $profile->label();
+ }
+ $user_input = $form_state->getUserInput();
+ $selected_option = NestedArray::getValue($user_input, array_merge($element['#parents'], ['profile_selection']));
+ if (!empty($selected_option)) {
+ // Keep the last selection in element state, so that the element knows
+ // where to return the customer upon cancelling form mode.
+ $element_state['selected_option'] = $selected_option;
+ }
+ elseif (!empty($element_state['selected_option'])) {
+ $selected_option = $element_state['selected_option'];
+ }
+ elseif ($default_profile = self::selectDefaultProfile($element, $profiles)) {
+ $selected_option = self::buildOptionId($default_profile, $element['#profile_latest_revision']);
+ }
+ $id_parts = explode('-', $selected_option);
+ if (!empty($id_parts[1])) {
+ $element['#profile'] = $profile_storage->loadRevision($id_parts[1]);
+ }
+ elseif (!empty($id_parts[0])) {
+ $element['#profile'] = $profile_storage->load($id_parts[0]);
+ }
+ else {
+ $element['#profile'] = $profile_storage->create([
+ 'type' => $element['#profile_type'],
+ 'uid' => $element['#profile_uid'],
+ ]);
+ }
+ $id_prefix = implode('-', $element['#parents']);
+ $wrapper_id = Html::getUniqueId("$id_prefix-ajax-wrapper");
+ // Pass the id along to other methods.
+ $element['#wrapper_id'] = $wrapper_id;
+ $view_builder = \Drupal::entityTypeManager()->getViewBuilder('profile');
+ $element['profile_selection'] = [
+ '#prefix' => "",
+ '#type' => 'select',
+ '#title' => $element['#title'],
+ '#options' => $profile_options,
+ '#default_value' => $selected_option,
+ '#ajax' => [
+ 'callback' => [get_called_class(), 'ajaxRefresh'],
+ 'wrapper' => $wrapper_id,
+ ],
+ '#limit_validation_errors' => [],
+ '#weight' => -1,
+ '#access' => !empty($profile_options),
+ ];
+ $element['profile'] = $view_builder->view($element['#profile'], 'default');
+ $element['profile']['#suffix'] = '
';
+ $url = Url::fromRoute('entity.profile.type.user_profile_form.add', ['user' => $element['#profile']->getOwnerId(), 'profile_type' => 'customer']);
+ $url->mergeOptions(['query' => \Drupal::destination()->getAsArray()]);
+ $element['new'] = [
+ '#type' => 'link',
+ '#url' => $url,
+ '#title' => t('Add new profile'),
+ '#attributes' => [
+ 'class' => ['use-ajax'],
+ 'data-dialog-type' => 'modal',
+ 'data-dialog-options' => json_encode([
+ 'width' => 700,
+ ]),
+ ],
+ ];
+ if (!$element['#profile']->isNew()) {
+ $url = Url::fromRoute('entity.profile.edit_form', ['profile' => $element['#profile']->id()]);
+ $url->mergeOptions(['query' => \Drupal::destination()->getAsArray()]);
+ $element['edit'] = [
+ '#type' => 'link',
+ '#url' => $url,
+ '#title' => t('Edit profile'),
+ '#attributes' => [
+ 'class' => ['use-ajax'],
+ 'data-dialog-type' => 'modal',
+ 'data-dialog-options' => json_encode([
+ 'width' => 700,
+ ]),
+ ],
+ ];
+ }
+ $element['#attached']['library'][] = 'core/drupal.dialog.ajax';
+ // Persist any changes made to $element_state.
+ self::setElementState($element['#parents'], $form_state, $element_state);
return $element;
}
/**
- * Validates the element form.
- *
- * @param array $element
- * The form element.
- * @param \Drupal\Core\Form\FormStateInterface $form_state
- * The current state of the form.
- *
- * @throws \Exception
- * Thrown if button-level #validate handlers are detected on the parent
- * form, as a protection against buggy behavior.
- */
- public static function validateForm(array &$element, FormStateInterface $form_state) {
- $form_display = EntityFormDisplay::collectRenderDisplay($element['#profile'], 'default');
- $form_display->extractFormValues($element['#profile'], $element, $form_state);
- $form_display->validateFormValues($element['#profile'], $element, $form_state);
- }
-
- /**
* Submits the element form.
*
* @param array $element
@@ -144,4 +242,95 @@ public static function submitForm(array &$element, FormStateInterface $form_stat
$element['#profile']->save();
}
+ /**
+ * Ajax callback.
+ */
+ public static function ajaxRefresh(array &$form, FormStateInterface $form_state) {
+ $triggering_element = $form_state->getTriggeringElement();
+ $element = NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -1));
+ return [
+ 'profile_selection' => $element['profile_selection'],
+ 'profile' => $element['profile'],
+ ];
+ }
+
+ /**
+ * Builds the option ID for the given profile.
+ *
+ * @param \Drupal\profile\Entity\ProfileInterface $profile
+ * The profile.
+ * @param bool $use_latest_revision
+ * (optional) Use the latest revision, defaults to TRUE.
+ *
+ * @return string
+ * The option ID.
+ */
+ public static function buildOptionId(ProfileInterface $profile, $use_latest_revision = TRUE) {
+ $option_id = $profile->id();
+ if (!$use_latest_revision) {
+ $option_id .= '-' . $profile->getRevisionId();
+ }
+ return $option_id;
+ }
+
+ /**
+ * Selects the default profile for the given element.
+ *
+ * @param array $element
+ * The element.
+ * @param array $profiles
+ * The available profiles.
+ *
+ * @return \Drupal\profile\Entity\ProfileInterface|null
+ * The default profile, or NULL if none found.
+ */
+ public static function selectDefaultProfile(array $element, array $profiles) {
+ $default_profile = NULL;
+ if (!empty($element['#profile'])) {
+ $default_profile = $element['#profile'];
+ }
+ elseif (!empty($profiles)) {
+ $default_profile = reset($profiles);
+ foreach ($profiles as $profile) {
+ if ($profile->isDefault()) {
+ $default_profile = $profile;
+ break;
+ }
+ }
+ }
+ return $default_profile;
+ }
+
+ /**
+ * Sets the element state.
+ *
+ * @param array $parents
+ * The element parents.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ * The current state of the form.
+ * @param array $element_state
+ * The element state.
+ */
+ public static function setElementState(array $parents, FormStateInterface $form_state, array $element_state) {
+ $parents = array_merge(['element_state', '#parents'], $parents);
+ NestedArray::setValue($form_state->getStorage(), $parents, $element_state);
+ }
+
+ /**
+ * Gets the element state.
+ *
+ * @param array $parents
+ * The element parents.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ * The current state of the form.
+ *
+ * @return array
+ * The element state.
+ */
+ public static function getElementState(array $parents, FormStateInterface $form_state) {
+ $parents = array_merge(['element_state', '#parents'], $parents);
+ $element_state = (array) NestedArray::getValue($form_state->getStorage(), $parents);
+ return $element_state;
+ }
+
}
diff -u b/modules/order/src/Plugin/Field/FieldWidget/BillingProfileWidget.php b/modules/order/src/Plugin/Field/FieldWidget/BillingProfileWidget.php
--- b/modules/order/src/Plugin/Field/FieldWidget/BillingProfileWidget.php
+++ b/modules/order/src/Plugin/Field/FieldWidget/BillingProfileWidget.php
@@ -33,7 +33,6 @@
$element['profile'] = [
'#type' => 'commerce_profile_select',
'#title' => $this->t('Select an address'),
- '#create_title' => $this->t('+ Enter a new address'),
'#profile' => $items[$delta]->entity,
'#profile_type' => 'customer',
'#profile_uid' => $order->getCustomerId(),
diff -u b/modules/order/tests/src/FunctionalJavascript/ProfileSelectTest.php b/modules/order/tests/src/FunctionalJavascript/ProfileSelectTest.php
--- b/modules/order/tests/src/FunctionalJavascript/ProfileSelectTest.php
+++ b/modules/order/tests/src/FunctionalJavascript/ProfileSelectTest.php
@@ -92,8 +92,11 @@
$this->drupalLogout();
$this->drupalGet(Url::fromRoute('commerce_order_test.profile_select_form'));
$this->assertSession()->pageTextContains('Profile select test form');
- $this->assertSession()->fieldNotExists('Select a profile');
- $this->getSession()->getPage()->fillField('profile[form][address][0][address][country_code]', $this->address1['country_code']);
+ $this->assertSession()->pageTextContains('Add new profile');
+ $this->assertSession()->pageTextNotContains('Edit profile');
+ $this->clickLink('Add new profile');
+ $this->waitForAjaxToFinish();
+ $this->getSession()->getPage()->fillField('[address][0][address][country_code]', $this->address1['country_code']);
$this->waitForAjaxToFinish();
$edit = [];
diff -u b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php
--- b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php
+++ b/modules/payment/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php
@@ -142,7 +142,6 @@
$pane_form['billing_information'] = [
'#type' => 'commerce_profile_select',
'#title' => $this->t('Select an address'),
- '#create_title' => $this->t('+ Enter a new address'),
'#profile' => $this->order->getBillingProfile(),
'#profile_type' => 'customer',
'#profile_uid' => $this->order->getCustomerId(),
diff -u b/modules/payment/src/PluginForm/PaymentMethodAddForm.php b/modules/payment/src/PluginForm/PaymentMethodAddForm.php
--- b/modules/payment/src/PluginForm/PaymentMethodAddForm.php
+++ b/modules/payment/src/PluginForm/PaymentMethodAddForm.php
@@ -66,7 +66,6 @@
'#parents' => array_merge($form['#parents'], ['billing_information']),
'#type' => 'commerce_profile_select',
'#title' => t('Select an address'),
- '#create_title' => t('+ Enter a new address'),
'#profile_type' => 'customer',
'#profile_uid' => $payment_method->getOwnerId(),
'#default_country' => $store ? $store->getAddress()->getCountryCode() : NULL,