Automattic\WooCommerce\Blocks\Domain\Services

CheckoutFieldsFrontend::save_account_form_fields()publicWC 1.0

Validates and saves additional address fields to the customer object on the My Account page.

Customer is not provided by this hook so we handle save here.

Method of the class: CheckoutFieldsFrontend{}

No Hooks.

Return

null. Nothing (null).

Usage

$CheckoutFieldsFrontend = new CheckoutFieldsFrontend();
$CheckoutFieldsFrontend->save_account_form_fields( $user_id );
$user_id(int) (required)
User ID.

CheckoutFieldsFrontend::save_account_form_fields() code WC 9.7.1

public function save_account_form_fields( $user_id ) {
	// phpcs:disable WordPress.Security.NonceVerification.Missing
	$customer          = new WC_Customer( $user_id );
	$additional_fields = $this->checkout_fields_controller->get_fields_for_location( 'contact' );
	$field_values      = array();

	foreach ( array_keys( $additional_fields ) as $key ) {
		$post_key = CheckoutFields::get_group_key( 'other' ) . $key;
		if ( ! isset( $_POST[ $post_key ] ) ) {
			continue;
		}

		$field_value = $this->checkout_fields_controller->sanitize_field( $key, wc_clean( wp_unslash( $_POST[ $post_key ] ) ) );
		$validation  = $this->checkout_fields_controller->validate_field( $key, $field_value );

		if ( is_wp_error( $validation ) && $validation->has_errors() ) {
			wc_add_notice( $validation->get_error_message(), 'error' );
			continue;
		}

		$field_values[ $key ] = $field_value;
	}

	// Persist individual additional fields to customer.
	foreach ( $field_values as $key => $value ) {
		$this->checkout_fields_controller->persist_field_for_customer( $key, $value, $customer, 'other' );
	}

	// Validate all fields for this location.
	$location_validation = $this->checkout_fields_controller->validate_fields_for_location( $field_values, 'contact', 'other' );

	if ( is_wp_error( $location_validation ) && $location_validation->has_errors() ) {
		wc_add_notice( $location_validation->get_error_message(), 'error' );
	}

	// phpcs:enable WordPress.Security.NonceVerification.Missing
	$customer->save();
}