Tuesday, August 6, 2013

cakephp string truncate function

String::truncate(string $text, int $length=100, array $options)
 
Parameters:
  • $text (string) – The text to truncate.
  • $length (int) – The length to trim to.
  • $options (array) – An array of options to use.
Example:
// called as TextHelper
echo $this->Text->truncate(
    'The killer crept forward and tripped on the rug.',
    22,
    array(
        'ellipsis' => '...',
        'exact' => false
    )
);

// called as String
App::uses('String', 'Utility');
echo String::truncate(
    'The killer crept forward and tripped on the rug.',
    22,
    array(
        'ellipsis' => '...',
        'exact' => false
    )
);
 
Output:
The killer crept... 

Reference url: http://book.cakephp.org/

Get Google Maps v3 to resize height of InfoWindow

Js
var infowindow = new google.maps.InfoWindow({
                                 content: lng,
                                 maxWidth: 200
                            });

google.maps.event.addListener(marker, 'click', function() {       
        var $content = $('<div class="infobox">').html("content here");
        infowindow.setContent($content.get(0));
        infowindow.open(map, marker);
});

CSS

.infobox{
    padding-bottom: 30px;
}

Have just one InfoWindow open in Google Maps API v3

google.maps.event.addListener(someMarker, 'click', function() {
   infowindow.setContent('Hello World');
   infowindow.open(map, someMarker);
});

Monday, August 5, 2013

$.browser is undefined

To keep things current, it seems that for jquery UI version 1.9, the autoHeight has been replaced by heightStyle. http://api.jqueryui.com/accordion/#option-heightStyle
  

                                              Or

just put the $.browser code in your js

var matched, browser;

jQuery.uaMatch = function( ua ) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    return {
        browser: match[ 1 ] || "",
        version: match[ 2 ] || "0"
    };
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
    browser[ matched.browser ] = true;
    browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
    browser.webkit = true;
} else if ( browser.webkit ) {
    browser.safari = true;
}

jQuery.browser = browser;

jQuery ui accordion height problem

heightStyleType: String

Default: "auto"

Controls the height of the accordion and each panel. Possible values:

    "auto": All panels will be set to the height of the tallest panel.
    "fill": Expand to the available height based on the accordion's parent height.
    "content": Each panel will be only as tall as its content.

Code examples:Initialize the accordion with the heightStyle option specified:

$( ".selector" ).accordion({ heightStyle: "content" });


Note - Use content to assign auto height to each accordion.

For this need to use jQuery 1.10 or update jQuery

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Friday, March 15, 2013

Jquery serialize function

<script>


$(document).ready(function () {
    $("#step2").validationEngine();
    $("#Button1").live('click', function () {
        var valid = $("#step2").validationEngine('validate');
        var vars = $("#step2").serialize();

        if (valid == true) {
             wait('Saveing.....');
                $.ajax({
                    type: 'POST',
                    url: SITEURL+'projects/save_edit_step2',
                    data: $("#step2").serialize(),
                    success: function(data){
                        clear();
                        $("#question-answer").html(data);
                    }
                });
            return false;
           
        } else {
            $("#step2").validationEngine();
        }
    });
});
</script>
<script>
$(document).ready( function() {
    $("#step2").validationEngine('');
     $("#step2").submit(function(){
            wait('Saveing.....');
                $.ajax({
                    type: 'POST',
                    url: SITEURL+'projects/save_edit_step2',
                    data: $(this).serialize(),
                    success: function(data){
                        clear();
                        $("#question-answer").html(data);
                    }
                });
            return false;
       });
    } );
   
</script>

Url rewriting using cakephp

Router::connect('/:slug', array('controller' => 'pages', 'action' => 'view'));

and controller code
$this->params['slug']; get the value of slug

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Error
MySQL said:

#1045 - Access denied for user 'root'@'localhost' (using password: YES)
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

Solution:check username and password in phpmyadmin/config.inc.php file


Function to Convert Multidimensional Arrays to stdClass Objects

<?php
    function arrayToObject($d) {
        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $d);
        }
        else {
            // Return object
            return $d;
        }
    }
?>

Php Function to Convert stdClass Objects to Multidimensional Arrays

<?php

    function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    }

?>

Php get directory list

echo "<pre>";
$images = scandir("directory_path", 1);
unset($images[count($images)-1]);
print_r($images);
die;

Php time ago function

function time_ago_en($time)
    {
        if(!is_numeric($time))
            $time = strtotime($time);

        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "age");
        $lengths = array("60","60","24","7","4.35","12","100");

        $now = time();

        $difference = $now - $time;
        if ($difference <= 10 && $difference >= 0)
            return $tense = 'now';
        elseif($difference > 0)
            $tense = 'ago';
        elseif($difference < 0)
            $tense = 'after';

        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        $period =  $periods[$j] . ($difference >1 ? '' :'');
        return "{$difference} {$period} {$tense} ";
    }

php print word by passing a string

function words($string, $limit)
{
    $words = explode(" ",$string);
    return implode(" ",array_splice($words,0,$limit));
}

Wordpress get child categories list passing parent category id

$args = array(
    'type'                     => 'post',
    'child_of'              => $cur_cat_id,
    'parent'                 => '',
    'orderby'              => 'name',
    'order'                   => 'ASC',
    'hide_empty'       => 1,
    'hierarchical'       => 1,
    'exclude'              => '',
    'include'               => '',
    'number'              => '',
    'taxonomy'          => 'category',
    'pad_counts'       => false
 );
$cat_child_data = get_categories( $args );

Wordpress get menu list by menu name

<?php
$menu_items = wp_get_nav_menu_items('city');
echo "<pre>";
print_r($menu_items);
?>
<select onChange="document.location.href=this[selectedIndex].value">
    <option value="<?php bloginfo('url'); ?>">-select-</option>
    <?php foreach($menu_items as $item){ ?>
    <option value="<?php echo $item->url; ?>"><?php echo $item->title; ?></option>
      <?php }?>
</select>

Wordpress wp-query or get all posts in a array

$loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 4));
$loop->posts();

Free Stock Chart Widgets for your Website and Blog

<div align="left" style="float: left;">
  <iframe scrolling="no" frameborder="0" align="middle" src="http://www.finalaya.com/Widget/MarketTicker.aspx?Theme=blue" allowtransparency="true" vspace="0" hspace="0" style="height:160px;width:660px;" valign="top" marginheight="0" marginwidth="0" id="ctl00_BodyCPH_ifrmMarketTracker"></iframe>
</div>

Cakephp checkbox creation

    <?php
    echo $this->Form->create('User');
    
    $options = array('29'=>'Active charge','25'=>'computer');
  
    $arr = array();
    for($i=1;$i<= 2;$i++){
      
        foreach ($options as $opt=>$val){
            $arr[$opt][$val][$i] = $i;      
        }
    }
    pr($arr);
    foreach ($options as $opt=>$val){
    echo $this->Form->input("User.charge.".$opt, array(
        'type' => 'select',
        'multiple' => 'checkbox',
        'options' =>$arr[$opt],
        'label'=>false
        ));
    }
    echo $this->Form->end('Send');
    ?>