0

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?

1 Answer 1

0

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);
...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.