Support

Account

Home Forums General Issues Check if subfield of repeater has any value, before the_row

Solved

Check if subfield of repeater has any value, before the_row

  • I want to hide the date, hours and rate table heading columns if the subfield has no value entered, but I’m having a lot of trouble doing it.

    I think what I need to do is somehow check if any of the repeater rows contain a value, but do this before the the_row begins.

    <?php if(have_rows('items')): ?>
    
    <?php $count = 1;( get_field('items') ); ?>
    
    <table class="count<?php echo $count; ?>">
    		
    		<thead>
    			<tr>
    				<th class="description">Description</th>
    				<th class="date">Date</th>
    				<th class="number-of-hours">Hrs</th>
    				<th class="hourly-rate">Rate</th>
    				<th class="cost">Cost</th>
    			</tr>
    		</thead>
    
    		<tbody>
    			
    		<?php while(have_rows('items')): the_row(); ?>
    
    			<tr>
    				<td class="description">
    					<?php the_sub_field('description'); ?>
    				</td>
    				<?php if( get_sub_field('date') ): ?>
    				<td class="date">
    					<?php the_sub_field('date'); ?>
    				</td>
    				<?php endif; ?>
    				<?php if( get_sub_field('cost_type') == 'hourly'): ?>
    				<td class="number-of-hours"><?php the_sub_field('hours'); ?></td>
    				<td class="hourly-rate">$<?php the_sub_field('rate'); ?></td>
    				<?php endif; ?>
    				<td class="cost">$<span id="jobcost<?php echo $count; ?>"></span></td>
    			</tr>	
    		
    		<?php $count++; endwhile; ?>
    	
    		</tbody>
    
    		<tfoot>
    			<tr class="total">
    				<td>Total: <span id="total"></span></td>	
    			</tr>
    		</tfoot>
    					
    </table>
    
    <?php endif; ?>
  • This is where output buffers come in handy, https://www.php.net/manual/en/book.outcontrol.php. I won’t repeat your entire code here, just the basics.

    
    <?php 
      // only send output if there is content
      $has_content = false; // a flag to output content
      ob_start(); // start output buffering
    ?>
    <p>this content will be buffered and only output if the repeater has values.</p>
    <?php 
      if (have_rows('repeater field')) {
        while (have_rows('repeater field')) {
          the_row();
          if (get_sub_field('sub field name')) {
            // row has content
            // output the sub field
            the_sub_field('sub field name');
            // set flag to output content
            $has_content = true;
          }
        }
      }
      
      // get the content of the buffer and clear it
      $content = ob_get_clean();
      // if the flag was set then output the content
      if ($has_content) {
        echo $content;
      }
    
    
  • Thanks! That has helped a lot, although the way I implemented it is probably all wrong, but the end result is that it works.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.