how to display result in view part in cakephp - cakephp

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;

Related

How to create search form from multiple tables cakePHP 3

In this issue I have 2 tables involved: jobs and areas.
I'm trying to create a search element which will be available on all views and contain a textfield for filtering rows by jobs title or jobs description and a droplist for filtering rows by areas and I want them to all work together.
So I created a search function on JobsController:
public function search()
{
if($this->request->data('area_select') != 'select area') {
$jobs = $this->Jobs
->find('all')
->contain(['Types', 'Categories' => function($q) {
return $q
->where([
'Jobs.title OR Jobs.description LIKE' =>
"%" . $this->request->data('keywords') . "%"
])
->where([
'Jobs.area LIKE' =>
"%" . $this->request->data('area_select') ."%"
]);
}]
);
} else {
$jobs = $this->Jobs
->find('all')
->contain(['Categories' => function($q) {
return $q->where([
'Jobs.title OR Jobs.description LIKE' =>
"%" . $this->request->data('keywords') . "%"
]);
}]
);
}
$this->set('jobs',$jobs);
}
it works good if I'm approaching to areas via jobs
<?php foreach($jobs as $job): ?>
<option><?php echo $job->area->name; ?></option>
<?php endforeach; ?>
the problem is that by accessing through jobs table it repeats the the same area as many times as the it appears in jobs table instead of only once...
so if I'm trying to get direct access like this:
<?php foreach($areas as $area): ?>
<option><?php echo $area->name; ?></option>
<?php endforeach; ?>
it is not working because I'm submitted to jobs controller.
How can I overcome this problem?

how to save select option value in database on cakephp

I wanna save a selected option in database in cakephp.
here is my add.ctp code
<?php
$options = array('0' => 'male', '1' => 'female');
echo $this->Form->select('gender', $options, array('escape' => false,'id'=>'gender'));
?>
and this is my action :
$user=$this->Users->newEntity();
if($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
print_r($user);
$this->Users->save($user);
}
But when I run it just the value 1 saved on database even I choose male.
please help.
The type of gender on database was bit I changed it to INT and every thing works correctly.

Codeigniter form populate with db results not working

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>

how give pagination to controllers

in controller
public function home($id=null){
$this->loadModel('Usermgmt.User');
if(isset($id)){
$groups=$this->User->findAllByuser_group_id($id);
$this->set('groups', $groups);
} else{
echo 'no id';
$users=$this->User->find('all');
$this->set('users', $users);
}
}
here i geeting value which matches the user_group_id and prints here i am geeting more then 10 users but i need to print only 5 on one page and need to give pagination how to give pagination here
view
<?php
if (!empty($groups)) {
// print_r($groups);
$sl=0;
foreach ($groups as $row1) {
//print_r($row1);
$sl++; ?>
<div style="width:100%;display:inline-block;">
<div style="float:left">
<?php
//echo $row1['id'];
echo $this->Html->link($this->Html->image('../files/user/photo/'.$row1 ['User']['photo_dir'].'/'.$row1 ['User']['photo'], array('width' => '180', 'height' => '180')),
array('controller'=>'Profiles','action'=>'index',$row1['User']['id']),
array('escape' => false));
?>
</div>
<div>
<?php echo h($row1['User']['first_name'])." ".h($row1['User']['last_name'])."</br>";
echo h($row1['User']['username'])."</br>";
echo h($row1['User']['email'])."</br>";
echo h($row1['User']['mobile'])."</br>";
echo h($row1['UserGroup']['name'])."</br>";
?></div>
<div style="clear:both;"></div>
</div>
<?php }
}?>
Call paginate
The equivalent paginate call to this:
$groups=$this->User->findAllByuser_group_id($id);
(incidentally - that should be findAllByUserGroupId) is this:
$groups = $this->paginate('User', array('user_group_id' => $id));
Changing default options
To achieve:
i need to print only 5 on one page
Modify the paginate property of your controller, e.g.:
class UsersController extends AppController {
public $paginate = array('limit' => 5);
function home($id = null) {
...
$conditions = array();
if ($id) {
$conditions['user_group_id'] = $id;
}
$groups = $this->paginate('User', $conditions);
...
}
}
View Modifications
In your view, the pagination helper, and the pagination information will automatically be available by calling paginate as shown above. To get pagination links use the pagination helper:
echo $this->Paginator->numbers();
See the documentation for more information and examples of using pagination.
As in cakephp pagination can be done using pagination helper of cakephp
In controller action use $this->paginate . From Model return all parameters like fields, conditions and so on in array format , so now in controller you will write
$data = $this->ModelName->functionname();
$currentPage = isset($_REQUEST['currentpage']) ? $_REQUEST['currentpage'] : '';
$this->paginate = array(
'fields' => $data['fields'],
'conditions' => $data['conditions'],
'order' => $data['order'],
'page' => $currentPage,
'limit' => 25
);
$currentPage is fetched from $_REQUEST['currentpage'];
and finally pass this data to Paginate Helper
$data = $this->paginate('ModelName');
Now in view you will use Pagination functions as shown below
<?php echo $this->Paginator->prev('revious'); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next'); ?>

Cakephp: combine input values to create hidden name input

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;
}

Resources