Like this:
Color
Red
Size
Medium
Price
$ 49,00
Add to cart
I tried:
- changing the field order in the product type and product variation type settings
- overriding commerce-product.html.twig
- adding some jQuery / Javascript code
- positioning the price div using CSS
- using hook_form_BASE_FORM_ID_alter() to alter the form
Solution #1 did not work out because the variation fields (color and size in this example) and the add-to-cart-button appear to be packed together as "Variations" in the product type settings.
Solution #2 has the same issue. The variation fields and add-to-cart-button are packed together in "product.variations" as one placeholder. I am not able to decompose it into seperate fields.
For solution #3 i tried moving the price div to the right location using jQuery, like this:
$("article .field--type-commerce-price").insertBefore(".commerce-order-item-add-to-cart-form .form-actions");
At first glance this works. However when the user starts changing variation fields the containing form gets removed along with the price. Commerce regenerates this form in order to update all the variation fields.
So far #4 gave the best results. I posted it on https://drupal.stackexchange.com/questions/248004/commerce-2-display-pri... but it is hacky. Using a top margin i created some space above the add-to-cart-button. Then i position the price div into that space. The CSS-code looks like this:
.commerce-order-item-add-to-cart-form .form-actions {
margin-top: 4em;
}
article .field--type-commerce-price {
position: absolute;
bottom: 2.5em;
}
For solution #5 i was able to insert custom text before the add-to-cart-button which looks promising:
function HOOK_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['test'] = array(
'#markup' => 'Here is where the price should go.',
'#weight' => 99
);
}
But then i cannot figure out how to obtain the actual price from there. Then i found a D7 solution at:
https://drupal.stackexchange.com/questions/105946/drupal-commerce-add-to...
It looks like this:
function mytheme_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
$product = $form_state['default_product'];
$view_mode = $form_state['context']['view_mode'];
$form['price'] = field_view_field('commerce_product', $product, 'commerce_price', $view_mode);
}
But i am not able to produce a D8 equivalent for this, in particular the last line.
function mytheme_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$product = $form_state->get('product'));
$view_mode = $form_state->get('form_display')->getMode();
// form['price'] = $product->get(???)
}
This is silly. I'm struggling for weeks now to get this working but I am getting nowhere. Does anyone have a better idea?