fredag den 1. november 2013

Yii Yii?

Chosing the right Framework for your project is Alpha && Omega.

Choose Yiisely

Choose Yii

http://YiiFrameWork.com

fredag den 18. oktober 2013

Yii Scopes Magic in Relations :)

In an earlier post I explained how much the life gets easier when unitlizing the Scopes.
Here is something more.

When accessing the Relation's data or the relative's data you can take advantage of the Scopes in this way:


$currentpost->comments( array( 'scopes'=>array( 'recent' ) ) );
In the above code, you fetch the 'recent' 'Comments' which are gives to a given 'Post'


$visit->course->courseQuizs( array( 'scopes'=>'post' ) )
In this example you fetch the 'post-Course' 'Quiz'.
 
/* Defining Scopes for the Model */
public function scopes()
{
 return array(
  'pre'=>array(
   'condition'=>'pre=1',
  ),
  'post'=>array(
   'condition'=>'pre=0',
  ),
 );
} 
 
 
As you see the Scopes can be type String or Mixed.
If Mixed then all the Scopes will be merged into a single Scope.

torsdag den 17. oktober 2013

Yii Magic, Use of Scope

Hi,

This is one the magical features of ActiveRecord (AR) in Yii Framework.

When you need to create a Scope or limitation, the only thing that needs to be done is to define and add the 'function scopes' in the model class and then you are able to define the Scope rules.

Example:

In this example the 'owner' scope is defined. If you are familiar with the CDBCriteria definitions, defining the Scope would be like a `walk in the park`.

public function scopes()
    {
        return array(
            'owner'=>array(
                'with'=>array('department'),               
                'condition'=>'t.department_id = department.id AND department.user_company_id=:user_company_id',
                'params'=>array(
                    ':user_company_id'=>Ccom::user()->userCompany->id,
                ),
            ),
        );
     }

/**
* Ccom::user()->userCompany->id 
* is my short hand for
* User::model()->findByPk(Yii::app()->user->id)->userCompany->id
*/

This rule is defined so the user can only access her or his own groups in the departments of his company.

't.' in this case is the Group table, and Group table is related to Department table by the foreign key 'department_id' and Department is related to the UserCompany table by the foreign key 'user_company_id'

To use this Scope you have many options.

Examples:
Use
$dataProvider=new CActiveDataProvider(Group::model()->owner());
Instead of
$dataProvider=new CActiveDataProvider('Group');

Group::model()->owner() return a type CDbCritera object, with every thing there is needed to make an approperiate Select from the database

Use
Department::model()->owner()->findAll();
Instead of
Department::model()->findAll();

Use
$model->owner()->search();
Instead of
$model->search();

I wish the Yii Core developers best of luck. They really do a great job.
Please leave a comment or link if you have related knowledge about this subject, thanks.

Read more here: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

tirsdag den 8. oktober 2013

Yii Select2, How to initiated selected (saved) values


To achieve this

In this scenarie we have 5 choice from which 3 are already saved and we wish to represent this selection again in our form by YiiBooster

Pay attention to text colors.

This widget call:

$this->widget(
        'bootstrap.widgets.TbSelect2',
        array(
            'asDropDownList' => false,
            'name' => 'userRoles',
            'data'=>$userRoles,
            'options' => array( // selected options by default
               
            ),
            'options' => array(           
                'tags' => $userRoles, // Array
                'placeholder' => '',
                'width' => '220px',
                'tokenSeparators' => array(',', ' '),
                'initSelection'=>'js:function(element, callback){
                    var data = [];
                    '.$s2InitStr.'
                    callback(data);
                }',
            ),
        )
    );

Produces this JS code

jQuery('#userRoles').select2(
{
'tags':['Admin','Authenticated','Guest','representative','yderzonen'],
'placeholder':'',
'width':'220px',
'tokenSeparators':[',',' '],
'initSelection':function(element, callback){
var data = [];
data.push({id:'Admin' , text: 'Admin'});
data.push({id:'Authenticated' , text: 'Authenticated'});
data.push({id:'representative' , text: 'representative'});
callback(data);
}});
 
 
After this is done you have to produce this JS code:
 
jQuery(function($) {
 
 /**
  * The selectors must be changed to match your Select2 ID 
  */
 
  $('#s2id_userRoles').select2('val','Admin');
  $('#s2id_userRoles').select2('val','Authenticated');
  $('#s2id_userRoles').select2('val','representative');
 
}); 


More Documentation
 
http://ivaynberg.github.io/select2/ 
http://stackoverflow.com/questions/15174635/proper-usage-of-jquery-select2s-initselection-callback-with-remote-data
http://yiibooster.clevertech.biz/widgets/forms_inputs/view/select2.html#config
 
If you have a better idea please leave a link. Thanks
 

mandag den 30. september 2013

How to upload a file using a model

http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

validating the file size:
 
In the model, in the rules functions add this line
 
 /**
  * @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(
                      'yourfile', 
                      'file', 
                      'types'=>'jpg, gif, png, jpeg',  
                      'maxSize'=>1024 * 1024 * 50,  
                      'tooLarge'=>'File has to be smaller than 50MB'
                    ),
                .....
                .....
                .....
                ); 
        }

tirsdag den 24. september 2013

Yii - If you like me searched for ajaxvalidation

Generate A form and try to add this in begin widget
<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'top-websites-cr-form',
        'enableAjaxValidation'=>true,
        'clientOptions' => array(
      'validateOnSubmit'=>true,
      'validateOnChange'=>true,
      'validateOnType'=>false,
         ),
)); ?>
work like charm ;-)

tirsdag den 17. september 2013

Yii how to open modal via AJAX via bootstrap

$this->widget('bootstrap.widgets.TbExtendedGridView', array(
    'type'=>'bordered',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'template'=>"{items}",
    'columns'=>array(
        'id',
        'firstName',
        'lastName',
        'language',
        'hours',
        array(
            'header'=>'Options',
            'class'=>'bootstrap.widgets.TbButtonColumn',
            'buttons'=>array(
                'view'=>
                    array(
                        'url'=>'Yii::app()->createUrl("person/view", array("id"=>$data->id))',
                        'options'=>array(
                            'ajax'=>array(
                                'type'=>'POST',
                                'url'=>"js:$(this).attr('href')",
                                'success'=>'function(data) { $("#viewModal .modal-body p").html(data); $("#viewModal").modal(); }'
                            ),
                        ),
                    ),
            ),
        )
    )));
?>

<!-- View Popup  -->
<?php $this->beginWidget('bootstrap.widgets.TbModal', array('id'=>'viewModal')); ?>
<!-- Popup Header -->
<div class="modal-header">
<h4>View Employee Details</h4>
</div>
<!-- Popup Content -->
<div class="modal-body">
<p>Employee Details</p>
</div>
<!-- Popup Footer -->
<div class="modal-footer">

<!-- close button -->
<?php $this->widget('bootstrap.widgets.TbButton', array(
    'label'=>'Close',
    'url'=>'#',
    'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
<!-- close button ends-->
 
 
// the action should look like this
 
public function actionView($id)
{
    if( Yii::app()->request->isAjaxRequest )
        {
        $this->renderPartial('view',array(
            'model'=>$this->loadModel($id),
        ), false, true);
    }
    else
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }
} 
 

Yii - How to enable SQL logging

'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=version2',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'tablePrefix' => '',
            'enableProfiling'=>true, // add this line to the db config
        ),

You should remember to uncomment the routes:

'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                // Default Class Profile Log Route
                array(
                    'class'=>'CProfileLogRoute',
                    'report'=>'summary',
                    // lists execution time of every marked code block
                    // report can also be set to callstack
                ),
           
                // yii-debug-toolbar is a good debugging tool(bar)
                array(
                    'class'=>'ext.yii-debug-toolbar-master.yii-debug-toolbar.YiiDebugToolbarRoute',
                    'ipFilters'=>array('127.0.0.1','192.168.1.19'),
                ),
            ),
        ),

Yii yii-debug-toolbar

This is a very nice Debugging toolbar

The ZIP archive one the extension page is old and it must be downloaded from Github
https://github.com/malyshev/yii-debug-toolbar

søndag den 15. september 2013

Customize YiiBooster CKeditor Toolbar


$ckeditor = 'js:[
 { name: "document", items : [ "NewPage", "Preview" ] },
        { name: "clipboard", items : [ "Cut","Copy","Paste","PasteText","PasteFromWord","-","Undo","Redo" ] },
        { name: "editing", items : [ "Find","Replace","-","SelectAll","-","Scayt" ] },
        { name: "insert", items : [ "Image","Flash","Table","HorizontalRule","Smiley","SpecialChar","PageBreak"
                 ,"Iframe" ] },
 "/", //Line Break
 { name: "styles", items : [ "Styles","Format" ] },
        { name: "basicstyles", items : [ "Bold","Italic","Strike","-","RemoveFormat" ] },
        { name: "paragraph", items : [ "NumberedList","BulletedList","-","Outdent","Indent","-","Blockquote" ] },
 

 { name: "links", items : [ "Link","Unlink","Anchor" ] },
 

 { name: "tools", items : [ "Maximize","-","About" ] }
 ]';
  
     echo $form->ckEditorRow($model, 'description', array( 'options'=>array(
            'disableNativeSpellChecker'=>false,
            'scayt_autoStartup'=>true,
            'fullpage'=>'js:true',
            'width'=>'768',
            'resize_maxWidth'=>'768',
            'resize_minWidth'=>'320',
            'toolbar'=>$ckeditor,
    )));


 More on options you can choose on this page: http://ckeditor.com/latest/samples/plugins/toolbar/toolbar.html

lørdag den 14. september 2013

Yii - really good image gallery

I like this one, I used XUpload before, but this one is more complete

http://www.yiiframework.com/extension/imagesgallerymanager/

Get it from BitBucket : https://bitbucket.org/z_bodya/gallerymanager

I'll try to write a "best practice" for integrating this with the rest of the site. But later when I know how :)

Yii - Add image manipulation to your site

Read this, very simple
http://www.yiiframework.com/extension/image/

And this is the modified version with more options:
https://bitbucket.org/z_bodya/yii-image/downloads

Yii YUM ( User Management ) Avatar Config Settings

This lines can be added in the protected/config/main.php

in the module section add

'avatar'=>
array(
'defaultController' =>'avatar', //default no need to add this
'enableGravatar' =>true,

// enable gravatar automatically for new registered users?
'enableGravatarDefault' => true,

// override this with your custom layout, if available
'adminLayout' => 'application.modules.user.views.layouts.yum', //Default

'layout' => 'application.modules.user.views.layouts.yum', //Default
'avatarPath' => 'images', //Default , change it to 'images/users/'

// Set avatarMaxWidth to a value other than 0 to enable image size check
'avatarMaxWidth' => 0,
'avatarThumbnailWidth' => 50, // For display in user browse, friend list
'avatarDisplayWidth' =>200,
),

torsdag den 12. september 2013

Adding your own layout for yii-user-management (YUM)

http://capstone3.blogspot.dk/2012/03/adding-your-own-layout-for-yii-user.html

her is the YUM's installation instructions
http://code.google.com/p/yii-user-management/wiki/InstallationInstructions

Fake sendmail for windows

A good way to solve the problem if you need sendmail for your WAMP or XAMP or other purposes

http://glob.com.au/sendmail/

Using twitter bootstrap with bottom sticky footer

http://mvcdiary.com/2012/04/04/using-twitter-bootstrap-with-bottom-sticky-footer/

YiiBooster


YiiBooster ( Yii Bootstrap ) developed by CleverTech
This one works together with Yii MenuBuilder
http://yii-booster.clevertech.biz/


This solution is based upon http://www.cniska.net/yii-bootstrap/

Yii - jQueryui datepicker widget setup


add this in your form..............

$this->widget('zii.widgets.jui.CJuiDatePicker', array(

'id'=>'ID-starting_date', // consider usinge CHtml::activeId

'model'=>'', // Use model here

'attribute'=>'starting_date',

'name'=>'UserOrder[starting_date]', // the modelName[attributeName]

'language'=>'da', // choose language, this one is Danish

'htmlOptions' => array(

'size' => '10',         // textField size

'maxlength' => '10',    // textField maxlength

),

'options' => array(

'showOn' => 'both',             // also opens with a button

'dateFormat' => 'yy-mm-dd',     // format of "2012-12-25"

'showOtherMonths' => true,      // show dates in other months

'selectOtherMonths' => true,    // can select dates in other months

'changeYear' => true,           // can change year

'changeMonth' => true,          // can change month

'yearRange' => '2013:2023',     // range of year

'minDate' => '2013-01-01',      // minimum date

'maxDate' => '2099-12-31',      // maximum date

'showButtonPanel' => true,      // show button panel

),

));

Yii-user mishamx, disable the registration link on login page

The only solution I found was to edit the view file and comment out the section.

in \protected\modules\user\views\user\login.php

find the section and comment it out.


<!-- div>
  <p class="hint">
    <?php echo CHtml::link(UserModule::t("Register"),Yii::app()->getModule('user')->registrationUrl); ?> |   <?php echo CHtml::link(UserModule::t("Lost Password?"),Yii::app()->getModule('user')->recoveryUrl); ?>
  </p>
</div -->

and add an "<?php exit; ?>" on the start of the page

in \protected\modules\user\views\user\registration.php