How to insert an else to display message in case there are no files to upload

2

Code

<?php
$files = $obj->field('upload');

foreach ($files as $file)
  {
    $file_url = get_attached_file($file['id']);
    echo '<a href="' . $file["guid"] . '">' . $file["post_title"] . '</a>';
    echo '<br>';
  }
?>

Error message when there is no attachment:

  

Warning: Invalid argument   supplied for foreach () in   /var/www/html/wp-content/plugins/pods/components/Templates/Templates.php(500)   : eval () 'd code on line 8

    
asked by anonymous 19.11.2015 / 19:48

3 answers

2

For your case, I think it's pretty simple:

<?php

$files = $obj->field('upload');
if (!empty($files)) {
    foreach ( $files as $file ) {
             $file_url = get_attached_file($file['id']);
             echo '<a href="' . $file["guid"] . '">'
                  . $file["post_title"]
                  . '</a>';
                  . '<br>';
    }
} else {
   echo "Não há arquivos enviados!";  die();
}

But I suggest doing something better worked, using exception:

function listFiles()
{
  $file = func_get_args(0);
  try {

      if (empty($file)) {
         throw new Exception("Não há arquivo(s) enviado(s)!");
      }
       $content = '';
      foreach ( $files as $file ) {
         $file_url = get_attached_file($file['id']);
         $content.= '<a href="' . $file["guid"] . '">'
                    . $file["post_title"]
                    . '</a>';
                    . '<br>';
      }
      return $content;

  } catch (Exception $e)  {
     return $e->getMessage();
  } 
} 

echo listFiles($obj->field('upload'));
    
19.11.2015 / 20:11
1

Use isset or empty to verify that this variable / array has values.

<?php
$files = $obj->field('upload');

if(!empty($files)){
foreach ($files as $file)
  {
    $file_url = get_attached_file($file['id']);
    echo '<a href="' . $file["guid"] . '">' . $file["post_title"] . '</a>';
    echo '<br>';
  }
} else {
 print "Nenhum ficheiro selecionado";
}
?>
    
19.11.2015 / 20:11
0

You can do a simple check in $files :

<?php

$files = $obj->field('upload');
if (count($files)) {
    foreach ( $files as $file ) {
    $file_url = get_attached_file($file['id']);
    echo '<a href="' . $file["guid"] . '">' . $file["post_title"] . '</a>';
       echo '<br>';
    }
}
    
19.11.2015 / 19:53