DonationItemPaneBase::submitPaneForm needs to update its internal state to reflect up to date donation order item

Created on 13 October 2021, almost 3 years ago
Updated 1 September 2023, about 1 year ago

Problem/Motivation

When a DonationItemPane is instantiated, it stores the donation item on an internal property. When the pane's form is submittedDonationItemPaneBase::submitPaneForm, that donation item is saved. However, the donation object stored in the pane instance holds all data as it existed when the pane was created. This means that if the donation order item is updated between pane instantiation and form submission, those changes are overridden with the values on the order item as they existed when the pane was instantiated.

Steps to reproduce

Add a custom donation_pane_validate() or donation_pane_submit() as below that updates the price of the donation.

function my_donation_pane_validate(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $route = \Drupal::routeMatch();
  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $route->getParameter('commerce_order');
  foreach ($order->getItems() as $order_item) {
    if ($order_item->get('type')->isEmpty()
      || $order_item->get('type')->target_id !== 'donation') {
      continue;
    }

    $set_unit_price = 300; // Some logic to get your new donation value.
    $price = new \Drupal\commerce_price\Price(
      $set_unit_price,
      $order->getStore()->getDefaultCurrencyCode()
    );

    // These are both needed as the donation amount is
    // used by commerce_donation_flow separately from the unit price
    $order_item->setUnitPrice($price, TRUE);
    $order_item->set('field_donation_amount', $price);
    $order_item->save();
  }
}

If the validation function updated the price from $10 to $300, submitForm reverts the price back to $10 because the original version of the order item, with the old unit price, is being saved.

Proposed resolution

Add a refresher method to ensure that the donationItem prop is current before executing the save. Attaching a patch to achieve this.

πŸ› Bug report
Status

Closed: outdated

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States mrweiner

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024