Tuesday, May 14, 2013

YII: Create a Delete Button with Post Action and Confirmation Dialog

Here is how to create a delete button or link with post action and also add confirmation dialog.

echo CHtml::link("Delete", '#', array('submit'=>array('post/delete', "id"=>$data->id), 'confirm' => 'Are you sure you want to delete?'));






In order to delete, you must pass variable through post action, not get action, so here is how you can make a delete button.


Tuesday, April 09, 2013

Using CJUIDatePicker in Yii CActiveForm Widget

If you want to add Jquery UI DatePicker in create/update form, you can do the following,
http://jqueryui.com/datepicker/

Inside
<?php
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'event-form',
    'enableAjaxValidation'=>false,
)); ?>


<?php $this->endWidget(); ?>

Find the row you want to add the datepicker,

<div class="row">
 <?php echo $form->labelEx($model,'created'); ?>
 <?php echo $form->textField($model,'created'); ?>
 <?php echo $form->error($model,'created'); ?>
</div>
 
Replace 
<?php echo $form->textField($model,'created'); ?> 
with
 
<?php 
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
 'name'=>"Event[created]", // the name of the field
 'value'=>$model->created,  // pre-fill the value
 // additional javascript options for the date picker plugin
 'options'=>array(
 'showAnim'=>'fold',
 'dateFormat'=>'yy-mm-dd',  // optional Date formatting
 'debug'=>true,
),
 'htmlOptions'=>array(
 'style'=>'height:20px;'
 ),
 )); 
?>
That's it!  Unfortunately, it didn't work for me, so I had to update old jquery-ui.css and jquery-ui.js.

To update them, download the latest stable version and upload them to PATH-TO-FRAMEWORK/web/js/source/jui/js / jquery-ui.min.js and jquery-ui-i18n.min.js and /web/js/source/jui/css/base / jquery-ui.css

Yay! It is working~
 

 

Friday, February 22, 2013

YII: How to Customize the Admin action

If you want to add condition, you can do the following: 

1) copy-paste your action and change only name of it, for example "actionList"
2) change 2 lines of method search in your model to

public function search($param = array())
{
  $criteria=new CDbCriteria($param);
.....................................

3) copy-paste your admin view and rename it to "list" then open it and change line
'dataProvider'=>$model->search(),

to


'dataProvider'=>$model->search(array('condition'=>'column_name=1')),
 
// Added by me 
4) Or if you want to just use same "admin" view page, you can just add a variable:
 
                $this->render('admin',array(
   'model'=>$model, 'condition'=>$condition,
  ));
 
And in the admin view page, you can 
change it as below. 
'dataProvider'=>$model->search(array('condition'=>$condition)),
 
 
Reference:
http://www.yiiframework.com/forum/index.php/topic/13079-customising-the-admin-action-created-by-crud/
 

Secure your website with JavaScript, NO RIGHT CLICK

No right click code for images. Block your visitors from right clicking on your website pages with 'no right click for source'. Disable "copy and paste" to protect your websites source code!

http://www.hypergurl.com/norightclick.html

Error Fix: Delete Action Calls for Get Request in YII CGridView

Error Fix: Delete Action Calls for Get Request in YII CGridView

Suddenly, I noticed that delete button in YII CGridView didn't work.

Yii::app()->request->isPostRequest would return false, which means that variables were passed through $_GET request.

After checking FireBug js error, I had to update jquery.ba-bbq.js file and jquery.yiigridview.js file and updated jquery.js just in case.

https://github.com/yiisoft/yii/issues/2069

http://code.google.com/p/zii/source/browse/trunk/widgets/assets/gridview/jquery.yiigridview.js?r=208


Be sure to delete the specific folder that saved the javascript file in assets folder to delete the cache.
Everything is working fine after that~

Friday, February 15, 2013

Installing Drupal

To install Drupal:

1. Download latest stable version of Drupal
2. Upload them to the directory that you want to install
3. Extract the tar.gz or zip file to the directory
4. Move one directory up because the tar.gz or zip file would be extracted in one directory
5. Copy /sites/default/default.settings.php and change default.settings.php (you would see two files inside /sites/default/ folder - default.settings.php and settings.php)
6. Modify file permission for settings.php
7. Run install
8. Change permission for settings.php and other folders as directed by Drupal
  • /default on 755
  • /default/files including all subfolders and files on 744 (or 755)
  • /themes including all subfolders and files on 755
  • /modules including all subfolders and files on 755
  • /default/settings.php and /default/default.settings.php on 444

That's it~

Monday, January 21, 2013

Tuesday, January 15, 2013

YII: Changing Number of Items in the GGridView

In order to change the number of items in the GGridView, you can go to model and find search() method and add the following.


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

                return new CActiveDataProvider(get_class($this), array(
                        'criteria' => $criteria,
                        'pagination' => array(    // pagination property
                                'pageSize' => 30, // page size
                        ),                        // 
                ));
        }

Saturday, December 29, 2012

Setting Up YII Framework for the first time

In order to setup YII Framework at ease, you would need SSH access for your production server
  1. Upload latest stable YII Framework to the directory you wish to install YII app 
  2. Open SSH or Terminal on Mac 
  3. Type ssh username@ip (or your domain name)
  4. Enter the password
  5. Using "ls" to view the directory and "cd" to move, go to the directory where you want to install YII
  6. Type directory where yii framework is located and write webapp and type the name of the application    e.g. php www/yii/framework/yiic webapp AppName
    This will create an application called AppName on the folder where you are in
  7. You are ready.  For security purposes, move the framework and application folder above www directory, so that they are not accessible on the web

Wednesday, September 26, 2012

Securely Storing Files on your server

Here are several ways to securely store files on your server

1. Store files in your web directory and secure them using .htaccess.

2. Or store the files in a directory that isn't web-accessible but is readable by the user PHP runs as.

3. If you are using Apache you can use htaccess to password protect directories. (http://www.javascriptkit.com/howto/htaccess3.shtml)

Tuesday, September 18, 2012

How to Customize cGridView Data Column

I wanted to display the building information in a cGridView table with a owner that has a foreign key with building ID.  Here is how you can customize cGridView Data column. 

In Controller, you can add a function

protected function gridDataBuildingInfo($data,$raw) {
        // ... generate the output for the column

        // Params:
        // $data ... the current row data  
        // $row ... the row index   
        $model=Building::model()->findByPk($data->building_id);
        return  $model->name;  
    }


/* Another example without the need to connect with the database */
protected function gridSeasonName($data,$row)
        {
            switch ($data->Season) {
                case 1:
                    return "Winter";
                    break;
                case 2:
                    return "Fall";
                    break;
                case 3:
                    return "Summer";
                    break;
                case 4:
                    return "Spring";
                    break;
            }
        }


And in the views/owner/admin.php, 
you can modify CGridView as below:

 $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'owner-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'id',
        'name',
        'phone',
        'email',
        array('name'=>'church_id', 'value'=>array($this,'gridDataBuildingInfo')),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
));  



Here is a link to yiiframework.com wiki about customizing complex data columns in cGridView.

http://www.yiiframework.com/wiki/278/cgridview-render-customized-complex-datacolumns/


YII: How to create a dropdown list with database information

I need to create a dropdown list from a database table data.

Here is an example that I created for displaying school quarter information.

You can use this in the /view folder _form.php file.
e.g. /view/season/_form.php 

<div class="row">
        <?php  /*  Display label */ 

                    echo $form->labelEx($model,'QuarterID'); ?>
                <?php   

                        /* Retrieve data - select QuarterID, Year, Season; ordered by QuarterID DESC */
                        $Qmodels = Quarter::model()->findAll(array('select'=>'QuarterID, Year, Season','order'=>'QuarterID DESC'));
                        $data = array();

                        /* Used array to rename the season name to something more clear */
                        $season    = array(1=>'Winter','Fall','Summer','Spring');
                       
                        foreach ($Qmodels as $Qmodel)
                            $data[$Qmodel->QuarterID] = $Qmodel->Year . ' '. $season[$Qmodel->Season];   ?>
                <?php 

                      /* Display "Select Quarter" by default */
                      echo $form->dropDownList($model,'QuarterID',$data, array('empty'=>'Select Quarter')) ;?>
        <?php echo $form->error($model,'QuarterID'); ?>
    </div>



Here is an another example from yiiframework.com.  It is a simple and good example.
http://www.yiiframework.com/forum/index.php/topic/601-how-to-populate-a-dropdown-list-with-database-data/

 $qAlbums=Album::model()->findAll($criteria);

                

                $albums = array();

                foreach($qAlbums as $p)

                {

                        $albums[$p->AlId] = $p->AlDescr;

                }

                return $albums;



and then give $albums as parameter to 
 
$form->dropDownList($model, 'attribute', $albums); 
 

Friday, August 03, 2012

Wordpress: limit string words and add continue_read_link

I am using twenty theme in Wordpress, and I wanted to limit the number of words. I found the string_limit_words function, but I wanted to add continue_reading_link. Below is the code that I used
http://wordpress.org/support/topic/limit-the-number-of-words-in-excerpt-without-plugins
Add the following code in functions.php in your theme folder (e.g. /wp-contents/themes/twentyten/functions.php).
/* for limiting string words */
function string_limit_words($string, $word_limit)
{
  $words = explode(' ', $string, ($word_limit + 1));
  if(count($words) > $word_limit)
  array_pop($words);
  return implode(' ', $words);
}

function get_excerpt($count){
  $permalink = get_permalink($post->ID);
  $excerpt = get_the_excerpt();
  $excerpt = string_limit_words($excerpt, $count);
  $excerpt = $excerpt.'... '.twentyten_continue_reading_link();
  return $excerpt;
}

If you are not using twentyten theme, you can look for the function that creates continue_reading_link or use the following code instead.

function get_excerpt($count){
  $permalink = get_permalink($post->ID);
  $excerpt = get_the_excerpt();
  $excerpt = string_limit_words($excerpt, $count);
  $excerpt = $excerpt.'...  <a href="'. get_permalink() . '">' . __( 'Read More', 'PUT_YOUR_THEME_NAME_HERE' ) . '</a>';   
  return $excerpt;
}


And in index.php or the page where you want to limit the excerpt words, put the following code
echo get_excerpt(125);
Please take note that 125 is the number of words, not number of characters.

Friday, June 08, 2012

YII: How to make Clean SEO-friendly URLs


* Create Slug field in your database table
If you prefer not to create slug every time someone goes to the homepage or the main news page, you can create slug field in your database table.  It is a lot easier to keep track and you can modify the slug later as well. 

* Use SlugBehaviors - http://www.yiiframework.com/extension/slug-behavior/
Installation was almost too easy.  You download and extract the release file under models/behaviors 
And in the model, add the following: (e.g. /protected/model/post.php)

public function behaviors(){
    return array(
        'SlugBehavior' => array(
            'class' => 'application.models.behaviors.SlugBehavior',
            'slug_col' => 'slug',
            'title_col' => 'title',
            'max_slug_chars' => 125,
            'overwrite' => false
        )
    );
}

That's it! 

* Modify config/main.php
The tricky part was how to modify the UrlManager in /protected/config/main.php as below: 

 'urlManager' => array(
….
                'post/<id:\d+>/<slug>/*' => 'post/view',
                'post/<id:\d+>/*' => 'post/view',
), 

Make sure the order is correct or else they wouldn't work because the first rule is applied first. 

* Use Chtml::link to create links
Then, you can use Chtml::link in the following way
 echo CHtml::link(CHtml::decode($data->title), array('/post/view/', 'id'=>$data->id, 'slug'=>$data->slug));
                
Here are some articles that was helpful!

Wednesday, June 06, 2012

YII: How to Customize YII pager in CGridView

If you want to customize YII pagination or pare in CGridView usually located in view files, you can specify cssFile in pager inside CGridView.
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'post-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
        'cssFile' => Yii::app()->theme->baseUrl."/css/cgridviewcss.css",
    'columns'=>array(
                'id',
                'title',
                'content',
                array(
                   'class'=>'CButtonColumn',
                ),
    ),
        'htmlOptions'=>array('class'=>'add_css_class_name_for_CGridView_here'),
        'pager'=> array(
            'header' => '',  //if you want to get read of pager heading
            'cssFile' =>Yii::app()->theme->baseUrl."/css/style-of-pager.css",
        ),
Then, you can create style-of-pager.css and modify the pager.css (that is in the Yii Framework).
http://www.yiiframework.com/forum/index.php/topic/26055-change-the-general-pager-css-for-all-application/ 

YII: How to Add CSS Class in Form textArea

You can add css class in the _form.php in YII views folder.

In _form.php file (/protected/views/post/_form.php)

echo $form->textArea($model,'title',array('class'=>'put_class_name_here')); 

YII: How to Sort or Reverse CGridView Display Order

Here is how you can sort or reverse the order of CGridView (showing the newest on top by default).

In the Controller (/protected/controllers/postController.php)

public function actionAdmin() {    $model = new Post('search');    $model->unsetAttributes();    if (isset($_GET['Post']))        $model->attributes = $_GET['Post'];
    $this->render('admin', array(        'model' => $model,    ));

In the Model (/protected/models/post.php)

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('foo',$this->foo,true);                $criteria->compare('bar',$this->bar,true);                ....
                return new CActiveDataProvider($this, array(                        'criteria' => $criteria,                        'sort' => array(                             'defaultOrder' => 'post_date DESC',  // this is it.                        ),                        'pagination' => array(                                'pageSize' => 30,                        ),                ));        }
 Thank softark for the answer!!
http://www.yiiframework.com/forum/index.php/topic/21523-yii-reverse-cgridview-display-order/

Monday, June 04, 2012

How to Specify each row's id with Zii Widgets Grid CGridView in Yii


When I tried to use zii.widgets.grid.CGridView in a different controller, CButtonColumn would mess up because the id would return the controller the CGridView is placed.

To specify each row's id for the CButtonColumn, you can do the following.  ^^

$this->widget('zii.widgets.grid.CGridView', array(
 'id'=>'label-grid',
 'dataProvider'=>$labelmodel,
 'columns'=>array(
  'id',
  'label',
  array(
                    'class'=>'CButtonColumn',
                    'viewButtonUrl'=>
                     'Yii::app()->controller->createUrl("label/view", 
                                       array("id"=>$data->id))',
                    'updateButtonUrl'=>
                     'Yii::app()->controller->createUrl("label/update",       
                                       array("id"=>$data->id))',
                    'deleteButtonUrl'=>
                   'Yii::app()->controller->createUrl("label/delete", 
                                      array("id"=>$data->id))',
  ),
 ),
));  

Friday, June 01, 2012

Top Three Surefire Steps to Increase # of "Likes" on your Facebook page (Work in Progress)



These are small suggestions but surefire steps that works:


1. Photo size.  Know that 90% of Facebook users interact in their Newsfeed.  They aren't going to read tiny letters inside the photos.


2. New Likes.  Interact with them and reward them with something valuable.  They will be the key influencer for your page to reach friends of friends.  

3. Invite friends.  Look out for a few active supporters of your page and ask them to become an "ambassador" on behalf of the page.  Continue interacting with them and reach out to their networks of friends. 


Suggest below things that you've tried and worked! 


How to Set dynamic page titles in YII

One way to specify the page title in YII, you can go to controller/action, and set it this way.
public function actionIndex() {
     $this->pageTitle = "Put page title here";
     $this->render('index');
}

In the header template or layout template, you can do the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="language" content="en" />   
    <title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
Or in the view page, you can specify the pageTitle. 
$this->setPageTitle('Put page title here');