Solved

Could you point how to make an Codeigniter's controller array to be visible in the view ?

Posted on 2016-10-26
20
79 Views
Last Modified: 2016-10-31
Hi Experts

Could you point how to make an Codeigniter's controller array to be visible in the view ?

Controllers code: It runs OK  (brings the file paths names to be downloaded if needed - by using links in the view)
$result = $this->reclamacao_model->new_get($array_select);

Open in new window


The View code where I need to present the links - based on $result values  (actually $result values are not accessible in the view)
foreach($result as $linha){
                        
	$anexo = $linha->nome_edital;
	
	$cell = "<a  href='";
	$cell .= base_url("xxxx/xxxx/"."/$anexo")."'";
	$cell .= ' target="_blank"';
	$cell .= ">";
	$cell .= $linha->nome_anexo;

	//Present the link
	echo $cell;
}

Open in new window


Thanks in advance
0
Comment
Question by:Eduardo Fuerte
  • 9
  • 9
  • 2
20 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41860940
These may be protected properties, and that means you would need to call methods to see them, but they should still be visible to print_r(), var_dump(), or var_export().  This is just a guess, but it's what I would try first.
$log = print_r($result, TRUE);
error_log($log);

foreach($result as $linha){
      
    $anexo = $linha->nome_edital;
    
    $cell = "<a  href='";
    $cell .= base_url("xxxx/xxxx/"."/$anexo")."'";
    $cell .= ' target="_blank"';
    $cell .= ">";
    $cell .= $linha->nome_anexo;

    //Present the link
    echo $cell;
}

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41860951
You need to pass your data into the view when you load it from the controller (usually as an array or object). Each key of the array or property of the object is then available as a variable:

$data = new stdClass();
$data->result = $this->reclamacao_model->new_get($array_select);
$this->load->view('yourViewName', $data);

Open in new window


Then you're view will have access to a $result variable
0
 

Author Comment

by:Eduardo Fuerte
ID: 41861014
Hi

Just in my case:
 img004
The way I coded:

$result = $this->reclamacao_model->new_get($array_select);
$this->load->view('reclamacao/index', $result);

Open in new window


The value isn't received at the view:
 <?php                      
	 foreach($result as $linha){                                                    
				$anexo = $linha->anexo;                                                    
				echo $anexo;
			}
?>

Open in new window


img005
Could you check?
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 41861060
Hey Eduardo,

CodeIgniter automatically extracts the keys or properties from the data you pass into your view, so you need to pass in an array or object:

$data['result'] = $this->reclamacao_model->new_get($array_select);
$this->load->view('reclamacao/index', $data);

Open in new window

You'll see that your $data array has a key called 'result' so when $data is passed to your view it will be extracted to a variable called $result. Whatever the key is called in the array - that's the name of the variable you'll have in your view.
1
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41861071
One other thing I'd point out. CodeIgniter comes with a URL helper, which would make your code for generating links a lot cleaner and easier to read:

foreach( $result as $linha ) {
    echo anchor("xxx/xxx/$linha->nome_edital", $linha->nome_anexo, "target='_blank'");
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41861084
Whatever the key is called in the array - that's the name of the variable you'll have in your view.
<sarcasm>extract()</sarcasm>

Just kidding -- I don't think CodeIgniter really does it with a dangerous function.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862008
Hi

So what I did is:

Controller code:
$array_select = array(
	'debug' => false,
	'fields' => 
			'sr.id_reclamacao,
			 sa.anexo as anexo',
	'where' => array(
			'sr.id_reclamacao' => $id  
	),
	'join' => array(0 => array('table' => 'system_anexos sa','equal' => 'sa.id_reclamacao = sr.id_reclamacao','type' => 'left')
	)
   
);

//Pass the array to the view
$data_anexo['resultado_anexo'] = $this->reclamacao_model->new_get($array_select);

//Ok -- Array is perfect formed
print_r($data_anexo);

Open in new window



View code:
<?php
                            
 foreach($resultado_anexo as $linha){
			$anexo = $linha->anexo;
		}
?>

Open in new window


But  doing this way the variable still isn't visible to the view

img001
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41862093
Hey Eduardo - your code seems to be missing the load->view() part. Can you show me the full controller code, rather than part of it.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862133
Hi @Chris


Here is the  Controller code - this method is called when the modal is opened:

 public function get($id)
    {
        try
        {
            if (empty($id))
                throw new Exception('ID não existe', 1);
            if (!$this->input->is_ajax_request())
                throw new Exception('Erro de requisição', 1);

             $result = (array )current($this->reclamacao_model->new_get(array('where' => array('id_reclamacao' => $id), 'fields' => array(
                    'id_reclamacao',
                    'DATE_FORMAT(data,"%d/%m/%Y %H:%m:%i") as data',
                    'interna_externa',
                    'enviado_por',
                    'nome_reclamante',
                    'genero',
                    'fisica_juridica',
                    'cpf_cnpj',             
                    'DATE_FORMAT(data_atendimento,"%d/%m/%Y") as data_atendimento',
                    'sise',                 
                    'updated_by',
                    'created_at',
                    'created_by', 
                    'updated_at',
                    'updated_by'))));
                    

                $array_select = array(
                'debug' => false,
                'fields' => 
                        'sr.id_reclamacao,
                         sa.anexo as anexo',
                'where' => array(
                        'sr.id_reclamacao' => $id  
                ),
                'join' => array(0 => array('table' => 'system_anexos sa','equal' => 'sa.id_reclamacao = sr.id_reclamacao','type' => 'left')
                )
               
            );
            
         
            $data_anexo['resultado_anexo'] = $this->reclamacao_model->new_get($array_select);
            
//Just to test
        //    print_r($data_anexo);
           // die;
     
            //Pass the array to the a view
            $this->load->view('reclamacao/index', $data_anexo);
            
             

        }
        catch (exception $e)
        {
            bootbox_alert($e->getMessage());
        }
        $this->output->set_content_type('application/json')->set_output(json_encode($result));
    }

Open in new window


      }
      else
      {
            echo "Não encontrado";
      }
?>
[/code]

img002

Embeded in View - modal code (always "Não Encontrado")
<?php
                            
	if(isset($resultado_anexo)){
		   echo $resultado_anexo;

	}
	else
	{
		echo "Não encontrado";
	}
?>

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41862257
Hey Eduardo,

Sorry - I'm getting a litle confused here. In your code, you seem to try and load a view, but then you go on to output JSON code, so it looks like your view is never going to get loaded. Instead you would get a JSON response.

Having said that, if that's the case, then I don't get how your isset() code is running as your view will never get loaded.

If you remove the JSON output line, then your reclamacao/index view will have access to your $resultado_anexo variable.

The fact that you've mentioned modal code leads me to believe there's something else going on here that we're not seeing.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862320
Really...

At begining and at the end of the view helpers are called.... I think what imports is:

<?php
	echo datatables_crud_modal(array(
		'controller' => 'reclamacao',
		'edit' => array(
			'action' => array(
				'save' => 'save',
				'entity' => 'get',   
				'status' => 'update',
			),
		),
		'view' => array(
			'action' => 'view'
		),
	));
?>

Open in new window



The helper:  (line 308 deals with the modal edit)
datatables_crud_modal_helper.php


Using this jQuery to code links to download files  seens to be extremelly complicated.

Is it possible to cohabit json output and  this:

 $this->load->view('reclamacao/index', $data_anexo);

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41862358
Now I've got no idea what is going on. This is the first time you've mentioned jQuery!

To start with you wanted to know how to pass data from your Controller to your View, which you do by passing an array to the view->load() method. This passes the variables to your view so you can access them.

Now you've brought jQuery into the mix.

We seem to be dealing with too many separate questions here.

Generally speaking, when your web page is requested, your Controller handles the data requests (maybe from a DB) and then passes that data into your View. In your View, you then access that data in the form of PHP variables, which you can manipulate (loop, echo etc.).

If you are dealing with JSON, then your jQuery script makes a call to your Controller, and the data is returned to your jQuery script for manipulation (maybe as complete HTML or JSON Data). You can't use PHP to manipulate the data returned to your jQuery script - they are two very different things.

It might be easier to take a step back from all the code snippets and explain in simple terms what you are trying to achieve.

Sorry I can't be more specific but at the moment, I really can't see what you're trying to do.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862424
Sorry, Chris..

This is a legate code I have to mantain.
This helper is used to fill the controls, it works ok since a maintenance like  put links to download files are demanded.
The helper must be rewrited to receive the files names (obtained in controller by the array bellow and be sent  by jason) and make the files to be available to be downloaded.
Did you see the helper (line 308) ?
If possible, could you suggest something? (if needed a new question could be open in this particular subject)
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41862481
We're definitely at cross purposes here Eduardo. The link to your modal_helper just shows code that generates the jQuery needed to edit and delete your data. It doesn't generate any HTML output, and it certainly isn't a conventional View.

Do you have anywhere where we can see this working - it might help us to understand exactly what you need.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862631
It's running local by now. I'm going to provide a link but I have no manner to do it now.

In the meanwhile another idea I had is to use Dropzone.js to download the files (since it had been uploaded by using it). Maybe if it's possible could be a workaround.
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41862644
No worries.

Not sure if that's a workaround or not. I tihnk the problem seems to be getting the list of files into your View, so I'm guessing you'd still have that problem if using Dropzone.
0
 

Author Comment

by:Eduardo Fuerte
ID: 41862646
Yes. Certainly...
0
 

Author Comment

by:Eduardo Fuerte
ID: 41866738
Hi @Chris

Your reply to my original question is ok.

In this complicated (fantasmagoric?) case the solution was:

In the controller this code was added:
    $query_arquivos = array('fields' => array(
                    'id_anexo',
                    'id_reclamacao',
                    'anexo'
                ),
                'where' => array('id_reclamacao' => $result['id_reclamacao'])
            );
            $result_anexo = $this->anexo_model_reclamacao->new_get($query_arquivos);

Open in new window


And in the helper:
			.on("edit", function(e, data) {


                //console.log("Em edit");

				var $form = $(this);

                                        //console.log(data);
				$.each(data, function(field, value) {
					//console.log(field+ " - " +value);
					var
						avoid = ' . json_encode($options['edit']['avoid']) . ',
						$field = $form.find(\'[name="\' + field + \'"]\'),
						tag = ($field.length ? $field.prop("tagName").toLowerCase() : undefined)
					;
                                        if(field ==="anexo"){
                                            if(value !==null){
                                                $(".anexo").show();
                                                var link = "";
                                                $.each(value,function(id, valor){
                                                    var anexo = valor.anexo;
                                                    anexo = anexo.split("/");
                                                    anexo = $(anexo).get(-1);
                                                    //console.log(valor.anexo);
                                                    link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a></p>";                                             ;
                                                });
                                                $("#anexo").html(link);
                                            }else{
                                                $(".anexo").hide();
                                            }
                                        }

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41866755
Good news. Pleased you got it working.
0
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41866762
Thank you for the guidance!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question