1

I have the following fields in a component:

<fieldset name="carousel_container">
    <field name="carousel" type="Repeatable" icon="list" description="" label="Carousel" default="">
        <fields name="params">
            <fieldset hidden="true" name="list_templates_modal" repeat="true">
                <field name="carouselimage" type="media" directory="" />
                <field name="carouselcaption" type="text" label="Caption" filter="raw" class="inputbox"  />
            </fieldset>
        </fields>
    </field>
</fieldset>

This then saves JSON to the database as follows:

{
    "carouselimage":
        ["images/1060333.jpg","images/2012861.jpg","images/2024459.jpg"],
    "carouselcaption":
        ["This is a caption","Another caption","and another on"]
}

I then get the repeatable field value and decode it:

$carousel_images = json_decode($this->item->carousel,true);

Then do the following:

// loop the result
foreach($carousel_images as $ca) {
    $image = $ca['carouselimage'];
    $caption = $ca['carouselcaption'];
       // do something clever for each of the images
       '<img src="' . $image .'"/><p>' . $caption . '</p>';
}

?>

But the variables aren't being called. I'm getting an error:

Notice: Undefined index: carouselimage
Notice: Undefined index: carouselcaption

How can I cycle through the foreach loop and separate the image and the caption for adding to the carousel?

2

It's how Repeatable field stores its data. Pick a field to iterate over and use its key to access value of another field:

foreach ($carousel_images['carouselimage'] as $key => $image)
{
    // do something clever for each of the images
    '<img src="' . $image .'"><p>' . $carousel_images['carouselcaption'][$key] . '</p>';
}

Or use array_combine() to build a normal associative array:

$carousel_images = array_combine($carousel_images['carouselimage'], $carousel_images['carouselcaption']);

// loop the result
foreach($carousel_images as $image => $caption)
{
       // do something clever for each of the images
       '<img src="' . $image .'"><p>' . $caption . '</p>';
}

If you are developing a new component, you should consider using Subform field instead which stores data differently. Repeatable field is deprecated and will be removed in J4.

Also, if you want semantic markup, you should use figure element with figcaption to define an image with a caption.

// do something clever for each of the images
'<figure><img src="' . $image .'"><figcaption>' . $carousel_images['carouselcaption'][$key] . '</figcaption></figure>';

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.