Search code examples
wordpressforeachundefinedrepeaterelementor

Elementor REPEATER Control with GALLERY Control inside, output undefined and foreach() warnings


I am currently developing an elementor widget and I have the following problem: I'd like to have a GALLERY Control inside a REPEATER Control as in the following image: my widget

Here's the code I have for blocks of fields in my widget:

$this->add_control(
    'my_list',
    [
        'label' => esc_html__( 'My List', 'texdomain' ),
        'type' => \Elementor\Controls_Manager::REPEATER,
        'fields' => [
            [
                'name' => 'list_title',
                'label' => esc_html__( 'Name #1', 'texdomain' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__( 'Name #1' , 'texdomain' ),
                'label_block' => true,
            ],

            [
                'name' => 'add_image',
                'label' => esc_html__( 'Add Images', 'texdomain' ),
                'type' => \Elementor\Controls_Manager::GALLERY,
                'label_block' => true,
                'default' => [],
            ],

        ],
        'default' => [
            [
                'list_title' => esc_html__( 'Title #1', 'texdomain' ),
                'add_image' => [],
            ],
        ],
        'title_field' => '{{{ list_title }}}',
    ]
);

And here's my render code:

if ( $settings['my_list'] ) {
    foreach ( $settings['my_list'] as $item ){
    
        echo '<div class="title">' . $item['list_title'] . '</div>';                                

        foreach ( $settings['add_image'] as $image) {
            echo '<img src="' . esc_attr( $image['url'] ) . '">';
        }

    } 

}

However, the output shows the following warnings:

Undefined array key "add_image"...

Foreach() argument must be of type array|object, null given...

Here are some reference links:

Repeater Control

Gallery Control

Any help will be greatly appreciated.


Solution

  • I managed to make things work. Since we have a foreach in foreach, I replaced settings with item in the code like this:

    if ( $settings['my_list'] ) {
        foreach ( $settings['my_list'] as $item ){
        
            echo '<div class="title">' . $item['list_title'] . '</div>';                                
    
            foreach ( $item['add_image'] as $image) {
                echo '<img src="' . esc_attr( $image['url'] ) . '">';
            }
    
        } 
    
    }