2

I have a lineItem option that needs validation. It’s actually an input field that can’t be blank, and different to the lineItem’s note.

The docs for Add to Cart mention using onBeforeAddToCart but it also needs to be validated if a customer decides to edit this field in the cart so perhaps commerce_cart.onBeforeAddToCart is not the right event here.

Can anyone offer an example of how to do this? This needs to be server-side validation, not front-end.

5

I've achieved something similar but used commerce_lineItems.onBeforeSaveLineItem.

This event is fired every time a line item is created or edited. Fired on /updateCart (product page) or /updateLineItem (cart page).

You might run into problems because the lineItems in the event won't contain a post request unless its the lineItem that triggered the event through a form.

You need to grab the events line item and check it against the lineItemId in the post request before doing any comparisons - unless its a new lineItem.

// Get the line item being saved from the event
$item = $event->params['lineItem'];

// Is this a new line item?
$isNewLineItem = $event->params['isNewLineItem'];

// Get the line item id that triggered the save from the post request
// (this will only exist if we're updated a line item that currently exists)
$lineItemId = craft()->request->getPost( 'lineItemId' );

// If the current line item being saved is new
// OR
// If its an existing line item and matches the one that triggered the event
if ( $isNewLineItem || $item->id == $lineItemId ) {
  //rest of the code
}

I then looked to see if the option was in the post request.

$text = craft()->request->getPost( 'options.Text' );

If it wasn't I added a flash message and stopped the action.

$event->performAction = false;
craft()->userSession->setFlash( "itemError", "You must add some text before adding this product to your basket" );
1
  • If you run into problems with line items being new/edited check my latest edits Jun 28 '16 at 16:24

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.