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.
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.
Add a refresher method to ensure that the donationItem prop is current before executing the save. Attaching a patch to achieve this.
Closed: outdated
1.0
Code
Not all content is available!
It's likely this issue predates Contrib.social: some issue and comment data are missing.