1

I have a field that allows a user to select multiple products and save them to the database for a plugin, but when I try to retrieve these values and have them selected in my form I get the error

Call to a member function getUiLabel() on array

Here is my field

{{ forms.elementSelectField({
    label: "Products Allowed",
    instructions: "Leave blank if this voucher has no product limits",
    id: 'products',
    name: 'products',
    elementType: productElementType,
    selectionLabel: "Add Products"),
    elements: (products is defined and products ? [products])
}) }}

The first question is, how do I store these values? Do I store it as it comes back? In an array, or do I encode that array to JSON? I've done both and both ways give the same error at retrieval.

Here is my retrieval code

$products = JSON::decode($variables['voucher']->products);


$variables['products'] = [];
foreach($products as $productId)
{
    $product = Commerce::getInstance()->getProducts()->getProductById($productId);
    ArrayHelper::append($variables['products'], $product);
}

As mentioned before, I've also just tried saving the products array without encoding to JSON and applying the saved results directing to $variables['products'] with the same results.

1

Well, I figured it out to an extent, I'm not sure why this works and I have a feeling it will break eventually, but here is my solution. Please let me know if there is a better one out there or something that is standard practice.

{{ forms.elementSelectField({
        label: "Products Allowed"|t('business-to-business'),
        instructions: "Leave blank if this voucher has no product limits",
        id: 'products',
        name: 'products',
        elementType: productElementType,
        selectionLabel: "Add Products"|t('business-to-business'),
        elements: (products is defined and products ? [products][0])
}) }}
| improve this answer | |

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.