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) );
Related
I have a Pjax container in which i want to load either books or authors.My active form has two tabs by which i choose what to load. I tested my sql in phpmyadmin and they are ok(returns what expected). Tried to var_dump after each row of my controller but it seems to be ok also. But when i comes to the 'magic of the pjax' the page get reloaded. There is no errors in the console log. The response from the request in the Network tab returns the whole html. Can you take a look and give and advance?
Controller action:
public function actionSingleGenre(){
$first_step = Yii::$app->getRequest()->getQueryParam('first_step');
$second_step = Yii::$app->getRequest()->getQueryParam('second_step');
$id = end(explode('-', $second_step));
$genresPage = Page::findOne(76);
$booksPage = Page::findOne(45);
$authorsPage = Page::findOne(46);
$lang = Lang::getCurrent();
$genre = Brands::findOne($id);
$banner = CategoryImage::find()->where(['page_id' => $genresPage->id])->one();
$pageSize = 12;
$entity = 'book';
$sql = "SELECT *
FROM `product` as p
LEFT JOIN `productLang` as pl ON p.`id`=pl.`product_id`
LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
WHERE bb.`brand_id`=$id";
if(Yii::$app->request->isPjax){
if(isset($_GET['type']) && $_GET['type'] != ''){
$type = $_GET['type'];
if($type == 1){
$sql = "SELECT *
FROM `product` as p
LEFT JOIN `productLang` as pl ON p.`id`=pl.`id`
LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
WHERE bb.`brand_id`=$id";
}
else if($type == 2)
{
$sql = "SELECT *
FROM `author` as a
LEFT JOIN `authorLang` as al ON a.`id`=al.`author_id`
WHERE a.`id` IN (
SELECT p.`author_id`
FROM `product` as p
LEFT JOIN `book_brand` as bb ON p.`id`=bb.`book_id`
WHERE bb.`brand_id`=$id
)";
$entity = 'author';
}
}
}
$count = count(Yii::$app->db->createCommand($sql)->queryAll());
$dataProvider = new SqlDataProvider([
'sql' => $sql,
'totalCount' => $count,
'pagination' => [
'pageSize' => $pageSize,
'route' => $first_step . '/' . $second_step
]
]);
$models = $dataProvider->getModels();
$pagination = new Pagination([
'pageSize' => $pageSize,
'totalCount' => $count,
'route' => $first_step . '/' . $second_step
]);
if(Yii::$app->request->isPjax){
return $this->renderAjax('single-genre', [
'genresPage' => $genresPage,
'authorsPage' => $authorsPage,
'lang' => $lang,
'banner' => $banner,
'booksPage' => $booksPage,
'genre' => $genre,
'models' => $models,
'pagination' => $pagination,
'entity' => $entity,
]);
}
return $this->render('single-genre', [
'genresPage' => $genresPage,
'authorsPage' => $authorsPage,
'lang' => $lang,
'banner' => $banner,
'booksPage' => $booksPage,
'genre' => $genre,
'models' => $models,
'pagination' => $pagination,
'entity' => $entity,
]);
}
jQuery:
function pjaxFilterForm() {
var dataString = $("#filter-group2").serialize();
$.pjax.defaults.timeout = false;
$.pjax({
container: "#booksGrid",
url: location.href.split("?")[0],
data: dataString,
scrollTo: false
});
return false;
}
View:
<div class="filter-tags-holder">
<?php \yii\bootstrap\ActiveForm::begin([
'method' => 'get',
'action' => '#',
'options' => ['data-pjax'=>true, 'onsubmit'=>'return pjaxFilterForm()', 'id'=>'filter-group2']
]) ?>
<div id="submit-helper-tab"></div>
<input type="hidden" name="type">
<ul id="filterGenresList" class="option-set">
<li><a class="selected" data-value="1" href="#"><?= Yii::t('app', 'app.Books') ?></a></li>
<li><a data-value="2" href="#"><?= Yii::t('app', 'app.Authors') ?></a></li>
</ul>
<?php \yii\bootstrap\ActiveForm::end(); ?>
</div>
<!-- Filter Nav -->
<!-- Recommended -->
<?php \yii\widgets\Pjax::begin(['id'=>'booksGrid']) ?>
<?php if($models) : ?>
<div id="filter-masonry" class="gallery-masonry">
<?php foreach ($models as $model){
if($entity == 'book'){
$model = \backend\modules\products\models\Product::findOne($model['product_id']);
echo $this->render('_authorBooks', ['book' => $model, 'lang' => $lang, 'booksPage' => $booksPage]);
}else if($entity == 'author'){
$model = \backend\models\Author::findOne($model['author_id']);
echo $this->render('_authorGenre', ['book' => $model, 'lang' => $lang, 'authorsPage' => $authorsPage]);
}
} ?>
</div>
<div class='pagination-holder'>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
'hideOnSinglePage' => true,
'prevPageLabel' => Yii::t('app', 'app.Prev'),
'nextPageLabel' => Yii::t('app', 'app.Next')
]) ?>
</div>
<?php endif; ?>
<?php \yii\widgets\Pjax::end() ?>
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!
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....
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'));
}
I am trying to figure out what's wrong here, but really not sure. I have a site with users, when a user edits details, it seems to override all other records with those details. This doesn't happen always but sometimes (of course the result is chaos!). Here is the code of update
public function update_edit()
{
/* echo " //// INSIDE UPDATE EDIT "; */
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|min_length[6]|max_length[100]');
//check that there are no form validation errors
if($this->form_validation->run() == FALSE)
{
/* echo " //// INSIDE FORM VALIDATION"; */
if(($this->session->userdata('username')!=""))
{
/* echo " //// INSIDE SESSION VALIDATION"; */
$data = array();
$data = $this->profileModel->load_user_editable_data($this->session->userdata('username'));
$this->load->view('layout/header');
$this->load->view('profile_edit', $data);
$this->load->view('layout/footer');
//$this->load->view('thankyou');
}else{
//$this->load->view('login');
$this->login();
}
}else{
$complete = $this->profileModel->update_profile($this->session->userdata('username'));
if($complete == 1)
{
$this->load->view('layout/header');
$this->load->view('update_complete');
$this->load->view('layout/footer');
}
}
}
This is the model code:
public function update_profile($username)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$fullImagePath;
if (isset($_FILES['profilepic']) && !empty($_FILES['profilepic']['name']))
{
if ($this->upload->do_upload('profilepic'))
{
$upload_data = $this->upload->data();
$fullImagePath = '/uploads/' . $upload_data['file_name'];
}
}else{
$fullImagePath = $this->session->userdata('profilepic');
}
$data = array(
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'telephone' => $this->input->post('telephone'),
'about' => $this->input->post('about'),
'address' => $this->input->post('address'),
'profilepic' => $fullImagePath,
);
$this->db->where('username', $username);
$this->db->update('free_user_members', $data);
return 1;
}
and this is the form:
<div class="content_container">
<div id="rt-main" class="mb8-sa4">
<div class="rt-container">
<div class="rt-grid-12">
<div dir="rtl" class="homecontent">
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('profile/update_edit'); ?>
<? $this->session->set_userdata('profilepic', $profilepic); ?>
<h5>الاسم الكامل</h5>
<? $data = array(
'name' => 'fullname',
'id' => 'round_input',
'value' => $fullname,
);
echo form_input($data); ?>
<h5>الايميل</h5>
<? $data = array(
'name' => 'email',
'id' => 'round_input',
'value' => $email,
'size' => '70'
);
echo form_input($data); ?>
<h5>الجوال</h5>
<? $data = array(
'name' => 'mobile',
'id' => 'round_input',
'value' => $mobile,
);
echo form_input($data); ?>
<h5>هاتف</h5>
<? $data = array(
'name' => 'telephone',
'id' => 'round_input',
'value' => $telephone,
);
echo form_input($data); ?>
<h5>العنوان</h5>
<? $data = array(
'name' => 'address',
'id' => 'round_input',
'value' => $address,
'size' => '70'
);
echo form_input($data); ?>
<h5>نبذة عني</h5>
<? $data = array(
'name' => 'about',
'id' => 'round_input',
'value' => $about,
'rows' => '3',
'cols' => '40',
);
echo form_textarea($data); ?>
<h5>الصورة الشخصية</h5>
<img width="300" height="300" src="<? echo $profilepic; ?>" />
<h5>إختيار صورة جديدة</h5>
<?
$data = array(
'name' => 'profilepic',
'id' => 'profilepic',
);
echo form_upload($data);
?>
<div><input type="submit" value="احفظ التغييرات" /></div>
</form>
</div>
<p> </p>
</div>
</div>
<div class="clear"></div>
</div>
</div>
will really appreciate it if someone tells me what I am doing that could lead to that chaos every now and then.
Regards,
You have to add code to check that username in the session exists.
If the session times out, codeigniter will return FALSE.
Querying MySQL on username = false will return all rows.