Undefined Variable: model - yii

I am new to Yii and learning it now. Here i am trying to get the listing of the user from the users table of the database.
Following is my Users Controller function for view:
class UsersController extends Controller
{
public function actionIndex()
{
$this->render('index');
}
public function actionView()
{
$model = new Users;
$this->render('view',array(
'model'=>$model,
));
}
}
Following is my Users Model:
class Users extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return '{{users}}';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fname, lname, email', 'required'),
array('fname, lname', 'length', 'max'=>50),
array('email', 'length', 'max'=>100),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, fname, lname, email', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'fname' => 'First Name',
'lname' => 'Last Name',
'email' => 'Email',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('fname',$this->fname,true);
$criteria->compare('lname',$this->lname,true);
$criteria->compare('email',$this->email,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
Following is my View:
<h1>Users</h1>
<p>
Below is the list of users, here you may add user.
</p>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'fname',
'lname',
'email',
),
)); ?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ? >
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('fname')); ?>:</b>
<?php echo CHtml::encode($data->fname); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('lname')); ?>:</b>
<?php echo CHtml::encode($data->lname); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('email')); ?>:</b>
<?php echo CHtml::encode($data->email); ?>
<br />
</div>
I am getting a PHP notice saying that undefined variable: model, please help thanks in advance.

It looks like you were pasting _view.php.
Make sure you hand your $model variable from view.php to _view.php, since in actionView() you are only handing it to 'view'.

field($model, 'VideoTitle')->textInput(['autofocus' => true, 'required' => true]) ?>
field($model, 'Description')->textInput(['autofocus' => true, 'required' => true]) ?>

Related

Required Rule on specific condition

I need to apply rule on a form. I have a country and dependent drop down of state.
I need to apply required rule on state field.
But if i choose India from drop down then required rule should be remove from the form.
I have enabled clientsidevalidation true in cactiveform.
View form:
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'cart',
'enableAjaxValidation' => false,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),
// we need the next one for transmission of files in the form.
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
echo $form->dropDownList($modelUser, 'country', Countries::getcountrylistwithcode(),
array('options' => array($currentCountry=>array('selected'=>true)),
'empty'=>'Select Country',
'class'=>'form-control input-lg',
));
echo $form->error($modelUser,'country');
echo $form->labelEx($modelUser,'state',array('class'=>"col-md-30"));
echo $form->dropDownList($modelUser, 'state', $stateList,array('class'=>"form-control input-lg",'prompt'=>'Select State'));
echo $form->error($modelUser,'state');
$this->endWidget();
?>
And model rules are like this:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,state,address_line_one,postcode', 'required'),
You can achieve this by adding a custom rule to your model.
Change your rules function to something like this
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,address_line_one,postcode', 'required'),
array('state', 'validateState'),
)
}
Next up would be to create the custom validation rule. This would look something like this
public function validateState ($attribute, $params)
{
$aCountriesWithState = array('USA');
if (in_array($this->$attribute, $aCountriesWithState) && empty($this->$attribute))
{
$this->addError($attribute, 'State is missing');
}
}

date field returns empty value after submitting in yii

I am new in Yii, I am currently trying to do a product page in my local system. I declare DateField as product_availability_date,product_end_date. but when I enter the dates in front end and submit, it again shows me an error to re-enter the dates. please say a solution to this. Thanks in advance.
ProductsController:
<?php
class ProductsController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','search'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','search'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','search'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Products;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
if($model->save())
$this->redirect(array('view','id'=>$model->product_id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
if($model->save())
$this->redirect(array('view','id'=>$model->product_id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Products');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Products('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Products']))
$model->attributes=$_GET['Products'];
$this->render('admin',array(
'model'=>$model,
));
}
//search
public function actionsearch()
{
$model=new Products;
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Products']))
$model->attributes=$_GET['Products'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Products the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Products::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Products $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='products-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Products model:
<?php
/**
* This is the model class for table "products".
*
* The followings are the available columns in table 'products':
* #property integer $product_id
* #property string $product_name
* #property string $description
* #property integer $quantity
* #property integer $category_id
* #property integer $location_id
* #property string $vendor
* #property string $status
* #property integer $stock
* #property string $prod_avl_date
* #property string $prod_end_date
*/
class Products extends CActiveRecord
{
public $vendor_name;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'products';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('product_name, description, quantity, category_id, location_id, status, stock', 'required'),
array('quantity, location_id, stock', 'numerical', 'integerOnly'=>true),
array('product_name, vendor', 'length', 'max'=>50),
array('status', 'length', 'max'=>2),
array('prod_avl_date, prod_end_date', 'date','format'=>array('yyyy/MM/dd','yyyy/MM/d')),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('product_id, product_name, description, quantity, category_id, location_id, vendor, status, stock, prod_avl_date, prod_end_date', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array('category_id' => array(self::BELONGS_TO, 'Category','category_id'),
'location_id' => array(self::BELONGS_TO, 'Location','location_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'product_id' => 'Product',
'product_name' => 'Product Name',
'description' => 'Description',
'quantity' => 'Quantity',
'category_id' => 'Category',
'location_id' => 'Location',
'vendor' => 'Vendor',
'status' => 'Status',
'stock' => 'Stock',
'prod_avl_date' => 'Prod Avl Date',
'prod_end_date' => 'Prod End Date',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('product_id',$this->product_id);
$criteria->compare('product_name',$this->product_name,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('quantity',$this->quantity);
$criteria->compare('category_id',$this->category_id);
$criteria->compare('location_id',$this->location_id);
$criteria->compare('vendor',$this->vendor,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('stock',$this->stock);
$criteria->compare('prod_avl_date',$this->prod_avl_date,true);
$criteria->compare('prod_end_date',$this->prod_end_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Products the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
form:
<?php
/* #var $this ProductsController */
/* #var $model Products */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'products-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'product_name'); ?>
<?php echo $form->textField($model,'product_name',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'product_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'quantity'); ?>
<?php echo $form->textField($model,'quantity'); ?>
<?php echo $form->error($model,'quantity'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'category_id');
echo $form->dropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'category_id', 'category_name'), array('prompt'=>'Select category','multiple' => 'multiple'));
?>
<?php echo $form->error($model,'category_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'location_id');
echo $form->dropDownList($model,'location_id', CHtml::listData(Location::model()->findAll(), 'location_id', 'location_name'), array('empty'=>'Select location'));?>
<?php echo $form->error($model,'location_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'vendor');
echo $form->dropDownList($model,'location_id',CHtml::listData(Vendor::model()->findAll(location_id),'location_id','vendor_name'),
array(// htmlOptions
'ajax'=>array(// special htmlOption through clientChange, for ajax
'type'=>'GET',
'url'=>$this->createUrl('Vendor/Vendordetails'),// action that will generate the data
'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
'dataType'=>'json',// type of data we expect back from the server
'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
),
)
);
//echo $form->dropDownList($model,'vendor', CHtml::listData(Vendor::model()->findAll(), 'location_id', 'vendor_name'), array('empty'=>'Select vendor'));?>
<?php echo $form->error($model,'vendor'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php $status=array("AVAILABLE","NOT AVAILABLE")?>
<?php echo $form->radioButtonList($model,'status',$status,array('separator'=>'')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'stock'); ?>
<?php echo $form->textField($model,'stock'); ?>
<?php echo $form->error($model,'stock'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'prod_avl_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>'prod_avl_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'prod_avl_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'prod_end_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>'prod_end_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'prod_end_date'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
problem in name of CJuiDatePicker:
replace
'name'=>'prod_avl_date',
with
'name'=>'Products[prod_avl_date]',
Do same thing for prod_end_date also
Note: You have to set date format in CJuiDatePicker exactly as it is in model rules
'dateFormat' => 'yy/mm/dd',

Custom validation rule is not working for CFormModel

My front end is Php Yii. I am trying to create a custom validation rule which checks to see if the username already exists in the database.
I don't have direct access to the database. I have to use the RestClient to communicate with the Database. My issue is that custom validation rule is not working with my CFormModel.
Here is my code:
public function rules()
{
return array(
array('name', 'length', 'max' => 255),
array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/' )
array('nickname','alreadyexists'),
);
}
public function alreadyexists($attribute, $params)
{
$result = ProviderUtil::CheckProviderByNickName($this->nickname);
if($result==-1)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
This doesn't seem to work at all, I also tried this:
public function alreadyexists($attribute, $params)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
Even then, it doesn't seem to work. What am I doing wrong here?
The problem with your code is that it doesn't return true or false.
Here is one of my rules to help you:
<?php
....
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, link', 'required'),
array('title, link', 'length', 'max' => 45),
array('description', 'length', 'max' => 200),
array('sections','atleast_three'),
);
}
public function atleast_three()
{
if(count($this->sections) < 3)
{
$this->addError('sections','chose 3 at least.');
return false;
}
return true;
}
...
?>
I met the same issue and finally got it solved. Hopefully, the solution could be useful for resolving your problem.
The reasons why the customised validation function is not called are:
this is a server side rather than client side validation
when you click the "submit" button, the controller function takes over the process first
the customised function won't be involved if you didn't call "$model->validate()"
Therefore, the solution is actually simple:
Add "$model->validate()" in the controller function. Here is my code:
"valid.php":
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'alloc-form',
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true,),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'valid_field'); ?>
<?php echo $form->textField($model,'valid_field'); ?>
<?php echo $form->error($model,'valid_field'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
"ValidForm.php":
class ValidForm extends CFormModel
{
public $valid_field;
public function rules()
{
return array(
array('valid_field', 'customValidation'),
);
}
public function customValidation($attribute,$params)
{
$this->addError($attribute,'bla');
}
}
"SiteController.php"
public function actionValid()
{
$model = new ValidForm;
if(isset($_POST['AllocationForm']))
{
// "customValidation" function won't be called unless this part is added
if($model->validate())
{
// do something
}
// do something
}
}

passing value from Yii CController class to CForm (Form Builder) config array

I'm new to Yii, and I'm trying to do my initial project the "right" way. I've created a CFormModel class that needs three fields to query for some data, a CForm config to construct the form, and a CController to tie it together (all given below).
The data request needs an account, and this can come from a couple of different places. I think retrieving it should be in the controller. However, I don't know how to get it into the form's hidden "account" field from the controller, so that it makes it to the arguments assigned to the CFormModel after submission. More generally, I know how to pass from CController to view script, but not to CForm. Is the registry (Yii::app()->params[]) my best bet?
I suppose I can just leave it out of the form (and required fields) and wait to populate it in the submit action (actionSummaries). Does that break the intention of CForm? Is there a best practice? Even taking this solution, can someone address the first issue, in case it comes up again?
Any other, gentle critique is welcome.
models/SummariesForm.php
class SummariesForm extends CFormModel
{
public $account;
public $userToken;
public $year;
public function rules () {...}
public function fetchSummary () {...}
static public function getYearOptions () {...}
}
views/account/select.php
<?php
$this->pageTitle=Yii::app()->name;
?>
<div class="form">
<?php echo $form->render(); ?>
</div>
controllers/AccountController.php
class AccountController extends CController
{
public $layout = 'extranet';
public function actionSelect ()
{
$model = new SummariesForm();
// retrieve account
require_once 'AccountCookie.php';
/*
*
* Here, I insert the account directly into the
* model used to build the form, but $model isn't
* available to selectForm.php. So, it doesn't
* become part of the form, and this $model doesn't
* persist to actionSummaries().
*
*/
$model->account = AccountCookie::decrypt();
if ($model->account === false) {
throw new Exception('Unable to retrieve account.');
}
$form = new CForm('application.views.account.selectForm', $model);
$this->render('select', array(
'form' => $form,
'account' => $model->account,
));
}
public function actionSummaries ()
{
$model = new SummariesForm();
if (isset($_POST['SummariesForm'])) {
$model->attributes = $_POST['SummariesForm'];
/*
*
* Should I just omit "account" from the form altogether
* and fetch it here? Does that break the "model"?
*
*/
if ($model->validate() === true) {
try {
$summaries = $model->fetchSummary();
} catch (Exception $e) {
...
CApplication::end();
}
if (count($summaries) === 0) {
$this->render('nodata');
CApplication::end();
}
$this->render('summaries', array('model' => $model, 'summaries' => $summaries));
} else {
throw new Exception('Invalid year.');
}
}
}
}
views/account/selectForm.php
<?php
return array(
'title' => 'Select year',
'action' => Yii::app()->createUrl('Account/Summaries'),
'method' => 'post',
'elements' => array(
'account' => array(
'type' => 'hidden',
'value' => $account,
),
'userToken' => array(
'type' => 'hidden',
'value' => /* get token */,
),
'year' => array(
'type' => 'dropdownlist',
'items' => SummariesForm::getYearOptions(),
),
),
'buttons' => array(
'view' => array(
'type' => 'submit',
'label' => 'View summaries',
),
),
);
The answer is NO to do what you asked. You can see $form variable which acted almost like array when it was passed from controller to view. The solution is you add more property $account into selectForm model and treat it like other elements. I don't think leaving the new field outside the form will be properly way if you want to submit its value also.
Edited:

yii update clistview by dropdownlist

I'm a very newbie in Yii framework. I would like to create a page. Which is when the dropdown list change, the listview/gridview will be change by dropdown value.
this is my view
<div class="row">
<?php
$records = Company::model()->findAll();
$company_list = CHtml::listData($records, 'id', 'name');
echo CHtml::dropDownList('company_id','', $company_list,
array(
'onchange'=>"$.fn.yiiListView.update('ajaxListView', {url: '".Yii::app()->createUrl('department/dynamicsectionlist')."?company_id='+$('#company_id option:selected').val()})",
'prompt'=>'Please select a company',
)); ?>
</div>
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view_section',
'id'=>'ajaxListView',
));
?>
This is model
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('p_id',$this->p_id);
$criteria->compare('created',$this->created,true);
$criteria->compare('updated',$this->updated,true);
$criteria->compare('company_id',$this->company_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
This is Controller
public function actionDynamicsectionlist()
{
$company_id = $_POST['company_id'];
$criteria=new CDbCriteria();
$criteria->condition .= 't.id IN (SELECT t2.id, t2.name FROM department t2 WHERE t2.company_id = :company_id)';
$criteria->params[':company_id'] = $company_id;
$dataProvider = new CActiveDataProvider( 'Department', array( 'criteria' => $criteria, ) );
$this->render( 'sectionlist', array( 'dataProvider' => $dataProvider ) );
}
But it is not working. Please help me.
Regads
Tharsoe
I solved it.
This is controller
// Initial view (department/depatmentlist)
public function actionDepartmentlist()
{
$model=new Department('search');
$model->unsetAttributes(); // clear any default values
$model->p_id = 0;
// $dataProvider->getData() will return a list of Post objects
// $dataProvider=new CActiveDataProvider('Department');
$this->render('list_department',array(
'model'=>$model,
));
}
// when the user selected the company from dropdown list
public function actionDynamicsectionlist()
{
$model=new Department('dsearch');
$model->unsetAttributes(); // clear any default values
$model->p_id = 0;
if(isset($_GET['company_id']))
$model->company_id = $_GET['company_id'];
$this->render('sectionlist',array(
'model'=>$model,
));
}
This is model (nothing change)
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('p_id',$this->p_id);
$criteria->compare('created',$this->created,true);
$criteria->compare('updated',$this->updated,true);
$criteria->compare('company_id',$this->company_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
This is view (list_department.php)
<h1>Departments List</h1>
<div class="row">
Company<br />
<?php
$records = Company::model()->findAll();
$company_list = CHtml::listData($records, 'id', 'name');
echo CHtml::dropDownList('company_id','', $company_list,
array('prompt'=>'Please select a company',)); ?>
</div>
<?php
/*
for ListView
$this->widget('zii.widgets.CListView', array(
//'dataProvider'=>$dataProvider,
'dataProvider'=>$model->search(),
'itemView'=>'_view_section',
'id'=>'ajaxListView',
));
*/
?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'department-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
//'p_id',
'created',
'updated',
//'company_id',
),
));
?>
<?php
Yii::app()->clientScript->registerScript('search',
"$('#company_id').change(function(){
var companyId = $('#company_id option:selected').val();
$.fn.yiiGridView.update(
'department-grid',
{ type: 'GET',
url: 'http://localhost/mmaig_ceo/ceo-control-system/index.php?r=department/dynamicdepartmentlist&ajax=department-grid&company_id=' + companyId
}
);
});
")
?>