Thursday, May 16, 2013

Using CakePHP FormHelper with Bootstrap Forms

CakePHP's FormHelper helpt to generate forms when making CakePHP applications. As one might assume, this includes generating input elements, like example:

 <form action="">  
 <fieldset>  
 <div class="control-group required error">  
   <label for="Fieldname" class="control-label">Fieldname</label>  
   <div class="controls">  
     <input name="data[Fieldname]" class="form-error" maxlength="255" type="text" value="" id="Fieldname"/>  
     <span class="help-inline">Error message</span>  
   </div>  
 </div>  
 </fieldset>  
 </form>  

The CakePHP code is:


 <?php echo $this->Form->create('ModelName', array(  
   'class' => 'form-horizontal',  
   'inputDefaults' => array(  
     'format' => array('before', 'label', 'between', 'input', 'error', 'after'),  
     'div' => array('class' => 'control-group'),  
     'label' => array('class' => 'control-label'),  
     'between' => '<div class="controls">',  
     'after' => '</div>',  
     'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),  
   )));?>  
 <fieldset>  
 <?php echo $this->Form->input('Fieldname1', array(  
   'label' => array('class' => 'control-label','text'=>'HERE YOU LABEL TEXT')  
   )); ?>  
 <?php echo $this->Form->input('Fieldname2', array(  
   'label' => array('class' => 'control-label','text'=>'HERE YOU LABEL TEXT')  
   )); ?>  
 </fieldset>   
 <?php echo $this->Form->end();?>  

Saturday, May 4, 2013

Bootstrap Typeahead CakePHP 2.0

Integrate Twitter Bootstrap Typeahead with your CakePHP 2.0 application.
You need:
- Cakephp 2.x
- Jquery
- Twitter bootstrap

First the form:
<input data-provide="typeahead" id="user-typeahead" type="text" />

Setting your url base
Put it into default.ctp before </head>
<script type="text/javascript">
  //get url base app
  var site_url='<?php echo $this->base; ?>';

</script>

The Jquery:
Put it into bottom in view

<script>  
$( document ).ready( function(){        
            $('#user-typeahead').typeahead({
                source: function (query, process) {
                    return $.ajax({
                        url: site_url+'/users/typeahead_search',
                        type: 'get',
                        data: {q: query},
                        dataType: 'json',
                        success: function (json) {
                            return process(json);
                        }
                    });
                }
            });  

 });                      
 </script>


UsersController
    public function typeahead_search() {
        $this->autoRender = false;
        $this->RequestHandler->respondAs('json');

        // get the search term from URL
        $term = $this->request->query['q'];
        $users = $this->User->find('all', array(
            'conditions' => array(
                'User.username LIKE' => '%' . $term . '%'
            )
                ));

        // Format the result for input
        $result = array();
        foreach ($users as $key => $user) {
            array_push($result, $user['User']['username']);
        }
        $users = $result;

        echo json_encode($users);
    }


This action will receive the request, search the database for relevant result and return it on JSON format.

Thursday, February 14, 2013

Upload single image or file using Cakephp 1.3

This tutorial for upload image or file using Cakephp 1.3.

Step 1 : Create table name 'uploads'

CREATE TABLE `uploads` (
 `id` CHAR(36) NOT NULL PRIMARY KEY,
 `title` VARCHAR(45) NOT NULL,
 `description` TEXT,
 `filename` VARCHAR(255) NOT NULL,
 `filesize` INT(11) UNSIGNED NOT NULL DEFAULT 0,
 `filemime` VARCHAR(45) NOT NULL DEFAULT 'text/plain',
 `created` DATETIME,
 `modified` DATETIME
);

Step 2 : Create view for 'uploads'
path : /views/uploads/add.ctp

<?php echo $this->Form->create(‘Upload’, array(‘type’ => ‘file’));?>
  <fieldset>
     <legend><?php __(‘Add Upload’); ?></legend>
  <?php
  echo $this->Form->input(‘title’);
  echo $this->Form->input(‘description’);
  echo $this->Form->input(‘file’, array(‘type’ => ‘file’));
  ?>
  </fieldset>
<?php echo $this->Form->end(__(‘Submit’, true));?>

Step 3 : Create controller 'uploads_controller'
path : /controllers/uploads_controller.php

Step 3.1 : create function add()

function add() {
  if (!empty($this->data)) {
   $this->Upload->create();
            if ($this->uploadFile() && $this->Upload->save($this->data)) 
{
                $this->Session->setFlash(__('The upload has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
            }
        }
    }


Step 3.2 :create function uploadFile()
path : /webroot/uploads
make sure create folder 'upload' in webroot and permission access to this folder


function uploadFile() {
  $file = $this->data[‘Upload’][‘file’];
  if ($file[‘error’] === UPLOAD_ERR_OK) {
    $id = String::uuid();
    if (move_uploaded_file($file[‘tmp_name’], APP.’webroot/uploads’.DS.$id)) {
      $this->data[‘Upload’][‘id’] = $id;
      $this->data[‘Upload’][‘filename’] = $file[‘name’];
      $this->data[‘Upload’][‘filesize’] = $file[‘size’];
      $this->data[‘Upload’][‘filemime’] = $file[‘type’];
      return true;
    }
  }
  return false;
}

Step 4 : Create view and function for download

i. create view index.ctp
path : /views/uploads/index.ctp

<h2><?php __('Upload'); ?></h2>
<table cellpadding="0" cellspacing="0">
    <tr>
        <th><?php __('id'); ?></th>
        <th><?php __('title'); ?></th>
        <th><?php __('download'); ?></th>
    </tr>
    <?php foreach ($uploads as $upload): ?>
        <tr>
            <td><?php echo $upload['Upload']['id']; ?>&nbsp;</td>
            <td><?php echo $upload['Upload']['title']; ?>&nbsp;</td>
            <td>
                <?php
                echo $this->Html->link(__('Download', true), array(
                    'action' => 'download', $upload['Upload']['id']));
                ?>&nbsp;</td>
        </tr>
    <?php endforeach; ?>
</table>
 
ii. create function download in uploads_controller.php

 
function download($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $upload = $this->Upload->find('first', array(
            'conditions' => array(
                'Upload.id' => $id,
            )
                ));
        if (!$upload) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->view = 'media';
        $filename = $upload['Upload']['filename'];
        $this->set(array(
            'id' => $upload['Upload']['id'],
            'name' => substr($filename, 0, strrpos($filename, '.')),
            'extension' => substr(strrchr($filename, '.'), 1),
            'path' => APP . 'webroot/uploads' . DS,
            'download' => true,
        ));
    }

Extra : Show image in view.ctp
path : /views/uploads/view.ctp

$id = $upload['Upload']['id'];
echo '<img src="'.$this->Html->url(array('controller' => 'uploads','action' => 'download',$id)).'"/>'; 

Wednesday, October 10, 2012

Create autoComplete Method Ajax in Cakephp

ref: http://book.cakephp.org/1.3/en/view/1358/AJAX
1.  You'll need to include the Ajax and Javascript helpers in your controller:

class PostsController extends AppController {
    var $name = 'Posts';
    var $helpers = array('Html','Ajax','Javascript');
    var $components = array( 'RequestHandler' );
}


2. Once you have the javascript in your controller, you can use javascript helper link() method to include Prototype and Scriptaculous in view/layout/default.ctp

echo $html->script('prototype');
echo $html->script('scriptaculous'); 


Download Prototype
 - save it in /webroot/js/prototype.js
Download Scriptaculous
 - save all it in /webroot/js/
  

3. You need to set up a controller action that fetches and organizes the data you'll need for your list, based on user input:

#/app/controllers/posts_controller.php
function autoComplete() {
    //Partial strings will come from the autocomplete field as
    //$this->data['Post']['title']
    $this->set('posts', $this->Post->find('all', array(
                'conditions' => array(
                    'Post.title LIKE' => $this->data['Post']['title'].'%'
                ),
                'fields' => array('title')
    )));
    $this->layout = 'ajax';
}

4. Create app/views/posts/auto_complete.ctp that uses that data and creates an unordered list:

 <ul>
 <?php foreach($posts as $post): ?>
     <li><?php echo $post['Post']['title']; ?></li>
 <?php endforeach; ?>
</ul>


 5.  Finally, utilize autoComplete() in a view to create your auto-completing form field:

<?php echo $this->Form->create('Post', array('url' => '/posts/index')); ?>
    <fieldset>
         <legend><?php __('Search Post'); ?></legend>
    <?php echo $ajax->autoComplete('Post.title', '/posts/autoComplete')?>
    </fieldset>
<?php echo $this->Form->end(__('Find!!!', true));?> 


Once you've got the autoComplete() call working correctly, use CSS to style the auto-complete suggestion box. You might end up using something similar to the following:
div.auto_complete    {
     position         :absolute;
     width            :250px;
     background-color :white;
     border           :1px solid #888;
     margin           :0px;
     padding          :0px;
} 
li.selected    { background-color: #ffb; }

Sunday, September 16, 2012

Setting up Twitter Bootstrap with CakePHP

Bootstrap

Sleek, intuitive, and powerful front-end framework for faster and easier web development.

Step 1: Download CakePHP and Twitter Bootstrap

To get CakePHP, go to CakePHP.org an download the latest release and head over to the Bootstrap site to get it.

Step 2: Copy the Bootstrap files to CakePHP setup



Bootstrap css,img,javascript source to copy














Cake source css,img,js Directory







Step 3. Setup the CakePHP default template

In the CakePHP source, go into the Views->Layouts directory and open up the default.ctp.

Replace this code

<!DOCTYPE html>
<html lang="en">
<head>
  <?php echo $this->Html->charset(); ?>
  <title><?php echo $title_for_layout; ?></title>
  <!--  meta info -->
  <?php
    echo $this->Html->meta(array("name"=>"viewport",
      "content"=>"width=device-width,  initial-scale=1.0"));
    echo $this->Html->meta(array("name"=>"description",
      "content"=>"this is the description"));
    echo $this->Html->meta(array("name"=>"author",
      "content"=>"TheHappyDeveloper.com - @happyDeveloper"))
  ?>

  <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
  <!--[if lt IE 9]>
  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->

  <!-- styles -->
  <?php
    echo $this->Html->css('bootstrap');
    echo $this->Html->css('bootstrap-responsive');
    echo $this->Html->css('docs');
    echo $this->Html->css('prettify');
    
    echo $javascript->link(array(
            'jquery.js',
            'prettify.js',
            'bootstrap.js',
          
        ));
  ?>
  <!-- icons -->
  <?php
    echo  $this->Html->meta('icon',$this->webroot.'img/favicon.ico');
    echo $this->Html->meta(array('rel' => 'apple-touch-icon',
      'href'=>$this->webroot.'img/apple-touch-icon.png'));
    echo $this->Html->meta(array('rel' => 'apple-touch-icon',
      'href'=>$this->webroot.'img/apple-touch-icon.png',  'sizes'=>'72x72'));
    echo $this->Html->meta(array('rel' => 'apple-touch-icon',
      'href'=>$this->webroot.'img/apple-touch-icon.png',  'sizes'=>'114x114'));
  ?>
  <!-- page specific scripts -->
    <?php echo $scripts_for_layout; ?>
</head>

<body data-spy="scroll" data-target=".subnav" data-offset="50">
  <div id="container">
  <!-- Navbar ============================================= -->
  <div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
      <div class="container">
        <a class="btn btn-navbar" data-toggle="collapse"
          data-target=".nav-collapse">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </a>
        <a class="brand" href="./index.html">Bootstrap</a>
        <div class="nav-collapse">
          <ul class="nav">
            <li class="active">
              <a href="<?php echo $this->webroot;?>">Home</a>
            </li>
            <li class="">
              <a href="./base-css.html">Base CSS</a>
            </li>
            <li class="">
              <a href="./components.html">Components</a>
            </li>
            <li class="">
              <a href="./javascript.html">Javascript plugins</a>
            </li>
            <li class="">
              <a href="./less.html">Using LESS</a>
            </li>
            <li class="divider-vertical"></li>
            <li class="">
              <a href="./download.html">Customize</a>
            </li>
            <li class="">
              <a href="./examples.html">Examples</a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <div id="row">
    <?php echo $this->Session->flash(); ?>
    <?php echo $content_for_layout; ?>
  </div>
  </div>
  <?php echo $this->element('sql_dump'); ?>
</body>
</html>



Tuesday, August 14, 2012

Changing File Permissions

On computer filesystems, different files and directories have permissions that specify who and what can read, write, modify and access them.

Permission Modes 

The permission mode is computed by adding up the following values for the user, the file group, and for everyone else. The diagram shows how.
  • Read 4 - Allowed to read files
  • Write 2 - Allowed to write/modify files
  • eXecute1 - Read/write/delete/modify/directory 

Example Permission Modes

Mode Str Perms Explanation
0477 -r--rwxrwx owner has read only (4), other and group has rwx (7)
0677 -rw-rwxrwxowner has rw only(6), other and group has rwx (7)
0444 -r--r--r--all have read only (4)
0666 -rw-rw-rw-all have rw only (6)
0400 -r--------owner has read only(4), group and others have no permission(0)
0600 -rw-------owner has rw only, group and others have no permission
0470 -r--rwx---owner has read only, group has rwx, others have no permission
0407 -r-----rwxowner has read only, other has rwx, group has no permission
0670 -rw-rwx---owner has rw only, group has rwx, others have no permission
0607 -rw----rwxowner has rw only, group has no permission and others have rwx