• About Sarwar
  • Portfolio
  • আমার বাংলা

sarwar's weblogs

~ story of web applications…..

sarwar's weblogs

Category Archives: Framework

quick setup of Auth Component for CakePHP 2.0

15 Sunday Jan 2012

Posted by Sarwar in CakePHP

≈ 4 Comments

Tags

Auth, CakePHP, component, Login


I found some new thing in cakephp 2.x.  I just tried to show here how quickly we can setup Auth Component in to our project.

First we need to setup configuration

// app/Controller/AppController.php
var $components = array(
        "Auth" => array(
            'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'), // After success where page goes to 
            'logoutRedirect' => array('controller' => 'users', 'action' => 'login') // This is login page 
        ),
        "Session");
function beforeFilter(){
.....
         $this->Auth->authenticate = array( 
                                        AuthComponent::ALL => array('userModel' => 'User', 'scope' => array("User.status" => 1)),
                                        'Form');


}

Logic check controller.

//app/Controller/UsersController.php
    function login() 
    {
        if($this->request->is('post')){
        {
              if($this->Auth->login()){
                  $this->loginUser = AuthComponent::user();  // Here $this->loginUser is defined so we can get the user values here. 
                  return $this->redirect($this->Auth->redirect());
              }else{
                  $this->Session->setFlash('Username or password is incorrect', 'default', array(), 'auth');
              }
          }   
        
        }
    }

Login view here, this is login form

    echo $this->Session->flash('auth'); // This will show the authentication error message
    echo $this->Form->create('User', array("controller" => "users", "action" => "login", "method" => "post"));

    echo $this->Form->input('User.username', array("label" => "Username:"));
    echo $this->Form->input('User.password', array("label" => "Password: "));
    echo $this->Form->end('Login');

When we create a user we need to setup the hash password field


If we need hash password, we need to do the follwoing 

//app/Model/User.php

function beforeSave(){
    if (isset($this->data[$this->alias]['password'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
}

I can add user normally and its work.

I just show here the basic login use which is used for quick setup.

Happy login 😀

If you want to go more advanced uses of component go to Docs

Advertisement

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

Multiple line html code assign to a javascript variable/ assign cakephp element to a javascript variable

05 Friday Aug 2011

Posted by Sarwar in CakePHP, JavaScript, PHP

≈ 36 Comments

Tags

cakephp element, js variable multiple line, json_encode


I was working with google map api, I have task to make a infowindow for a marker. I faced some problem when I assigned multiple line code to a javascript variable. I tried to put a html code to a javascrpt variable which will use for info window.

I need to put block of html code (cakephp element) to a variable. if we do like the following

<script>
var infowindow = '<div class="map_info_content">
    <table cellpadding="3" cellspacing="3">
        <tr>
            <td colspan="2">
                <h1 class="map_title"><?=$map_title?></h1>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <img src="<?=$imgurl?>" style="<?=$style_img?>" /> 
            </td>
            <td align="left" valign="top">
                <p>
                    <?=$msg?>
                </p>
            </td>
        </tr>
    </table>';
</script>

Its not not working, we need to put a slash / each end of line or need to write infowindow += “” for each line.
Now If we keep that html code to a cakephp element and just call the element and make it json_encode it work or keep this in to a php variable and make it json encode it working lets see

<?php
    $html = '<div class="map_info_content">
    <table cellpadding="3" cellspacing="3">
        <tr>
            <td colspan="2">
                <h1 class="map_title">Title</h1>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <img src="info.jpg" style="" /> 
            </td>
            <td align="left" valign="top">
                <p>
                    HERE IS YOUR MSG
                </p>
            </td>
        </tr>
    </table>';
// Now make it json encode
$html = json_encode($html);
?>
// Now Assign it to a javascript variable
<script>
 var infowindow = <?=$html?> 
// OR if cakephp element
 var infowindow = <?=json_encode($this->element("infowindow"))?>

</script>

json_encode is very useful method to working like this.
🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

jquery UI tab – ajax loading CKEDITOR in a tab and some issues

28 Thursday Jul 2011

Posted by Sarwar in Ajax, CakePHP, ckeditor, jQuery UI, PHP

≈ 42 Comments

Tags

ajax, ckeditor, Jquery UI, PHP


I tried to load CKEDITOR in a jquery tab via ajax. I got problem that only first time the ckeditor is working but when I click on other tab and again got o ckeditor tab its not working. in Load section for tab I put the following code.

load: function(event, ui) {
  if(ui.index == 3){ // Checked tab no 4
    var instance = CKEDITOR.instances['reditor']; // reditor is text area id, check if instances exists for readitor or not 
    if(instance){ 
       CKEDITOR.remove(instance); //if existed then remove it
    }
    CKEDITOR.replace( 'reditor' ); // Create instance for 'reditor'
 }
}

in this way we can get rid the problem of “CKEditor instance already exists”

Here is whole configuration

$(document).ready(function () {
           var $tabs = $("#tabs").tabs({ 
                                
                                alignment: "top",
                                spinner : false,
                                ajaxOptions: {
                                    error: function( xhr, status, index, anchor ) {
                                                    $( anchor.hash ).html( "Couldn't load this tab. Please try again.");
                                                },
                                    complete: function(){
                                        
                                        
                                    }
                                    
                                },
                                load: function(event, ui) {
                                    if(ui.index == 3){
                                        var instance = CKEDITOR.instances['reditor'];
                                        if(instance){
                                            CKEDITOR.remove(instance);
                                        }
                                    }
                                },
                                select: function(e, ui){
                                            $(ui.panel).html('<img src="img/ajax_loader.gif" />'); // Loader after click on each tab
                                        }
                                
                                });
           $tabs.tabs('select', <?=$tab_no?>); // used for selected default tab
           
        });
        

Here is HTML/PHP (I used cakephp syntax for url ) used “TEXT” in a link to show the loading text on tab otherwise it will not show the loading tabl

<div id="tabs">
    <ul>
        <li>
            <?=$html->link("<span>Information</span>", array("controller" => "listings", "action" => "information", $id), array("escape" => false, "title" => "Information"))?>
            
        </li>
        <li>
            <?=$html->link("<span>Detail</span>", array("controller" => "listings", "action" => "detail", $id), array("escape" => false))?>
        </li>
        <li>
            <?=$html->link("<span>Peoples</span>", array("controller" => "listing", "action" => "peoples", $id), array("escape" => false))?>
        </li>
        <li>
            <?=$html->link("<span>Enhance</span>", array("controller" => "listings", "action" => "enhance", $id), array("escape" => false))?>
       </li>
    </ul>
 </div>

In this way I did and it work for me 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

cakephp- CONCAT in query, Virtual Fields and make a drop down

18 Saturday Jun 2011

Posted by Sarwar in CakePHP, PHP

≈ 13 Comments

Tags

CakePHP, CONCAT, virtual fields


I need to make a dropdown list of a staff. In dorpdown i need to put last name and first name. I already have a column in database name which contain first name and last name. But i need to show order last name then first name.

I tied to put CONCAT in query its working but the array result not showing properly. In this case I found that if i put a virtual fields in model that help me to fetch proper data.

In model

   var $virtualFields = array('dropdown_name' => 'CONCAT(Staff.last_name, " ", Staff.first_name)');

In controller query:

// Generate list
 $staff_list =  $this->Staff->find("list", array(
                                                        "fields" => array("id", "dropdown_name"),
                                                        "order" => array("Staff.name ASC"),
                                                        "conditions" => array('Staff.status' => '1')
                                                        ));

The above code give me the proper list of staff.
In view to generate dropdown

    echo $form->input("Reports.staff_id", 
                                array(
                                    'options' => $staff_list, 
                                    'empty' => '--Please Select--' ,
                                    'label'=> false, 
                                    ));    

In this way we can generate dropdown with different column in a one field.

The following I tried

          $staff_list = $this->Staff->find("list", array(
                                                        "fields" => array("Staff.id", "CONCAT(`Staff`.`last_name`, ' ', `Staff`.`first_name`)"),
                                                        "order" => array("AgencyStaff.name ASC"),
                                                        "conditions" => array('Staff.status' => '1')
                                                        ));

The query is runing properly but the result array doesn’t keep the CONACT fields, it only keep the id balnk.

But I run the query in cakephp and check what actually give it the result .

$list = $this->Staff->query("SELECT `Staff`.`id` , CONCAT( `Staff`.`last_name` , ' ', `Staff`.`first_name` ) 
                                        FROM `staffs` AS `Staff`
                                            WHERE `Staff`.`status` =1
                                            ORDER BY `Staff`.`name` ASC");

Result is the following

Array
(
    [0] => Array
        (
            [Staff] => Array
                (
                    [id] => 5
                )

            [0] => Array
                (
                    [CONCAT( `Staff`.`last_name` , ' ', `Staff`.`first_name` )] => Johnson Ashley
                )

        )
................
................

Thats why cakephp couldn’t make the proper array if we use their ORM.

I tried to use CONCAT( `Staff`.`last_name` , ‘ ‘, `Staff`.`first_name` ) as `Staff`.`name`
but it still not working.

SO I choose the virtual fields concept and it working properly for me 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

.htaccess killing 3 hours

17 Tuesday May 2011

Posted by Sarwar in .htaccess, Apache, CakePHP

≈ Leave a comment

Tags

.htaccess, apache, CakePHP, url rewrite


I’m working in cakephp for last two years, I developed and hosted many times, during hosting I got many problem all these are .htaccess related.

Today I tried to host one of my project, I created a server on rackspace cloud and installing all features apache, mysql, phpmyadmin and configure everything, I installed sugarcrm there and it worked, but when I tried to run my cakephp project, its always displaying “PAGE NOT FOUND”. the rewrite mdoule was on and i checked it working for others,

I checked apache error/access log, not clue found, doing some google no result, but I never give-up again trying to do some google got a reference in drupal site and check my apache configuration.

Only one thing I left in apache configuration.

// Open the apache site available
sudo nano /etc/apache2/sites-available/default

The article says that for URL rewriting we need to make “AllowOverride none” to “AllowOverride All”

I open that file and changed it.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride All 
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All 
                Order allow,deny
                allow from all
        </Directory>
...... 
......
...

Done, went to my site and its working properly, 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

Access session data in a model -cakephp

14 Saturday May 2011

Posted by Sarwar in CakePHP

≈ 7 Comments

Tags

CakePHP, component, model, session


Sometime we may need auth data for inserting in bforeSave method, i know it break the MCV rule but we sometime we need it for doing faster.

I used it in beforeSave method in a module

function beforeSave(){
   App::import('Component', 'SessionComponent'); 
   $session = new SessionComponent(); 
   // say we just retrieve the auth data
   $auth = $session->read("Auth.user");
  // here i used to add row value
  $this->data['ModelName']['field_name'] = $auth['login_user_id'];
   
  return true;
}

In this way we can use full session component data here. 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

cakephp ajax pagination using jquery

26 Tuesday Apr 2011

Posted by Sarwar in CakePHP, Framework, JavaScript, jquery, PHP

≈ 9 Comments

Tags

ajax, ajax pagination cakephp, jquery, paginator


I tried to use cakephp default ajax pagination, it seems not working with me. I tried with different way.

The following code using for pagination.

<div class="paginator">
        <?php echo $paginator->first(' First ', null, null, array('class' => 'disabled')); ?>
        <?php echo $paginator->prev('Previous ', null, null, array('class' => 'disabled')); ?>
        <?php echo $paginator->numbers(); ?>
       <?php echo $paginator->next(' Next ', null, null, array('class' => 'disabled')); ?>
        <?php echo $paginator->last(' Last ', null, null, array('class' => 'disabled')); ?>
</div>   

Now below that code I used the following java script code

<script>
    $(document).ready(function(){
        $(".paginator a").click(function(){
            $("#updated_div_id").load(this.href);
            return false;
        })
    });
</script>

Here, I just fire an event on click under paginator div, once you click on a link under that div, it fetch the url (this.herf) and calling page using ajax, You must prepared the controller for ajax based.

for example your controller calling ‘ajax_pages’ action.

function ajax_pages(){
        $this->layout = 'ajax';
        $this->paginate = array(
                                'order' => array('Module.created_date' => 'desc'), 
                                'recursive' => -1,
                                "limit" => PAGINATION_LIMIT
                                );
        
        $conditions['Module.module_type'] = $module_type;
        $data = $this->paginate("Module", $conditions);
        $this->set(compact("data"));  
}

Its work for me 🙂

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

How to hide label when we attempt to create cakephp form input

28 Monday Jun 2010

Posted by Sarwar in CakePHP

≈ Leave a comment

Tags

CakePHP, Form Helper, Input, Label


When I’m trying to create a input using cakephp form helper its automatically generated a label.

// when I'm trying to use 
<?=$form->input("User.name");?>
//it generated the following code
<div class="input text">
  <label for="UserName">Name</label><input type="text" id="UserName" name="data[User][name]">
</div>

I can get rid of label from the following code

<?=$form->input("User.name",array('label'=>false))?>
<div class="input text">
<input type="text" id="UserName" name="data[User][name]">
</div>

its very simple but sometime this type of issues killing our most valuable time.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

how to cakephp in a sub-directory, access it from root using .htaccess

16 Tuesday Mar 2010

Posted by Sarwar in CakePHP, PHP

≈ 13 Comments

Tags

.htaccess, CakePHP, sub-directory, url


Sometime we may need to put cakephp in a sub directory insted of document root directory, and we need to get the site from root.
Our document root directory is /httpdocs/ and we put the cakephp inside it /httpdocs /cake_sub/ and we want access the site from http://www.my-domain-name.com not http://www.my-domain-name.com/cake_sub

1. In this case we need to create a .htaccess file and put it to /httpdocs/ and the content is as follow

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule    ^$ cake_sub/app/webroot/    [L]
RewriteRule    (.*) cake_sub/app/webroot/$1 [L]
</IfModule>

So we need to on the RewriteEngine Now we need to edit the .htaccess files from the following locaiton

  • cake_sub/
  • cake_sub/app
  • cake_sub/webroot

2. Need to edit the .htaccess from /httpdocs/cake_sub as following


<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /cake_sub/
RewriteRule    ^$ app/webroot/    [L]
RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>
3. Need to edit the .htaccess from /httpdocs/cake_sub/app as following
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /cake_sub/app/
RewriteRule    ^$    webroot/    [L]
RewriteRule    (.*) webroot/$1    [L]
</IfModule>

4. Need to edit the .htaccess from /httpdocs/cake_sub/app/webroot as following

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /cake_sub/app/webroot/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>


Done, It worked with me and hope it’ll work with you too. I just put the document root httpdocs and sub directory name as an example.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

passing get variable in cakephp pagination url

12 Tuesday Jan 2010

Posted by Sarwar in CakePHP, Framework, PHP

≈ 17 Comments

Tags

argument, CakePHP, GET, pagination, paginator, parameter passed, PHP


For searching we many need to pass variable like ?keyword=test, and we may need to add pagination withen the search, Here I describe multiple cases where we may need to use pagination and how we manage the url for pagination when we make some searching

Case 1: if the url like the following
http://www.mydomain.com/controller/method/?keyword=test1&opt=test2

In this case we need to add the paginator option like this
First we retrive the passing variable and assign value, we can get it from “$this->params[‘url’]

$urls = $this->params['url']; $getv = "";
foreach($urls as $key=>$value)
{
if($key == 'url') continue; // we need to ignor the url field
$getv .= urlencode($key)."=".urlencode($value)."&"; // making the passing parameters
}
$getv = substr_replace($getv ,"",-1); // remove the last char '&'

Now we have the all get parameter, lest assign this to paginator option

$paginator->options(array('url' => array("?"=>$getv)));

Now all the pagination links always taking this get parameter so now if we gos to the next page the url look like this
http://www.mydomain.com/controller/method/page:2?keyword=test1&opt=test2

Now If we need passing an argument as id like the following
http://www.mydomain.com/controller/method/1/?keyword=test1&opt=test2
where 1 is an id or something we get this 1 from $this->passedArgs[0] So now we have to set the paginator option like this

$paginator->options(array('url' => array($this->passedArgs[0],"?"=>$getv)));

If we have passed more than one argument, we need to take it

$pass_argument = $this->passedArgs[0]."/"$this->passedArgs[1]."/".$this->passedArgs[2]."/";
$paginator->options(array('url' => array($pass_argument,"?"=>$getv)));

It depend on you how much you want to passed the argument, if you faced any problem print the $this->passedArgs and see how it organize the argument. Its really easy and I’ve already used it. Cheers

–new update
I got the idea from comments, here is update, the following code will useful for multiple arguments or params.

//extract the get variables
$url = $this->params['url'];
unset($url['url']);
$get_var = http_build_query($url);

$arg1 = array(); $arg2 = array();
//take the named url
if(!empty($this->params['named']))
$arg1 = $this->params['named'];

//take the pass arguments
if(!empty($this->params['pass']))
$arg2 = $this->params['pass'];

//merge named and pass
$args = array_merge($arg1,$arg2);

//add get variables
$args["?"] = $get_var;

$paginator->options(array('url' => $args));

done.. But I’m trying to make better solution, will update it soon.

Share this:

  • Tweet
  • Email

Like this:

Like Loading...

Author

  • Sarwar

Categories

  • .htaccess
  • Apache
  • API
  • CSS
  • Debug
  • Framework
    • CakePHP
  • HTML
  • JavaScript
    • Ajax
    • ckeditor
    • jquery
    • jQuery UI
    • tinymce
  • Joomla
    • Virtumart
  • Linux
  • MySQL
  • PHP
  • SVN
  • Twitter
  • WHM/cPanel
View Sarwar Hossain's profile on LinkedIn
Follow bdsarwar on Twitter

Tweets

  • RT @ESPNUK: If Erling Haaland wanted to match Cristiano Ronaldo's 700 league goals, he'd have to score 40 goals a season until the year 203…    1 month ago
  • RT @Cristiano: Great team effort and a good victory. We stand together. Let’s go, United! 💪🏽 https://t.co/GnjAR3oM3s    3 months ago
  • RT @Cristiano: Hard work always pays off 🙏🏽💪🏽 https://t.co/kMqIpB2nfV    5 months ago
  • RT @realDonaldTrump: Just finished a very good conversation with President Xi of China. Discussed in great detail the CoronaVirus that is r…    2 years ago
  • “Running a small business without a plan is a lot like driving without directions.” — @GoldmanSachs via @appexchange    6 years ago
  • RT @TechCrunch: 5K people turn up to catch Pokémon in Chicago tcrn.ch/2aaLRys https://t.co/VVQSd7nmN4    6 years ago

Flickr Photos

From Helipad ViewAbove the CloudHillNear to SkySunset Moment#sunset #beach #ocean #coxsbazar#jamroll #food #deliciousfood #homemade  #homemadefood#seaside #ocean #oceanview #travelphotography #coxsbazar #bayofbengal #travel #longestbeach#beach #lifeguard #seaside #holiday #tour #longestbeach #travel #travelphotography #coxsbazar #bayofbengal#resort #mountains
More Photos

Archives

  • February 2012 (1)
  • January 2012 (2)
  • August 2011 (1)
  • July 2011 (1)
  • June 2011 (2)
  • May 2011 (2)
  • April 2011 (1)
  • March 2011 (3)
  • December 2010 (3)
  • November 2010 (1)
  • October 2010 (4)
  • September 2010 (1)
  • June 2010 (1)
  • May 2010 (2)
  • April 2010 (1)
  • March 2010 (1)
  • January 2010 (2)
  • July 2009 (1)
  • January 2009 (1)
  • August 2008 (1)

Recent Comments

  • Kush on how to cakephp in a sub-directory, access it from root using .htaccess
  • Mr Griever on Access session data in a model -cakephp
  • apnarahimyarkhan on cakephp- CONCAT in query, Virtual Fields and make a drop down
  • Toko Kunci Pintu Murah on set & reset form text value onfocus, onblur, onclick using javascript
  • nevitaputri1.doodlekit on cakephp- CONCAT in query, Virtual Fields and make a drop down
  • RSS - Posts
  • RSS - Comments

Meta

  • Register
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com

Create a free website or blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • sarwar's weblogs
    • Join 328 other followers
    • Already have a WordPress.com account? Log in now.
    • sarwar's weblogs
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d bloggers like this: