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

sarwar's weblogs

~ story of web applications…..

sarwar's weblogs

Tag Archives: CakePHP

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

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

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…    2 months ago
  • RT @Cristiano: Great team effort and a good victory. We stand together. Let’s go, United! 💪🏽 https://t.co/GnjAR3oM3s    4 months ago
  • RT @Cristiano: Hard work always pays off 🙏🏽💪🏽 https://t.co/kMqIpB2nfV    7 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

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: