Fix single product page extra fields in array format

This commit is contained in:
Pedro Silva 2023-08-11 16:09:11 +01:00
parent 75bbdb6635
commit 53bf234a4c
No known key found for this signature in database
GPG key ID: E2EE20C0669D24B3
2 changed files with 29 additions and 10 deletions

View file

@ -5,31 +5,46 @@
export default class FormHelper {
static getPrefixedFields(formElement, prefix) {
const formData = new FormData(formElement);
let fields = {};
for(const element of formElement.elements) {
if( ( ! prefix ) || element.name.startsWith(prefix) ) {
fields[element.name] = element.value;
for (const [name, value] of formData.entries()) {
if (!prefix || name.startsWith(prefix)) {
fields[name] = value;
}
}
return fields;
}
static getFilteredFields(formElement, exactFilters, prefixFilters) {
const formData = new FormData(formElement);
let fields = {};
let counters = {};
for(const element of formElement.elements) {
if (!element.name) {
for (let [name, value] of formData.entries()) {
// Handle array format
if (name.indexOf('[]') !== -1) {
const k = name;
counters[k] = counters[k] || 0;
name = name.replace('[]', `[${counters[k]}]`);
counters[k]++;
}
if (!name) {
continue;
}
if (exactFilters && (exactFilters.indexOf(element.name) !== -1)) {
if (exactFilters && (exactFilters.indexOf(name) !== -1)) {
continue;
}
if (prefixFilters && prefixFilters.some(prefixFilter => element.name.startsWith(prefixFilter))) {
if (prefixFilters && prefixFilters.some(prefixFilter => name.startsWith(prefixFilter))) {
continue;
}
fields[element.name] = element.value;
fields[name] = value;
}
return fields;
}
}

View file

@ -115,7 +115,11 @@ abstract class AbstractCartEndpoint implements EndpointInterface {
// Add extras to POST, they are usually added by custom plugins.
if ( $product['extra'] && is_array( $product['extra'] ) ) {
foreach ( $product['extra'] as $key => $value ) {
// Handle cases like field[]
$query = http_build_query( $product['extra'] );
parse_str( $query, $extra );
foreach ( $extra as $key => $value ) {
$_POST[ $key ] = $value;
}
}