Cakephp 1.3 Set/Pass ID to the view - php

I have a table called Policy and a table called Declination. Policy hasMany Declination. Declination belongs to Policy. Now with that said, I am trying to save the ID of a policy in a field called Policy_id in the Declination table. Unfortunately, I'm having no luck. I believe I having trouble with my view. Let me explain what I am doing..in my controller I am reading 1 record and then setting the ID from that array to policy_id. Once I do that I send that variable to the view via set(). Once there I am using that variable in a hidden field. When I run my script there the data saves but the id does not populate. I have been stuck on this over 2 days and can't wrap my head around it! One thing I might add..I am passing the ID from that policy in via the URL. So the url looks something like localhost/site/add/xxxx-xxxx-xxxx. Im not sure if I should grab it from there or not. If I should can you explain or point me somewhere as to where I can learn. If I shouldn't please inform me as to why not. Thanks!
Model
<?php
class Declination extends AppModel {
public $name = 'Declination';
public $virtualFields = array(
'name' => 'CONCAT(Declination.first_name,\' \',Declination.last_name)'
);
public $belongsTo = array(
'Policy' => array(
'className' => 'Policy',
'foreignKey' => 'policy_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Reason' => array(
'className' => 'Reason',
'foreignKey' => 'reason_id'
),
'ContactType' => array(
'className' => 'ContactType',
'foreignKey' => 'contact_type_id'
)
);
public function beforeSave() {
if (array_key_exists('dated', $this->data[$this->alias]) && !empty($this->data[$this->alias]['dated'])) {
$this->data[$this->alias]['dated'] = date('Y-m-d', strtotime($this->data[$this->alias]['dated']));
}
if(array_key_exists('reason_id', $this->data[$this->alias])) {
if (!$this->Reason->isOther($this->data[$this->alias]['reason_id'])) {
$this->data[$this->alias]['other'] = null;
}
}
return true;
}
Controller
class DeclinationsController extends AppController {
public $name = 'Declinations';
/**
* add function.
*
* #access public
* #param mixed $id (default: null)
* #return void
*/
public function add($id = null) {
if (!empty($this->data)) {
$this->loadmodel('Policy');
$policy = $this->Policy->read('id', $id);
$policy_id = $policy['Policy']['id'];
$this->Declination->create();
if ($this->Declination->saveAll($this->data['Declination'])) {
$this->Session->setFlash(__('Declinations saved.', true));
$this->redirect(array(
'controller' => 'coverages',
'action' => 'view',
$id
));
} else {
$this->Session->setFlash(__('Declinations failed to save.', true));
}
}
$reasons = $this->Declination->Reason->find('list');
$contactTypes = $this->Declination->ContactType->find('list');
$this->set(compact('id', 'reasons', 'contactTypes', '$policy_id'));
}
View
<?php echo $this->Ui->widgetHeader(__('Policy Declinations', true)); ?>
<?php $this->Ui->widgetContent(); ?>
<?php echo $this->UiForm->create('Declination', array(
'url' => array(
'controller' => 'declinations',
'action' => 'add',
$id
)
)); ?>
<?php for ($i = 0; $i < 3; $i++): ?>
<h4>Declination <?php echo ($i + 1); ?></h4>
<?php echo $this->UiForm->create("Declination.{$i}.policy_id", array('type' => 'hidden', 'value' => '$policy_id')); ?>
<?php echo $this->UiForm->input("Declination.{$i}.first_name"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.last_name"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.company"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.contact_type_id"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.phone_number"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.reason_id"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.other", array(
'label' => 'If other, please supply a reason'
)); ?>
<?php echo $this->UiForm->input("Declination.{$i}.dated", array(
'type' => 'text',
'readonly' => 'readonly',
'data-datepicker' => ''
)); ?>
<?php endfor; ?>
<?php echo $this->UiForm->end('Continue'); ?>
<?php echo $this->Ui->widgetContentEnd(); ?>

I'm guessing UiForm is a custom helper of some sort. If it's similar to the Form helper, then it looks like an error in your create statement. It should be:
<?php echo $this->UiForm->create('Declination'); ?>
<?php echo $this->UiForm->input("Declination.{$i}.policy_id", array('type' => 'hidden', 'value' => '$policy_id')); ?>

I figured it out. I grabbed the $id variable that was in my view and set it as my value. So in stead of my value being $policy_id....it is $id. I also deleted some things out of my controller that I did not need. Please see below. Hope this helps someone!
View
<?php echo $this->Ui->widgetHeader(__('Policy Declinations', true)); ?>
<?php $this->Ui->widgetContent(); ?>
<?php echo $this->UiForm->create('Declination', array(
'url' => array(
'controller' => 'declinations',
'action' => 'add',
$id
)
)); ?>
<?php for ($i = 0; $i < 3; $i++): ?>
<h4>Declination <?php echo ($i + 1); ?></h4>
<?php echo $this->UiForm->create('Declination'); ?>
<?php echo $this->UiForm->input("Declination.{$i}.policy_id", array('type' => 'hidden', 'value' => $id)); ?>
<?php echo $this->UiForm->input("Declination.{$i}.first_name"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.last_name"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.company"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.contact_type_id"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.phone_number"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.reason_id"); ?>
<?php echo $this->UiForm->input("Declination.{$i}.other", array(
'label' => 'If other, please supply a reason'
)); ?>
<?php echo $this->UiForm->input("Declination.{$i}.dated", array(
'type' => 'text',
'readonly' => 'readonly',
'data-datepicker' => ''
)); ?>
<?php endfor; ?>
<?php echo $this->UiForm->end('Continue'); ?>
<?php echo $this->Ui->widgetContentEnd(); ?>
Controller
public function add($id = null) {
if (!empty($this->data)) {
$this->Declination->create();
if ($this->Declination->saveAll($this->data['Declination'])) {
$this->Session->setFlash(__('Declinations saved.', true));
$this->redirect(array(
'controller' => 'policies',
'action' => 'view',
$id
));
} else {
$this->Session->setFlash(__('Declinations failed to save.', true));
}
}
$reasons = $this->Declination->Reason->find('list');
$contactTypes = $this->Declination->ContactType->find('list');
$this->set(compact('id', 'reasons', 'contactTypes'));
}

Related

codeigniter update error: Invalid argument supplied for foreach()

I'm a bit confused about this error when I am updating the data. Can anyone help me with this? My codes are the following:
Controller:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
public function student_update_info($id, $data)
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
My View ( edit page )
<?php echo form_open('student_update/student_update_info');
$data = array(
'id' => 'input',
'name' => 'hid',
'value' => $single_student['student_id']
);
echo form_hidden($data);
echo form_label('First Name: ', 'first');
$data = array(
'id' => 'input',
'name' => 'first',
'placeholder' => 'Enter First Name',
'value' => $single_student['student_fname']
);
echo form_input($data);
echo form_label('Last Name: ', 'last');
$data = array(
'id' => 'input',
'name' => 'last',
'placeholder' => 'Enter Last Name',
'value' => $single_student['student_lname']
);
echo form_input($data);
echo form_label('Male ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'checked' => 'checked',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo form_label('Female ', 'gender');
$data = array(
'id' => 'radio',
'name' => 'gender',
'value' => $single_student['student_gender']
);
echo form_radio($data);
echo "<br />";
echo form_label('Course', 'course');
$data = array(
'id' => 'input',
'name' => 'course',
'placeholder' => 'Enter Student Course',
'value' => $single_student['student_course']
);
echo form_input($data);
echo form_label('Company', 'company');
$data = array(
'id' => 'input',
'name' => 'company',
'placeholder' => 'Enter Company Name',
'value' => $single_student['student_company']
);
echo form_input($data);
$data = array(
'id' => 'update',
'name' => 'update',
'value' => 'Update'
);
echo form_submit($data);
echo form_close(); ?>
My View ( list of data )
<?php foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } ?>
And this error occurs
error message
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view_student_list.php
Line Number: 27
Can anyone help me solve this problem?
Please check if any value is present in your variable $results This error comes only when there is no value in the variable with foreach loop.
To avoid these situations always use :
<?php if($results && !empty($results)){ foreach ($results as $row) { ?>
<tr>
<td><?php echo $row->student_fname . " " . $row- >student_lname; ?></td>
<td><?php echo $row->student_course; ?></td>
<td><?php echo $row->student_company; ?></td>
<td>delete
update
</td>
</tr>
<?php } } ?>
Also your result variable will not contain any data to loop since your method update_students does not returns anything.
The main reason you are not getting any results back from your update method is because you are not returning anything.
Secondly, I would change your get_student_id() method as it doesn't quite fit with MVC principals. It works for this particular task, however, you should really be getting the uri value in the controller and then passing it through to your model:
Controller method:
public function show_student($id)
{
$data['single_student'] = $this->student_view_model->get_student_id($id);
$this->load->view('view_student_update', $data);
}
Assuming that "show_student" would be the 2nd uri segment you can do the above.
Model method:
public function get_student_id($id)
{
$query = $this->db->get_where('tbl_student', array('student_id' => $id));
return $query->row_array();
}
This way you can get the row for the student without depending on the student_id always being the 3rd uri segment.
So, with you're results method, you could:
Controller Meothod
public function update_student()
{
$data = array(
'student_fname' => $this->input->post('first'),
'student_lname' => $this->input->post('last'),
'student_gender' => $this->input->post('gender'),
'student_course' => $this->input->post('course'),
'student_company' => $this->input->post('company')
);
$data['results'] = $this->student_view_model->update_student($this->input->post('hid'), $data);
$this->load->view('view_student_list', $data);
}
Model Method:
public function update_student($id, $data)
{
$this->db->where('student_id', $id);
$this->db->update('tbl_student', $data);
return $this->get_student_id($id);
}
Again, with models you should always pass data to them (for quite a few reasons)!
Lastly, I would also think about change the name of get_student_id() to something like get_student_by_id or get_student as get_student_id() suggests t me that you are just going to be getting the id. Also, you really should look at using the Form Validation in codeigniter as your code is very, Very vulnerable at the minute.
Hope this helps!

CakePHP 1.2 pagination link is disabled

In my CakePHP application, my custom pagination is not working at all. There are three problems I'm facing:
It's always showing only a single page
Links are disabled
Ending record is incorrect. I have total 7 records. I used LIMIT 3, so only 3 records should be visible per page, the last record being record no. 3 in the first page. But instead, record no. 7 is being displayed as the ending record in the first page.
I have set debug mode to 2 to try to find out any problems that may exist in my code. But was unable to find any.
Here's my controller code:
var $name = 'HomeLoanDistributions';
function index() {
$user = $this->Session->read('User');
$user_role = $user['User']['user_role_id'];
$actions = $this->Session->read('actions');
$display_actions = array();
foreach ($actions as $action) {
array_push($display_actions, $action['pm_controller_actions']['name']);
}
$this->set('display_actions', $display_actions);
$this->set('user_role', $user_role);
$branch_id = $this->branchCheck();
$this->set('branch_id', $branch_id);
$conditions = array('branch_id' => $branch_id);
$this->set('HomeLoanDistributions', $this->paginate($conditions));
$this->HomeLoanDistribution->Branch->recursive = 0;
$this->set('BranchInformation', $this->HomeLoanDistribution->Branch->read(array('Branch.id', 'Branch.name', 'Region.name', 'District.name', 'SubDistrict.name', 'Cluster.name'), $branch_id));
}
function branchCheck() {
// check for matching branch
if (isset($this->params['named']['branch_id'])) {
if (empty($this->params['named']['branch_id'])) {
$this->Session->setFlash(__('Branch could not be found. Please, try again.', true));
$this->redirect(array('controller' => 'Branches', 'action' => 'index', $this->name));
} else {
$this->HomeLoanDistribution->Branch->recursive = -1;
if ($this->HomeLoanDistribution->Branch->find('count', array('conditions' => array('Village.id' => $this->params['named']['branch_id']))) != 1) {
$this->Session->setFlash(__('The Branch could not be found. Please, try again.', true));
$this->redirect(array('controller' => 'Branches', 'action' => 'index', $this->name));
}
}
return $this->params['named']['branch_id'];
}
}
Here's my model code:
var $name = 'HomeLoanDistribution';
var $actsAs = array('Logable' => array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list', // options are 'list' or 'full'
'description_ids' => TRUE // options are TRUE or FALSE
));
var $validate = array(
'entry_date' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
),
'branch_id' => array('numeric'),
'customer_id' => array('numeric'),
'home_group_id' => array('numeric'),
'voucher_no' => array('numeric'),
'no_of_installment' => array('numeric'),
'loan_amount' => array('numeric'),
'service_charge' => array('numeric'),
'security' => array('numeric'),
'loan_taken_term' => array('numeric'),
'installment_amount' => array('numeric'),
'installment_service_charge' => array('numeric'),
'effective_date' => array('numeric'),
);
var $belongsTo = array(
'Branch' => array(
'className' => 'Branch',
'foreignKey' => 'branch_id',
'conditions' => '',
'fields' => 'id,name',
'order' => ''
),
);
function paginate($conditions, $fields, $order, $page = 1, $recursive = null, $extra = array()) {
$recursive = 0;
$fields = array('entry_date');
$group = array('branch_id');
$order = array('entry_date DESC');
$limit = 3;
return $this->find('all', compact('fields', 'order', 'limit', 'page', 'recursive', 'group'));
$this->paginateCount($conditions);
}
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$recursive = 0;
$fields = array('entry_date');
$group = array('branch_id');
$order = array('entry_date DESC');
$results = $this->find('all', compact('fields', 'order', 'limit', 'page', 'recursive', 'group'));
return count($results);
}
And my view codes:
<?php echo $this->renderElement('BranchInformation'); ?>
<?php
$paginator->options(
array(
'url' => array('controller' => 'HomeLoanDistributions', 'action' => $this->action, 'branch_id' => $BranchInformation['Branch']['id'])));
?>
<h2><?php __('Home Loan Distribution'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo 'SL NO.'; ?></th>
<th><?php echo $paginator->sort('Loan Distribution Month', 'entry_date'); ?></th>
<th class="actions"><?php __('Actions'); ?></th>
<!--th class="actions"><--?php __('Actions');?></th-->
</tr>
<?php
$start = (int) $paginator->counter('%start%');
$i = 0;
foreach ($HomeLoanDistributions as $HomeLoanDistribution):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class; ?>>
<td>
<?php echo $start++; ?>
</td>
<td class="taRight">
<?php
$returnDate = date_format(date_create($HomeLoanDistribution['HomeLoanDistribution']['entry_date']), "M-Y");
print_r($returnDate);
?>
</td>
<td class="actions">
<?php echo $html->link(__('View', true), array('action' => 'view', $HomeLoanDistribution['HomeLoanDistribution']['entry_date'], 'branch_id' => $BranchInformation['Branch']['id'])); ?>
<?php echo $html->link(__('Edit', true), array('action' => 'edit', $HomeLoanDistribution['HomeLoanDistribution']['entry_date'], 'branch_id' => $BranchInformation['Branch']['id'])); ?>
<?php echo $html->link(__('Delete', true), array('action' => 'delete', $HomeLoanDistribution['HomeLoanDistribution']['entry_date'], 'branch_id' => $BranchInformation['Branch']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $HomeLoanDistribution['HomeLoanDistribution']['entry_date'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="paging">
<?php echo $paginator->prev('<< ' . __('previous', true), array(), null, array('class' => 'disabled')); ?>
<?php echo $paginator->numbers(); ?>
<?php echo $paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled')); ?>
<span style="float:right;"><?php
echo $paginator->counter(array(
'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)
));
?></span>
</div>
My CakePHP version is 1.2.5 and my PHP version is 5.2.11, since this is a very old project back from 2008-09.
When he called:
$this->set('HomeLoanDistributions', $this->paginate($conditions));
I think he used : http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
and $limit should be passed in configuration of PaginationComponent .. isnt it ?
does there are $paginate var in AppController or in this one ?
Edit : try use paginate from your MOdel :
Change
$this->set('HomeLoanDistributions', $this->paginate($conditions));
by
$this->set('HomeLoanDistributions', $this->HomeLoanDistribution->paginate($conditions) );

Connecting Radio Button to Database using CodeIgniter

I got trouble inputing the radio button value to database, when i choose "submit" it won't add into database. This is the form view:
<?php
$form = array(
'no pengujian' => array(
'name' => 'NO_PENGUJIAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_PENGUJIAN', isset($form_value['NO_PENGUJIAN']))),
'id kendaraan' => array(
'name' => 'ID_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('ID_KENDARAAN', isset($form_value['ID_KENDARAAN']))),
'no kendaraan' => array(
'name' => 'NO_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_KENDARAAN', isset($form_value['NO_KENDARAAN']))),
'lampu' => array(
'name' => 'LAMPU',
'size' => '30',
'class' => 'radio',
'value' => set_value('LAMPU', isset($_POST['LAMPU']))),
'submit' => array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Simpan'
)
);
?>
<h2><?php echo $breadcrumb ?></h2>
<!-- pesan start -->
<?php if (! empty($pesan)) : ?>
<div class="pesan">
<?php echo $pesan; ?>
</div>
<?php endif ?>
<!-- pesan end -->
<!-- form start -->
<?php echo form_open($form_action); ?>
<p>
<?php echo form_label('No Pengujian', 'NO_PENGUJIAN'); ?>
<?php echo form_input($form['no pengujian']); ?>
</p>
<?php echo form_error('NO_PENGUJIAN', '<p class = "field_error">', '</p>');?>
<p>
<?php echo form_label('Id Kendaraan', 'ID_KENDARAAN'); ?>
<?php echo form_input($form['id kendaraan']); ?>
</p>
<?php echo form_error('ID_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('No Kendaraan', 'NO_KENDARAAN'); ?>
<?php echo form_input($form['no kendaraan']); ?>
</p>
<?php echo form_error('NO_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('Lampu', 'LAMPU'); ?>
<input type ="radio" name = "lulus" value="Lulus"/> Lulus
<input type ="radio" name = "lulus" value= "Gagal"/> Gagal
</p>
<p>
<?php echo form_submit($form['submit']); ?>
<?php echo anchor('pengujian', 'Batal', array('class' => 'cancel')) ?>
</p>
<?php echo form_close(); ?>
This is the controller (tambah is "insert" function to database)
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class Pengujian extends MY_Controller
{
public $data = array(
'modul' => 'pengujian',
'breadcrumb' => 'Pengujian',
'pesan' => '',
'pagination' => '',
'tabel_data' => '',
'main_view' => 'view_pengujian/pengujian_view',
'form_action' => '',
'form_value' => '',
'option_uji' => '',
);
public function __construct()
{
parent::__construct();
$this->load->model('Pengujian_model', 'pengujian', TRUE);
$this->load->helper('form');
//$this->load->model('Penguji_model', 'penguji', TRUE);
}
public function index($offset = 0)
{
$this->session->unset_userdata('no_pengujian_sekarang', '');
$pengujian = $this->pengujian->cari_semua($offset);
if ($pengujian)
{
$tabel = $this->pengujian->buat_tabel($pengujian);
$this->data['tabel_data'] = $tabel;
$this->data['pagination'] = $this->pengujian->paging(site_url('pengujian/halaman'));
}
else
{
$this->data['pesan'] = 'Tidak ada data pengujian';
}
$this->load->view('template', $this->data);
}
public function tambah()
{
$this->data['breadcrumb'] = 'Pengujian > Tambah';
$this->data['main_view'] = 'view_pengujian/pengujian_form';
$this->data['form_action'] = 'pengujian/tambah';
//$penguji = $this->penguji->cari_semua();
//if($penguji)
//{
// foreach($penguji as $row)
// {
// $this->data['option_pengujian'][$row->id_penguji] = $row->penguji;
//}
//}
//else
//{
$this->data['option_pengujian']['00'] = '-';
// $this->data['pesan'] = 'Data penguji tidak tersedia. Silahkan isi dahulu data penguji.';
// if submit
if($this->input->post('submit'))
{
if($this->pengujian->validasi_tambah())
{
if($this->pengujian->tambah())
{
$this->session->set_flashdata('pesan', ' Proses tambah data berhasil');
redirect('pengujian');
}
else
{
$this->data['pesan'] = 'Proses tambah data gagal';
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
This is the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Pengujian_model extends CI_Model
{
public $db_tabel ='pengujian';
public $per_halaman = 100;
public $offset = 0;
public function cari_semua($offset = 0)
{
if (is_null($offset) || empty($offset))
{
$this->offset = 0;
}
else
{
$this->offset = ($offset * $this->per_halaman) - $this->per_halaman;
}
return $this->db->select('NO_PENGUJIAN, ID_KENDARAAN, NO_KENDARAAN, LAMPU, EMISI, REM, WAKTU_UJI')
->from($this->db_tabel)
->limit($this->per_halaman, $this->offset)
->order_by('NO_PENGUJIAN', 'ASC')
->get()
->result();
}
public function buat_tabel($data)
{
$this->load->library('table');
$tmpl = array('row_alt_start' => '<tr class="zebra">');
$this->table->set_template($tmpl);
$this->table->set_heading('No', 'No Pengujian', 'Id Kendaraan', 'No Kendaraan', 'Lampu','Emisi','Rem', 'Waktu Uji', 'Aksi');
$no = 0 + $this->offset;
foreach ($data as $row)
{
$this->table->add_row(
++$no,
$row->NO_PENGUJIAN,
$row->ID_KENDARAAN,
$row->NO_KENDARAAN,
$row->LAMPU,
$row->EMISI,
$row->REM,
$row->WAKTU_UJI,
anchor('pengujian/edit/'.$row->NO_PENGUJIAN,'Edit',array('class' => 'edit')).' '.
anchor('pengujian/hapus/'.$row->NO_PENGUJIAN,'Hapus',array('class' => 'delete','onclick'=>"return confirm('Anda yakin menghapus data ini?')")));
}
$tabel = $this->table->generate();
return $tabel;
}
public function paging($base_url)
{
$this->load->library('pagination');
$config = array(
'base_url' => $base_url,
'total_rows' => $this->hitung_semua(),
'per_page' => $this->per_halaman,
'num_links' => 4,
'use_page_number' => TRUE,
'first link' => '|< First',
'last link' => 'Last >|',
'next link' => 'Next >',
'prev_link' => '< Prev',
);
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function hitung_semua()
{
return $this->db->count_all($this->db_tabel);
}
private function load_form_rules_tambah()
{
$form = array(
array(
'field' => 'NO_PENGUJIAN',
'label' => 'no pengujian',
'rules' => 'required'
),
array(
'field' => 'ID_KENDARAAN',
'label' => 'id kendaraan',
'rules' => 'required'
),
array(
'field' => 'NO_KENDARAAN',
'label' => 'no kendaraan',
'rules' => 'required'
),
array(
'field' => 'LAMPU',
'label' => 'lampu',
'rules' => 'required'
),
);
return $form;
}
public function validasi_tambah()
{
$form = $this->load_form_rules_tambah();
$this->form_validation->set_rules($form);
if($this->form_validation->run())
{
return TRUE;
}
else
{
return FALSE;
}
}
public function tambah()
{
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I got no trouble in the formfield. The trouble is the radio button "lampu"
The best thing to do, I think, is to check where it's going wrong. I usually do this, in this case, by checking if the value is being passed back to the controller and model. This way you understand better what's going on inside your code. Do something like this:
In the model:
public function tambah()
{
// Check to see if we get a value. If not, do the same in the controller
var_dump($this->input->post('lampu'));
exit;
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I hope this helps a bit....

yii ajax depedent dropdown issue

i am working on ajax dependent dropdown its working fine but one issue is there ,the dropdownn which is dependendent on another dropdown has a prompt ----- "select".but when the parent dropdown is selected the prompt in dependent dropdown disapppears and is filled with the related data,i want that the prompt should be present there and user should select from dropdown.
right now by difault first data is selected
view form code
<div class="row">
php echo $form->labelEx($model, 'quarter'); ?>
<?php
$options = array(1 => 'First', 2 => 'Second', 3 => 'Third', 4 => 'Fourth');
$curMonth = date("m", time());
$curQuarter = ceil($curMonth/3);
$qr = array();
$qr[$curQuarter] = $options[$curQuarter];
$qr[$curQuarter-1] = $options[$curQuarter-1];
echo $form->dropDownList($model, 'quarter', $qr,array(
'prompt' => 'Select a quarter',
ajax' => array(
'type' => 'POST',
'url' => Yii::app()->controller->createUrl('dynamicProjectUserRoles'),
'update' => '#A2fs_role_id'
)
)) ?>
<?php echo $form->error($model, 'quarter'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'role_id'); ?>
<?php echo $form->dropDownList($model, 'role_id', array(),array(
'prompt' => 'Select a role',
'ajax' =>array(
'type' => 'POST',
'url' => Yii::app()->controller->createUrl('questions'),
'update' => '#ques'
)
)); ?>
<?php echo $form->error($model, 'role_id'); ?>
</div>
// Controller code
public function actionDynamicProjectUserRoles() {
$project_id = $_POST['A2fs']['project_id'];
$quarter = $_POST['A2fs']['quarter'];
$employee = $_POST['A2fs']['employee_id'];
//$this->pr($project_id);
$id = $this->getEmployeeId($employee);
$conditon = $this->getQuarterDate($quarter);
// find roles of partcular employee
$q = "SELECT role_id FROM employee_project_role WHERE employee_id=$id AND project_id = $project_id and $conditon ";
$cmd = Yii::app()->db->createCommand($q);
//$result = $cmd->queryRow();
$role = $cmd->queryAll();
foreach ($role as $r){
$criteria = new CDbCriteria();
$criteria = array(
'select' => 'role',
'condition' => 'id=:id',
'params' => array(
':id' => $r['role_id']
)
);
$name = Role::model()->find($criteria);
echo CHtml::tag('option',
array(),CHtml::encode($name->role),true);
}
}
This is how it works - it renders the whole element by given ID. Just add
echo CHtml::tag('option', array('value' => ''), 'Select a role', true);
before
foreach ($role as $r){
in controller file.

ZF2 Dynamic Menu with Zend\Navigation\Navigation

I want ask you about this problem.
What do i need to create Dynamic Menu with Zend\Navigation\Navigation?
In ZF1 i made like this:
$container = new Zend_Navigation();
$pages = array(
array(
'label' => 'Save',
'action' => 'save',
),
array(
'label' => 'Delete',
'action' => 'delete',
),
);
// add two pages
$container->addPages($pages);
and then in view:
$this->navigation()->menu();
But in ZF2 pages are taking from config.
Now i create \config\autoload\nav.global.php and here create page array. But i need to do page array in method and send it into navigation helper, but ii dont know how ((
i tried to do this in my controller:
use Zend\Navigation\Navigation;
$pages =array(
// All navigation-related configuration is collected in the 'navigation' key
'navigation' => array(
// The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
'default' => array(
// And finally, here is where we define our page hierarchy
'account' => array(
'label' => 'faq',
'route' => 'faq',
'pages' => array(
'news' => array(
'label' => 'news',
'route' => 'news',
),
'manual' => array(
'label' => 'manual',
'route' => 'manual',
),
),
),
),
),
);
$Menu = new Navigation($pages);
and then this in view:
$this->Menu()->menu();
but i have a lot of mistakes...
i think you understand my problem.
please help.
sorry for my english.
Follow these easy steps to create the multilevel menu dynamically Step
1:create a partial menu.phtml file and save it in layout folder or the
module,eg application/view/layout/menu.phtml
<ul id="menu" >
<?php foreach ($this->container as $page): ?>
<li <?= $page->isActive()? 'class="active"' : 'class="drop"' ?>>
<?php echo $this->navigation()->menu()->htmlify($page). PHP_EOL ?>
<div class="dropdown_2columns" >
<?php foreach ($page as $catpage) :?>
<div class="col_1" >
<h3 <?= $page->isActive()? 'class="active"' : 'class="drop"' ?> >
<?= $this->navigation()->menu()->htmlify($catpage). PHP_EOL ?>
</h3>
<ul >
<?php foreach ($catpage as $subpage) :?>
<li <?= $subpage->isActive()? 'class="active"' : 'class="drop"' ?>>
<?= $this->navigation()->menu()->htmlify($subpage). PHP_EOL ?>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
</div><!-- End dropdown container -->
</li>
<?php endforeach; ?>
</ul>
Step 2 in your module.php
public function getServiceConfig()
{
return array(
'initializers' => array(
function ($instance, $sm) {
if ($instance instanceof \Zend\Db\Adapter\AdapterAwareInterface) {
$instance->setDbAdapter($sm->get('Zend\Db\Adapter\Adapter'));
}
}
),
'invokables' => array(
'menu' => 'Application\Model\MenuTable',
),
'factories' => array(
'Navigation' => 'Application\Navigation\YourNavigationFactory'
)
);
}
in src/navigation folder in your module create YourNavigation.php and
YourNavigationFactory.php
namespace Application\Navigation;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Navigation\Service\DefaultNavigationFactory;
use Admin\Model\Entity\Tablepages;
class YourNavigation extends DefaultNavigationFactory
{
protected function getPages(ServiceLocatorInterface $serviceLocator)
{
if (null === $this->pages) {
$fetchMenu = $serviceLocator->get('menu')->fetchAll();
$configuration['navigation'][$this->getName()] = array();
foreach($fetchMenu as $key=>$row)
{
$subMenu = $serviceLocator->get('menu')->fetchAllSubMenus($row['id']);
if($subMenu){
$pages = array();
foreach($subMenu as $k=>$v)
{
foreach($v as $field=>$value){
$page['label'] =$value['heading'];
$page['route'] = 'visas';
if ($value['path'] == $row['path']){
$page['params'] = array('action'=>'index',
'category'=> $this->$row['path'],
);
}
$subCatMenu = $serviceLocator->get('menu')->fetchAllSubCatMenus($value['id']);
$subcatpages = array();
$subcatgroup = array();
$group = array();
if($subCatMenu>0){
foreach($subCatMenu as $k=>$v)
{
foreach($v as $field=>$value1){
$subpage['label'] =$value1['heading'];
$subpage['route'] = 'visas';
if ($value['path'] ==$row['path']){
$subpage['params'] = array('action'=>'index',
'category'=> $row['path'],
'sub_category'=> $value1['path']);
}elseif($row['id'] ==76){
$subpage['params'] = array('action'=>'index',
'category'=>$value['path'],
'sub_category'=>$value1['path']);
}else{
$subpage['params'] = array('action'=>'index',
'category'=> $row['path'],
'sub_category'=> $value['path'],
'id'=> $value1['path']);
}
}
$group[] =$subpage;
}
$page['pages'] =$group;
$pages[] =$page;
}
}
}
}
$configuration['navigation'][$this->getName()][$row['name']] = array(
'label' => $row['name'],
'route' => 'visas',
'params' => array(
'action' => 'index',
'category' => $row['path'],
),
'pages' => $pages,
);
}
if (!isset($configuration['navigation'])) {
throw new Exception\InvalidArgumentException('Could not find navigation configuration key');
}
if (!isset($configuration['navigation'][$this->getName()])) {
throw new Exception\InvalidArgumentException(sprintf(
'Failed to find a navigation container by the name "%s"',
$this->getName()
));
}
$application = $serviceLocator->get('Application');
$routeMatch = $application->getMvcEvent()->getRouteMatch();
$router = $application->getMvcEvent()->getRouter();
$pages = $this->getPagesFromConfig($configuration['navigation'][$this->getName()]);
$this->pages = $this->injectComponents($pages, $routeMatch, $router);
}
return $this->pages;
}
}
YourNavigationFactory.php
namespace Application\Navigation;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class YourNavigationFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$navigation = new MyNavigation();
return $navigation->createService($serviceLocator);
}
}
in your layout.phtml
<?php echo $this->navigation('navigation')->menu()->setPartial('menu')->render(); ?>
to create dynamic sitemap from navigation
$this->navigation('navigation')
->sitemap()
->setUseXmlDeclaration(false)
->setServerUrl('http://www.yourdomain.com')
->setFormatOutput(true);?>
echo $this->navigation()->menu()->setMinDepth(null)->setMaxDepth(null)->setOnlyActiveBranch(false)->setRenderInvisible(true);
to create breadcrumbs
echo $this->navigation()
->breadcrumbs()
->setLinkLast(true)
->setMaxDepth(1)
->setSeparator(' ▶' . PHP_EOL);
I Hope it helps you to save your time
For some backgrounds you might read this answer on another, but similar question regarding Zend\Navigation. The point is you want MVC pages and MVC pages in Zend Framework 2 need a way to assemble the url and find our if the url is active or not.
Every MVC page has a route name. The route stack routes the request and gets a route match. You must inject this route match into the navigation, so every page could check its own route against the matched one.
Similar for the url assembly. If you want to convert the route name into an url, you need the route stack ('router'). Inject the router in your application too and you are able to assemble.
In short:
use Zend\Navigation\Service\ConstructedNavigationFactory;
class MyController extends AbstractActionController
{
public function indexAction()
{
$config = array(
// your config here
);
$factory = new ConstructedNavigationFactory($config);
$navigation = $factory->createService($this->getServiceLocator());
return new ViewModel(array(
'navigation' => $navigation;
));
}
}
And similar as above answer, in your view:
<?php echo $this->navigation($navigation)->menu()?>
My previous answer is not correct. The following code works. For one page. In controller, edit action:
$page = new \Zend\Navigation\Page\Mvc(array(
'route' => 'application/default',
'controller' => 'album',
'action' => 'edit',
'use_route_match' => true,
));
$r = $this->getEvent()->getRouter();
$rm = $this->getEvent()->getRouteMatch();
$page->setRouter($r);
$page->setRouteMatch($rm);
echo $page->isActive() ? 'true' : 'false'; // true
echo $page->getHref(); // /test_app/public/application/album/edit/id1
You need to do so
In the controller
$pages = new \Zend\Navigation\Page\Mvc(array(
'pages'=>
array(
'album' => array(
'label' => 'Album3',
'controller' => 'album',
'action' => 'edit',
'params' => array('id'=>2),
'route' => 'album/default',
)
)
));
$navigation = new \Zend\Navigation\Navigation();
$serviceLocator = $this->getServiceLocator()->get('Application');
$routeMatch = $serviceLocator->getMvcEvent()->getRouteMatch();
$router = $serviceLocator->getMvcEvent()->getRouter();
$pages->setRouteMatch($routeMatch);
$pages->setDefaultRouter($router);
$navigation->addPage($pages);
In view
<?php echo $this->navigation($this->navigation)->menu() ?>
Eremite answer is not really wrong. I have tested all the recommendations given here and actually when the default route have several child_routes mark as default, menus doesn't mark the active flag correctly. So it is needed to pass the matched route as a parameter. But perhaps I'm doing something wrong.
Cheers

Categories