Home › Forums › Add-ons › Repeater Field › Hide empty repeater rows
Hi,
I got a Repeater field for adding files. I also made a div to show this.
When there is no files i want to hide it.
My problem is when a row is added to the repeater field but no file is attached the code i made doesn’t hide the div, it only hides it if there are no rows added to the repeater field.
Is there a way to see if the row is empty and hide my div?
Here’s my code so far:
<?php
if (get_field('repeater_field')):
if( have_rows('repeater_field') ): ?>
<div>
<h3>Title</h3>
</div>
<div class="box-atachment">
<?php
while ( have_rows('repeater_field') ) : the_row();
$atachment = get_sub_field('repeater_files');
$title = $atachment["title"];
$url = $atachment["url"];
if( $atachment ) { ?>
<a href="<?php echo $url_anexo; ?>"><?php echo $nome_anexo; ?></a><br>
<hr>
<?php
}
endwhile;
endif;
?>
</div>
<?php
endif;
?>
Thanks
There isn’t an easy way to accomplish what you’re doing.
One easy solution would be to make the field field required. This would prevent the user from adding a row without selecting a file.
The other option would be to loop through the repeater and store the values in an array and then loop over the array to create your output.
<?php
$files = array();
if (have_rows('repeater_field')) {
while (have_rows('repeater_field')) {
the_row();
if (get_sub_field('repeater_files')) {
$atachment = get_sub_field('repeater_files');
$title = $atachment["title"];
$url = $atachment["url"];
$files[] = '<a href="'.$url.'">'.$title.'</a>';
} // end if get_sub_field
} // end while have_rows
} // end if have_rows
// see if there is anything in files
if (!empty($files)) {
?>
<div><h3>Title</h3></div>
<div class="box-atachment">
<?php
foreach ($files as $file) {
echo $file,'<br /><hr />';
}
?>
</div>
<?php
} // end if files !empty
?>
Hi, Thanks!
Your code worked fine. In my case making the field required wouldn’t work beacuse its optional.
The topic ‘Hide empty repeater rows’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.