Yii: use ajax function via htmlOptions attribute

By: lars

If you want to trigger an ajax call on a Yii form element onchange, you can pass an array of ajax attributes as one of the “htmlOptions” like so:

<?php echo $form->textField($model,'my_input_field',array(
	'ajax' => array(
		'type'=>'POST', //request type
		'url'=>$this->createUrl('site/ajaxAction'), // url to call controller action
		'success'=>' function(data) { $(\'#my_output_field\').val(data) }',// function to call onsuccess 
             // "data" is returned data and function can be regular js or jQuery
             // here we are are updating the value of another field that has id "my_output_field"
	),
	'size'=>60,
	'maxlength'=>128,
)); ?>

and the (site) controller action would look something like:

public function actionAjaxAction() {
  [check/filter inputs...]
  [data functions...]
  echo $my_val_string;
  Yii::app()->end()
}

Creating a CSS Driven Drop Down Menu using CMenu

By: Yii

CMenu offers great functionality and the ability to customize just about every aspect of the output. There are many times when I need to create a drop down menu or simply modify the look to make the designers happy. Because this seems to be a common task for me, I figured I would share my code to create a very simple drop down menu that other people could use.

There are many ways to approach this but I wanted to start out very simply so we are going to accomplish this using nothing but CSS.

Here is our desired output:

<div id="menu-top"> 
  <ul id="yw1">
    <li id="itemCompany"><a id="menuCompany" href="/company/index">Company</a>
      <ul>
        <li class="active"><a href="/company/index">Our Mission</a></li>
        <li><a href="/company/aboutUs">About Us</a></li>
        <li><a href="/company/careers">Careers</a></li>
        <li><a href="/company/contactUs">Contact Us</a></li>
        <li><a href="/company/storeLocator">Store Locator</a></li>
      </ul>
    </li>
    <li><a id="menuBlog" href="/blog/post/index">Blog</a></li>
    <li id="itemChange"><a id="menuChange" href="/change/index">Change</a>
      <ul>
        <li><a href="/change/index">Community Involvement</a></li>
        <li><a href="/change/ecoPolicy">Eco Responsibility</a></li>
        <li><a href="/change/responsibility">Responsibility</a></li>
      </ul>
    </li>
    <li><a id="menuBuy" href="/shop">Shop</a></li>
  </ul>
</div>

And here is the code we are going to use to create this output:

<div id="menu-top">
<?php
$this->widget('zii.widgets.CMenu',array(
  'activeCssClass'=>'active',
  'activateParents'=>true,
  'items'=>array(
    array(
      'label'=>'Company',
      'url'=>array('/company/index'),
      'linkOptions'=>array('id'=>'menuCompany'),
      'itemOptions'=>array('id'=>'itemCompany'),
      'items'=>array(
        array('label'=>'Our Mission', 'url'=>array('/company/index')),
        array('label'=>'About Us', 'url'=>array('/company/aboutUs')),
        array('label'=>'Careers', 'url'=>array('/company/careers')),
        array('label'=>'Contact Us', 'url'=>array('/company/contactUs')),
        array('label'=>'Store Locator', 'url'=>array('/company/storeLocator')),
      ),
    ),
    array(
      'label'=>'Blog',
      'url'=>array('/blog/post/index'),
      'linkOptions'=>array('id'=>'menuBlog')
    ),
    array(
      'label'=>'Change',
      'url'=>array('/change/index'),
      'linkOptions'=>array('id'=>'menuChange'),
      'itemOptions'=>array('id'=>'itemChange'),
      'items'=>array(
        array('label'=>'Community Involvement', 'url'=>array('/change/index')),
        array('label'=>'Eco Responsibility', 'url'=>array('/change/ecoPolicy')),
        array('label'=>'Responsibility', 'url'=>array('/change/responsibility')),
      ),
    ),
    array(
      'label'=>'Shop',
      'url'=>array('/shop'),
      'linkOptions'=>array('id'=>'menuBuy')
    ),
  ),
)); ?>
</div>

Let’s dig into the code to see what is happening here.

CMenu::activeCssClass is simply the CSS class that will be assigned to the active menu item. The active menu item simply indicates the current page you are viewing by adding some style to that menu link.CMenu::activateParents means that when a child item is activated, the parent of that item will be given the ‘active’ css class assignment as well.

You will notice that the ‘Company’ item has another CMenu::items array set under it that will be the items that show up in the drop down when a user hovers over ‘Company’ in the menu.

Also, in the parent items ( Company, Blog, Affecting Change, Shop ) you will see that we take advantage of theCMenu::linkOptions property in order to add an ID to tag that Yii will output wrapping the label. I needed to do this because the menu I am creating uses sprites which means I need an ID for each menu item to specify the background-position property of each item independently.

Ok so now that we have our PHP setup, let’s dig into the CSS part. I am also not going to include the code for the sprites to keep things simple.

#menu-top ul { list-style: none; margin: 0; padding: 0; position: relative; height: 30px; }

#menu-top ul li { display: block; height: 28px; float: left; overflow: visible; }
#menu-top ul li:hover > ul { display: block; }

#menu-top ul li a { float: left; display: block; }

#menu-top ul li ul { display: none; position: absolute; top: 100%;
                    background: #000; color: #fff; height: auto;
}

#menu-top ul li ul li a { color: #ccc; padding: 4px 14px; display: block; }

#menu-top ul li ul li.active a,
#menu-top ul li ul li a:hover { color: #fff; }

An important part to pay attention to is setting the overflow to visible on the ‘#menu-top ul li’ elements. Otherwise, when you mouseover an parent item, the child items will not be visible.

The line that does all the magic is: #menu-top ul li:hover > ul { display: block; }

This simply means that when a user hovers over a parent item ( ul li ), take any child ul elements and switch them from ‘display: none;’ to ‘display: block;’ making them visible.

Once you put this all together, you should have a nice little drop down menu with active highlighting.

Referenced by: http://www.yiiframework.com/wiki/211/creating-a-css-driven-drop-down-menu-using-cmenu/

How to create a Custom Pagination Widget for Yii Framework

By:

Agile Web Application Development with Yii 1.1 and PHP5Yii Framework is great, I truly like this framework, makes complicated things an easy task and its learning curve quite easy. But… yeah man, is always a but… what happens to all those fellow programmers, like me, that do not like the way ‘automated things’ are? Where are the tutorials to change and improve the framework and make it work just the way we like? There are not many around…

Again, a programmer needs to investigate the guts of the framework, in order to find out how to properly do it. But don’t worry, if you have a question in the format: would I be able to do this with Yii? The answer will be always positive. It is a great framework.

So, I would like to share with you guys my personal experience and put some small tutorials to ‘open’ the minds of others begginning with this framework. This will be the first of a set of small tuts on this Framework.

Creating a Custom Pagination Widget

A pagination Widget is the responsible of displaying a set of numbered links that lead to different pages of target. When you first create a Web application through the yiic tool – this tool creates the skeleton of the application, the automated CMS works with CLinkPager widget and its style and Page Links were not suitable for my project. My project had to end up making AJAX calls and its STYLE like the following picture:

Please not that if you want to just change its style, you can create a skin as exposed here:http://www.yiiframework.com/doc/guide/topics.theming#customizing-widgets-globally. Once I look at the code, I realized that creating a custom widget was easier than I thought. The first thing we need to do is to extend our new Widget class from CLinkPager, my class is named SimplaPager as I have used a template admin theme called SIMPLA.

1
class SimplaPager extends CLinkPager

Now, there are three methods to override from our father and grandfather classes (CLinkPager and CBasePager). The parent methods we need to override are run and createPageButtons and from our grandfather class createPageUrl.

a)  run Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public function run()
{
     //
     // here we call our createPageButtons
     //
     $buttons=$this->createPageButtons();
     //
     // if there is nothing to display return
     if(empty($buttons))
          return;
     //
     // display the buttons
     //
     echo $this->header; // if any
     echo implode("&nbsp;",$buttons);
     echo $this->footer;  // if any
 }

b) createPageButton Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Creates a page button.
 * You may override this method to customize the page buttons.
 * @param string the text label for the button
 * @param integer the page number
 * @param string the CSS class for the page button. This could be 'page', 'first', 'last', 'next' or 'previous'.
 * @param boolean whether this page button is visible
 * @param boolean whether this page button is selected
 * @return string the generated button
 */
protected function createPageButton($label,$page,$class,$hidden,$selected)
{
       //
       // CSS_HIDDEN_PAGE and CSS_SELECTED_PAGE
       // are constants that we use to apply our styles
       //
    if($hidden || $selected)
        $class=' '.($hidden ? self::CSS_HIDDEN_PAGE : self::CSS_SELECTED_PAGE);
    $class .= ' number';
       //
       // here I write my custom link - site.call is a JS function that takes care of an AJAX call
       //
    return CHtml::link($label,'#',array(
                'class'=>$class,
                'onclick'=>"site.call(CONST_MAIN_LAYER,'{$this->createPageUrl($this->getController(),$page)}');"));
}

c) createPageUrl Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Creates the URL suitable for pagination.
* This method is mainly called by pagers when creating URLs used to
* perform pagination. The default implementation is to call
* the controller's createUrl method with the page information.
* @param CController the controller that will create the actual URL
* @param integer the page that the URL should point to. This is a zero-based index.
* @return string the created URL
*/
public function createPageUrl($controller,$page)
{
    // HERE I USE POST AS I DO AJAX CALLS VIA POST NOT GET AS IT IS BY
    // DEFAULT ON YII
    $params=$this->getPages()->params===null ? $_POST : $this->getPages()->params;
    if($page>0) // page 0 is the default
       $params[$this->getPages()->pageVar]=$page+1;
   else
      unset($params[$this->getPages()->pageVar]);
   return $controller->createUrl($this->getPages()->route,$params);
}

Styling is controlled by a couple of constants in CLinkPager class, so the only thing we need to do is to override those constants.

1
2
const CSS_HIDDEN_PAGE='hidden';
const CSS_SELECTED_PAGE='current';

How to use the Widget

In order to use this widget first we create a widget subfolder in our application’s protected folder (in my case I saved a file named SimplaPager.php) and call it in our views like this:

1
2
3
$this->widget('application.widgets.SimplaPager', array(
    'pages'=>$pagination,
));

I have created another widget to display records in a table because I had the same problems than with the pagination so I use the the pagination within the Table Widget I created like this:

1
2
3
4
5
/**
 * @var array the configuration for the pager. Defaults to <code>array('class'=>'CLinkPager')</code>.
* @see enablePagination
 */
public $pager=array('class'=>'application.widgets.SimplaPager');

I promise I will discuss how to create a Table Widget in the next post :) . Nevertheless, you can view how both widgets look at the end:

SimplaTable and SimplaPager working together

DOWNLOAD

Please remember than this class has some AJAX calls in its createPageButton function that is exclusive for my project. Change that part to suit your needs. This class was for you to better understand how to create custom Widgets by extending those from Yii framework.

How to create a breadcrumb widget

By:

Here’s a simple way to create a breadcrumb widget to be used in your templates. The idea is just to isolate how the breadcrumb is generated based on an array of crumbs.

Info: Please note, that new versions of Yii Framework already contain a bulit-in breadcrumbs widget. See this class reference chapter for more information. Information in this article may be, however, usable to build custom one, not descending from bulit-in one.

components/BreadCrumb.php:

<?php
class BreadCrumb extends CWidget {

    public $crumbs = array();
    public $delimiter = ' / ';

    public function run() {
        $this->render('breadCrumb');
    }

}
?>

components/views/breadCrumb.php:

<div id="breadCrumb">   
    <?php 
    foreach($this->crumbs as $crumb) {
        if(isset($crumb['url'])) {
            echo CHtml::link($crumb['name'], $crumb['url']);
        } else {
            echo $crumb['name'];
        }
        if(next($this->crumbs)) {
            echo $this->delimiter;
        }
    }
    ?>
</div>

Usage in views

<?php $this->widget('application.components.BreadCrumb', array(
  'crumbs' => array(
    array('name' => 'Home', 'url' => array('site/index')),
    array('name' => 'Login'),
  ),
  'delimiter' => ' &rarr; ', // if you want to change it
)); ?>

Codeigniter | Paypal Integration

By:Nithin K Varrier

Here is a simple tutorial for integrating Paypal with your Codeigniter project. For easiest integration of Paypal you need to download paypal lib.

Extract the downloaded zip file. Copy Paypal_Lib.php from paypal_lib->application->libraries and paste this file to your application->libraries. One more file you need to copy. That is paypallib_config.php from paypal_lib->application->config and paste this file to your application->config.

Then you create a control paypal.php. It should be like this:

class Paypal extends CI_Controller{

  function __construct(){
      parent::__construct();
      $this->load->library( 'paypal_lib' );

   }

   function index(){
      $this->load->view('payment');
   }
}

Here you created a control named paypal. And you included paupal_lib library. Then in index method you called payment view.

Then create a payment.php in your view folder. It should be like this:

<?php echo anchor (base_url()."index.php/paypal/pay",
 'Paypal', array('id'=>'paypal')); ?>

Here you created a Hyperlink paypal and it call method ‘pay’ in your paypal control. So you need to create ‘pay’ method in your paypal control, like this:

function pay(){

  $item_name = 'Product Name';

  $price = '50';

  $item_id = 'Product Id';  // Optional

  $quantity = 1;

  $this->paypal_lib->add_field('business',’paypal@email.com’); // Business Email

  $this->paypal_lib->add_field('return',base_url().'returnpage'); // Return URL

  $this->paypal_lib->add_field('cancel_return', base_url().'cancel'); // Cancel URL

  $this->paypal_lib->add_field('notify_url', base_url().'ipn'); // <-- IPN url

  $this->paypal_lib->add_field('custom', $item_id);  // Optional

  $this->paypal_lib->add_field('item_name', $item_name); // Product Name

  $this->paypal_lib->add_field('quantity', $quantity); // Quantity

  $this->paypal_lib->add_field('amount', $price); // Price

  $this->paypal_lib->paypal_auto_form();

}

In the above method ‘pay’ you gave all information about your product like name, price, quantity, etc. Here you gave a return URL and it called the method ‘returnpage’. So you need to create ‘returnpage’ method in your paypal controle, like:

function returnpage(){

  if(!$this->input->post('payer_id')){

     echo "Success !!";

  }else{

     echo "Error !!";

  }

}

Then create a ‘cancel’ method for cancel URL, like:

function cancel(){

    redirect(base_url().'paypal');

}

Finally You need to create a method ‘ipn’ for IPN-URL, like:

function ipn(){

   $to    = 'Your Email';

   if ($this->paypal_lib->validate_ipn()) {

      $body  = 'An instant payment notification was successfully received from ';

      $body .= $this->paypal_lib->ipn_data['payer_email'] . 
       ' on '.date('m/d/Y') . ' at ' . date('g:i A') . "\n\n";

      $body .= " Details:\n";

      foreach ($this->paypal_lib->ipn_data as $key=>$value)
            $body .= "\n$key: $value";

      // load email lib and email results

     $this->load->library('email');

     $this->email->to($to);

     $this->email->from($this->paypal_lib->ipn_data['payer_email'],
     $this->paypal_lib->ipn_data['payer_name']);

     $this->email->subject('Received Payment');

     $this->email->message($body);

     $this->email->send();

   }

}

Then call paypal control and see How its work…………..Thank you

Referenced by: http://eccoding.wordpress.com/2011/11/28/codeigniter-paypal-integration/

How to Create a Custom Facebook Share Button for your iFrame Tab

A common feature of Facebook is the use of being able to ‘Share’ objects whether these objects are videos or links. If you’re anything like us then you like to have full control over what and how you share it, this proved rather difficult until now. In this tutorial we are going to show you, in two easy steps, how to create a custom Facebook ‘Share’ button to use on your Facebook iFrame tab that will allow viewers to share and post your custom content to their Wall. The difference between this ‘Share’ button and the standard ‘Share’ button is that every element (custom message, custom title and custom thumb image) within the share window is completely customizable, giving you total control over what you want to share.

The Code

Step 1: PHP

<source lan=’java’>
<?php
$title=urlencode('Title of Your iFrame Tab');
$url=urlencode('http://www.facebook.com/wordpressdesign');
$summary=urlencode('Custom message that summarizes what your tab is about, or just a simple message to tell people to check out your tab.');
$image=urlencode('http://www.yourdomain.com/images/share-thumbnail.jpg');
?>
</source>

Each line within the PHP allows you customize every element within the share window. Every bit of coding within the “(‘…‘)” that you see effects those elements. To understand which PHP element affects what, take a look at the screenshot below:
fb share gragh
Keep note that the $url section must contain a URL. This directs people to your tab once the share has been published on the poster’s wall. Also, the $image must contain a full URL. If your link to the image is “images/share-thumbnail.jpg”, it will not be read correctly because the share window is coming from Facebook’s server, not yours. As for the size of your thumbnail image ($image), it will automatically be proportionately resized to fit either 100px wide or 100px tall (depending which measurement is larger of the original image). So ideally, you should make your thumbnail 100px X 100px to prevent unwanted resizing.

Step 2: XHTML

<source lan=’java’>
<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&amp;p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Insert text or an image here.</a>
</source>

As you can see, the onClick=”window.open(‘…’);” will create a popup window that contains the ‘Share’ information (see picture above). Do not change this information. The only bits of coding you need to change are the width and the height of the code (if you are not satisfied with the measurements). These measurements define the width and height of the popup window containing the “Share” information.

The other bit of coding you can change is where it says; “Insert text or an image here”. This is where you can insert whatever element you choose to become the link. This can simply be text or a fancy button that you created yourself. The choice is up to you!

Completed Code

<source lan=’java’>
<?php
$title=urlencode('Title of Your iFrame Tab');
$url=urlencode('http://www.facebook.com/wordpressdesign');
$summary=urlencode('Custom message that summarizes what your tab is about, or just a simple message to tell people to check out your tab.');
$image=urlencode('http://www.yourdomain.com/images/share-thumbnail.jpg');
?>

<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&amp;p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Insert text or an image here.</a>
</source>

Demo

You can view the live demo here.
Download the code here.

Please Note

Your iFrame tab must be a PHP file in order for this to work.

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible.

How to remove index.php in Codeigniter URL

By default, the index.php file will be included in your URLs:

example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:


<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]</code>

In the above example, any HTTP request other than those for index.php, images, and robots.txt is treated as a request for your index.php file.