warning for empty in_array

Asked

Viewed 97 times

1

I have a code that to generate a PDF it checks what is marked in the checkbox. But if I don’t mark anything, it still opens the PDF, only with the blank sheet. It has how to make a if that if nothing has been marked, show an alert on the screen to the user. My code is written in Codeigniter, and in view report has the following code:

if (in_array("foto", $itens)) {
     //código para mostrar a foto se está marcada a opção no checkbox
}

On my controller is:

$itens = $this->input->post('itens');
        if (!empty($itens)) {
            $data['itens'] = $itens;
        } else {
            $data['itens'] = array(null);
        }
 $this->load->view('ViewDoRelatorio', $data);
  • try to give a die(); or exit(); before generating the code, and after the exception.

  • @Ivanferrer I put but there appeared nothing different

  • @Ivanferrer I put your response code and it really worked, it fixed another mistake I had. I think I misexpressed myself, not exactly the mistake I was talking about. Thank you so much in the same way, with the code you sent me corrected another error that there was.

2 answers

2

To treat the error, you can do the following:

function seuMetodoQueGeraPDF() {
   /* seu codigo vem dentro do seu método,
      e para qualquer condição de erro, 
      você cria uma exceção. */
  if (!in_array("foto", $itens)) { 
      throw new Exception("Marque a opção selecionada"); 
   }
}

try {
//dentro do "try" você executa seu método de gerar PDF.
 seuMetodoQueGeraPDF();

} catch(Exception $e) {
    echo $e->getMessage(); 
} 
  • Once an exception is generated nothing else is executed, so the die is not the most ?

  • is mania. hehehe

  • +1 for the comments on the script and for the simplicity.

0

You can use the Try catch block for this, so instead of you creating an array by passing null you create a treated error.

Code example

<?php

try {
  $itens = $this->input->post('itens');
  if (!empty($itens)) {
     $data['itens'] = $itens;
  } else {
     throw new Exception('Erro: marque alguma opção!');
  }
  $this->load->view('ViewDoRelatorio', $data);
} catch (Exception $ex) {
     echo $ex->getMessage();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.