selimppc

Yii-1-guide-

Dec 27th, 2016
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 17.13 KB | None | 0 0
  1. Criteria Search Testing ::
  2. ================================
  3.  
  4. <?php
  5.  
  6.     function actionController(){
  7.        
  8.         $criteria=new CDbCriteria;
  9.        
  10.         $criteria -> compare ('email', 'gmail');
  11.         $criteria -> addInCondition('id', array(2,3));
  12.         $criteria -> addNotInCondition('id', array(2,3));
  13.         $criteria -> addBetweenCondition ('id', 1,2);
  14.         $criteria -> condition = "name = 'H'";
  15.         $criteria -> addCondition("id = 1");
  16.        
  17.         $criteria -> select="t.id, t.identification, t.email, t.numbers, c.numbers";
  18.         $criteria -> join = "INNER JOIN DataTable c ON c.id = t.id";
  19.         $criteria -> order = "id DESC";
  20.         $criteria -> limit ="10";
  21.        
  22.         $criteria-> with=array(
  23.                             "ciudad"=>array(
  24.                                 "condition"=>"id=1",
  25.                                 "on"=>"id=1",
  26.                                 "joinType"=>"INNER JOIN",
  27.                                     ),
  28.                             "experience");
  29.                            
  30.                            
  31.         $criteria->addSearchCondition('name',  strtoupper( $_GET['term']) ) ;
  32.         $criteria->addSearchCondition('code', strtoupper ( $_GET['term']), true, 'or');
  33.        
  34.         $criteria -> compare('id', $this->id, true);
  35.         $criteria -> compare('number', $this->number, true);
  36.         $criteria -> compare('identification', $this->identification, true);
  37.         $criteria -> compare('email', $this->email, true);
  38.  
  39.        
  40.         $usuarios= Data::model()->findAll($criteria);
  41.         $model= new Data;
  42.         $usuarios= new CActiveDataProvider($model, array('criteria'=>$criteria));
  43.         $usuarios= Data::model()->findAllByPk(array(1,2));
  44.         $usuarios= Data::model()->findAllByAttribute(array('id'+.1));
  45.        
  46.         $sql="SELECT * FROM data WHERE id=1";
  47.         $data= Data::model()->findAllBySql($sql);
  48.        
  49.     }
  50. ?>
  51.  
  52.  
  53.  
  54.    
  55.     AutoComplete Search in Controller by Criteria::
  56.     ==============================================
  57.    
  58. <?php
  59.    
  60.     public function actionJuiList()
  61.     {
  62.         $arr = array();
  63.  
  64.         if (isset($_GET['term']))
  65.         {
  66.             $criteria = new CDbCriteria();
  67.             $criteria->addSearchCondition('name', $_GET['term']);
  68.             $models = Data::model()->findAll($criteria);
  69.             foreach ($models as $model)
  70.             {
  71.                 $arr[] = array(
  72.                     'name'=>$model->data,
  73.                     'label'=>CHtml::image('path/to/image').' '.$model->data,
  74.                     'id'=>$model->id,
  75.                 );
  76.             }
  77.         }
  78.         echo CJSON::encode($arr);
  79.         Yii::app()->end();
  80.     }
  81. ?>
  82.  
  83.  
  84. Model Rules For Existance Validation
  85. ====================================
  86. <?php
  87.     public function rules()
  88.         {
  89.             return array(
  90.                 array('cm_code', 'cmCode'),
  91.             );
  92.         }
  93.    
  94.    
  95.     public function cmCode($cm_code)
  96.     {
  97.         if(!empty($this->cm_code))  
  98.         {    
  99.             $record = Productmaster::model()->findByAttributes(array('cm_code' => $this->cm_code));
  100.             if($record === null)
  101.             {
  102.                 $this->addError($cm_code, 'Invalid Product Code');
  103.             }
  104.         }
  105.      }
  106.  
  107.      
  108.      
  109.      public function imRcvQuantity($im_RcvQuantity)
  110.     {
  111.         if(!empty($this->im_RcvQuantity))  
  112.         {    
  113.             $record = VwPurchasedt::model()->findByAttributes(array('cm_code' => $this->cm_code))->pp_quantity;
  114.            // var_dump($record) ;
  115.             //exit();
  116.             if($record < $this->im_RcvQuantity)
  117.             {
  118.                 $this->addError($im_RcvQuantity, 'Received quantity must be Less OR Equal to Quantity');
  119.             }
  120.         }
  121.      }
  122. ?>
  123.  
  124. Using own function in validation rules- In the rule specify the function with attribute like this-
  125. ===================================================================================================
  126. <?php
  127. array('username','checkuniquename'),
  128.  
  129. public function checkuniqueemail($attribute)
  130. {
  131.     $record=Users::model()->findByAttributes(array($attribute=>$this->email));
  132.     if($record!==null)
  133.          $this->addError($attribute, 'This email has been already taken please choose a different one');
  134.  
  135. }
  136.  
  137. ?>
  138.  
  139.  
  140. Visible
  141. =======
  142.  
  143. <?php
  144.         ('.Yii::app()->user->name.')
  145.        
  146.         'visible' => Yii::app()->user->isGuest
  147.         'visible'=>!Yii::app()->user->isGuest
  148.         'visible'=>Yii::app()->user->checkAccess('operations')
  149. ?>
  150.  
  151.  
  152. Menu Condition
  153. ==============
  154.  
  155. <?php if (Yii::app()->user->isGuest){ ?>
  156.  
  157. <?php  } else { ?>
  158.  
  159. <?php } ?>
  160.  
  161.  
  162.  
  163. Multiply Two Text Field and view to another
  164. ===========================================
  165. <?php
  166.     <script type="text/javascript">
  167.         $(function() {
  168.             $("#discrate").change(function(){
  169.                     setTarget()
  170.             });
  171.                 $("#discamt").change(function(){
  172.                     setTarget();
  173.             });
  174.             });
  175.  
  176.             function setTarget(){
  177.                 var a = $("#discrate").val();
  178.                 var b = $("#discamt").val();
  179.                 var data = (a * b);
  180.                 $('#amount').val(data);
  181.             }
  182.     </script>
  183. ?>
  184.  
  185.  
  186. JOIN Query
  187. ==========
  188. <?php
  189. $rows = Yii::app()->db->createCommand()
  190.             ->select('j.*, p.orderno, p.category, o.bidno')
  191.             ->from('jobs j')
  192.             ->join('projects p','j.projid = p.projid')
  193.             ->join('orders o', 'p.orderno = o.orderno')
  194.             ->where('j.projid=:id', array(':id'=>$id))
  195.             ->order('j.jobno,j.projid')
  196.             ->queryRow();
  197.            
  198.            
  199. $user = Yii::app()->db->createCommand()
  200.     ->select('id, username, profile')
  201.     ->from('tbl_user u')
  202.     ->join('tbl_profile p', 'u.id=p.user_id')
  203.     ->where('id=:id', array(':id'=>$id))
  204.     ->queryRow();
  205. ?>
  206.  
  207.  
  208.  
  209. add more information to Yii::app()->user
  210. ========================================
  211.  
  212. <?php
  213. **use the UserIdentity class
  214.  
  215.         else
  216.         {
  217.             $this->_id=$user->id;
  218.             $this->setState('username', $user->username); //// place here
  219.             $this->errorCode=self::ERROR_NONE;
  220.         }
  221.         return !$this->errorCode;
  222.  
  223.  
  224.  
  225. use anywhere::
  226. $username=Yii::app()->user->username;
  227.  
  228. ?>
  229.  
  230.  
  231. Delete Confirmation
  232. ===================
  233.  
  234. <?php
  235.  
  236.     array
  237.     (
  238.             'class'=>'CButtonColumn',
  239.             'deleteConfirmation'=>"js:'Do you really want to delete record with ID '+$(this).parent().parent().children(':nth-child(2)').text()+'?'",
  240.     ),
  241.  
  242. ?>
  243.  
  244.  
  245.  
  246. Image Path in array
  247. ===================
  248. <?php
  249.  
  250.  array(
  251.     'image'=>Yii::app()->baseUrl.'/path/to/img3', 'imageOptions'=>array('style'=>'display: block; margin: 10px auto;'),
  252.       ),
  253. ?>
  254.  
  255.  
  256. Hide if Not New Records
  257. =========================
  258.  
  259. <?php  if (!$model->isNewRecord): ?>
  260. <input type="hidden" name="update_id"
  261.        value=" <?php echo $model->id; ?>"/>
  262. <?php endif; ?>
  263.  
  264.  
  265.  
  266.  
  267. Ajax Dependable texfiled with a Dropdown list in Yii
  268. ====================================================
  269.  
  270. My Form::
  271. <?php
  272. <div class="row">
  273.     <?php echo $form->labelEx($model,'pp_store'); ?>
  274.     <?php // echo $form->dropDownlist($model,'pp_store', CHtml::listData(Branchmaster::model()->findAll(), 'cm_branch', 'cm_branch')); ?>
  275.     <?php $storeArray = CHtml::listData(Branchmaster::model()->findAll(),'cm_branch','cm_branch');
  276.        echo $form->dropDownList($model,'pp_store', $storeArray,
  277.                       array(
  278.                             'empty'=>"Select Warehouse",
  279.                             'ajax' => array(
  280.                                 'type'=>'POST',
  281.                                 'url'=>CController::createUrl('purchaseordhd/GetCurrency' ),
  282.                                 'update' => '#currencyid',  
  283.                                 'data'=>array('store'=>'js:this.value',),  
  284.                                 'success'=> 'function(data) {$("#currencyid").empty();
  285.                                $("#currencyid").val(data);
  286.                                } ',
  287.                       ),
  288.  
  289.         )); ?>
  290.     <?php echo $form->error($model,'pp_store'); ?>
  291. </div>
  292.  
  293. <div class="row">
  294.     <?php echo $form->labelEx($model,'pp_currency'); ?>
  295.     <?php echo $form->textField($model,'pp_currency', array('id'=>'currencyid', 'readonly'=> true)); ?>
  296.     <?php echo $form->error($model,'pp_currency'); ?>
  297. </div>
  298.  
  299. ?>
  300.  
  301. My Controller::
  302.  
  303. <?php
  304.  
  305.    public function actionGetCurrency()
  306.     {
  307.         $q = $_POST['store'];
  308.  
  309.         $sql = "SELECT cm_currency as value FROM cm_branchmaster WHERE cm_branch= '$q' ";
  310.         $command = Yii::app()->db->createCommand($sql);
  311.         $result= $command->queryScalar();
  312.         echo $result;
  313.  
  314.     }
  315. ?>
  316.  
  317.  
  318. Display Data from related tables in CGridview in yii
  319. ==================================================
  320. view of grid view:::
  321. <?php
  322.     $this->widget('zii.widgets.grid.CGridView', array(
  323.         'id'=>'users-grid',
  324.  
  325.         'dataProvider'=>$dataProviderObj,
  326.         'columns'=>array(
  327.  
  328.             'productName',
  329.             'productType',
  330.             'productBrand',
  331.             'description',
  332.             array(
  333.                 'name' => '<column_name>'
  334.                 'value' => array($this,'gridCreateduser')
  335.             )
  336.          ),
  337.     ));
  338. ?>
  339.  
  340.  
  341. Now in controller:::
  342. <?php
  343.  
  344.     public function gridCreateUser($data,$row){
  345.  
  346.      $user = $data-> <colmn_name>;
  347.      //do your stuff for finding the username or name with $user
  348.      //for eg.
  349.      $detail = User::model()->findByPk($user);
  350.      // 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.
  351.      return $detail->username;
  352.     }
  353. ?>
  354.  
  355. OR you can use in a simple manner by defining relation between models inside model whose gridview you are creating
  356.  
  357. <?php
  358.     public function relations(){
  359.             return array(
  360.             'users' => array(self::HAS_MANY, 'Users', '<column_name>'),
  361.             );
  362.         }
  363.    
  364.    
  365.     // ::::: Then you can directly access it in you grid view ::::
  366.  
  367.     $this->widget('zii.widgets.grid.CGridView', array(
  368.     'id'=>'users-grid',
  369.  
  370.     'dataProvider'=>$dataProviderObj,
  371.     'columns'=>array(
  372.         'productName',
  373.         'productType',
  374.         'productBrand',
  375.         'description',
  376.         array(
  377.             'name' => '<column_name>'
  378.             'value' => $data->users->username
  379.         )
  380.      ),
  381.     ));
  382.  
  383. ?>
  384.  
  385.  
  386. Admin Filter  Dropdown Search:
  387. ============================================================
  388.  
  389. <?php
  390.     array(
  391.             'name'=>'cm_orgname',
  392.             'value'=>'$data->cm_orgname',
  393.             'filter'=>CHtml::listData(Suppliermaster::model()->findAll(), 'cm_supplierid', 'cm_orgname')
  394.         ),
  395.  
  396. ?>
  397.  
  398.  
  399.  
  400. Model Search with Join Query from Model
  401. ===========================================
  402. <?php
  403.  
  404.     $criteria->select = 't.*, m.cm_description, n.cm_orgname';
  405.     //$criteria->condition = "t.pp_purordnum = '$pp_purordnum' ";
  406.     $criteria->join = 'INNER JOIN cm_branchmaster m ON t.pp_branch = m.cm_branch';
  407.     $criteria->join .= ' INNER JOIN cm_suppliermaster n ON t.cm_supplierid = n.cm_supplierid';
  408.        
  409.        
  410. ?>
  411.  
  412. Dataprovider with Multiple Join query in Controller:::
  413. ===============================================================
  414. <?php
  415. public function actionName( $im_transfernum, $im_status ){
  416.        
  417.         $criteria = new CDbCriteria();
  418.         $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";
  419.         $criteria -> join = "INNER JOIN im_transferhd c  ON  c.im_transfernum = t.im_transfernum ";
  420.         $criteria -> join .= " INNER JOIN cm_productmaster n ON t.cm_code = n.cm_code";
  421.         $criteria -> condition = "t.im_transfernum = '{$im_transfernum}'";
  422.  
  423.         $dataProvider = new CActiveDataProvider('Transferdt',array(
  424.             'criteria' => $criteria
  425.         ));
  426.        
  427.          $this->render('transfer_number', array('dataProvider' => $dataProvider));
  428.         }
  429.        
  430. ?>
  431.  
  432.  
  433. Set Flash in View
  434. =========================================================
  435. <?php if(Yii::app()->user->hasFlash('success')):?>
  436.         <div class="flash-success">
  437.                 <?php echo Yii::app()->user->getFlash('success'); ?>
  438.                 <?php
  439.                     Yii::app()->clientScript->registerScript(
  440.                         'myHideEffect',
  441.                         '$(".flash-success").animate({opacity: 1.0}, 3000).fadeOut("slow");',
  442.                         CClientScript::POS_READY
  443.                     );
  444.                 ?>
  445.         </div>
  446. <?php endif; ?>
  447.  
  448.  
  449.  
  450.  
  451. ========== Relation between model or table ===================
  452.  
  453. === In Model =====
  454. public $product_search;
  455.  
  456. return array(
  457.     array('product_search', 'safe', 'on'=>'search'),
  458. )
  459.  
  460. public function relations()
  461.     {
  462.         return array(
  463.             'product' => array(self::BELONGS_TO, 'Productmaster', 'cm_code'),
  464.         );
  465.     }
  466.  
  467. public function search()
  468.     {
  469.         $criteria->with = array( 'product' );
  470.         $criteria->compare( 'product.cm_name', $this->product_search, true );
  471.        
  472.         return new CActiveDataProvider($this, array(
  473.             'criteria'=>$criteria,
  474.         ));
  475.     }
  476.  
  477.  
  478. ===== In View/Admin Page ============
  479. Cgridview:::::
  480. ======
  481.  
  482. array( 'name'=>'product_search', 'value'=>'$data->product->cm_name' ),
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489. ==================================================================================
  490. Dropdown List with Concat in yii form with another MODEL
  491. ==================================================================================
  492. <?php   $coa = Chartofaccounts::model()->findAll();
  493.                 $data = array();
  494.                 foreach ($coa as $coa)
  495.                     $data[$coa->am_accountcode] = $coa->am_accountcode . ' '. $coa->am_description;
  496.  
  497.         echo $form->dropDownList($model, 'am_accountcode', $data ,array('prompt' => '- Select Account -', 'required'=>TRUE,));
  498.  
  499. ?>
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507. Check Exist in model data
  508. ============================
  509. <?php
  510. In Controller:::
  511.  
  512.  
  513.     private function actionAdjustmentExist($transaction_number){
  514.         $model = new Adjustdt();
  515.         return $model->exists('transaction_number = :transaction_number', array(':transaction_number'=>$transaction_number));
  516.  
  517.     }
  518.    
  519.    
  520.     OR :::::::::
  521.    
  522.     private function actionCheckTransaction($transaction_number){
  523.         $sql="SELECT 1 FROM im_adjustdt WHERE transaction_number='$transaction_number' ";
  524.         $cmd=Yii::app()->db->createCommand($sql);
  525.         $result= $cmd -> queryScalar();
  526.         return $result;
  527.     }
  528.    
  529. ?>
  530.  
  531.  
  532. Redirect to same page
  533. ==========================
  534.  
  535. <?php
  536.     $this->redirect(Yii::app()->request->urlReferrer);
  537. ?>
  538.  
  539.  
  540.  
  541. A link on Image in Yii
  542. =========================
  543. <?php echo CHtml::link(CHtml::image(Yii::app()->request->baseUrl.'/images/action_btn_xls.png' alt=''), array('PostToGl', 'am_vouchernumber'=>$am_vouchernumber));
  544. ?>
  545.  
  546.  
  547.  
  548.  
  549.  
  550.  
  551. CDbException Error in Controller
  552. ================================
  553. <?php
  554.     try{
  555.         $model->save();
  556.         Yii::app()->user->setFlash('success', Yii::t('Product', 'Success Message : Data Added Successfully !'));
  557.     }catch(CDbException $e){
  558.         Yii::app()->user->setFlash('error', Yii::t('Product', 'Warning Message: Invalid request ! Product code already exist!'));
  559.     }
  560. ?>
  561.  
  562.  
  563.  
  564. Quantity Should not be blank or zero ::: Model Rules
  565. ====================================================
  566. <?php
  567.  
  568.     return array(
  569.         array('pp_quantity', 'greaterThanZero'),
  570.     ),
  571.  
  572.  public function greaterThanZero($pp_quantity)
  573.     {
  574.  
  575.         if ($this->$pp_quantity<=0)
  576.             $this->addError($pp_quantity, 'Quantity should not be blank or zero');
  577.  
  578.     }
  579.  
  580. ?>
  581.  
  582.  
  583. Auto-Complete Search with some Value/text / Condition:
  584. ======================================================
  585. <?php
  586.  
  587.     $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
  588.         'name'=>'product_name',
  589.         'model'=>$model,
  590.         //'source'=>CController::createUrl('/smheader/autocompleteTestNew'),
  591.         'source'=>'js: function(request, response) {
  592.             $.ajax({
  593.                 url: "'.$this->createUrl('smheader/autocompleteTestNew').'",
  594.                 dataType: "json",
  595.                 data: {
  596.                     term: request.term,
  597.                     productClass: $("#productClass").val(),
  598.                     warehouse: $("#warehouse").val(),
  599.                 },
  600.                 success: function (data) {
  601.                         response(data);
  602.                 }
  603.             })
  604.          }',
  605.         'options'=>array(
  606.             'minLength'=>'1',
  607.             'select'=>'js:function( event, ui ) {
  608.                     $("#product_name").text(ui.item.label);
  609.                     $("#code").val(ui.item.code);
  610.                  }',
  611.         ),
  612.         'htmlOptions'=>array(
  613.             'id'=>'product_name',
  614.             'placeholder'=>'search by product name or code',
  615.             //'style' => 'width: 96%; padding: 8px; margin-bottom: 10px; border: 1px solid orange;',
  616.             //'onClick' => 'document.getElementById("cm_code").value= ""',
  617.         ),
  618.     ));
  619.  
  620.    
  621.    
  622.     Controller:::
  623.     =============
  624.    
  625.     public function actionAutocompleteTestNew() {
  626.  
  627.         $productClass = $_GET['productClass'];
  628.         $warehouse = $_GET['warehouse'];
  629.         $date = date("Y-m-d");
  630.  
  631.         if($productClass == 'PRODUCT'){
  632.             if (!empty($_GET['term'])) {
  633.  
  634.                 $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
  635.                     FROM cm_productmaster t
  636.                     INNER JOIN im_vw_stock r ON t.cm_code = r.cm_code
  637.                     WHERE r.im_storeid='$warehouse' AND r.im_ExpireDate >='$date' AND t.cm_name LIKE :qterm
  638.                     GROUP BY r.cm_code";
  639.  
  640.                 $sql .= ' ORDER BY label ASC';
  641.                 $command = Yii::app()->db->createCommand($sql);
  642.                 $qterm = $_GET['term'].'%';
  643.                 //$command->bindValue(":qterm", $_GET['term'].'%', PDO::PARAM_STR);
  644.                 $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
  645.                 $result = $command->queryAll();
  646.  
  647.                 echo CJSON::encode($result); exit;
  648.  
  649.             } else {
  650.                 return false;
  651.             }
  652.         }
  653.  
  654.  
  655. ?>
  656.  
  657.  
  658.  
  659. CgridView Row Background color with condition of a data:::
  660. ==========================================================
  661. <?php $this->widget('zii.widgets.grid.CGridView', array(
  662.     'id'=>'transferdt-grid',
  663.     'rowCssClassExpression'=>'($data->available <= 10) ? "red-alert": "especial" ',
  664.  
  665.     'columns'=>array(
  666.  
  667.     ),
  668. )); ?>
  669.  
  670. Style color::::
  671. <?php
  672.     <style type="text/css">
  673.         .red-alert{
  674.             background-color: #FFB9B9;
  675.         }
  676.         .especial{
  677.             background-color: #eeedeb;
  678.         }
  679.     </style>
  680. ?>
Advertisement
Add Comment
Please, Sign In to add comment