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