Score:0

Set minimum commerce product price

cn flag

I want to set a minimum price that can be entered in the product add/edit form of Commerce. If users enter a lower price, an error should be displayed, when they click on the save button.

I am using the following code to achieve that.

function THEME_form_commerce_product_default_add_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#validate'][] = '_custom_formvalidation_number_price_validate';
}
    
function _custom_formvalidation_number_price_validate(&$form, FormStateInterface $form_state) {
  if ($form['variations']['widget']['entity']['price']['widget'][0]['#default_value'] = ['number' => 2,'currency_code' => 'EUR'] > 2) {
    $form_state->setErrorByName('price', t('The price must be at least 2'));
  }
}

I need to check the entered value, not the default value. Which element is that exactly?

griz avatar
jp flag
You should write a simple module containing your custom validation function. The module should also contain a 'hook_form_alter' function that targets your form, and adds a reference to your validation function to form's the '#validate' array. https://drupal.stackexchange.com/questions/183685/how-do-i-add-a-custom-validation-handler-to-an-existing-form-field https://www.drupal.org/forum/support/module-development-and-code-questions/2017-02-11/form-custom-validation-after-hook
cn flag
This is very helpful but I still can't set a minimum price value.
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.