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

Thursday, May 31, 2012

Nine Easy Steps to Get Higher EdgeRank for Your Facebook Posts


Have you noticed how many of your fans your posts are actually reaching to?  Average 5 to 10%.  First you'd be shocked at it, then second, you'd definitely want to get into the EdgeRank.  Do you want to improve your posts to be seen by more people?  Here are easy steps to get started:

1. Increase "Affinity," (relevance of a post) by increasing interactions.  I've written a blog about how to do that here:

2. Increase "Weight," (popularity of a post) by increasing "Like's".  Someone might say # of "Like's"doesn't really matter but content is the king-  Well, at least when it comes to the EdgeRank, # of "Like's" determines the "weight" of a post and it matters (with other factors) to your content's visibility.  I've also written a post on how to increase # of "Likes" on your Facebook page here.


3. Increase "Weight" (popularity of a post) by posting manual posts than app-driven posts.

4. Increase "Weight" (popularity of a post) by varying your post types.  Here is the list: Photo > Video > Links > Status > App-driven post

5. Increase "Time Decay" (recency of a post) factor of EdgeRank by posting fresh contents consistently.

6. Go to Facebook Insights at the end of each day to see and recycle what performed well.

7. Go to Facebook Insights to check your "hides" daily so that you can avoid those posts next time.


8. Reward and encourage high influencers of the week with something valuable.  


9. Target your status updates.  Especially for global entities, certain countries might respond better depending on the contents of a post.  This connects to a bigger marketing principle - clarify the target audience and be in their shoes.  



Hope this helps get you started! "Share" if you liked it.  

Wednesday, May 30, 2012

Six Easy Steps to Lead Your Community on Facebook Page



You might have come across with a Facebook page with 10,000+ fans that doesn’t get as much # of Talking About or # of engagement.  For sure, you can’t be all things to all fans.  But here are a few simple steps of how you can get started in seeding to your fan base.


1. “Friend” new fans from your page and say "Thank You".  Feel free to ask simple questions like how they found the page, their interest, and what they’d like to hear from your page.  I'd recommend to "like" not only those who "liked" your page, but also the ones who "liked" or "shared" your posts.


2. If you are posting a photo on your wall, you can tag fans to give them heads-up. (You should be careful through, trying not to tag recklessly or without relevant information).


3. Engage in your target community, interact, and offer valuable feedbacks.


4. Set up a content strategy.  Let's say you divided up your contents into Top Ten categories.  Create a content storeroom per each category where you can draw from and rotate the contents from.  This will help you to post with consistency.


5. Give value.  Imagine you give a gift to someone who is important to you.  You would think about how to word it, how to wrap it, how to deliver it, and most importantly - the value.  Not for the giver, but for the recipient.

6. Invite friends.  Look out for a few active supporters of your page and ask them to become an "ambassador" of your page.  Continue interacting with them and reach out to their friends network. 

"Share" and "comment" if this was helpful! 

Tuesday, May 29, 2012

YII Adding a parameter to the Action

This is for security and better control of your website.

If you are adding a parameter to your action and you are using that parameter to get data from the database, make sure you throw error page when there is no data from the database.

In config/main.php - for managing URL with alias
'components'=>array(
      ...
      'urlManager' => array(
           'post/<alias>' => 'post/page',
));
URL 
http://www.example.com/post/alias_name_here
Controller
<?php
class PostController extends Controller {
       ...
       public function actionPage($alias) {
             echo $alias;
             /* Using $alias to get data */
            $alias_data = Post::model()->find(array(
                'condition'=>"active='Y' AND alias='".$alias."'",
                'order'=>'id DESC',
                'select'=>'title, content',
                'limit'=>1,
            ));
           if (is_object($alias_data)) {
                 /* Display alias_data */
                 ...
           } else
                 /* Through error page when there is no data */
                 throw new CHttpException(404,'The specified page cannot be found.');
           }
      }
}

Yii Deployment

Yii directory paths
1. Move runtime out of protected folder to out of webroot
2. Move framework out of webroot
3. Move an application out of webroot

Then, modify index.php

// change the following paths if necessary
$yii=dirname(__FILE__).'/../../framework/yii.php';
$config=dirname(__FILE__).'/../../protected/config/main.php';

and add runtime in /protected/config/main.php

return array(
      'runtimePath' => Yii::getPathOfAlias('system') . '/../runtime/', 
      ...
);

Setting custom layout for 404 error page in YII Framework

If you want to set a custom layout for 404 error page in YII Framework, you can do the following:

1. Modify config/main.php
'components'=>array(
...
        'errorHandler'=>array(
            'errorAction' => 'site/error'
        ),
...
),
The site/error is where the error page resides.  It is in the views/site/error.php page.  In order for the pages in views/site/ to show, it needs the controller, and SiteController located in /controllers/SiteController.php.  

controllers/SiteController.php
    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;

        if( $error )
        {
            $this -> render( 'error', array( 'error' => $error ) );
        }
    }

If you do not want to use the site controller, you can create a new view and controller folder.  For example, you can create views/general/error.php and controllers/GeneralController.php and modify 'errorAction' => 'general/error'.  


controllers/GeneralController.php

<?php 
 class GeneralController extends Controller {
    public $layout='main_general';  //layout goes here    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;

        if( $error )
        {
            $this -> render( 'error', array( 'error' => $error ) );
        }
    }   ?>
the main_general should be located in either WebRoot/themes/ThemeName
As indicated in the link here http://www.yiiframework.com/doc/guide/1.1/en/topics.error
'main_general' (layout) is either located in 3 location.  
It is either 
1. in your main theme view folder /WebRoot/themes/ThemeName/views/main_general.php
2. in the WebRoot/protected/views/main_general.php (default)
3. in yii/framework/views - the standard system view directory provided by the Yii framework.


views/site/error.php or views/general/error.php
<div class="errorSummary">
    <p>
    Sorry, it seems like a(n) <?= $error['code']; ?> error has occured during your request.
    </p>

    <p><strong>Message:</strong> <?= $error['message']; ?></p>
</div>




Wednesday, March 07, 2012

Adding your own layout for yii-user-management

http://www.yiiframework.com/extension/yii-user-management/

If you want to use your own layout for yii-user-management extension, you can go to the following location

app folder/modules/user/UserModule.php

and modify these two lines.

public $loginLayout = 'application.modules.user.views.layouts.yum';
public $adminLayout = 'application.modules.user.views.layouts.yum';


For me, I created a new theme, so I specified it as below.

Add this on top of the page:
Yii::setPathOfAlias('YumThemes' , dirname(Yii::app()->request->scriptFile).'/themes/my_theme/');

public $loginLayout = 'YumThemes.views.layouts.yum_layout';
public $adminLayout = 'YumThemes.views.layouts.yum_layout';

Then, you can go to www/theme/my_theme/views/layouts/yum_layout.php and modify yum_layout.php to modify the layout for the login and the admin layout. ^^

I think I forgot to mention that you also need to change $baseLayout as a base layout.

Sunday, February 12, 2012

For getting entry script file path in Yii

If you want to return entry script file path (www directory without index.php), you can use the following code. It works great.

dirname(Yii::app()->request->scriptFile);


This results in the full directory names of the web root.
e.g. /home/example.org/www/yii/protected

http://www.yiiframework.com/forum/index.php?/topic/536-basepath-url/page__hl__scriptFile%20__fromsearch__1

The one below returns " /yii/protected/ ".

<?php echo Yii::app()->request->baseUrl; ?>

Monday, February 06, 2012

Yii CListView AJAX filtering

When I was using zii widgets CListView, I came across some problems. When I click on a different page (e.g. page 4), I would get duplicate list views.

This has been fixed specifying the id for this widget. ^___^

See the code example here:
http://www.yiiframework.com/wiki/185/clistview-ajax-filtering/

Saturday, January 14, 2012

Testing TrackStar Application with YII

Chapter 5. Project CRUD
  • Design the database schema to support projects
  • Build the needed tables and all other database objects indentified in the schema
  • Create the Yii AR model classes needed to allow the application to easily interact with the created database table(s)
  • Create the Yii controller class(es) that will house the functionality to:
    a. Create new projects
    b. Fetch a list of existing projects for display
    c. Update metadata on existing projects
    d. Delete existing projects
  • Create the Yii view files and present their logic in a way that will:
    a. Display the form to allow for new project creation
    b. Display a list of all the existing projects
    c. Display the form to allow a user to edit an existing project
    d. Add a delete button to the project listing to allow for project deletion
Chapter 6. Project CRUD
  • Design the database schema to support projects
  • Build the needed tables and all other database objects indentified in the schema
  • Create the Yii AR model classes needed to allow the application to easily interact with the created database table(s)
  • Create the Yii controller class(es) that will house the functionality to:
    a. Create new projects
    b. Fetch a list of existing projects for display
    c. Update metadata on existing projects
    d. Delete existing projects
  • Create the Yii view files and present their logic in a way that will:
    a. Display the form to allow for new project creation
    b. Display a list of all the existing projects
    c. Display the form to allow a user to edit an existing project
    d. Add a delete button to the project listing to allow for project deletion
Source: Agile Web Application Development with Yii 1.1 and PHP5

Tuesday, January 10, 2012

Basic Setup to using Yii Framework

1. Install Yii Framework
2. Setup User-friendly URLs
http://www.yiiframework.com/doc/guide/1.1/en/topics.url
3. Using Gii for automatic code generation tool
http://www.yiiframework.com/doc/guide/1.1/en/topics.gii
4. Set DB information in localhost/your_project/protected/config/main.php

In running the command line, make sure to add
* path="c:\xampp\php" or path to php

Now basic preparation for web application is set in place. ^___^

Monday, January 09, 2012

Using MySQL Workbench

I am using MySQL Workbench for Entity-Relationship Diagramming (ERD) tool to plan and make blueprint of my new web project. It's a great tool for any database work with MySQL.