Score:0

How can I alter an order item field depending on inline entity form (IEF) validation?

fr flag

I extended my order item type with an additional boolean field. Before the order item gets submitted via "order edit form" (/admin/commerce/orders/{order_id}/edit), it should be validated and the boolean field should become "true" or remain "false".

The "order edit form" contains multiple inline entity forms (IEF). One of the IEF handles the order items of the order. I add a custom validation function with my custom module first:

function MYMODULE_inline_entity_form_entity_form_alter(array &$entity_form, FormStateInterface &$form_state)
{
...
array_unshift($entity_form['#element_validate'],'MYMODULE_inline_entity_form_validate_hide_gross_price');
...
}

The custom validation function is invoked successfully and the general business/process logic of the custom validation function is working fine too.

The problem is, that I haven't found a way to set the value of my boolean field inside my order-item-type yet, depending on IEF validation. I tried it with the $form_state->setValueForElement() API function (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormStateInterface.php/function/FormStateInterface%3A%3AsetValueForElement/9.3.x):

function MYMODULE_inline_entity_form_validate_hide_gross_price(array &$entity_form, FormStateInterface $form_state) {
...
$form_state->setValueForElement($entity_form["field_MYFIELD_hide_gross_price"]["widget"]["value"],["#value"=> true]);
...
}

I get an error message

This value should be of the correct primitive type. Drupal\Core\TypedData\Plugin\DataType\BooleanData: value

If I modify the code like following:

$form_state->setValueForElement($entity_form["field_MYFIELD_hide_gross_price"]["widget"]["value"]["#value"], true);

I get an PHP error in the watchdog logs:

TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setValueForElement() must be of the type array, int given

So what is the correct syntax to set a boolean field value inside an order-item-type with IEF form?

Score:0
fr flag

I got the hint, that I used the wrong array elements. So it worked for me:

function MYMODULE_inline_entity_form_validate_hide_gross_price(array &$entity_form, FormStateInterface $form_state) {
...
$form_state->setValueForElement($entity_form["field_MYFIELD_hide_gross_price"]["widget"]["value"], true);
...
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.