Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Criteria Search Testing ::
- ================================
- <?php
- function actionController(){
- $criteria=new CDbCriteria;
- $criteria -> compare ('email', 'gmail');
- $criteria -> addInCondition('id', array(2,3));
- $criteria -> addNotInCondition('id', array(2,3));
- $criteria -> addBetweenCondition ('id', 1,2);
- $criteria -> condition = "name = 'H'";
- $criteria -> addCondition("id = 1");
- $criteria -> select="t.id, t.identification, t.email, t.numbers, c.numbers";
- $criteria -> join = "INNER JOIN DataTable c ON c.id = t.id";
- $criteria -> order = "id DESC";
- $criteria -> limit ="10";
- $criteria-> with=array(
- "ciudad"=>array(
- "condition"=>"id=1",
- "on"=>"id=1",
- "joinType"=>"INNER JOIN",
- ),
- "experience");
- $criteria->addSearchCondition('name', strtoupper( $_GET['term']) ) ;
- $criteria->addSearchCondition('code', strtoupper ( $_GET['term']), true, 'or');
- $criteria -> compare('id', $this->id, true);
- $criteria -> compare('number', $this->number, true);
- $criteria -> compare('identification', $this->identification, true);
- $criteria -> compare('email', $this->email, true);
- $usuarios= Data::model()->findAll($criteria);
- $model= new Data;
- $usuarios= new CActiveDataProvider($model, array('criteria'=>$criteria));
- $usuarios= Data::model()->findAllByPk(array(1,2));
- $usuarios= Data::model()->findAllByAttribute(array('id'+.1));
- $sql="SELECT * FROM data WHERE id=1";
- $data= Data::model()->findAllBySql($sql);
- }
- ?>
- AutoComplete Search in Controller by Criteria::
- ==============================================
- <?php
- public function actionJuiList()
- {
- $arr = array();
- if (isset($_GET['term']))
- {
- $criteria = new CDbCriteria();
- $criteria->addSearchCondition('name', $_GET['term']);
- $models = Data::model()->findAll($criteria);
- foreach ($models as $model)
- {
- $arr[] = array(
- 'name'=>$model->data,
- 'label'=>CHtml::image('path/to/image').' '.$model->data,
- 'id'=>$model->id,
- );
- }
- }
- echo CJSON::encode($arr);
- Yii::app()->end();
- }
- ?>
- Model Rules For Existance Validation
- ====================================
- <?php
- public function rules()
- {
- return array(
- array('cm_code', 'cmCode'),
- );
- }
- public function cmCode($cm_code)
- {
- if(!empty($this->cm_code))
- {
- $record = Productmaster::model()->findByAttributes(array('cm_code' => $this->cm_code));
- if($record === null)
- {
- $this->addError($cm_code, 'Invalid Product Code');
- }
- }
- }
- public function imRcvQuantity($im_RcvQuantity)
- {
- if(!empty($this->im_RcvQuantity))
- {
- $record = VwPurchasedt::model()->findByAttributes(array('cm_code' => $this->cm_code))->pp_quantity;
- // var_dump($record) ;
- //exit();
- if($record < $this->im_RcvQuantity)
- {
- $this->addError($im_RcvQuantity, 'Received quantity must be Less OR Equal to Quantity');
- }
- }
- }
- ?>
- Using own function in validation rules- In the rule specify the function with attribute like this-
- ===================================================================================================
- <?php
- array('username','checkuniquename'),
- public function checkuniqueemail($attribute)
- {
- $record=Users::model()->findByAttributes(array($attribute=>$this->email));
- if($record!==null)
- $this->addError($attribute, 'This email has been already taken please choose a different one');
- }
- ?>
- Visible
- =======
- <?php
- ('.Yii::app()->user->name.')
- 'visible' => Yii::app()->user->isGuest
- 'visible'=>!Yii::app()->user->isGuest
- 'visible'=>Yii::app()->user->checkAccess('operations')
- ?>
- Menu Condition
- ==============
- <?php if (Yii::app()->user->isGuest){ ?>
- <?php } else { ?>
- <?php } ?>
- Multiply Two Text Field and view to another
- ===========================================
- <?php
- <script type="text/javascript">
- $(function() {
- $("#discrate").change(function(){
- setTarget()
- });
- $("#discamt").change(function(){
- setTarget();
- });
- });
- function setTarget(){
- var a = $("#discrate").val();
- var b = $("#discamt").val();
- var data = (a * b);
- $('#amount').val(data);
- }
- </script>
- ?>
- JOIN Query
- ==========
- <?php
- $rows = Yii::app()->db->createCommand()
- ->select('j.*, p.orderno, p.category, o.bidno')
- ->from('jobs j')
- ->join('projects p','j.projid = p.projid')
- ->join('orders o', 'p.orderno = o.orderno')
- ->where('j.projid=:id', array(':id'=>$id))
- ->order('j.jobno,j.projid')
- ->queryRow();
- $user = Yii::app()->db->createCommand()
- ->select('id, username, profile')
- ->from('tbl_user u')
- ->join('tbl_profile p', 'u.id=p.user_id')
- ->where('id=:id', array(':id'=>$id))
- ->queryRow();
- ?>
- add more information to Yii::app()->user
- ========================================
- <?php
- **use the UserIdentity class
- else
- {
- $this->_id=$user->id;
- $this->setState('username', $user->username); //// place here
- $this->errorCode=self::ERROR_NONE;
- }
- return !$this->errorCode;
- use anywhere::
- $username=Yii::app()->user->username;
- ?>
- Delete Confirmation
- ===================
- <?php
- array
- (
- 'class'=>'CButtonColumn',
- 'deleteConfirmation'=>"js:'Do you really want to delete record with ID '+$(this).parent().parent().children(':nth-child(2)').text()+'?'",
- ),
- ?>
- Image Path in array
- ===================
- <?php
- array(
- 'image'=>Yii::app()->baseUrl.'/path/to/img3', 'imageOptions'=>array('style'=>'display: block; margin: 10px auto;'),
- ),
- ?>
- Hide if Not New Records
- =========================
- <?php if (!$model->isNewRecord): ?>
- <input type="hidden" name="update_id"
- value=" <?php echo $model->id; ?>"/>
- <?php endif; ?>
- Ajax Dependable texfiled with a Dropdown list in Yii
- ====================================================
- My Form::
- <?php
- <div class="row">
- <?php echo $form->labelEx($model,'pp_store'); ?>
- <?php // echo $form->dropDownlist($model,'pp_store', CHtml::listData(Branchmaster::model()->findAll(), 'cm_branch', 'cm_branch')); ?>
- <?php $storeArray = CHtml::listData(Branchmaster::model()->findAll(),'cm_branch','cm_branch');
- echo $form->dropDownList($model,'pp_store', $storeArray,
- array(
- 'empty'=>"Select Warehouse",
- 'ajax' => array(
- 'type'=>'POST',
- 'url'=>CController::createUrl('purchaseordhd/GetCurrency' ),
- 'update' => '#currencyid',
- 'data'=>array('store'=>'js:this.value',),
- 'success'=> 'function(data) {$("#currencyid").empty();
- $("#currencyid").val(data);
- } ',
- ),
- )); ?>
- <?php echo $form->error($model,'pp_store'); ?>
- </div>
- <div class="row">
- <?php echo $form->labelEx($model,'pp_currency'); ?>
- <?php echo $form->textField($model,'pp_currency', array('id'=>'currencyid', 'readonly'=> true)); ?>
- <?php echo $form->error($model,'pp_currency'); ?>
- </div>
- ?>
- My Controller::
- <?php
- public function actionGetCurrency()
- {
- $q = $_POST['store'];
- $sql = "SELECT cm_currency as value FROM cm_branchmaster WHERE cm_branch= '$q' ";
- $command = Yii::app()->db->createCommand($sql);
- $result= $command->queryScalar();
- echo $result;
- }
- ?>
- Display Data from related tables in CGridview in yii
- ==================================================
- view of grid view:::
- <?php
- $this->widget('zii.widgets.grid.CGridView', array(
- 'id'=>'users-grid',
- 'dataProvider'=>$dataProviderObj,
- 'columns'=>array(
- 'productName',
- 'productType',
- 'productBrand',
- 'description',
- array(
- 'name' => '<column_name>'
- 'value' => array($this,'gridCreateduser')
- )
- ),
- ));
- ?>
- Now in controller:::
- <?php
- public function gridCreateUser($data,$row){
- $user = $data-> <colmn_name>;
- //do your stuff for finding the username or name with $user
- //for eg.
- $detail = User::model()->findByPk($user);
- // make sure what ever model you are calling is accessible from this controller other wise you have to import the model on top of the controller above class of the controller.
- return $detail->username;
- }
- ?>
- OR you can use in a simple manner by defining relation between models inside model whose gridview you are creating
- <?php
- public function relations(){
- return array(
- 'users' => array(self::HAS_MANY, 'Users', '<column_name>'),
- );
- }
- // ::::: Then you can directly access it in you grid view ::::
- $this->widget('zii.widgets.grid.CGridView', array(
- 'id'=>'users-grid',
- 'dataProvider'=>$dataProviderObj,
- 'columns'=>array(
- 'productName',
- 'productType',
- 'productBrand',
- 'description',
- array(
- 'name' => '<column_name>'
- 'value' => $data->users->username
- )
- ),
- ));
- ?>
- Admin Filter Dropdown Search:
- ============================================================
- <?php
- array(
- 'name'=>'cm_orgname',
- 'value'=>'$data->cm_orgname',
- 'filter'=>CHtml::listData(Suppliermaster::model()->findAll(), 'cm_supplierid', 'cm_orgname')
- ),
- ?>
- Model Search with Join Query from Model
- ===========================================
- <?php
- $criteria->select = 't.*, m.cm_description, n.cm_orgname';
- //$criteria->condition = "t.pp_purordnum = '$pp_purordnum' ";
- $criteria->join = 'INNER JOIN cm_branchmaster m ON t.pp_branch = m.cm_branch';
- $criteria->join .= ' INNER JOIN cm_suppliermaster n ON t.cm_supplierid = n.cm_supplierid';
- ?>
- Dataprovider with Multiple Join query in Controller:::
- ===============================================================
- <?php
- public function actionName( $im_transfernum, $im_status ){
- $criteria = new CDbCriteria();
- $criteria -> select = "c.im_status, t.id, t.im_transfernum, t.cm_code, t.im_unit, t.im_quantity, t.im_rate, n.cm_name";
- $criteria -> join = "INNER JOIN im_transferhd c ON c.im_transfernum = t.im_transfernum ";
- $criteria -> join .= " INNER JOIN cm_productmaster n ON t.cm_code = n.cm_code";
- $criteria -> condition = "t.im_transfernum = '{$im_transfernum}'";
- $dataProvider = new CActiveDataProvider('Transferdt',array(
- 'criteria' => $criteria
- ));
- $this->render('transfer_number', array('dataProvider' => $dataProvider));
- }
- ?>
- Set Flash in View
- =========================================================
- <?php if(Yii::app()->user->hasFlash('success')):?>
- <div class="flash-success">
- <?php echo Yii::app()->user->getFlash('success'); ?>
- <?php
- Yii::app()->clientScript->registerScript(
- 'myHideEffect',
- '$(".flash-success").animate({opacity: 1.0}, 3000).fadeOut("slow");',
- CClientScript::POS_READY
- );
- ?>
- </div>
- <?php endif; ?>
- ========== Relation between model or table ===================
- === In Model =====
- public $product_search;
- return array(
- array('product_search', 'safe', 'on'=>'search'),
- )
- public function relations()
- {
- return array(
- 'product' => array(self::BELONGS_TO, 'Productmaster', 'cm_code'),
- );
- }
- public function search()
- {
- $criteria->with = array( 'product' );
- $criteria->compare( 'product.cm_name', $this->product_search, true );
- return new CActiveDataProvider($this, array(
- 'criteria'=>$criteria,
- ));
- }
- ===== In View/Admin Page ============
- Cgridview:::::
- ======
- array( 'name'=>'product_search', 'value'=>'$data->product->cm_name' ),
- ==================================================================================
- Dropdown List with Concat in yii form with another MODEL
- ==================================================================================
- <?php $coa = Chartofaccounts::model()->findAll();
- $data = array();
- foreach ($coa as $coa)
- $data[$coa->am_accountcode] = $coa->am_accountcode . ' '. $coa->am_description;
- echo $form->dropDownList($model, 'am_accountcode', $data ,array('prompt' => '- Select Account -', 'required'=>TRUE,));
- ?>
- Check Exist in model data
- ============================
- <?php
- In Controller:::
- private function actionAdjustmentExist($transaction_number){
- $model = new Adjustdt();
- return $model->exists('transaction_number = :transaction_number', array(':transaction_number'=>$transaction_number));
- }
- OR :::::::::
- private function actionCheckTransaction($transaction_number){
- $sql="SELECT 1 FROM im_adjustdt WHERE transaction_number='$transaction_number' ";
- $cmd=Yii::app()->db->createCommand($sql);
- $result= $cmd -> queryScalar();
- return $result;
- }
- ?>
- Redirect to same page
- ==========================
- <?php
- $this->redirect(Yii::app()->request->urlReferrer);
- ?>
- A link on Image in Yii
- =========================
- <?php echo CHtml::link(CHtml::image(Yii::app()->request->baseUrl.'/images/action_btn_xls.png' alt=''), array('PostToGl', 'am_vouchernumber'=>$am_vouchernumber));
- ?>
- CDbException Error in Controller
- ================================
- <?php
- try{
- $model->save();
- Yii::app()->user->setFlash('success', Yii::t('Product', 'Success Message : Data Added Successfully !'));
- }catch(CDbException $e){
- Yii::app()->user->setFlash('error', Yii::t('Product', 'Warning Message: Invalid request ! Product code already exist!'));
- }
- ?>
- Quantity Should not be blank or zero ::: Model Rules
- ====================================================
- <?php
- return array(
- array('pp_quantity', 'greaterThanZero'),
- ),
- public function greaterThanZero($pp_quantity)
- {
- if ($this->$pp_quantity<=0)
- $this->addError($pp_quantity, 'Quantity should not be blank or zero');
- }
- ?>
- Auto-Complete Search with some Value/text / Condition:
- ======================================================
- <?php
- $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
- 'name'=>'product_name',
- 'model'=>$model,
- //'source'=>CController::createUrl('/smheader/autocompleteTestNew'),
- 'source'=>'js: function(request, response) {
- $.ajax({
- url: "'.$this->createUrl('smheader/autocompleteTestNew').'",
- dataType: "json",
- data: {
- term: request.term,
- productClass: $("#productClass").val(),
- warehouse: $("#warehouse").val(),
- },
- success: function (data) {
- response(data);
- }
- })
- }',
- 'options'=>array(
- 'minLength'=>'1',
- 'select'=>'js:function( event, ui ) {
- $("#product_name").text(ui.item.label);
- $("#code").val(ui.item.code);
- }',
- ),
- 'htmlOptions'=>array(
- 'id'=>'product_name',
- 'placeholder'=>'search by product name or code',
- //'style' => 'width: 96%; padding: 8px; margin-bottom: 10px; border: 1px solid orange;',
- //'onClick' => 'document.getElementById("cm_code").value= ""',
- ),
- ));
- Controller:::
- =============
- public function actionAutocompleteTestNew() {
- $productClass = $_GET['productClass'];
- $warehouse = $_GET['warehouse'];
- $date = date("Y-m-d");
- if($productClass == 'PRODUCT'){
- if (!empty($_GET['term'])) {
- $sql = "SELECT t.cm_name as label, t.cm_code as code, t.cm_sellrate as rate, t.cm_stkunit as unit, t.cm_selltax as tax, r.cm_code, SUM(available) as available
- FROM cm_productmaster t
- INNER JOIN im_vw_stock r ON t.cm_code = r.cm_code
- WHERE r.im_storeid='$warehouse' AND r.im_ExpireDate >='$date' AND t.cm_name LIKE :qterm
- GROUP BY r.cm_code";
- $sql .= ' ORDER BY label ASC';
- $command = Yii::app()->db->createCommand($sql);
- $qterm = $_GET['term'].'%';
- //$command->bindValue(":qterm", $_GET['term'].'%', PDO::PARAM_STR);
- $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
- $result = $command->queryAll();
- echo CJSON::encode($result); exit;
- } else {
- return false;
- }
- }
- ?>
- CgridView Row Background color with condition of a data:::
- ==========================================================
- <?php $this->widget('zii.widgets.grid.CGridView', array(
- 'id'=>'transferdt-grid',
- 'rowCssClassExpression'=>'($data->available <= 10) ? "red-alert": "especial" ',
- 'columns'=>array(
- ),
- )); ?>
- Style color::::
- <?php
- <style type="text/css">
- .red-alert{
- background-color: #FFB9B9;
- }
- .especial{
- background-color: #eeedeb;
- }
- </style>
- ?>
Advertisement
Add Comment
Please, Sign In to add comment