I have been trying for days now using the form class to populate the text fields from my database. I have also been searching to find out how to do it without any luck.
Please could somebody take a look at my code and tell me what I'm doing wrong.
Model
//This function brings up the selected users information for editing.
public function edit_user($id)
{
$this->db->select('id, email, name, lastname, homeaddress, posteladdress,
mobile, hometel, idnum');
$this->db->where('id', $id)->limit(1);
$query = $this->db->get('user');
return $query->result();
}
Controller
public function get_user_edit($id)
{
$this->load->helper('form');
$this->load->model('model_users'); //Load the user model
//Get the database results from the model
$data['results'] = $this->model_users->edit_user($id);
foreach ($data['results'] as $key => $row)
{
$data['results'] = array( 'id' => $row->id,
'email' => $row->email,
'name' => $row->name,
'lastname' => $row->lastname,
'homeaddress' => $row->homeaddress,
'posteladdress' => $row->posteladdress,
'mobile' => $row->mobile,
'hometel' => $row->hometel,
'idnum' => $row->idnum);
}
$this->load->view('edit_user', $data);
}
View
<div id="body">
<p>Edit user information.</p>
<?php
echo form_open('user_admin/user_update', $results);
echo validation_errors();
echo "<p><lable>Email:</lable>";
echo form_input('email', set_value('email'));
echo "</p>";
echo "<p><lable>Name:</lable>";
echo form_input('name', set_value('name'));
echo "</p>";
echo "<p>";
echo form_submit('edit_submit', 'Update');
echo "</p>";
echo form_close();
?>
I keep getting this error
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: helpers/form_helper.php
Line Number: 1010
First thing. You're expecting a single row to be returned from the database, right? But you're looping through the result in your controller. Instead of doing that in your model:
return $query->result();
do this:
return $query->row();
and remove the foreach loop from your controller (it even has an unused $key var in there). You'll end up having cleaner and shorter code. Only if you're getting a single row, which seems to be the case.
Moving on.
Have you read the documentation here: https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html ?
form_open('user_admin/user_update', $results); - what are you trying to do here?
You use the second parameter to pass attributes to the opening tag. Now looking at your code, your $results array has values for each field. Doesn't make much sense to push all this into the form opening tag, does it?
Field rendering with the correct values.
This is an example from the documentation how to configure and render an input field:
$data = array(
'name' => 'username',
'id' => 'username',
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%',
);
echo form_input($data);
So, your email input should be formatted having the minimal config like that:
$data = array(
'name' => 'email',
'value' => $results['email']
);
echo form_input('email', $data);
On validation (in your user_update() method in user_admin controller), you'll have to do some logic to capture the value you're validating. So you'll need something like:
$results['email'] = set_value('email');
Hope that makes sense!
Thank you very much for your help. I'm sure you must have realised that I'm new to Codeigniter, but with your help I was able to sort out the problem that I had.
I changed the query to return only the one result that it found like you suggested
return $query->row();
and you were right I didn't need the foreach loop to populate an array to pass to the view.
Thanks for pointing out that I was trying to pass the results from db as the attribute for the form.:)
I added my code below for anybody that come across my question with the same problem. Maybe it will help them.
My controller
public function get_user_edit($id)
{
$this->load->model('model_users'); //Load the user model
//Get the database results from the model
$data['results'] = $this->model_users->edit_user($id);
$this->load->view('edit_user', $data);
}
My model
//This fetches the selected users information for editing.
public function edit_user($id)
{
$this->db->select('id, email, name, lastname, homeaddress, posteladdress,
mobile, hometel, idnum');
$this->db->where('id', $id)->limit(1);
$query = $this->db->get('user');
return $query->row();
}
My view
<div id="container">
<h1>Edit user</h1>
<div id="body">
<p>Edit user information.</p>
<?php
echo form_open('user_admin/user_update');
echo validation_errors();
echo form_hidden('id', $results->id);
echo "<p><lable>Email:</lable>";
echo form_input('email', $results->email);
echo "</p>";
echo "<p><lable>Name:</lable>";
echo form_input('name', $results->name);
echo "</p>";
echo "<p><lable>Last name:</lable>";
echo form_input('lastname', $results->lastname);
echo "</p>";
echo "<p><lable>Home address:</lable>";
echo form_input('homeaddress', $results->homeaddress);
echo "</p>";
echo "<p><lable>Postal address:</lable>";
echo form_input('posteladdress', $results->posteladdress);
echo "</p>";
echo "<p><lable>Mobile number:</lable>";
echo form_input('mobile', $results->mobile);
echo "</p>";
echo "<p><lable>Home telephone:</lable>";
echo form_input('hometel', $results->hometel);
echo "</p>";
echo "<p><lable>ID number:</lable>";
echo form_input('idnum', $results->idnum);
echo "</p>";
echo "<p>";
echo form_submit('edit_submit', 'Update');
echo "</p>";
echo form_close();
?>
</div>
Related
Here's the thing that I'm using the ACF repeater subfield (firma) to store some data. Usually the user is typing here his parent company name like: google, alibaba, sodexo etc. So it might happen that in multiple posts, the value of this field will be the same. At the moment I have following code:
$args = array(
'post_type' => 'opencourses',
'meta_key' => 'terminy_warsztatow'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
echo '<select type="text" class="form-control" name="filtr_lokalizacja">';
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('terminy_warsztatow')):
while (have_rows('terminy_warsztatow')) : the_row();
// display your sub fields
$filtr_var = get_sub_field('firma');
echo '<option value="'. $filtr_var .'">';
echo $filtr_var;
echo '</option>';
endwhile;
else :
// no rows found
endif;
endwhile;
echo '</select>';
endif;
And it works - meaning: it shows all typed values. But instead of showing only UNIQUE values it generates a list similar to this:
Google
Alibaba
Google
Sodexo
Sodexo
Tesla
Tesla
Sodexo
How to avoid showing same values and hide empty as well? I know that there is php function array_unique but I was unable to implement that. I've done sth like:
$filtr_var = get_sub_field('firma');
$result = array_unique($filtr_var);
echo $result;
but then it shows no values at all.
I assume that "firma" is simple text input type in repeater. if so then arrya_unique function won't work for string output.
you need to save each value in array and then use in_array function to make it unique.
see below code.
$args = array(
'post_type' => 'opencourses',
'meta_key' => 'terminy_warsztatow'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
echo '<select type="text" class="form-control" name="filtr_lokalizacja">';
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('terminy_warsztatow')):
// $PreValue = array();
while (have_rows('terminy_warsztatow')) : the_row();
// display your sub fields
$filtr_var = get_sub_field('firma');
// compare current value in saved array
if( !in_array( $filtr_var, $PreValue ) )
{
echo '<option value="'. $filtr_var .'">';
echo $filtr_var;
echo '</option>';
}
// save value in array
$PreValue[] = $filtr_var;
endwhile;
else :
// no rows found
endif;
endwhile;
echo '</select>';
endif;
Hope this will help you!
Enjoy
i am trying to make an simple cakephp aplication!
I have a form that creates a new article.. my problem is that i have an input field for the artice slug but when i cakephp submits te form the slug field in database remains empty..
here is the add method from my articleController
public function add(){
$article = $this->Articles->newEntity(); //gffdgfd
if ($this->request->is('post')){
$this->Articles->patchEntity($article, $this->request->data());
if($this->Articles->save($article)){
$this->Flash->success(__('Your Article has been saved!'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Cannot save article! Please try again!!'));
}
$this->set('article', $article);
}
and my add.ctp
<h1>Add Article</h1>
<?php
echo $this->Form->create($article);
echo $this->Form->control('user_id', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('published', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('title');
echo $this->Form->control('slug');
echo $this->Form->control('body', ['rows' => 5 ]);
echo $this->Form->button(__('Save Article'), ['class' => 'button', 'style' => 'margin-right:10px; margin-left:10px']);
echo $this->Html->link('Back', ['action' => 'index'], ['class' => 'button']);
echo $this->Form->end();
?>
If slug field is present in your request data, then you should check if this field is accessible for assignment in your entity. Look at file src/Model/Entity/Article.php, on top of class body you will have an array named $_accessible - check if your slug field is present, and if not, set it to true:
protected $_accessible = [
/* other fields */
'slug' => true
];
Please check more about assignment of properties in docs: CakePHP 3 Entities - Mass Assignment
public function outofstock(){
$this->loadModel('Store');
$store=$this->Store->find('all',array('fields' => array('Store.store_shortcode')));
$this->set('store',$store);
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$item=$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
foreach($item as $item1){
echo $item1['Item']['item_name'];
echo $store_shortcode;
}
endforeach;
$this->set('item',$item);
}
This is my controller part code .
I want to display echo $item1['Item']['item_name'] , $store_shortcode in view part . Actually in controller its displaying properly but in view part its not displaying . store_shortcode is GLF,DLLK,MKL . Item Name is ADASHG , GRAFGHJ, Store names or columns of item table and store_name of store table .
Controller ($items[ ]):
public function outofstock(){
$this->loadModel('Store');
$store=$this->Store->find('all',array('fields' => array('Store.store_shortcode')));
$this->set('store',$store);
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$items[] =$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
endforeach;
$this->set('items',$items);
}
In the view.ctp:
foreach($items as $item){
echo $item['Item']['item_name'];
}
But generally you have a a bad approach,
Do hasMany relational between the Store and Item model, and then easily with the help of a one query take data.
Use this in view file
foreach($store as $store):
$store_shortcode= $store['Store']['store_shortcode'];
$item=$this->Item->find('all',array('conditions' => array($store_shortcode.' =' => 0 )));
foreach($item as $item1){
echo $item1['Item']['item_name'];
echo $store_shortcode;
}
endforeach;
I'm using the CakePHP SimplePasswordHasher to hash my customer password. Is it possible to retrieve the un hashed password in the edit view? At the moment my edit view shows the hashed password. I want it to show the original password because if the hashed password is shown in the edit and the user submits the form the hash hashes that hash value and the password changes. My code is as follows:
edit.ctp
<div class="customers form">
<?php echo $this->Form->create('Customer'); ?>
<fieldset>
<legend><?php echo __('Edit Customer Details'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('customer_name', array('required'=>false));
echo $this->Form->input('customer_address');
echo $this->Form->input('customer_suburb');
echo $this->Form->input('customer_state', array('options' => array('SA' => 'SA', 'VIC' => 'VIC','ACT' => 'ACT', 'NSW' => 'NSW', 'NT'=> 'NT', 'QLD'=>'QLD','TAS'=> 'TAS','WA'=>'WA','empty'=>'(choose one)')));
echo $this->Form->input('customer_postcode', array('required'=>false));
echo $this->Form->input('customer_dob',array('required'=>false,'id'=>'datepicker','type'=>'text'));
echo $this->Form->input('customer_anniversary',array('required'=>false,'id'=>'datepicker2','type'=>'text'));
echo $this->Form->input('customer_phone1', array('required'=>false));
echo $this->Form->input('customer_phone2', array('required'=>false));
echo $this->Form->input('customer_phone3', array('required'=>false));
echo $this->Form->input('customer_fax', array('required'=>false));
echo $this->Form->input('customer_email', array('required'=>false));
echo $this->Form->input('customer_gender', array('required'=>false,'options' => array('M' => 'M', 'F' => 'F','empty'=>'(choose one)')));
echo $this->Form->input('customer_type', array('required'=>false,'options' => array('Gold' => 'Gold', 'Silver' => 'Silver','Bronze'=> 'Bronze','empty'=>'(choose one)')));
echo $this->Form->input('customer_username', array('required'=>false));
echo $this->Form->input('customer_PW', array('required'=> false));
echo $this->Form->input('companies_id', array('label' =>'Company Name','options'=>$companies, 'label'=>'Company Name','required'=>false));
echo $this->Form->input('employees_id', array('label' =>'Employee name','options'=>$employees, 'label'=>'Employee name','required'=>false));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
customersController:
class CustomersController extends AppController {
//some code
public function edit($id = null) {
if (!$this->Customer->exists($id)) {
throw new NotFoundException(__('Invalid customer'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Customer->save($this->request->data)) {
$this->Session->setFlash(__('The customer has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The customer could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Customer.' . $this->Customer->primaryKey => $id));
$this->request->data = $this->Customer->find('first', $options);
}
//$companies = $this->Customer->Companies->find('list');
$companies= $this->Customer->Companies->find('list',array('order'=>'company_name ASC','fields'=>array('id','company_name')));
$employees= $this->Customer->Employees->find('list',array('order'=>'employee_name ASC','fields'=>array('id','employee_name')));
$this->set(compact('companies'));
$this->set(compact('employees'));
}
//some code
}
Can some one please help?
SimplePassword Hasher uses the md5 encryption.
md5 is supposed to be a one way encryption. The reason you use it, is so only the user knows their password, but you can still validate the password.
How you validate it is to create an md5 hash of the password supplied by the user, and compare that with the md5 hash of the password in the database.
The whole idea behind a one way encryption is to generate a hashed value that cannot be decrypted to reveal the original string.
That's the reason that when dealing with lost passwords administrators typically reset it to a new value.
I think you just have to empty the password field while editing in edit.ctp like
echo $this->Form->input('customer_PW', array('value'=> ''));
Do you really want the password to be on the form for the user to edit?
You might want to just clear the password fields so your users can edit and save the rest of profile without bothering with the password. If they post the form, and the password field has been filled out, you know that they have entered a new password which should be hashed and saved. If the password field is blank, then make sure you delete the password field from the array before you save the Model from the Controller.
If you use jquery, it is simple to make sure the password field is empty.
$(document).ready(function() {
$('#CustomerPW').val('');
});
I've searched high and low for a solution but can't seem to get this figured out. What I'm trying to do is upon adding a product, I want the name field to be populated from the inputs in the form. So the name would include the values the user selects for type_id,category_id and subcategory_id. Does anyone know of a way to accomplish this?
Add product View page
<fieldset>
<legend><?php echo __('Add Product'); ?></legend>
<?php
echo $this->Form->input('type_id');
echo $this->Form->input('category_id', array('label' => 'Vendor'));
echo $this->Form->input('subcategory_id', array('label' => 'Model'));
echo $this->Form->input('location', array('label' => 'Location'));
echo $this->Form->input('sku', array('label' => 'Asset Tag'));
echo $this->Form->input('mac');
echo $this->Form->input('description', array('label' => 'Notes'));
echo $this->Form->input('name', array( 'value' => ['type_id']['category_id'] , 'type' => 'hidden'));
//echo $this->Form->input('cost');
// echo $this->Form->input('Tag');
?>
</fieldset>
Product controller add function
public function add() {
if ($this->request->is('post')) {
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$this->Session->setFlash(__('The product has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The product could not be saved. Please, try again.'));
}
}
$subcategories = $this->Product->Subcategory->find('list',array('order'=>'Subcategory.name asc'));
$categories = $this->Product->Category->find('list',array('order'=>'Category.name asc'));
$types = $this->Product->Type->find('list',array('order'=>'Type.name asc'));
$this->set(compact('subcategories', 'categories', 'types'));
}
In order to do it the way you are trying to do it, you would have to use client-side javascript to update the input value "on-the-fly", but that's not very safe and can easily be messed with. It would make much more sense to drop the name input altogether and just handle this in the beforeSave method of your Product model (or alternatively by defining the name value in your Controller just before saving).
public function beforeSave($options = array()) {
// Generate the name based on type and category
$this->data['Product']['name'] = $this->data['Product']['type_id'] .
$this->data['Product']['category_id'];
return true;
}
Update based on your comment.
In order to get the names, just find those names (assuming your models are associated) and define those:
public function beforeSave($options = array()) {
// Get the type name
$type = $this->Type->field('name', array(
// Set the condition for the field
'Type.id' => $this->data['Product']['type_id']
));
// Get the category name
$category = $this->Category->field('name', array(
// Set the condition for the field
'Category.id' => $this->data['Product']['category_id']
));
// Generate the name based on type and category
$this->data['Product']['name'] = $type . $category;
return true;
}