Yii2 Pjax reloads the page - php

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() ?>

Related

Yii2 ActiveQuery join relation issue

ActiveQuery doesn't select map.src_fin_position_id column
$query = FinancePossibleFinPositions::find()
->select (['dst.row_num', 'dst.src_value', 'map.src_fin_position_id'])
->from('finance.possible_fin_positions dst')
->leftJoin('finance.fin_pos_mapping map','map.map_fin_position_id = dst.possible_fin_positions_id')
->leftJoin('finance.possible_fin_positions src','src.possible_fin_positions_id = map.src_fin_position_id AND src.possible_fin_docs_id = :possible_fin_docs_id',[":possible_fin_docs_id"=> 95])
->where('dst.possible_fin_docs_id=:possible_fin_docs_id', [":possible_fin_docs_id"=> 88])
->orderBy('dst.row_num')
->all();
gives
array(2) {
["row_num"]=>
string(4) "1000"
["src_value"]=>
string(18) "My value"
}
although
$query = (new \yii\db\Query())
->select(["dst.row_num", "dst.src_value", "map.src_fin_position_id"])
->from('finance.possible_fin_positions dst')
->join('LEFT JOIN','finance.fin_pos_mapping map','map.map_fin_position_id = dst.possible_fin_positions_id')
->join('LEFT JOIN','finance.possible_fin_positions src','src.possible_fin_positions_id = map.src_fin_position_id AND src.possible_fin_docs_id = :possible_fin_docs_id',[":possible_fin_docs_id"=> $fin_doc])
->where('dst.possible_fin_docs_id=:possible_fin_docs_id', [":possible_fin_docs_id"=> $main_fin_doc])
->orderBy('dst.row_num')->all();
gives the result I need to get with ActiveQuery
array(3) {
["row_num"]=>
string(4) "1000"
["src_value"]=>
string(18) "My value"
["src_fin_position_id"]=>
int(3426)
}
I would use \yii\db\Query() but when I fill tabular form with this array the $_POST is empty.
Does anyone know how to solve this issue?
UPDATE
Simpler example
form.php
<div class="col-md-6">
<?php
$form = ActiveForm::begin(['id'=>'post-multiple','action' => ['submit-posts']]);
echo TabularForm::widget([
'form' => $form,
'dataProvider' => $dataProvider,
'serialColumn' => false,
'actionColumn' => false,
'checkboxColumn' => false,
'attributes' => [
'post_id' => ['type' => TabularForm::INPUT_STATIC, 'columnOptions'=>['hAlign'=>GridView::ALIGN_CENTER]],
'post_title' => ['type' => TabularForm::INPUT_STATIC],
'post_description' => ['type' => TabularForm::INPUT_TEXT, 'options' => ['class' => 'droppable']],
],
'gridSettings' => [
'floatHeader' => true,
'panel' => [
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Manage Books</h3>',
'type' => GridView::TYPE_PRIMARY,
'after'=>
Html::a(
'<i class="glyphicon glyphicon-plus"></i> Add New',
'#',
['class'=>'btn btn-success']
) . ' ' .
Html::a(
'<i class="glyphicon glyphicon-remove"></i> Delete',
'#',
['class'=>'btn btn-danger']
) . ' ' .
Html::submitButton(
'<i class="glyphicon glyphicon-floppy-disk"></i> Save',
['class'=>'btn btn-primary']
)
]
]
]);
ActiveForm::end(); ?>
</div>
Controllers
public function actionTabular()
{
// $query = (new \yii\db\Query())
// ->select("post_id, post_title, post_description")
// ->from('posts');
$query = Posts::find()->indexBy('post_id');
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
return $this->render('tabular', [
'dataProvider'=>$dataProvider,
]);
}
public function actionSubmitPosts()
{
var_dump(Yii::$app->request->post());exit;
}
$query = Posts::find()->indexBy('post_id');
<input type="text" id="posts-40-post_description" class="droppable form-control ui-droppable" name="Posts[40][post_description]" value="tre">
$_POST is not empty
$query = (new \yii\db\Query())
->select("post_id, post_title, post_description")
->from('posts');
<input type="text" id="-28-post_description" class="droppable ui-droppable" name="[28][post_description]" value="tre">
$_POST is empty
Both queries fill the form correctly
The difference is inputs names. But I don't need to validate this form and it is strange why
[28][post_description] doesn't go into $_POST.
From Yii 2 Guide:
Note: If you call select() while eagerly loading relations, you have to make sure the columns referenced in the relation declarations are being selected. Otherwise, the related models may not be loaded properly. For example,
$orders = Order::find()->select(['id', 'amount'])->with('customer')->all();
// $orders[0]->customer is always null.
// To fix the problem, you should do the following:
$orders = Order::find()
->select(['id', 'amount', 'customer_id'])
->with('customer')->all();
I figured this out.
For yii\db\Query
I should have used
<?= Html::beginForm(['save-posts','method'=>'post']); ?>

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.

Cakephp : Multi-Model Comment system

I'm using cakephp, I have a model "comment" with two fields : "model_type" and "model_id" in order to comment every item of my application (eg Picture, News, Article, ...) with a single Comment model.
I wonder how to make this. (A component "Comment" for controller that could be commented ?)
Finally I want to list comment in view just with a helper:
$comment->show('model_name', 'item_id');
that would display correctly paginated comments and a form for adding a new comment to the item.
Thanks.
Edit: See this too : http://bakery.cakephp.org/articles/AD7six/2008/03/13/polymorphic-behavior
The Solution
A multi model commenting system and pagination just with :
<?php echo $this->element('comments',
array(
'model_type' => "model_name",
'model_id' => $data['model']['id'],
'order_field' => 'created',
'order' => 'asc')); ?>
The model
Scheme :
- id
- model_type
- model_id
- content
(optional:)
- user_id
- created
- updated
- rating
- ...
The Comment Model :
// {app}/models/comment.php
class Comment extends AppModel{
public $name = 'Comment';
// List of model that could be commented
protected $model_list = array(
'news' => array(
'name' => 'News', // here it's the model's name
'field' => 'validated'), // A field for validation ( allow comments only on validaded items)
'articles' => array(
'name' => 'Article',
'field' => 'validated')
);
// This is an example
public $belongsTo = array(
'User' => array(
'conditions' => 'User.validated = true'
)
);
public $validate = array(
'model_type' => array(
'rule' => 'checkModelType',
'message' => "Something goes wrong !"
),
'model_id' => array(
'rule' => 'checkModelId',
'message' => "Something goes wrong !"
),
'content' => array(
'rule' => 'notEmpty',
'message' => "Empty content !"
)
);
// Check if the model is commentable
public function checkModelType($data){
$model_type = $data['model_type'];
return in_array($model_type, array_keys($this->model_list));
}
// Check if the item exists and is validated
public function checkModelId($data){
$model_id = intval($data['model_id']);
$model = $this->model_list[$this->data['Comment']['model_type']];
$params = array(
'fields' => array('id', $model['field']),
'conditions' => array(
$model['name'].'.'.$model['field'] => 1, // Validated item
$model['name'].'.id' => $model_id
)
);
// Binding model to Comment Model since there is no $belongsTo
return (bool) ClassRegistry::init($model['name'])->find('first', $params);
}
}
The Controller
// {app}/controllers/comments_controller.php
class CommentsController extends AppController
{
public $name = 'Comments';
// Pagination works fine !
public $paginate = array(
'limit' => 15,
'order' => array(
'Comment.created' => 'asc')
);
// The action that lists comments for a specific item (plus pagination and order !)
public function view($model_type, $model_id, $order_field = 'created', $order = 'DESC'){
$conditions = array(
'Comment.model_type' => $model_type,
'Comment.model_id' => $model_id
);
// (optional)
if($order_field != 'created') {
$this->paginate['order'] = array(
'Comment.'.$order_field => $order,
'Comment.created' => 'asc');
}
// Paginate comments
$comments = $this->paginate($conditions);
// This allow to use paginator with requestAction
$paginator = ClassRegistry::getObject('view')->loaded['paginator'];
$paginator->params = $this->params;
return compact('comments', 'paginator');
}
public function add(){
// What you want !
}
}
The views
Comments element
/* {app}/views/elements/comments.ctp
#params : $model_type
* : $model_id
*
* */
$result = $this->requestAction("/comments/view/$model_type/$model_id/$order_field/$order/", $this->passedArgs);
$paginator = $result['paginator'];
$comments = $result['comments'];
$paginator->options(array('url' => $this->passedArgs));
?>
<h2>Comments</h2>
<fieldset class="commentform">
<legend>Add un commentaire</legend>
<?php
// Form
echo $form->create('Comment', array('action' => 'add'));
echo $form->hidden('model_type', array('value' => $model_type));
echo $form->hidden('model_id', array('value' => $model_id));
echo $form->input('content');
<?php
echo $form->end('Send');
?>
</fieldset>
<div class="paginationBar">
<?php
echo $paginator->prev('<< ', null, null, array('class' => 'disabled'));
echo '<span class="pagination">',$paginator->numbers(),'</span>';
echo $paginator->next(' >>', null, null, array('class' => 'disabled'));
?>
</div>
<?php
foreach($comments as $comment){
echo $this->element('comment', array('comment' => $comment));
}
?>
<div class="paginationBar">
<?php
echo $paginator->prev('<< ', null, null, array('class' => 'disabled'));
echo '<span class="pagination">',$paginator->numbers(),'</span>';
echo $paginator->next(' >>', null, null, array('class' => 'disabled'));
?>
<p><br />
<?php
echo $paginator->counter(array('format' => 'Page %page% on %pages%, displayi %current% items of %count%'));
?>
</p>
</div>
Comment element
//{app}/views/elements/comment.ctp
// A single comment view
$id = $comment['Comment']['id'];
?>
<div class="comment">
<p class="com-author">
<span class="com-authorname"><?=$comment['User']['name']?> </span>
<span class="com-date">(<?=$comment['Comment']['created']?>)</span>
</p>
<p class="com-content"><?=$comment['Comment']['content']?></p>
</div>
hm... it would be pretty complicated if you want to display paginated comments like that. You should use lazy loading: don't actually load the comments until the user click on it or something.
You should probably make an element. you can pass model_name and model_id to it. And in the element, you can create a comment 'widget' that can directly send the comment to your comments controller, using ajax; and load the paginated comments using ajax also.
Check out this plugin (it's actually a component) developed by CakeDC.
You could either implement that or, use that to create your own solution.

Categories