Monday, January 23, 2012

create link on image in cake php

Displaying a image in cakephp 
 
<?php echo $html->image('home.gif');?>
 
Create a link in cake php
<?php echo $html->link("Home", array('action' => 'features'),
array('escape' => false));?>
so when we talk about create a link on image we can combine both of these
echo $html->link(
    $html->image('img.png'),
    'img.png',
    array(),
    array( 'escape' => false ),     
  );
 
 
Obvious img.png is image name You have to set the path by default it goes webroot/img/
 
 
 
  • <?php echo $html->link($html->image("products.gif"), array('controller'=>'products', 'action' => 'features'), array('escape' => false));?>
 
 

Thursday, December 1, 2011

RequestAction in CakePhp

RequestAction
 
 
   
I am in a situation where i need to fetch data from 6 models. i can't use associations as they are not related. So what should i use $uses or request action or any other solution



Syntax of requestAction

requestAction(string $url, array $options)

This function calls a controller's action from any location and returns data from the action. The $url passed is a CakePHP-relative URL (/controllername/actionname/params). To pass extra data to the receiving controller action add to the $options array.


Example


  1. echo $this->requestAction(array('controller' => 'articles', 'action' => 'featured'), array('return'));

This allows the requestAction call to bypass the usage of Router::url which can increase performance. The url based arrays are the same as the ones that HtmlHelper::link uses with one difference - if you are using named or passed parameters, you must put them in a second array and wrap them with the correct key. This is because requestAction merges the named args array (requestAction's 2nd parameter) with the Controller::params member array and does not explicitly place the named args array into the key 'named'; Additional members in the $option array will also be made available in the requested action's Controller::params array.


Suppose there is a function in class


class CommentsController extends AppController {
function latest() {
$comments = $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));
if (!empty($this->params['requested'])) {
return $comments;
} else {
$this->set(compact('comments'));
}
}

}



And there is we r using the requestAction




$comments = $this->requestAction('/comments/latest');
foreach($comments as $comment) {
echo $comment['Comment']['title'];
}
 


Sunday, November 27, 2011

validation in cakephp

This i s basic Approch that the data we need to enter in database is correct and Validating data is must for it i am providing few of examples to see the validation methods via Models

In next session i will tell u how to be validate data via controller and vai java script validation
but Now focus on Validation via Models


. The usage of the new validation rules follows the following pattern (in your model):
var $validate = array('field' => array('rule' =>
array('validationmethod',
'param1', 'param2')));
Ok, let’s have a look at the validation methods.
alphaNumeric should be self-explanatory, it allows only letters and strings. Useful for e.g. user names:
var $validate = array('username' => 
array('rule' => array('alphaNumeric')));
between is a bit misleading, as I expected that it checks whether a number is in a certain range. But what it actually does is to check the string length. In the following example the length of the user name must be at least 3 characters, and maximal 10 characters:
var $validate = array('username' => array('rule' =>
array('between', 3, 10)));
blank validates that a field is blank or contains only whitespace characters like tabs or spaces. It doesn’t look very useful to me. Its usage is:
var $validate = array('x' => array('rule' => array('blank')));
cc doesn’t stand for “carbon copy”, it stands for “credit card”. It checks whether a credit card number is valid. If you want to check for Visa numbers, you would do the following:
var $validate = array('creditcard' => 
array('rule' => array('cc', array('visa'))));
comparison is used to compare numeric values. It supports “is greater”, “is less”, “greater or equal”, “less or equal”, “is less”, “equal to”, and “not equal”. To check whether the provided age was higher than 18 you would do:
var $validate = array('age' => 
array('rule' => array('comparison', '>=', 18)));
or
var $validate = array('age' =>
array('rule' => array('comparison', 'greater or equal', 18)));
custom is also a bit misleading imho. It allows you to define a regular expression.
var $validate = array('username' => array('rule' =>
array('custom', '/^[0-9a-z]+$/i')));
date checks for a valid date. It allows different formats, see the API for details. To check whether the entered date is of the format yyyy-mm-dd resp. yy-mm-dd you would do:
var $validate = array('startdate' => 
array('rule' => array('date', 'ymd')));
decimal checks for a valid decimal number. If you want to have decimal numbers with two digits after the dot you have to use:
var $validate = array('price' =>
array('rule' => array('decimal', 2)));
It is obvious, what email does: it checks for a valid email address:
var $validate = array('email' => array('rule' => array('email')));
I am not sure whether money is fully implemented yet, at least I was not able to use this validation rule.
numeric is a simple wrapper for the PHP function is_numeric:
var $validate = array('age' => array('rule' => array('numeric')));
phone validates phone numbers. At the moment it supports only US phone numbers, if you want to validate other phone numbers you have to provide a regular expression.
var $validate = array('phone' => array('rule' => 
array('phone', null, 'us')));
postal is used to validate zip codes from the U.S., Canada, and the U.K. For other zip codes you have to provide a regular expression.

var $validate = array('zipcode' =>
array('rule' => array('postal', null, 'us')));
ssn validates social security numbers from the U.S., Denmark, and the Netherlands. For other social security numbers you have to provide a regular expression.

var $validate = array('ssn' => 
array('rule' => array('ssn', null, 'us')));
url is used to validate urls.
var $validate = array('website' => 
array('rule' => array('url')));
If you look at the validation class you will notice several other public methods. equalTo, file, ip, minLength, maxLength, multiple, and number are validation rules which are not implemented yet, so I don’t have described them. The userDefined method looks like it allows you to create custom validation methods, but up to now I couldn’t figure out how to use it…

var $validate = array('username' =>
array('rule' => array('minLength', 3)));
And to validate that a string can consist of maximal 20 characters you do:
var $validate = array('username' =>
array('rule' => array('maxLength', 20)));
 Also ip has been implemented, which is used to validate IP addresses.
var $validate = array('ip' => array('rule' => 'ip'));
 
 
 
More validation methods are
 
  • alphaNumeric
  •  between
  •  blank
  •  boolean
  •  cc
  • comparison
  •  date
  • decimal
  •  email
  •  equalTo
  •  extension
  •  file
  •  ip
  •  isUnique
  •  minLength
  •  maxLength
  •  money
  •  multiple
  •  inList
  •  numeric
  •  notEmpty
  •  phone
  •  postal
  •  range
  •  ssn
  •  url
Examples


<?php
class User extends AppModel
{
var $name = 'User';
var $validate = array(
'login' => '/[a-z0-9\_\-]{3,}$/i',
'password' => VALID_NOT_EMPTY,
'email' => VALID_EMAIL,
'born' => VALID_NUMBER
);
}
?>





    Naming conventions in cakephp

    •Naming conventions
    –Class name :MyFirstClassfilename: my_first_name.php
    –Classname: Book tablename: books
    –Classname: BooksController
    Ex:
    Database table : books
    Model class : Book
    Controller class : BooksController
    View found at : /app/views/books/index.ctp
    Steps
    •Creating the database
    •Creating a model
    •Creating a controller
    •Creating the views
    Creating the database
    •Create a new table (name should be according to the naming conventions)
    •Enter the data.
    •(Using phpmyadmin)
    Creating a model
    •Separates the domain logic from presentation isolating the application logic.
    •Extends AppModel(extends Model)
    •Contains data validation rules, association information and methods specific to the table it uses.
    •For complete reference http://api.cakephp.org
    •Cakephpdynamically creates a model object
    class Book extends AppModel{
    var$name = ‘Book';
    }
    •We do can add some behaviors to each model.
    Creating a controller
    •Manages the logic for a part of our application
    •Can access the model object by $this->Book
    class BooksControllerextends AppController{
    var$name = 'Books';
    function index() {
    $this->set('books', $this->Book->find('all'));
    }
    }
    •$this->loadModel(‘Article'); loads a different model
    •Components (packages of logic that are shared between controllers)
    Creating the views
    •Layouts (placed in /app/views/layouts)
    •Elements (reusable parts)
    •Helpers
    (var$helpers = array('Form', 'Html', 'Javascript', 'Time');)
    Sample model
    <?php
    class Book extends AppModel
    {
    var$name = 'Book';
    var$validate = array(
    'title' => array(
    'rule' => 'notEmpty'
    ),
    'author' => array(
    'rule' => 'notEmpty'
    )
    );
    }
    ?>
    Sample Controller
    <?php
    class BooksControllerextends AppController{
    var$name = 'Books';
    var$helpers = array('Html','Ajax','Javascript');
    function index()
    {
    $this->set('books', $this->Book->find('all'));
    }
    function view($id = null) {
    $this->Book->id = $id;
    $this->set('book', $this->Book->read());
    print_r($this->viewVars);
    }
    }
    Sample view
    <h1>Books</h1>
    <table>
    <tr>
    <th>Id</th>
    <th>Title</th>
    <th>Author</th>
    </tr>
    <?phpforeach($books as $book: ?>
    <tr>
    <td><?phpecho $book*‘Book'+*'id'+; ?></td>
    <td>
    <?php echo $html->link($book*‘Book+*'title'+,
    array('controller' => ‘books’, 'action' => 'view', $book*‘Book+*'id'+)); ?>
    </td>
    <td><?php echo $book*‘Book+*‘author'+; ?></td>
    </tr>
    <?php endforeach; ?>
    </table>

    Add fck editor in cakephp

    Installation
    1) Copy fckeditor folder to app/webroot/js/
    2) Copy fckeditor.php, fckeditor_php4.php, fckeditor_php5.php to app/vendors/

    Setup
    Create a file in helpers called fck.php in view

    <?php
    App::import('Vendor', 'fckeditor');
    class FckHelper extends AppHelper {
        /**
        * creates an fckeditor textarea
        *
        * @param array $namepair - used to build textarea name for views, array('Model', 'fieldname')
        * @param stirng $basepath - base path of project/system
        * @param string $content
        */
        function fckeditor($namepair = array(), $basepath = '', $content = ''){
            $editor_name = 'data';
            foreach ($namepair as $name){
                $editor_name .= "[" . $name . "]";
            }
            $oFCKeditor = new FCKeditor($editor_name) ;
            $oFCKeditor->BasePath = $basepath . '/js/fckeditor/' ;
            $oFCKeditor->Height="400px";
            $oFCKeditor->Value = $content ;
            $oFCKeditor->Create() ;
        }
    }
    ?>

    Core Helpers in Cakephp

    Helpers
    Helpers represent component-like classes for the presentation layer of your application, which contain presentational logic shared between many views, elements or layouts.

    The CakePHP framework needs a controller in order to make usage of helpers. Each controller has a $helpers property that lists the helpers to be made available in the view. To enable a helper in your view, add the name of the helper to the controller’s $helpers array.


    Example
    <?php
    class ExampleController extends AppController {
    var $name = 'Example';
    var $helpers = array('Html','Ajax','Javascript');
    }

    CakePHP features a number of helpers that aid in view creation. They assist in creating well-formed markup (including forms), aid in formatting text, times and numbers, and can even speed up Ajax functionality. Here is a summary of the built-in helpers.
    CakePHP Helper
    Description
    Ajax
    Used in tandem with the Prototype JavaScript library to create Ajax functionality in views. Contains shortcut methods for drag/drop, ajax forms & links, observers, and more.
    Cache
    Used by the core to cache view content.
    Form
    Creates HTML forms and form elements that self populate and handle validation problems.
    Html
    Convenience methods for crafting well-formed markup. Images, links, tables, header tags and more.
    Js
    Used to create Javascript compatible with various Javascript libraries. Replaces JavascriptHelper and AjaxHelper with a more flexible solution.
    Used to escape values for use in JavaScripts, write out data to JSON objects, and format code blocks.
    Number
    Number and currency formatting.
    Model data pagination and sorting.
    Convenience methods for outputting RSS feed XML data.
    Session
    Access for reading session values in views.
    Text
    Smart linking, highlighting, word smart truncation.
    Time
    Proximity detection (is this next year?), nice string formatting(Today, 10:30 am) and time zone conversion.
    Xml
    Convenience methods for creating XML headers and elements.
     *if any type of help is needed regarding prog or concept contact me on dadhich.priyank@gmail.com

    APPROACH TO THE MVC ARCHITECTURE

    Cake is based on an MVC-like architecture that is both powerful and easy to grasp: controllers, models and views guarantee a strict but natural separation of business logic from data and presentation layers.
    Controllers contain the logic of your application. Each controller can offer different functionality; controllers retrieve and modify data by accessing database tables through models; and they register variables and objects, which can be used in views.

    Models are active representations of database tables: they can connect to your database, query it (if instructed to do so by a controller) and save data to the database. It is important to note that in order to correctly apply the MVC architecture, there must be no interaction between models and views: all the logic is handled by controllers.


    Views can be described as template files(means that contans the html or designs) that present their content to the user: variables, arrays and objects that are used in views are registered through a controller. Views should not contain complex business logic; only the elementary control structures necessary to perform particular operations, such as the iteration of collected data through a foreach construct, should be contained within a view.

    This architecture can greatly improve the maintainability and the organization of your site’s code:

    It separates business logic from presentation and data retrieval.
    A site is divided into logical sections, each governed by a particular controller.
    When testing and debugging an application, any developer accustomed to CakePHP’s structure will be able to locate and correct errors without knowing all of the details of the code.
    Controllers, models and views are stored in pre-defined directories within CakePHP’s directory structure. Here’s the directory structure that’s used:

    app/
    config/
    controllers/
    models/
    plugins/
    tmp/
    vendors/
    views/
    webroot/
    cake/
    config/
    docs/
    libs/
    vendors/
    This directory scheme must be preserved, as it is essential if the framework itself is to work. Cake, like Rails, believes in the importance of convention over configuration: in order to deploy an application, rather than modify dozens of different configuration files, it’s important only to place everything in its proper place; then, you can let the framework do the rest.

    Although this may seem worrisome for some developers, it’s a good compromise that can really accelerate the development process.

    The MVC Pattern

    Model-View-Controller is a software design pattern that helps you logically separate your code, make it more reusable, maintainable, and generally better. Model View Controller was once described by the author group Gang of Four. Dean Helman wrote (an extract from Objective Toolkit Pro white paper):
    "The MVC paradigm is a way of breaking an application, or even just a piece of an application's interface, into three parts: the model, the view, and the controller. MVC was originally developed to map the traditional input, processing, output roles into the GUI realm.
    Input -> Processing -> Output
    Controller -> Model -> View
    "The user input, the modeling of the external world, and the visual feedback to the user are separated and handled by model, view port and controller objects. The controller interprets mouse and keyboard inputs from the user and maps these user actions into commands that are sent to the model and/or view port to effect the appropriate change. The model manages one or more data elements, responds to queries about its state, and responds to instructions to change state. The view port manages a rectangular area of the display and is responsible for presenting data to the user through a combination of graphics and text."
    In Cake terms, the Model represents a particular database table/record, and it's relationships to other tables and records. Models also contain data validation rules, which are applied when model data is inserted or updated. The View represents Cake's view files, which are regular HTML files embedded with PHP code. Cake's Controller handles requests from the server. It takes user input (URL and POST data), applies business logic, uses Models to read and write data to and from databases and other sources, and lastly, sends output data to the appropriate view file.
    To make it as easy as possible to organize your application, Cake uses this pattern not only to manage how objects interact within your application, but also how files are stored, which is detailed next.



    Enjoy