• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I pass variables in a foreach loop into a view?

#1
[eluser]alexandervj[/eluser]
I have a table populated with a foreach loop. I'm trying to make it so when you click on the search20.png image it opens the popup view, and passes the corresponding $subtime for that row into the popup view to use.

It works ok except that for each search20.png image you click on it gives the same $subtime. I'm not sure how to go about making it so that the $subtime corresponds to the $r->Submitted variable for each row in the table. Here's my code...

Thanks!

Code:
<table width="100%">
   <tr >
    <td></td>
    <td  bold;" min-width="120px">Submitted:</td>
    <td  bold;" min-width="120px">First Name:</td>
    <td  bold;" min-width="120px">Last Name:</td>
    <td  bold;" min-width="150px">Email:</td>
    <td  bold;" min-width="100px">Phone Number:</td>
    <td  bold;">Sent:</td>
   </tr>
   &lt;?php foreach($rows as $r){ ?&gt;
   &lt;?php $data['subtime'] = $r->Submitted; ?&gt;
   <tr>
    <td  vertical-align: middle;">
        <div class="button"><a href="#"><img src="assets/images/search20.png"/></a></div>
        &lt;?php $this->load->view('popup', $data); ?&gt;
    </td>
    <td>&lt;?php echo date("F j, Y, g:i a", $r->Submitted); ?&gt;</td>
    <td>&lt;?php echo $r->firstName; ?&gt;</td>
    <td>&lt;?php echo $r->lastName; ?&gt;</td>
    <td>&lt;?php echo $r->email; ?&gt;</td>
    <td>&lt;?php echo $r->phone; ?&gt;</td>
    <td ">&lt;input type="checkbox" name="check" value="check"&gt;&lt;/td>
   </tr>
  &lt;?php } ?&gt;
  </table>

#2
[eluser]RobertSF[/eluser]
You can't pass that data as a variable because, when you say $this->load->view('popup', $data);, $data is not what it was when you built each row in the table. It's whatever it is at the moment.

Instead, hard-code the data into each link in your table. You can use an array structure instead of an array variable as an argument, like this

$this->load->view('popup', array('subtime' = > $r->Submitted));

That way, the $r->Submitted specific to each table row gets embedded in the array you pass to the view.

#3
[eluser]alexandervj[/eluser]
Thanks Robert! I will give that a try

#4
[eluser]alexandervj[/eluser]
Having a little trouble figuring out exactly how to hard-code the data into each link. I've never done that before

#5
[eluser]RobertSF[/eluser]
Oops, sorry, now that I look closer at the code, are you sure it's working except for the wrong $data? I ask because according to the link you have there
Code:
<td  vertical-align: middle;">
    <div class="button"><a href="#"><img src="assets/images/search20.png"/></a></div>
    &lt;?php $this->load->view('popup', $data); ?&gt;
</td>
nothing at all should happen when you click on it. The load->view you're doing would happen when the page is rendered, not when the link is clicked. In other words, the code loads the view into the table cell. It wouldn't seem to open it when you clicked the view. Are you using some Javascript that makes it work?

Ok, if I needed to have a custom link for each row in a table that opened a window and passed it different data, here's how I would do it.

First, I'd setup a controller called "popup"

Code:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Popup extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        if (isset($_GET['subtime']))
        {
            $data = array('subtime' => $_GET['subtime']);
            $this->load->view('popup', $data);
        }
    }
}

Then, in the code that builds the table, I'd do this:

Code:
$this->load->helper('url'); // in the constructor for this class

&lt;?php
    $popup_vars = array(
        'width' => '800',
        'height' => '600',
        'scrollbars' => 'yes',
        'status' => 'yes',
        'resizable' => 'yes',
        'screenx' => '0',
        'screeny' => '0');

foreach ($rows as $r)
{
?&gt;
    <tr>
        <td  vertical-align: middle;">
            <div class="button">
            &lt;?php echo anchor_popup(
                'popup?subtime=' . $r-&gt;Submitted,
                '<img src="assets/images/search20.png"/>',
                $popup_vars); ?&gt;
            </div>
        </td>
        <td>&lt;?php echo date("F j, Y, g:i a", $r->Submitted); ?&gt;</td>
        <td>&lt;?php echo $r->firstName; ?&gt;</td>
        <td>&lt;?php echo $r->lastName; ?&gt;</td>
        <td>&lt;?php echo $r->email; ?&gt;</td>
        <td>&lt;?php echo $r->phone; ?&gt;</td>
        <td ">&lt;input type="checkbox" name="check" value="check"&gt;&lt;/td>
    </tr>

That anchor_popup() is a function in the URL helper. It creates a popup link. The link is to a page (controller) called popup, and it includes the GET variable subtime=whatever-subtime-is. When you click on the link, it calls the popup controller, which should open in a new window. The popup controller looks for the GET variable, puts it into the $data array, and loads the popup view (which is separate from the popup controller).

I know it looks kind of complicated. If someone else knows of a simpler way, I hope they post it.

#6
[eluser]alexandervj[/eluser]
Thanks for all your help! I see hard coding the value into the link is definitely the way to go

I was trying to use a Javascript code that would make a modal popup kind of like one of these...
http://www.ericmmartin.com/projects/simplemodal-demos/

I dont know if its even possible to pass a value into a window like that?

I'm trying to create a little more control over what the user can do. These windows will have the editable details of our product sheet requests so I'm trying to steer clear of making another browser window open unless its some kind of dialogue window that wont allow you to do anything else until you close that window. Do you know of any way I can achieve something like this?

#7
[eluser]RobertSF[/eluser]
You're welcome! Just so you know, I've since corrected a couple of errors in the source I provided. One is the missing parenthesis in if (isset($_GET['subtime']). There is an old programming language called LISP, and many witticisms arose from its use of parenthesis. The second error was that anchor_popup() must be echoed. It only generates the strong; it doesn't send it to the HTML source. I've since tested what I posted, so if you ever need a non-modal popup window, that's a way of doing it in Codeigniter.

I don't know much about Javascript, but I looked at the project page for SimpleModal, and it seems you can send data to it. The project page says
Quote:As a stand-alone function, a modal dialog can be created by passing a jQuery object, a DOM element, or a plain string (which can contain HTML). For example:
$.modal("<div><h1>SimpleModal</h1></div>");
You could pass it the value of $r->Submitted, but that value would have to be embedded in the HTML code for each row in your table, and I think you'd also need to add onclick="$.modal(....)" to the img tag in each row.

Here's what I hope is a valuable discussion about passing data generated by PHP to Javascript.
http://stackoverflow.com/questions/23740...javascript

If you've done any development in Visual Studio/Visual Basic, this will seem very different because the web operates in a stateless manner. The application runs and ends with each page load, unlike in desktop development, where the application is always running in memory. I'm pretty new at it too, and it sure is confusing sometimes! Smile

#8
[eluser]alexandervj[/eluser]
hm that sounds a little over my head at the moment. I just started using CodeIgniter.

Maybe I'll just start with passing the value to another view and try doing it with a popup later on.

So in my view I have...

Code:
&lt;?php echo anchor("main/request_details/$r->Submitted", 'View'); ?&gt;


in my model i have the function...

Code:
function getDetail(){
        $q = $this->db->query("SELECT `submit_time` AS 'Submitted',
                max(if(`field_name`='firstName', `field_value`, null )) AS 'firstName',
                max(if(`field_name`='lastName', `field_value`, null )) AS 'lastName',
                max(if(`field_name`='email', `field_value`, null )) AS 'email',
                max(if(`field_name`='phone', `field_value`, null )) AS 'phone',
                max(if(`field_name`='affiliation', `field_value`, null )) AS 'affiliation',
                max(if(`field_name`='interest', `field_value`, null )) AS 'interest',
                max(if(`field_name`='productSheets', `field_value`, null )) AS 'productSheets',
                max(if(`field_name`='referredBy', `field_value`, null )) AS 'referredBy',
                max(if(`field_name`='comments', `field_value`, null )) AS 'comments',
                GROUP_CONCAT(if(`file` is null or length(`file`) = 0, null, `field_name`)) AS 'fields_with_file'
                FROM `wp_cf7dbplugin_submits`
                WHERE `form_name` = 'PSRequestForm' AND submit_time = ".$submitTime."
                GROUP BY `submit_time`
                ORDER BY `submit_time` DESC
                LIMIT 0,100");
        if($q->num_rows() > 0){
            foreach($q->result() as $rows){
                $data[] = $rows;
            }
            return $data;
        }
    }


and in my controller I have the function...

Code:
public function request_details(){
if ($this->session->userdata('is_logged_in')){
  $this->load->model('model_data');
  $data['rows'] = $this->model_data->getDetail($submitTime);
  $this->load->view('request_detail', $data);
  
} else {
     redirect('restricted');
}

    }

I feel like I'm almost there but a little confused still on how to get the data in the request_details.php view based on the submitTime value

#9
[eluser]RobertSF[/eluser]
I think I see the problem.

In your view, you have:
Code:
&lt;?php echo anchor("main/request_details/$r->Submitted", 'View'); ?&gt;

And in your controller, you have:
Code:
public function request_details() {

Your function definition needs a parameter to receive the argument you're sending it. It should look something like this:
Code:
public function request_details($r_Submitted) {

Then, deeper into your controller code, if you want to pass that value to the model when you do your query, instead of:
Code:
$data['rows'] = $this->model_data->getDetail($submitTime);

you would have:
Code:
$data['rows'] = $this->model_data->getDetail($r_Subtmitted);

I don't know what $submitTime is. Generally, variables declared or used in one function are not available in other functions. You can make variables global, so they're available anywhere in your code or project, but in most cases, that's considered poor practice.

A note about names, too. There is no connection between the name of the variable you pass as an argument and the name of the parameter in your function definition. You could call the parameter $george, as long as you referred to it as $george in your function.

Code:
&lt;?php
public function square($george)
{
  return $george * $george;
}

$x = 33;
$y = 2;
echo square($x);
echo square($y);
echo square(20);

One last thing. In your model function getDetail(), you have:

Code:
$q = $this->db->query("SELECT etc, etc.
                LIMIT 0,100");
if($q->num_rows() > 0){
    foreach($q->result() as $rows){
        $data[] = $rows;
    }
    return $data;
}

The function has no return in case of zero rows. A function should have a return even if it's just to return zero or false.

Also, that whole if statement and the foreach inside can be replaced with Codeigniters' result_array(), like this:

Code:
$q = $this->db->query("SELECT etc, etc.
                LIMIT 0,100")->result_array();
return $q
}

Then, back at the ranch, you can test if $q (which will be an array) has any elements in it.

Anyway, I hope putting in the missing parameter is all you need to make it basically work. Does your editor have a debugger? The debugger for PHP is called XDebug, and many editors designed for PHP integrate it into their functions. I know Aptana, Code Lobster, and PHPEdit have it. Even Notepad++ has an XDebug plug in. It's invaluable to be able to execute your code line by line and see what's happening.

#10
[eluser]alexandervj[/eluser]
Thanks again Robert! that cleared it up. Always helpful


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.