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.
Related
Im working on a piece of code to alter permissions for users of an app. Currently, each permission is added one at a time, Im revising it to be added in a faster way, being able to select multiple permissions to add at once.
The checkboxes aren't going to be the same number, since they are only the permissions the user doesn't yet have. It needs to pass an id with the permissions.
The problem is, my checkbox form doesn't appear to be sending any data to the controller. Upon submitting, it just loads a blank page with the url of the controller.
Heres the view code, that generates the checkbox form
<?php
if (!empty($lstAvailablePermissions)) {
$c=0;
echo $form->create('Administrator', array('action'=>'addPermission'));
echo $form->input('id');
foreach($lstAvailablePermissions as $key){
echo "<br>";
echo $form->input(
'permission',
array(
'id'=>$key,
'label'=>$key,
'type'=>'checkbox',
'multiple'=>'checkbox',
'value' => $key,
'name' =>'data[Administrator][permission]['.$c.']'
));
$c=$c+1;
}
echo $form->button(__('Add', true), array('type'=>'submit', 'class' => 'button', 'style'=>'padding: 2px; font-size: 12px;'));
echo $form->end();
}
?>
and the method in the controller
function AddPermission() {
if (empty($this->data)) { $this->RedirectWithFlash(__("Only POST Requests", true), "/administrators"); }
ErrorLogWarning("This is the form data sent to the controller", $this->data);
$length=count($this->data['Administrator']['permission']);
for ($i = 0; $i < $length; $i++){
$this->Acl->allow(
array('model' => 'Administrator', 'foreign_key' => $this->data['Administrator']['id']),
$this->data['Administrator']['permission'][$i]
);
}
$this->RedirectWithSuccessFlash(__("Permission added", true), array('action'=>'edit', $this->data['Administrator']['id']));
}
can anyone help me figure out whats going on? I assume ill need to loop through the data once its in the controller, but it doesn't even send the error message as of right now.
EDIT: problem appears to be fixed by adding the name property at the bottom of the form echo, which send it as an array which can be looped through in the controller.
I think the problem might be that you specify 'action'=>'addPermission' when you create the form, but your controller action is named AddPermission (capital A). Try changing to 'action'=>'AddPermission'.
Also, I think you might only get the last permission input because you're adding the permission inputs in a loop. Try indexing the inputs like this:
foreach($lstAvailablePermissions as $i => $key) {
echo "<br>";
echo $form->input(
"Administrator.{$i).permission",
so I've been trying to get select2Row to work for me forever and I just can't seem to get a hang of it. What I'm trying to do is provide the user with Tags that list a school/university name, while at the same time storing the value of said tag when I save the form. I've noticed that I cannot use both data and tags, else my drop down wont populate so that's not an option. Tags only seem to want text, rather than text and matching values. Any ideas?
<div class="row">
<?php
echo $form->select2Row($model, 'school_id', array(
'asDropDownList'=>false,
'options'=>array(
'tags'=>School::model()->schoolNames,
//'maximumSelectionSize'=>1,
'width'=>'297px',
'tokenSeparators'=>array(','),
),
));
?>
<?php echo $form->error($model,'school_id'); ?>
</div>
And here is the function for schoolNames
public function getSchoolNames()
{
$schools = array();
$result = $this->findAllBySQL("SELECT DISTINCT name FROM School");
foreach($result as $school){
$schools[] = $school->name;
}
return $schools;
}
I've tried using this instead, but the tags won't populate
public function getSchools()
{
$query = "SELECT id,name FROM School";
$results = $this->findAllBySQL($query);
return CHtml::listData($results, 'id', 'name');
}
So at the moment, select2Row is generating a list of tags using getSchoolNames() and that all works fine, except once you submit the form using those tags you'll get this
Please fix the following input errors:
School must be an integer.
Sorry for all the trouble, I'm still a little new to this. I'm sure the answer is probably right in front of me. Thanks either way =)
try this:
echo $form1->select2Row($model, 'school_id', array(
'data' => School::model()->schoolNames,
'multiple' => 'multiple',
'options' => array(
"width" => '70%',
),
));
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
I am trying to pass the id of the person whosoever logs-in to my site. I am using Auth for login in cakephp. So can anyone tell me how to pass the value during the login and retrieve it at the home page? I am new to cakephp.
This is what I have tried.
app controller.php
class AppController extends Controller {
//...
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'members', 'action' => 'home',$member['Member']['id']),
'logoutRedirect' => array('controller' => 'members', 'action' => 'index')
)
);
MembersController.php
public function home($id = null) {
$this->Member->id = $id;
}
home.ctp
<div align='center'><h2>Hi user welcome to home page </h2></div>
<?php
//I am just trying to print the id of the logged in person
echo $this->Form->value('User.id');
?>
<?php
echo $this->Html->link('LogOut',array('controller'=>'users','action'=>'logout'));
?>
echo $this->Form->value('User.id');
Is part of the FormHelper.
If you would like to have your form prefilled, make use of the conventions. Simply create an input field like this:
echo $this->Form->input('User.id');
If the $this->request->data contains this value ($this->request->data['User']['id']) it will automatically fill your form.
In order to retrieve values from the AuthComponent You can simply do something like $userName= $this->Auth->user('name'); (Just make sure the column 'name' exists in your 'users` database).
In order to pass variables to your view, you can simply use the method set which is defined in the Controller, which is extended by the AppController which is extend by FooBarsController.
If you want to set this variable to your view (as mentioned earlier) use set.
$this->set('userName', $userName);
In your view you can now do:
printf('Welcome %s', $userName);
Blog tutorial to get your started
AuthComponent
FormHelper
How Views work
How Controllers work
How Models work
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.