I need to create validation for dynamically created fields on the checkout page.
class Myclass ()
{
private $_active_fields;
public function generate_fields () {
/**
/* Some previous logic to create an $items array based on products in the cart.
*/
$items = array(
"question-7" => array(
"option 1-1",
"option 1-2",
),
"question-4" => array(
"option 2-1",
"option 2-2",
),
);
foreach( $items as $key => $val ) {
woocommerce_form_field('box_field-'.$key, array(
'type' => 'radio',
'options' => $val,
....
),
$checkout->get_value( 'box_field-'.$key ));
$this->_active_fields[] = 'box_field-'.$key;
}
var_dump($this->_active_fields) // lists correctly all added items
}
public function add_fields () {
add_action( 'woocommerce_after_order_notes', array( $this, 'generate_fields' ) );
}
public function generate_validation () {
$fields = $this->_active_fields;
var_dump($fields); // Empty array
foreach ( $fields as $key => $val ) {
if ( ! $_POST[$val] {
wc_add_notice( 'Please fill field'.$val, 'error' );
}
}
}
public function add_validation() {
add_action( 'woocommerce_checkout_process', array( $this, 'generate_validation' ) );
}
}
So I run the following code
$form = new Myclass();
$form->add_fields();
$form->add_validation();
When I try to access the $_active_fields
property within the generate_valiadation()
method, it is empty. However if I call var_dump($this->_active_fields)
at the end of generate_fields()
method, it is listing all generated field keys correctly.
So I guess I'm doing something wrong. Any ideas on how to set $_active_fields
inside generate_fields()
and get it's values in generate_valiadation()
?