woocommerce/plugins/woocommerce-blocks/docs/examples/validate-cart.md

13 lines
411 B
Markdown
Raw Normal View History

Store API: Refactored validation handling and introduced `woocommerce_store_api_cart_errors` hook (https://github.com/woocommerce/woocommerce-blocks/pull/5904) * Introduce 'wooocommerce_store_api_validate_cart' action This action can be used by third party developers to add extra 'errors' in cart route responses. This is meant to function as a replacement of the legacy 'woocommerce_check_cart_items' hook. * Introduce a new 'wooocommerce_blocks_draft_order_updated' action The new action can be used to modify the finalized draft order object. Additionally, developers can use it to throw a RouteException in order to prevent access to the checkout block. The PR also shuffles some existing code that checks the order instance and sets the draft order ID before the 'woocommerce_blocks_checkout_update_order_meta' gets fired. * Fix PHPCS * Revert changes to Checkout route * Add some extra content to the 'woocommerce_blocks_checkout_update_order_meta' docblock on the effect of exceptions thrown from callbacks * Add __experimental prefix to 'wooocommerce_store_api_validate_cart' action * Remove long ooo * Add example * Refactor cart error getters as wrappers to the validate functions * Refactor stock_exceptions_to_wp_errors to return a single wp error. * Add type hint in custom exception * Fix namespace versioning and some minor improvements * Move InvalidCartException catcher from AbstractCartRoute to AbstractRoute * Introduce the __experimental_woocommerce_store_api_cart_errors filter * Handle all notices and group them into a single WP_Error instance * Cleanup doc and update example * Cleanup NoticeHandler * Fix doc * Fix WP_Error namespace * Update NoticeHandler unit tests * Fix Unit tests typo * Add docs to tests to bypass precommit scripts * Refactor wp error grouping with merge_from * Remove previous cart getters and refactor the get_cart_errors * Fix CartSchema error getter and minor fixes * Revert NoticeHandler exception namespace * Unit test fix for get_cart_errors * Switch back to do_action * Update the example doc * Duplicate use statement * Update docblock in validate_cart() method for validation hooks * Update action docs * Remove __experimental prefix Co-authored-by: Manos Psychogyiopoulos <psyx@somewherewarm.com> Co-authored-by: Mike Jolley <mike.jolley@me.com>
2022-03-02 12:21:31 +00:00
```php
// The action callback function.
function my_function_callback( $errors, $cart ) {
// Validate the $cart object and add errors. For example, to create an error if the cart contains more than 10 items:
if ( $cart->get_cart_contents_count() > 10 ) {
$errors->add( 'my_error_code', 'Too many cart items!' );
}
}
add_action( 'woocommerce_store_api_cart_errors', 'my_function_callback', 10 );
```