Populate form fields from database using Codeigniter - php

i am trying to populate two form fields from data that is retrieved from a database, in order for the user to update them. The table is called records and it is quite simple:
Record_ID
title
content
My model:
function get_data()
{
$r = $this->uri->segment(3);
$query = $this->db->get_where('records', array('Record_ID' => $r));
return $query->result();
}
My controller:
function set_values()
{
$data = $this->entries_model->get_data();
$this->load->view('update_view', $data);
}
and my update record view:
<?php
echo form_open('site/update',$data);?>
Title:
<?php echo form_input('title',set_value('title'));?>
Content:
<?php echo form_input('content',set_value('content'));
echo form_submit('submit', 'Submit');?>
<?php echo form_close();?>
The problem is that i get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/update_view.php
Line Number: 10
My question is twofold:
How do i access this data in my view form and
how do i populate the respective fields with it.
I am new to Codeigniter, my questions may look simplistic but any help would be appreciated. Thanks in advance.

There are a few things going on here:
$data is an array or object that is passed to a view. It's ELEMENTS are then available as variables in the view. So, $data['myelement'] = 'somevalue' in the controller would be accessed as $somevalue in the view.
If you pass a 2nd parameter to the form_open() method, it is expected to be a key/value pair of attributes for the tag that will be generated. like, array('class' => 'form_class', 'id' => 'form_id')
If you want to set the values of your form inputs, use the view helper function set_value(). In your case, use the controller to set elements in the $data array you'll pass to the view. $data['form_values'] = array('title' => $title, 'content' => $content);
Then, in the view:

You should pass a array to your view file. So replace:
$data = $this->entries_model->get_data();
with:
$data['entries_data'] = $this->entries_model->get_data();
and on your view file replace:
echo form_open('site/update',$data);?>
with:
echo form_open('site/update',$entries_data);?>

first you need to pass data in proper way
replace
$data = $this->entries_model->get_data();
with:
$data['data'] = $this->entries_model->get_data();
for setting value in set_value you need to do the in-line condition check to check either data is an object or not if object then put value other wise just empty
<?php echo form_input('title',set_value((is_object($data)?$data->title:'')));?>
you have to do the same thing for your all form fields

Jcory has answered your question but let me add a little to it.
In you model instead of return $query->result(); do this return $query->row(); this is because using returning a return object requires that you should loop through the resultset in your view
Instead of $data = $this->entries_model->get_data(); do this $data['entry'] = $this->entries_model->get_data();
In your view do this <?php echo form_input('title',set_value('title',$entry->title));?>
I hope these changes may solve the problem

Related

Using URL data in laravel views

struggling to figure out how to best do what I would normally in simple PHP.
I have the following URL:
/viewbuild/2
The aim is that viewbuild is the view and 2 is the id of the database row.
Normally It would simply be:
$id = $_GET['id'];
But cant figure out to do it PROPERLY using laravel.
This is my route:
Route::get('viewbuild', function()
{
return View::make('viewbuild');
});
And on my view I have done e.g.:
<?php
$build = Build::find(20);
?>
{{ $build->id }}
This correctly searches the builds table for a row with the id of 2 and then displays its id.
What I now want to do is pull the '20' value from the URL.
I have tried:
Route::get('/viewbuild/{build_id}', function($build_id = null)
{
$data = array(
'build_id' => $build_id,
);
return View::make('viewbuild', $data);
});
And then on my view:
$build = Build::find(build_id);
But I get undefined constant errors.
Any help on this?
Basically i can see two things from quick looking at your code:
A typo when setting the array to be passed to the view build_ud should be build_id i presume
You are referencing a constant for the build_id (no $ sign) in your view instead of the passed variable which is passed to the view. Ie:
$build = Build::find(build_id);
should be:
$build = Build::find($build_id);
Your route closure should look like this:
Route::get('/viewbuild/{build_id?}', function($build_id = null)
{
// Query the database here instead of inside the view
$build = Build::find($build_id);
return View::make('viewbuild', compact('build'));
});

Undefined variable in select when submitting form in Laravel 4

I'm trying to pull data from a table, populate a select input with that data, then post that information (and other info) to another table. When the view is rendered, it correctly populates the select with the data required, however when I submit the form, I receive an undefined variable error.
Undefined variable: secondarygenre
View
{{ Form::select('genre', $secondarygenre, null, array('class' => 'form-control', 'id' => 'genre')) }}
Controller
//Data is passed to the form in the view
public function addSubmission() {
$secondarygenre = Genre::lists('friendlyName', 'id');
return View::make('add')
->with('secondarygenre', $secondarygenre);
}
//Form is submitted
public function successfulSubmission() {
$track = new Track();
$track->genre_id = Input::get('genre');
$track->save();
}
If it's populating the select input with data, I know that it's the variable is not undefined.
I apologise if I've missed something, this is my first project with Laravel (or any MVC framework).
Any help would be greatly appreciated!
In the post, you have to also return the view with the variable, it looks like you're only doing that with the get, but you need to use ->with('secondarygenre', $sg) once for each type of request.

Codeigniter: Accessing a array in view

I am completely new in the codigniter i just started day befire Yesterday i am having a problem
Here is my snippet of my controller code
$allcalldetails_array = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->session->set_userdata('logged',$allcalldetails_array);
I want to iterate the $allcalldetails_array in my views please tell me the way to do this
i tried iterating logged but could not get anything .
If i am printing the array in my views like print_r($allcalldetails_array); but this is also disappointing me .Please help me to get back on track .
Thanks
Its not necessary for session variables to be parsed via controller, access it on view directly:
$logged = $this->session->userdata('logged');
print_r($logged);
If you would like data to be send to your view as variables, you should add the corresponding data to your view load.
Controller:
$logged = $this->session->userdata('logged');
$this->load->view('viewfile', $logged);
View
print "logged id:".$id;
best regards.
Jonas
To get the data from session your need to do the following:
// controller logic
$logged = $data['logged_for_view'] = $this->session->userdata('logged'); // since 'logged' is the name you set it to
// more controller logic
$this->load->view('view_name', $data);
// in view
var_dump($logged_for_view); // this is the key of the $data variable you assigned for the view
Regarding the CodeIgniter's documentation :
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading function.
Then you could use something like :
// Controller side
$data['allcalldetails_array'] = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->load->view('your_view', $data);
// View side
print_r($allcalldetails_array);
// Loop through your array
foreach ($allcalldetails_array as $detail){
// Do something with your $detail.
}

Zend View array variable inside a partialLoop

Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray

Search using cakePHP

First of all I have a Model user.php which connects to users table.
I have a controller UsersController.
I created a view for search: (filename: index.ctp)
<p><?php
echo $this->Form->create("Users", array('action' => 'search'));
echo $this->Form->input("Search Label", array('action' => 'search', 'name' => 'txt_search'));
echo $this->Form->end("Search");
?></p>
And this will go to UsersController/search() function
function search() {
if (!empty($this->data))
{
$name = $this->data['Users']['txt_search'];
$conditions = array("User.name Like " => "%$name%");
$result = $this->User->find('all', array('conditions'=> $conditions));
$this->set('users', $result);
}
}
And this will load search.ctp
My problem is, when I use the variable $users in search.ctp, it gives me an error Undefined variable: Users [APP\views\users\search.ctp, line 10].
I don't understand.
Please help. Thanks!
You're specifying a custom name for your input and then you're checking $this->data which will be empty because you're input is not named properly (and does not get auto populated in $this->data). Use the following.
echo $this->Form->input("txt_search", array('label' => 'Search Label'));
A couple of things you should be looking at.
Set a default value to your users variable so your page doesn't break if they request it directly. Have $result = array(); at the top and do an empty() check on it in search.ctp
Why have you specified an action attribute in your input? You don't need that.

Categories