I have this code inside my view.
$country = array(
'id' => 'country',
'name' => 'country',
'value' => get_user_info('country'),
'size' => 30
);
<tr>
<td><?php echo form_label('Country', $country['id']); ?></td>
<td><?php echo form_input($country); ?></td>
<td style="color: red;"><?php echo form_error($country['name']); ?><?php echo isset($errors[$country['name']])?$errors[$country['name']]:''; ?></td>
</tr>
The get_user_info() is a function defined in my form_helper like this:
Form_Helper.php
if(! function_exists('get_user_info')){
function get_user_info($field)
{
$ci = & get_instance();
$ci->load->model('users');
return $ci->users->get_user_profile($field);
}
}
As you can see , inside this function I access the database through the users Model.
User_Model
function get_user_profile($field)
{
$user_id = $this->session->userdata('user_id');
$this->db->select($field);
$this->db->where('user_id',$user_id);
$query = $this->db->get($this->profile_table_name);
if($query->num_rows()==1)return $query->row();
return NULL;
}
The idea is to auto fill the Country field of the form while the page loads.
But in the view I am getting this error
A PHP Error was encountered
Severity: Warning
Message: htmlspecialchars() expects parameter 1 to be string, object given
Filename: helpers/form_helper.php
Line Number: 646
What can be the problem ?Can someone knows what is happening ? Or has someone did a such a thing in the past ?
Is it the right way to access the Model within a helper function ?
Thanks
EDIT
To do better and faster I simply call the model from my controller and then pass the different values to the view.
Controller
$d = $this->users->get_user_profile('country, telephone, city, street, address, town');
$d2 = Array(
'telephone' => $d->telephone,
'country' => $d->country,
'city' => $d->city,
'street' => $d->street,
'address' =>$d->address,
'town' => $d->town);
$this->template->write_view('contentw','dashboard/profile', $d2);
$this->template->render();
So I delete the function I added to my Helper file.
This method is working for me.
Thank you all for your answers
Generally helpers are used as Global functions to do some simple work. Most people would say it is wrong to invoke a Model in the middle of a helper. Helpers should be used like the PHP function explode; it has a single task, receives input, and provides output based on the input very mechanically.
It might be better instead for the controller to access the model and get that value, then pass it into the view and use it directly
As for the error:
You are probably getting that error because you are returning $query->row() instead of an actual value in that field. $query->row() is most likely an object and $query->row()->country is the actual value
Helpers aren't hooked into the rest of CI as far as I'm aware. I'm sure there's some way to get them to work like that, but maybe it would be more productive to just create a library?
If you create a library, you can have access to all the great stuff in CI through &=get_instance(); and it won't really be much different. You could make a Users library and call it like this:
$this->load->library('users');
$this->users->get_user_info('country');
Related
Actually , I did the JSON calling from the PHP file named as student_detail.php
localhost/demo/student_details.php
I need to call the JSON file inside the student_details.php file. like
localhost/demo/student_details/get_Students_Details
by calling this way it shows an error like object not found. Here my code
<?php
include('database.php');
class student_details
{
public function get_Students_Data()
{
$query = "select * from student_table";
$result = mysql_query($query);
$student_data = array();
while($row = mysql_fetch_assoc($result))
{
$student_data[] = array(
'Student Id' => $row["student_id"],
'Register No' => $row["student_register_no"],
'Roll No' => $row["student_roll_no"],
'Name' => $row["student_name"],
'Date Of Birth' => $row["student_DOB"],
'Gender' => $row["student_gender"],
'Nationality' => $row["student_nationality"],
'City' => $row["student_city"],
'Pincode' => $row["student_pincode"]
);
};
echo json_encode($student_data,JSON_PRETTY_PRINT);
}
}
?>
How do I resolve it.?
You are using "clean urls", which pure PHP doesnt support.
Its unclear if you are using a framework which does support that or not.
Your code, as is, should work if you are using a framework with clean urls.
Please provide some more informations for further help.
If you do NOT use a framework, all you have to do is create a new file, which will be called if you want to request a JSON response. Then you create a new object of your student_details class and call the method get_Student_Data().
i.e:
<?php
include('classes/student_details.php');
$student = new student_details;
$student->get_Student_Data();
Unrelated, but still important: do NOT use mysql_* functions, since they are deprecated in PHP 5.5 and removed from PHP 7. Use mysqli_* or PDO instead.
I need to load a view into a view within CodeIgniter, but cant seem to get it to work.
I have a loop. I need to place that loop within multiple views (same data different pages). So I have the loop by itself, as a view, to receive the array from the controller and display the data.
But the issue is the array is not available to the second view, its empty
The second view loads fine, but the array $due_check_data is empty
SO, I've tried many things, but according to the docs I can do something like this:
Controller:
// gather data for view
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->view('checks/due_checks',$view_data);
But the array variable $due_check_data is empty
I'm just getting this error, saying the variable is empty?
Message: Undefined variable: due_check_data
You are passing the $view_data array to your view. Then, in your view, you can access only the variables contained in $view_data:
$loop
$check_cats
$page_title
There is no variable due_check_data in the view.
EDIT
The first view is contained in the variable $loop, so you can just print it in the second view (checks/due_checks):
echo $loop;
If you really want to have the $due_check_data array in the second view, why don't you simply pass it?
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests',
'due_check_data' => $due_check_data
);
$this->load->view('checks/due_checks',$view_data);
Controller seems has no error. Check out some notices yourself:
<?=$due_check_data?>
This only available in PHP >= 5.4
<? echo $due_check_data; ?>
This only available when you enable short open tag in php.ini file but not recommended
You are missing <?php. Should be something like this
<?php echo $due_check_data; ?>
OK, i managed to solve this by declaring the variables globally, so they are available to all views.
// gather data for view
$view_data = array(
'due_check_data' => $combined_checks,
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->vars($view_data);
$this->load->view('checks/due_checks');
I have to create a form for a set of models, but unfortunately, I don't know how to do.
My first idea is to create a single form and a controller action which renders the view containing the form. But, this idea let me face an error. I create an action like this :
public function actionAddInfo($id){
$participant = Participant::model()->find('id_participant = ' . $id);
$info = InfoComp::model()->findAll('id_event = ' . $participant->id_event);
// here I must save the model if submitted
$this->render('addInfo', array('model' => $info));
}
In fact, the relationship in my models Participant, Evenement is below :
'idEvent' => array(self::BELONGS_TO, 'Evenement', 'id_event');
When accessing the variable $info in the view,
echo count($info);
I got the exception :
Undefined variable $info
This exception let me ask whether it is possible to proceed like that. I need your help. Else, can somebody suggest me another way to proceed ?
You are sending the variable with name model and you are trying to access it with name $info..
All you need to change is this:
$this->render('addInfo', array('info' => $info));
I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.
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.