On my table it displays all the categories from my database
As you can see in image below there is a category id with 1
And there are two category with parent category id with 1 also
Question: If any categories have a parent category id that matches
another category have them display under that category.
Currently Table Looks Like
Model
public function get_categories() {
$data = array();
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $result) {
$data[] = array(
'category_id' => $result['category_id'],
'parent_category_id' => $result['parent_category_id'],
'name' => $result['name'],
'url' => $result['url'],
'status' => $result['status'],
'date_added' => $result['date_added'],
'category_delete' => anchor('admin/category/delete/' . $result['category_id'], 'Delete', array('class' => 'btn btn-danger btn-block')),
'category_edit' => anchor('admin/category/update/' . $result['category_id'], 'Edit', array('class' => 'btn btn-primary btn-block'))
);
}
} else {
return false;
}
return $data;
}
Controller
<?php
class Category extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$this->dynamic->set_title('Category');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'active' => '',
'href' => anchor('admin/dashboard', 'Home')
);
$data['breadcrumbs'][] = array(
'active' => 'class="active"',
'href' => 'Category'
);
$this->load->library('table');
$template = array(
'table_open' => '<table class="table table-striped table-bordered">',
'thead_open' => '<thead>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
$this->table->set_heading(array('Category ID', 'Parent ID', 'Category Name', 'Category URL', 'Category Status', 'Category Date Added', 'Category Delete', 'Category Edit'));
$this->table->set_template($template);
$data['categories'] = $this->table->generate($this->get_categories());
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$data['timeout'] = Modules::run('admin/common/timeout/index');
$data['navbar'] = Modules::run('admin/common/navbar/index');
$this->load->view('template/catalog/category_view', $data);
}
public function get_categories() {
$data = array();
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $result) {
$data[] = array(
'category_id' => $result['category_id'],
'parent_category_id' => $result['parent_category_id'],
'name' => $result['name'],
'url' => $result['url'],
'status' => $result['status'],
'date_added' => $result['date_added'],
'category_delete' => anchor('admin/category/delete/' . $result['category_id'], 'Delete', array('class' => 'btn btn-danger btn-block')),
'category_edit' => anchor('admin/category/update/' . $result['category_id'], 'Edit', array('class' => 'btn btn-primary btn-block'))
);
}
} else {
return false;
}
return $data;
}
}
Inside get categories function, add the order by call.
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$this->db->order_by('parent_category_id asc , category_id asc');
$query = $this->db->get();
Solution
I have had to use multiple foreach loop in model.
<?php
class Category_model extends CI_Model {
public function get_categories() {
$data = array();
// 1st level category
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$this->db->where('parent_id', '0');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $result) {
$data[] = array(
'name' => $result['name'],
'url' => $result['url'],
'status' => ($result['status']) ? 'Enabled' : 'Disabled',
'date_added' => $result['date_added'],
'category_delete' => anchor('admin/category/delete/' . $result['category_id'], 'Delete', array('class' => 'btn btn-danger btn-block')),
'category_edit' => anchor('admin/category/update/' . $result['category_id'], 'Edit', array('class' => 'btn btn-primary btn-block'))
);
// 2nd level category
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$this->db->where('sub_id', '0');
$this->db->where('parent_id', $result['category_id']);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$parent_category_name = $this->get_parent_category_name($result['parent_id']);
$data[] = array(
'name' => '<b>' . $parent_category_name->name . '</b>' . ' > '. $result['name'],
'url' => $result['url'],
'status' => ($result['status']) ? 'Enabled' : 'Disabled',
'date_added' => $result['date_added'],
'category_delete' => anchor('admin/category/delete/' . $result['category_id'], 'Delete', array('class' => 'btn btn-danger btn-block')),
'category_edit' => anchor('admin/category/update/' . $result['category_id'], 'Edit', array('class' => 'btn btn-primary btn-block'))
);
// 3rd level category
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category');
$this->db->where('sub_id', $result['category_id']);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$parent_category_name = $this->get_parent_category_name($result['parent_id']);
$sub_category_name = $this->get_parent_category_name($result['sub_id']);
$data[] = array(
'name' => '<b>' . $parent_category_name->name . '</b>' . ' > '. '<b>' . $sub_category_name->name . '</b>' . ' > '. $result['name'],
'url' => $result['url'],
'status' => ($result['status']) ? 'Enabled' : 'Disabled',
'date_added' => $result['date_added'],
'category_delete' => anchor('admin/category/delete/' . $result['category_id'], 'Delete', array('class' => 'btn btn-danger btn-block')),
'category_edit' => anchor('admin/category/update/' . $result['category_id'], 'Edit', array('class' => 'btn btn-primary btn-block'))
);
}
}
}
return $data;
} else {
return false;
}
}
public function get_parent_category_name($parent_category_id) {
$this->db->where('category_id', $parent_category_id);
$query = $this->db->get($this->db->dbprefix . 'category');
if ($query->num_rows() > 0) {
return $query->row();
} else {
return false;
}
}
public function get_sub_category_name($sub_category_id) {
$this->db->where('category_id', $sub_category_id);
$query = $this->db->get($this->db->dbprefix . 'category');
if ($query->num_rows() > 0) {
return $query->row();
} else {
return false;
}
}
}
Related
How can I do: I have 2 multi-select fields Select2, the first field for Branches, second for Workers.
When I choose branches, in second field I need to show Workers, who work in this branches.
View file
<label><?= $model->getAttributeLabel('branch') ?></label>
<?php echo Select2::widget([
'name' => 'branch',
'id' => 'branches',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => $branchList,
'options' => [
'placeholder' => Yii::t('app', 'Choose branch'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);?>
<label><?= $model->getAttributeLabel('Workers') ?></label>
<?php echo Select2::widget([
'name' => 'worker',
'id' => 'workers',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => [],
'options' => [
'placeholder' => Yii::t('app', 'Choose workers'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);
?>
JS
$("#branches").change(function(){
change();
});
function change() {
var selectValue = $("#branches").val();
$("#workers").empty();
$.post( "'.Yii::$app->urlManager->createUrl('constructor/lists?id=').'"+selectValue,
function(data){
$("#workers").html(data);
}
);
};
ConstructorController
public function actionLists($id)
{
if ($id != null) {
$ids = explode(",", $id);
foreach ($ids as $id_branch) {
$workers = Report::getWorkers($id_branch);
if (count($workers) > 0) {
foreach ($workers as $worker) {
echo "<option value='" . $worker . "'>" . $worker . "</option>";
}
} else {
echo "'<option>-</option>'";
}
}
}
}
i create image module and i edit image more then 1mb then can not show errormsg.
i used codigniter fremwork.
controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!empty($_FILES['agent_image']['name'])) {
if ($this->upload->do_upload('agent_image')) {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
} else {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
}
}
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
MY question: I edit image for particular user then image uploaded,but if image size more then 1mb ,then image can not upload and display error message.
so my question how to show errormsg.
$uploaded = $this->upload->do_upload('file'); //'file' is input field name
if($uploaded) {
$upload_data = $this->upload->data();
// do database stuff
} else {
$data['errors'] = array("error" => $this->upload->display_errors());
}
I am having a trouble on getting the value of the selected drop-down list(package_id) to populate the next fields particularly the Departure Time and Price which is in the Package Model.
Here is my code in View/Reservations/package.ctp:
<?php echo $this->Form->create('Reservation'); ?>
<table cellspacing="10">
<?php
echo $this->Html->tableCells(array(
array(
'Date: ',
$this->Form->input('date', array('label' => false, 'type' => 'text', 'class' => 'datepicker'))
),
array(
'Package Name:',
$this->Form->input('package_id', array('label' => false, 'options' => $name, 'id' => 'PackageID', 'empty' => '-- Select Package --'))
),
array(
'Departure Time:',
$this->Form->input('departure_time', array('label' => false, 'type' => 'label', 'id' => 'test'))
),
array(
'Price:',
$this->Form->input('price', array('label' => false, 'id' => 'test'))
),
array(
'Number of Person:',
$this->Form->input('number_of_people', array('label' => false))
),
array(
'Total Price:',
$this->Form->input('price', array('label' => false))
),
array(
'',
$this->Form->Submit('Book Now', array('class' => 'button'))
),
));
?>
</table>
and Here is my code in public function package():
$options = $this->Packages->find('list'); //or whatever conditions you want
$this->set('name', $options);
I was trying to use JS helper but I can't get it right here is my code:
$this->Js->get('#PackageID');
$this->Js->event('change',
$this->Js->request(array(
'controller'=>'Reservation',
'action'=>'getPackage'
), array(
'update'=> '#test',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
Feel free to ask questions for clarification. Thank You in advance :)
Try this :
in the view .ctp , add this js function :
<script language="JavaScript">
jQuery(document).ready(function() {
$("#PackageID").chosen().bind('change', function() {
$.post('/project_name/controller_name/listDeparetementByPackage/'+$(this).val(), function(data) {
$("#test").empty().append(data);
$("#test").trigger("liszt:updated");
}, 'html');
});
});
</script>
and in your controller , here is the function to get the departements by pacakge id :
function listDeparetementByPackage($package = null ) {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender = false;
$data = $this->Package->Departement->find('list', array('fields' => array('Departement.id', 'Departement.libelle'),
'conditions' => array('Departement.package_id' => $package),
'recursive' => 0 ));
if(count($data)>0){
foreach($data as $key => $val) {
echo "<option value=$key>$val</option>";
}
}else{
echo "<option></option>"; // if the result is empty , show a select empty
}
}
Hope it helps .
I'm very new to codeigniter.my question is after submitting billing and shipping address how to i redirect to paypal.I mean is there any way to redirect/form submission from controller.Below is my place order function in controller
function place_order()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('bill_first_name', 'First Name', 'trim|required');
$this->form_validation->set_rules('bill_last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'trim|required');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required');
if ($this->form_validation->run())
{
$data_to_store = array(
'bill_first_name' => $this->input->post('bill_first_name'),
'bill_last_name' => $this->input->post('bill_last_name'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'phone' => $this->input->post('phone'),
'country' => $this->input->post('country'),
'city' => $this->input->post('city'),
'zip' => $this->input->post('zip'),
'user_id' => $this->session->userdata('sess_user_id'),
'session_id' => $this->session->userdata('session_id'),
'create_date' => date('Y-m-d H:i:s')
);
$customer=$this->checkout_model->add_user('tbl_customer',$data_to_store);
if($customer){
$data = array(
'customer_id' => $customer,
'user_id' => $this->session->userdata('sess_user_id'),
'session_id' => $this->session->userdata('session_id'),
'create_date' => date('Y-m-d H:i:s')
);
$order=$this->checkout_model->add_user('tbl_order',$data);
if($order)
{
if ($cart = $this->cart->contents()):
foreach ($cart as $item):
$order_detail = array(
'order_id' => $order,
'product_id' => $item['id'],
'qty' => $item['qty'],
'product_price' => $item['price'],
'sub_total' => $item['qty'] * $item['price']
);
$cust_id = $this->checkout_model->add_user('tbl_order_details',$order_detail);
endforeach;
endif;
}
$this->cart->destroy();
}
paypallllllllllllllllllllllll
}
}
On the bottom of this page of the manual, you can find the redirect()-function (using the URL-helper).
--- EDIT ---
Maybe something like this (see this answer):
$query_data = array(
'business' => 'your-paypal-email-address',
'cmd' => '_xclick',
'item_name' => 'Order #' . $order,
'amount' => '100.00', // update with your total price
'shipping' => '10.00'
);
header('Location: https://www.paypal.com/cgi-bin/websrc/?' . http_build_query($query_data));
I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.