cakephp – CodeForest https://www.codeforest.net Thu, 14 Oct 2021 17:32:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.5 https://www.codeforest.net/wp-content/uploads/2017/06/cropped-Asset-3-32x32.png cakephp – CodeForest https://www.codeforest.net 32 32 Development news and resources #1 https://www.codeforest.net/development-news-and-resources-1?utm_source=rss&utm_medium=rss&utm_campaign=development-news-and-resources-1 Tue, 06 Mar 2012 21:07:50 +0000 https://www.codeforest.net/?p=1213 Many great things happened in the last few weeks in development world, so I am writing a small roundup of news and resources.

It is hard to follow all the changes, so I will try to make this kind of roundups every now and then to help you find only the freshest and coolest news on development tools, programming languages and links that are interesting.

So let’s begin.

PHP 5.4 released

Few days ago, PHP 5.4 was released. It is a big step forward with many optimization changes and new features. Some of the biggest news is exlpained below.

Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

An example:

[code lang=”php”]
trait HelloWorld {
public function sayHello() {
echo ‘Hello World!’;
}
}

class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo ‘Hello Universe!’;
}
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
[/code]

Built in Web Server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

This web server is designed for developmental purposes only, and should not be used in production.

Shorter array syntax

PHP 5.4 brings us the shorter syntax for arrays.
For example:
[code lang=”php”]
// same as in JavaScript
$cars = [‘Ford’, ‘Honda’, ‘BMW’];
// associative array
$car = [‘type’ => ‘BMW’, ‘serie’ => ‘5’];
[/code]

Old syntax also work!

Other features

Use of $this in closures, class member access on instantiation, <?= is always available.

PHP 5.4.0 significantly improves performance and memory footprint. Also, Content-Type: text/html; charset=utf-8 is always sent; so there is no need to set that HTML meta tag, or send additional headers for UTF-8 compatibility. This is one step forward towards full Unicode support.

CakePHP 2.1.0 released

New minor version of CakePHP was released yesterday. There are over 90 features, changes and improvements in this release of this popular framework. Some of the most interesting:

New content type views

Two new view classes have been added to CakePHP. The new JsonView and XmlView allow you to more easily generate XML and JSON views.

Extending views

The View class has a new method allowing you to wrap or ‘extend’ a view/element/layout with another file.

Plugin.view

All layout/view/element names can now use Plugin.view to indicate that a plugin view should be used. The plugin option for View::element() is deprecated.

Improved errors

The debug() function output is now cleaner and more readable. We have also added interactive stack traces to exception pages.

General purpose event system

A new, generic event system has been built and it replaces the way callbacks are dispatched. You can dispatch your own events and attach callbacks to them at will.

Deep saving

saveAll and friends (saveMany, saveAssociated, validateAssociated …) now accept a new deep option param. For instance you can save the Author, Posts and related comments in just one call. You can also set the fieldList option to these methods, to provide a set of fields that are allowed to be saved.

New ACL engine

In addition to the good old database ACL engine, we have added a new one based on configuration files. This is a great alternative to the database solution for those who want to get a speedy permissions checking system when not requiring a database to dynamically manage permissions.

HtmlHelper::media()

The HtmlHelper gained a new media() method to generate HTML5 compatible audio and video tags with support for multiple alternate sources.

Many more new features are available.

Zend Framework 2.0.0beta3 Released!

Zend Framework is really near its 2.0.0 release.

Featured components and functionality of 2.0.0beta3 include:

  • Refactored Config component
    • All configuration readers have been moved under the Zend\Config\Reader namespace
    • A Zend\Config\Factory has been added to simplify retrieving a config object from a config file
    • Supported configuration formats now support importing additional configuration files
    • All constant processing has been moved to a Zend\Config\Processor namespace, and expanded to be more powerful
  • New View layer
    • New subcomponents include Zend\View\Model, Zend\View\Resolver, Zend\View\Renderer, and Zend\View\Strategy
    • The old Zend_View class has been moved to Zend\View\Renderer\PhpRenderer, and rewritten to move most of its responsibilities into collaborators, greatly simplifying its design while simultaneously giving it more capabilities.
    • A new class, Zend\View\View, allows selecting rendering strategies on a per-template basis, based on arbitrary criteria, and optionally injecting rendering results into a Response object
    • MVC integration streamlines common use cases, including View Model creation and injection, 404 and error page creation, and more.
  • Rewritten DB layer
    • New architecture features low-level drivers, which also provide access to the PHP resource being consumed; adapters, which provide basic abstraction for common CRUD operations; new SQL abstraction layer, with full predicate support; abstraction for ResultSet’s, with the ability to cast rows to specific object types; abstraction for SQL metadata; and a revised Table and Row Data Gateway.
  • New AgileZen component
  • PHP 5.4 Support
    • A number of issues when running ZF2 under PHP 5.4 were identified and corrected.

Sencha Touch 2.0 released

Sencha Touch 2 delivers a major upgrade to the app experiences that you create, the efficiency of your work as a developer, and the ability of your apps to participate in the mobile ecosystem.

Sencha Touch 2 is optimizing scrolling frame rates, layout speed, load time, and even how quickly a button responds to touch.

It is more than 200% faster in start up, scrolling and changing orientation.

New app loader caches your entire application within localStorage. This bypasses the need to download the app on a user’s second visit- in fact your app could load without making a single web request.

This can yield a stunning improvement in the startup speed of your web app – the second visit time is 250% faster when using the loader.

Pinterest Auto Pin for WordPress

Pinterest auto pin

Pinterest Auto Pin for WordPress allows you to quickly and easily add hover – over pin it buttons to your images on the fly making them instantly pinable to any board on Pinterest!

Advanced Custom Fields

Advanced Custom Fields

The Advanced Custom Fields plugin gives you the tools to create your own custom edit screens. Boasting a professional interface and a powerfull API, it’s a must have for any web developer working with WordPress.Field types include: Wysiwyg, text, textarea, image, file, select, checkbox, page link, post object, date picker, color picker and more!

This is one of the best plugins I ever used. It can be downloaded from official site.

Scope: Agency / Business WordPress Theme

scope

Scope is the perfect theme for the creative agency, freelancer or general business. Strong lines, strong colours and a bunch of super-awesome features to keep you busy.

Custom Backgrounds – Scope allows you to set a custom background for each individual post, page and portfolio project. A super-quick way to get creative with your site.

Post formats – Support for post formats means you can jazz up your blog with your own self-hosted video, audio, images, galleries, asides, links, quotes and of course good old standard posts.

That’s it for now. Don’t forget that there are plenty of resources available on Themescripts site!

]]>
CakePHP tip: Custom Find Types https://www.codeforest.net/cakephp-tip-custom-find-types?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-tip-custom-find-types https://www.codeforest.net/cakephp-tip-custom-find-types#comments Sun, 09 Jan 2011 17:06:27 +0000 https://www.codeforest.net/?p=709 You probably used some of the great built-in find types in CakePHP like find(‘all’) and find(‘count’). If you haven’t, here is an article on how to retrieve your data in CakePHP from CakePHP book.

This types are smart enough to retrieve data from database in any way you see fit.

But, there is a way to write your own custom find types. Then, you can use something like:

[code lang=”php”]
$Post->find(‘latest’);
[/code]

Yes, you will now tell me that you can use $Post->query to write custom SQL, but it is not efficient as this solution.

Cake’s base Model class has an attribute defined that keeps track of all the default find types. It
looks like this:

[code lang=”php”]
var $_findMethods = array(
‘all’ => true, ‘first’ => true, ‘count’ => true,
‘neighbors’ => true, ‘list’ => true, ‘threaded’ => true
);
[/code]

To create your custom find type you need to add it to this list. If your custom find type was latest you would do something like this:

[code lang=”php”]
class PostModel extends AppModel {
var $_findMethods = array(‘latest’ => true);
}
[/code]

So, in your Model class you would add new custom find method. Now you have to create the method that will be called. The method name must match the pattern _findCustomType. In our example it would be _findLatest.

[code lang=”php”]
function _findLatest($state, $query, $results = array()) {
if ($state == ‘before’) {
$query[‘limit’] = 10;
$query[‘order’] = ‘created DESC’;
return $query;
} elseif ($state == ‘after’) {
return $results;
}
}
[/code]

The trick behind this code is that this method will be called twice. Once before the database query is made and once after.

In the before state you will have access to the $query array, where you can set conditions, limit, order…all the usual find options. In the after state the $results array is passed. You can then alter $results to fit whatever you’re trying to do or just return it directly.

This way your CakePHP code is much more smaller and efficient.

]]>
https://www.codeforest.net/cakephp-tip-custom-find-types/feed 3
CakePHP from Scratch: Theming in real life example – Part Two https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-theming-in-real-life-example-part-two https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two#comments Sun, 24 Oct 2010 19:57:05 +0000 https://www.codeforest.net/?p=569 Long time no CakePHP on Codeforest. Let me correct that and finally finish the theming tutorial.

If you missed the first one, go to CakePHP theming in real life example – part one and read it carefully. Then return for the second part.

Last time I showed you how easy it is to add theme support to CakePHP and how to adjust xHTML/CSS template to make it work through CakePHP engine.

Today, we will adjust the template a bit by removing some unneeded elements and then adjust the CakePHP views so our application will look and work better.


If you didn’t follow the first part, download the files here.

First, we will remove some elements, so open /app/views/themed/default/layouts/default.ctp and change it to this:

[code lang=”php”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title_for_layout; ?></title>
<?php echo $this->Html->css(‘default’); ?>
</head>

<body>
<!–Header Background Part Starts –>
<div id="header-bg">
<!–Header Contant Part Starts –>
<div id="header">
<?php
echo $html->link($html->image("logo.gif"), array(‘controller’=>’jobs’, ‘action’ => ‘index’), array(‘escape’ => false));
?>
<!– –>
<!–Login Background Starts –>
<div id="login-bg">
<!–Login Area Starts –>
<div id="login-area">
<form action="" method="post" name="Login" id="Login">
<label>Members Login:</label>
<input type="text" name="username" id="username" />
<input type="password" name="pass" id="pass" />
<input type="image" src="images/login-btn.gif" class="login-btn" alt="Login" title="Login" />
<br class="spacer" />
</form>
</div>
<!–Login Area Ends –>
</div>
<!–Login Background Ends –>
<br class="spacer" />
</div>
<!–Header Contant Part Ends –>
</div>
<!–Header Background Part Ends –>
<?php echo $this->element(‘menu’, array(‘cache’ => true)); ?>
<!–Our Company Bacground Part Starts –>
<div id="ourCompany-bg">
<!–Our Company Part Starts –>
<div id="ourCompany-part">
<h2 class="ourCompany-hdr"><?php echo $title_for_layout; ?></h2>
<?php echo $content_for_layout; ?>
<br class="spacer" />
</div>
<!–Our Company Part Ends –>
</div>
<!–Our Company Bacground Part Ends –>
<!–Footer Part Starts –>
<div id="footer-bg">
<!–Footer Menu Part Starts –>
<div id="footer-menu">
<ul class="footMenu">
<li class="noDivider"><a href="#" title="Home">Home</a></li>
<li><a href="#" title="About">About</a></li>
<li><a href="#" title="Services">Services</a></li>
<li><a href="#" title="Support">Support</a></li>
<li><a href="#" title="Chat">Chat</a></li>
<li><a href="#" title="History">History</a></li>
<li><a href="#" title="Contact">Contact</a></li>
</ul>
<br class="spacer" />
<p class="copyright">Copyright?&amp;copy; Package 2007 All Rights Reserved</p>
<p class="copyright topPad">Powered by TemplateKingdom.com</p>
</div>
<!–Footer Menu Part Ends –>
</div>
<!–Footer Part Ends –>
</body>
</html>
[/code]

This way, I removed the Future plans div which we don’t need (at the moment).

Now open your default.css file which is located in /app/views/themed/default/webroot/css/ and find these lines:

[code lang=”css”]
div#ourCompany-bg div#ourCompany-part{
width:922px; margin:0 auto; padding:26px 0 28px 0;
background:url(../img/our-company-bg-pic.jpg) 606px 0 no-repeat;
}
[/code]

and comment the background line like this:

[code lang=”css”]
div#ourCompany-bg div#ourCompany-part{
width:922px; margin:0 auto; padding:26px 0 28px 0;
/*background:url(../img/our-company-bg-pic.jpg) 606px 0 no-repeat;*/
}
[/code]

What we just did? We got rid of the package image on the right of our content div, so we can stretch the content further.

Now, let us adjust the index view for Jobs. Open /app/views/themed/default/jobs/index.ctp, and change it to this:

[code lang=”php”]
<h2 class="ourCompany-hdr">Jobs</h2>
<div class="jobs index">
<?php
if(!empty($jobs)) {
$i = 0;
echo ‘<ul class="jobs_list">’;
foreach ($jobs as $job):
$class = null;
if ($i++ % 2 != 0) {
$class = ‘ class="odd"’;
}
echo ‘<li’.$class.’>’;
echo ‘<h3>’.$this->Html->link($job[‘Job’][‘title’], array(‘action’ => ‘view’, $job[‘Job’][‘id’])).'</h3>’;
echo ‘<div class="details">’;
echo ‘<span class="category">’.$job[‘Job’][‘job_type’].'</span>’;
echo ‘ – ‘ . $job[‘Job’][‘company’];
echo ‘<span class="date">’ . date(‘M d’, strtotime($job[‘Job’][‘created’])) . ‘</span>’;
echo ‘<div>’;
echo ‘</li>’;
endforeach;
echo ‘<ul>’;
} else {
echo ‘No Jobs found …’;
}
?>
[/code]

We are removing links to actions and pagination links (we will style and add these back in next tutorial) and adding some new HTML markup for showing jobs.

Let us add some CSS styles for this markup in /app/views/themed/default/webroot/css/default.css

[code lang=”css”]
ul.jobs_list { width: 565px; }
ul.jobs_list li { margin:10px 0; padding:20px; position:relative; text-shadow:0 0 1px rgba(0, 0, 0, 0.3); -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px;}
ul.jobs_list li:hover, ul.jobs_list li.odd:hover{ background:#ded698; }
ul.jobs_list li.odd{ background:#e4db98; border:1px solid #c7c77c; -moz-box-shadow:0 0 6px rgba(51,51,51,0.1); -webkit-box-shadow:0 0 6px rgba(51,51,51,0.1); box-shadow:0 0 6px rgba(51,51,51,0.1); }
ul.jobs_list li h3 { font-size:21px; margin: 0 0 5px 0; text-shadow:0 0 1px rgba(51, 51, 51, 0.1); }
ul.jobs_list li h3 a { color: #082733; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
ul.jobs_list li h3 a:hover { color: #000; text-decoration: underline; }
ul.jobs_list li .details { font-size: 13px; }
ul.jobs_list li .details .category { font-size: 16px; font-weight: normal; color: #70322C; text-transform: uppercase; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
ul.jobs_list li .details .date { position:absolute; top:38px; right:20px; }
[/code]

Looking good. Add some jobs by going to http://localhost/jobs/jobs/add (if your cakePHP app is in /wamp/www/jobs) and view the Home page.

Now, we have to change the look of our Job details page. You can see it by clicking on Job’s title. So let’s change the markup. Open /app/views/themed/default/jobs/view.ctp and change it to this:

[code lang=”php”]
<h3 class="jobs_view_h3"><?php echo $job[‘Job’][‘title’]; ?></h3>
<div class="jobs view">
<?php
echo ‘<div class="info">’;
echo ‘<span class="category">’.$job[‘Job’][‘company’].'</span>’;
echo ‘ – ‘ . $job[‘Job’][‘job_type’];
echo ‘<span class="date">’ . date(‘M d’, strtotime($job[‘Job’][‘created’])) . ‘</span>’;
echo ‘</div>’;
echo ‘<div class="job_details">’;
echo ‘<p>’ . nl2br($job[‘Job’][‘body’]) . ‘</p>’;
echo ‘</div>’;

?>
[/code]

And add this to /app/views/themed/webrot/css/default.ctp file:

[code lang=”css”]
.job_details { margin:10px 0; padding:20px; position:relative; text-shadow:0 0 1px rgba(0, 0, 0, 0.3); -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; width: 600px; background:#e4db98; border:1px solid #c7c77c; -moz-box-shadow:0 0 6px rgba(51,51,51,0.1); -webkit-box-shadow:0 0 6px rgba(51,51,51,0.1); box-shadow:0 0 6px rgba(51,51,51,0.1); }
.job_details p { font-size: 15px; line-height: 21px;}

.info { width: 640px; font-size: 13px;}
.info .category { font-size: 16px; font-weight: normal; color: #70322C; text-transform: uppercase; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
.info .date { float:right; }

.jobs_view_h3 { font-size:21px; margin: 0 0 5px 0; text-shadow:0 0 1px rgba(51, 51, 51, 0.1); }
[/code]

Now, click on the title of some Job on the front page and you will see the change in your view.

That’s it for now, stay tuned as we continue next time.

Make sure your read our previous tutorials in CakePHP series:

]]>
https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two/feed 6
CakePHP from Scratch: Theming in real life example – Part one https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-one?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-theming-in-real-life-example-part-one https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-one#comments Sun, 03 Oct 2010 21:46:41 +0000 https://www.codeforest.net/?p=483 As I already explained, we are going to build a jobs board application using CakePHP. If you followed our previous tutorials, you should already have a full working application. It is currently in default CakePHP look and feel. Today, we are going to change that and apply the free template from the internet.

Second task is to separate that template and make a theme, so in the future, we can just replace the design, and change the theme. It is similar to WordPress themes.

I downloaded a simple template from Template Kingdom and it looks like this:

f css 01

As you can see, the template has more stuff then we need, but we will deal with this as we go along with our application.

From now on, I will make everything by hand and will not use the Bake command prompt tool. The goal is to show the whole code and the process, so you can learn as much as possible about CakePHP and what is going on under the hood.

So, first, download the template from here (or use your own template, it will be even more interesting).

There is a PSD file included and please read the included license file carefully if you plan on using this theme!

In order to make a theme, you will need to create the folders that will hold the theme files. Go to /app/views and create a new folder named themed. Inside that folder, create a folder named default. This will hold our theme files. Now, copy all the folders and files from /app/views to /app/views/themed/default folder.

Our CSS and Javascript files will be stored in /app/views/themed/default/webroot folder, so please create it. Inside the new created folder, create folders css, img and js. Copy the CSS files from the downloaded template to /app/views/themed/default/webroot/css folder and rename the style.css to default.css. Copy the images folder to /app/views/themed/default/webroot/img. Now, open your CSS file and change the paths to images to ../img so it can find them.

Now, let’s go and open the /app/views/themed/default/layouts/ and copy the index.html file from downloaded template and paste it here. In order to make a layout for for our theme, rename it to default.ctp.

I personally like to put .ctp extension to be recognized as PHP files in my editor, so the syntax highlighting work.

Ware done with preliminary work for theming. Now, we need to tell CakePHP that we want to use the Theme features and what is the name of our theme. As we will be using the same theme all over our application, the best place to do it is in our app_controller. App controller is a class that extends the basic CakePHP Controller class and is called in every controller.

So go ahead and create /app/app_controller.php and paste in this code:

[code lang=”php”]
class AppController extends Controller {
public $view = ‘Theme’;
public $theme = ‘default’;
}
[/code]

This way we are overriding the default View class for every controller and telling the engine to use Theme class. At the same time, we are telling CakePHP that our theme is called default.

Now, CakePHP is looking at our newly created folders for our theme.

If a view file can’t be found in the theme, CakePHP will try to locate the view file in the /app/views/ folder. This way, you can create master view files and simply override them on a case-by-case basis within your theme folder.

Now, point your browser to http://localhost/cake/ (or wherever your application resides) and you should see that this is working. You have got HTML from the downloaded templates without implemented styles.

If you comment out the two lines we just added in our app_controller.php file and refresh the browser, you should see default CakePHP template. OK, uncomment the lines and let’s get that CSS fixed.

If you are wondering why the CSS is not working, it is because the path to the CSS file is wrong. So, open up your /app/views/themed/default/layouts/default.ctp file. This is our layout for the application. You can create as many layouts as you wish: just place them in the app/views/layouts directory (or /app/views/themed/layouts if you are using themes), and switch between them inside of your controller actions using the controller’s $layout variable, or setLayout() function.

CakePHP features two core layouts (besides CakePHP’s default layout) you can use in your own application: ajax and flash. The Ajax layout is handy for crafting Ajax responses – it’s an empty layout (most ajax calls only require a bit of markup in return, rather than a fully-rendered interface). The flash layout is used for messages shown by the controllers flash() method.

Three other layouts xml, js, and rss exist in the core for a quick and easy way to serve up content that isn’t text/html.

But let’s get to work. First change your character set to this:

[code lang=”php”]
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
[/code]

We will work our way from up to bottom. First, we need to make our titles dynamic. SO change your title tag to this:

[code lang=”php”]
<title><?php echo $title_for_layout; ?></title>
[/code]

$title_for_layout will hold the Page title. Now replace the CSS tag to this line to connect the correct path to CSS:

[code lang=”php”]
<?php echo $this->Html->css(‘default’); ?>
[/code]

Now, refresh the page and you should see that CakePHP has correctly rendered our layouts and use themed CSS. Notice that the images are not working as they are on the wrong path. But, this is something we will deal with in the next tutorial.

Let’s go on. I will correct the logo image, so it will look nicer and you can see how it is done. Find this line:

[code lang=”html”]

[/code]

and change it to:

[code lang=”php”]
echo $html->link($html->image("logo.gif"), array(‘controller’=>’jobs’, ‘action’ => ‘index’), array(‘escape’ => false));
[/code]

Refresh your page and the logo appears leading to your home page controller.

Now, we will move our menu out of default.ctp and create a new element out of it. This way, we can change it in one place and the changes will be visible to our whole application.

Cut this code:

[code lang=”html”]
<!–Navigation Background Part Starts –>
<div id="navigation-bg">
<!–Navigation Part Starts –>
<div id="navigation">
<ul class="mainMenu">
<li><a href="#" class="selectMenu" title="Home">Home</a></li>
<li><a href="#" title="About">About</a></li>
<li><a href="#" title="Services">Services</a></li>
<li><a href="#" title="Support">Support</a></li>
<li><a href="#" title="Chat">Chat</a></li>
<li><a href="#" title="History">History</a></li>
<li class="noBg"><a href="#" title="Contact">Contact</a></li>
</ul>
<a href="#" class="signup" title="signup now"></a>
<br class="spacer" />
<!– <ul class="subNav">
<li class="noBg"><a href="#" title="Our Benefits">Our Benefits</a></li>
<li><a href="#" title="What Our Future Plans">What Our Future Plans</a></li>
<li><a href="#" title="Our Success">Our Success</a></li>
<li><a href="#" title="Ratings">Ratings</a></li>
<li><a href="#" title="Latest Blogs">Latest Blogs</a></li>
<li><a href="#" title="News">News</a></li>
<li><a href="#" title="Testimonials">Testimonials</a></li>
<li><a href="#" title="Comments">Comments</a></li>
</ul> –>
<br class="spacer" />
</div>
<!–Navigation Part Ends –>
</div>
<!–Navigation Background Part Ends –>
[/code]

Create file menu.ctp in /app/views/themed/default/elements, copy the menu code in it. Paste this on the place where menu was in default.ctp:

[code lang=”php”]
<?php echo $this->element(‘menu’, array(‘cache’ => true)); ?>
[/code]

The cache part is telling CakePHP engine that we want to cache this element. This is great, as it almost never changes.

Now, let’s adjust our menu to work better:

[code lang=”php”]
<!–Navigation Background Part Starts –>
<div id="navigation-bg">
<!–Navigation Part Starts –>
<div id="navigation">
<ul class="mainMenu">
<li><?php echo $html->link(‘Home’, array(‘controller’=>’jobs’, ‘action’ => ‘index’));?></li>
<li><?php echo $html->link(‘Categories’, array(‘controller’=>’categories’, ‘action’ => ‘index’));?></li>
<li><?php echo $html->link(‘Users’, array(‘controller’=>’users’, ‘action’ => ‘index’));?></li>
</ul>
<a href="#" class="signup" title="signup now"></a>
</div>
<!–Navigation Part Ends –>
</div>
<!–Navigation Background Part Ends –>
[/code]

This is how our menu looks now. I removed the submenu part, as we will not need it for the moment. If refresh the page, you will see that nothing changed. That is because we told CakePHP to cache the element, and now we have to go to /app/tmp/cache/views and delete the cache file (it is called element__menu). Refresh the page and our menu is working like charm.

The last and most important part is to include our actual views into our layout. Find all this code and remove it:

[code lang=”php”]
<!–Our Company Left Part Starts –>
<div id="ourCompany-leftPart">
<h2 class="faq-Hdr">Latest F.A.Q?s</h2>
<ul class="ourCompany-list">
<li>Nulla congue pretium elit. Integer enim risus, mollis.</li>
<li>Eget, accumsan id, feugiat eu, velit. Sed molestie.</li>
<li>lectus id nisi.</li>
</ul>
<h2 class="moreIdeas-Hdr">More Ideas About Us</h2>
<ul class="ourCompany-list noBottomPadding">
<li>Quisque laoreet, elit at tincidunt porta, massa torr.</li>
<li>Porttitor magna, at vehicula pede dui id enim.</li>
<li>Pellentesque rhoncus metus quis nulla. Donecllus.</li>
<li>Metus, vehicula nec, scelerisque commodo.</li>
<li>Egestas eget.</li>
</ul>
</div>
<!–Our Company Left Part Ends –>
<!–Our Company Right Part Starts –>
<div id="ourCompany-rightPart">
<h2 class="moreInfo-Hdr">More Informations</h2>
<ul class="ourCompany-list noBottomPadding">
<li><a href="#">Aenean viverra sapien a enim pellentesque</a></li>
</ul>
<p class="moreInfo-Text">Pellentesque id nunc at leo<br />
vestibulum lobortis</p>
<h2 class="searchUrl-Hdr">Search Our Url’s</h2>
<ul class="ourCompany-list noBottomPadding">
<li><a href="#">www.,elit at tincidunt/porta.com</a></li>
<li><a href="#">www.vehicula pede /a/dui id enim.com</a></li>
<li><a href="#">www. quis nulla.com</a></li>
<li><a href="#">www.scelerisque commodo.com</a></li>
</ul>
</div>
<!–Our Company Right Part Ends –>
[/code]

And add this to its place:

[code lang=”php”]
<?php echo $content_for_layout; ?>
[/code]

And change the h2 above it to:

[code lang=”php”]
<h2 class="ourCompany-hdr"><?php echo $title_for_layout; ?></h2>
[/code]

Refresh the page in browser and click on the links in menu. Our application is not looking good but is fully working in our new theme.


That is it for the part one, in part two we will write a little bit of CSS to repair the layout and add some things that we will need. So stay tuned.

Make sure your read our previous tutorials in CakePHP series:

]]>
https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-one/feed 13
CakePHP from scratch: Introduction to layouts and theming https://www.codeforest.net/cakephp-from-scratch-introduction-to-layouts-and-theming?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-introduction-to-layouts-and-theming https://www.codeforest.net/cakephp-from-scratch-introduction-to-layouts-and-theming#comments Thu, 23 Sep 2010 20:44:43 +0000 https://www.codeforest.net/?p=452 Views are the V in MVC. Views are responsible for generating the specific output required for the request. Often this is in the form of HTML, XML, or JSON, but streaming files and creating PDF’s that users can download are also responsibilities of the View Layer.

CakePHP view files are common PHP files with a .ctp (CakePHP template) extension. Views are presentation layer of the application which is parsing the data received from model and controller and preparing it to be presented to the viewer (user).

Views can be made up of different parts. Those parts are layouts, elements and helpers.

  • layouts: view files that contain presentational code that is found wrapping many interfaces in your application. Most views are rendered inside of a layout.
  • elements: smaller, reusable bits of view code. Elements are usually rendered inside of views.
  • helpers: these classes encapsulate view logic that is needed in many places in the view layer. Among other things, helpers in CakePHP can help you build forms, build AJAX functionality, paginate model data, or serve RSS feeds.

The basic layout can look similar to this (taken from the CakePHP manual):

[code lang=”php”]



<?php echo $title_for_layout?>





[/code]

As you can see, we have some variables in layout which help us render other view parts easily. The most important one is $content_for_layout . This is the actual place where our view will show.

Layouts are stored in /app/views/layouts folder.

CakePHP features two core layouts (besides CakePHP’s default layout) you can use in your own application: ‘ajax’ and ‘flash’. The Ajax layout is handy for crafting Ajax responses – it’s an empty layout (most ajax calls only require a bit of markup in return, rather than a fully-rendered interface). The flash layout is used for messages shown by the controllers flash() method.

Three other layouts xml, js, and rss exist in the core for a quick and easy way to serve up content that isn’t text/html. We will cover all this things in future tutorials.

Second parts of views in CakePHP are elements. They live in /app/view/elements folder. Many times you need some small bits of code to be included in your application presentation layer like navigation, ads, images, login forms … An element is actually a mini view that can be included in layouts, views and even inside other elements.

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

Little bit about theming. CakePHP has a really great support for theming. To use a theme simple add its name in /app/app_controller.php:

[code lang=”php”]
var $view = ‘Theme’;
[/code]

And to render it add something like this to you beforeRender method inside the same controller:

[code lang=”php”]
$this->theme = “mythemename”;
[/code]

Theme view files need to be within the /app/views/themed/ folder. Within the themed folder, create a folder using the same name as your theme name. Beyond that, the folder structure within the /app/views/themed/example/ folder is exactly the same as /app/views/.

For example, the view file for an edit action of a Posts controller would reside at /app/views/themed/example/posts/edit.ctp. Layout files would reside in /app/views/themed/example/layouts/.

If a view file can’t be found in the theme, CakePHP will try to locate the view file in the /app/views/ folder. This way, you can create master view files and simply override them on a case-by-case basis within your theme folder.

If you have CSS or JavaScript files that are specific to your theme, you can store them in a themed folder within webroot. For example, your stylesheets would be stored in /app/webroot/themed/example/css/ and your JavaScript files would be stored in /app/webroot/themed/example/js/.

All of CakePHP’s built-in helpers are aware of themes and will create the correct paths automatically. Like view files, if a file isn’t in the theme folder, it’ll default to the main webroot folder.

That’s it for today. Next time we will implement all this gained knowledge on our jobs board application to change its appearance. I downloaded a template from the net and we will implement it as our design for the application.

]]>
https://www.codeforest.net/cakephp-from-scratch-introduction-to-layouts-and-theming/feed 4
CakePHP from scratch: Reviewing and changing baked code to fit our needs https://www.codeforest.net/cakephp-from-scratch-reviewing-and-changing-baked-code-to-fit-our-needs?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-reviewing-and-changing-baked-code-to-fit-our-needs https://www.codeforest.net/cakephp-from-scratch-reviewing-and-changing-baked-code-to-fit-our-needs#comments Wed, 15 Sep 2010 20:21:35 +0000 https://www.codeforest.net/?p=413 If you did not follow previous tutorials in the CakePHP from scratch series, you can download what we did the last time from here. Just extract the files wherever is your www or htdocs directory.

So, let us see what did our Baking from last time produced. Open up your /app/models/category.php file. CakePHP left us some commented stuff in there, so you can easily understand what to do. We are going to change just a validation message here, so uncomment that line and change your validation criteria to this:

[code lang=”php”]
var $validate = array(
‘name’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘The name field can not be empty’,
),
),
);
[/code]

OK that’s it for this model, open /app/models/job.php and just change its validation to this:

[code lang=”php”]
var $validate = array(
‘category_id’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
//’message’ => ‘Your custom message here’,
),
),
‘user_id’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
//’message’ => ‘Your custom message here’,
),
),
‘title’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Title field can not be empty’
),
),
‘body’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Body is required field’
),
),
‘company’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Company is required field’
),
),
‘job_type’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘You must choose job type!’
),
),
);
[/code]

I will not explain much, as it is quite self explaining. You can test these settings in you application, just try to add new job without writing anything in the fields and CakePHP will return your custom messages below each field.

Now, open /app/models/user.php and change its validation to this:

[code lang=”php”]
var $validate = array(
‘username’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Username is required field’,
),
),
‘pass’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Password is required field’,
),
‘between’ => array(
‘rule’ => array(‘between’, 5, 15),
‘message’ => ‘Password must be between 5 to 15 characters’
)
),
‘name’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Name is required field’,
),
),
’email’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Email is required field’,
),
’email’ => array(
‘rule’ => array(’email’, true),
‘message’ => ‘Please enter a valid email address’
)

),
);
[/code]

Here we added some more validation to password and email fields. Interesting part is email validation. This checks whether the data is a valid email address. Passing a boolean true as the second parameter for this rule will also attempt to verify that the host for the address is valid. Fancy and awesome.

We will do some more stuff in user model. If you tested the app, you can see that our password field is plain text input. Let us change that. Open /app/views/users/add.php and change your form to this:

[code lang=”php”]
echo $this->Form->input(‘username’);
echo $this->Form->input(‘pass’, array(‘type’ => ‘password’));
echo $this->Form->input(‘pass2’, array(‘type’ => ‘password’, ‘label’ => ‘Repeat password’));
echo $this->Form->input(‘name’);
echo $this->Form->input(‘location’);
echo $this->Form->input(‘address’);
echo $this->Form->input(’email’);
echo $this->Form->input(‘web’);
[/code]

We added type to pass field and we added a whole new field: Repeat password. This is a common field you see on most sites and its purpose is to prevent users from making a typing error.

We must add this functionality to our app. Open /app/models/user.php and add this rule:

[code lang=”php”]
‘pass2’ => array(
‘notempty’ => array(
‘rule’ => array(‘notempty’),
‘message’ => ‘Repeat password is required field’,
),
‘custom’ => array(
‘rule’ => array(‘CheckPasswordMatch’),
‘message’ => ‘Passwords did not match’,
),
),
[/code]

We are checking that the field is not empty. And adding a custom rule. For this custom rule to work, we will add a function directly above association rules in our user model:

[code lang=”php”]
function CheckPasswordMatch($data) {
return $this->data[‘User’][‘pass’] == $this->data[‘User’][‘pass2’];
}
[/code]

This function simply checks if the passwords match, returning true or false. $this->data contains all posted data.

There is one more thing I want to show you today. That is routing. By default, CakePHP responds to a request for the root of your site (i.e. http://www.example.com) using its PagesController, rendering a view called “home”. Instead, we’ll replace this with our JobsController by creating a routing rule.

Cake’s routing is found in /app/config/routes.php. You’ll want to comment out or remove the line that defines the default root route. It looks like this:

[code lang=”php”]
Router::connect (‘/’, array(‘controller’=>’pages’, ‘action’=>’display’, ‘home’));
[/code]

And add this:

[code lang=”php”]
Router::connect (‘/’, array(‘controller’=>’jobs’, ‘action’=>’index’));
[/code]

This will connect users requesting ‘/’ to the index() action of our JobsController. Point your browser to http://localhost/cake (or wherever you have your application) and you will see that it works awesomely.

This is it for today, stay tuned as next time we will check out layouts and how to change them, styling and other interesting stuff.

Make sure your read our previous tutorials in CakePHP series:

]]>
https://www.codeforest.net/cakephp-from-scratch-reviewing-and-changing-baked-code-to-fit-our-needs/feed 3
CakePHP from scratch: Baking with dependancy tables https://www.codeforest.net/cakephp-from-scratch-baking-with-dependancy-tables?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-baking-with-dependancy-tables https://www.codeforest.net/cakephp-from-scratch-baking-with-dependancy-tables#comments Mon, 06 Sep 2010 20:39:08 +0000 https://www.codeforest.net/?p=348 In the last tutorial I showed how easy it is to bake model, controller and view for our Categories table. I am repeating for those who are new, we are building a Jobs board application which will be used to post a job opening in a certain category, to list, filter and search the jobs, to register and login, to apply to a job and other interesting stuff.

Along the way, I hope that I will show you all aspects of this incredible framework and convince you to start using it.

So, if you created the tables in our database, please drop them, as I added some new fields. Here are the new tables:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

CREATE TABLE IF NOT EXISTS `jobs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`title` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci,
`company` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`job_type` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`web` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

[/code]

We will bake files for all 3 tables to establish our relationships. As you can see if you look at the Jobs table structure, it has category_id and user_id fields. This two fields will be used to create relationships (associations) between the tables.

There is a naming convention which must be followed if we want Bake to generate a proper relationship. Field must be in singular form of the relationship’s table name (table is called Categories, so we have category_id field).

So, let’s get Baking. Go to your command prompt browse to your working directory and type in cake bake. Type M for baking a model and press Enter. Choose your default database configuration by pressing Enter.

Type in 1 for baking our Categories model. Script asks you to provide a validation criteria, so type in y for yes. Choose 28 for id, 19 (not empty) for name field.

Now, the interesting part. Bake script is asking if we want to build Model association. Type in y and press Enter. Bake will correctly ask if Category hasMany Job. So answer yes.

bake1

After that answer no and again yes if everything looks OK. If you followed previous tutorials, it will ask you to overwrite the file category.php, please do so.

We skip the SimpleTest question by always answering No.

OK, let’s bake our Job model, so M for model, 2 for Job. For validation, choose yes and these rules: for id field type in 28, for category_id and users_id type in 19 (not empty), you can put 19 (not empty) for title, body, company and job_type fields.

Now, when we come to our association criteria, Bake asks as if Job belongs to Category, the answer is Yes. And after correctly asking if Job belongs to User, answer is again Yes.

Now, do the same for the users table.You can see on the image below how I managed my validation and association criteria:

bake2

It is now time to bake our controllers. So type in C and press Enter and Enter again for default database configuration. Type in 1 for Categories controller and yes to build it interactively. Then choose no for scaffolding, yes for creating some basic methods and no for admin routing. Type no for both Helpers and Components question and yes for Session messages. On the image below is the whole process:

bake3

Repeat this steps for other two controllers. Our next step is to build our views for all three controllers. So type in V and follow the steps on picture below:

bake4

Repeat this steps for remaining two controllers. We are finished. Point your browser to your Cake application and Categories controller (for example: http://localhost/cake/categories) and try to add some users and categories.

When you go to Add new job, you will see options to choose category and user.


Now we have a full working application. Obviously the work is not finished, so stay tuned. Next time, we are going to adjust some things that Cake Baked, like error messages and similar.

Make sure your read our previous tutorials in CakePHP series:

]]>
https://www.codeforest.net/cakephp-from-scratch-baking-with-dependancy-tables/feed 2
CakePHP from scratch: Baking our application https://www.codeforest.net/cakephp-from-scratch-baking-our-application?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-baking-our-application https://www.codeforest.net/cakephp-from-scratch-baking-our-application#comments Tue, 31 Aug 2010 20:34:31 +0000 https://www.codeforest.net/?p=312 The CakePHP Bake console can create any of CakePHP’s basic ingredients: models, views and controllers. And I am not just talking skeleton classes: Bake can create a fully functional application in just a few minutes.

I am going to explain how to bake all in the new version of CakePHP (1.3.3) on Windows computer as it takes a little more tweaking. Bake is basically a PHP CLI console application which generate code according to our database model. To run this application, Windows users must add some Environment variables to their system.

First, go ahead and download a fresh copy of CakePHP and extract it somewhere inside your www folder. Make sure that it is working and is connected to database. If you don’t know how to do it, read my CakePHP installing and the basics tutorial.

Let me presume that our fresh CakePHP install is under c:\\wamp\\www\\cakephp folder. Right click on My Computer, click Properties and then Advanced. On the bottom part of the screen find Path variable, select it and click Edit. After last path add a semicolon and then path to our CakePHP console folder (c:\\wamp\\www\\cakephp\\cake\\console\\) then another semicolon and enter a path to PHP executable (mine is C:\\wamp\\bin\\php\\php5.3.0\\). Click OK and close all.

Let us create the tables for our application which will be a jobs board:

[code lang=”sql”]
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM ;

CREATE TABLE IF NOT EXISTS `jobs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) DEFAULT NULL,
`title` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci,
`company` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`job_type` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM ;

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`web` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
[/code]

This is easy setup with 3 tables which will be used in our future application. Now, open your command prompt and go to your application folder (c:\\wamp\\www\\cakephp).

Enter this code in your command prompt:

[code lang=”php”]
cake bake all
[/code]

If everything went ok, you should see something like this:

bake 1

My path is different, so do not mind that. If you get prompted for a database configuration, like I was above, just press Enter to confirm default configuration. After that bake will prompt us for which table in the database do we want to bake an application. So write 1 for our Categories table and press Enter. You should see something like this:

bake 2

When you get prompted about Unit test classes, always just answer no. After you write n to Unit test and press Enter, Bake will create the controllers and views and exit.

That’s it, you have got a full working application for your categories table. You don’t believe me? Point your browser to your application and call categories controller (for example http://localhost/cakephp/categories ) and you will see nice full working app.

Bake generated the links for List jobs and New job, but it is not working at this moment as we did not bake files for jobs table yet. I will cover this next time.

I am not satisfied with this as we did not have a chance to supply validation criteria for our Categories model, so let’s do this another way. Run cake bake command in your command prompt. Now, you will get a different user interface with full control over what you are baking.

Just follow the steps in this video :

Now, point your browser to your categories controller. Go ahead and try to add an empty category. Validation is working, but messages need some tweaking. Notice how CakePHP added a Pagination below the table with Categories. Nice. And if you click on column names, data is sorted by that column! How cool is that? Do you remember how much time it took us in two parts tutorial to achieve this?

I will finish for today.

Make sure your read our previous tutorials in CakePHP series:

Next time we will bake files for Jobs and Users tables, create relationship between tables and more. So, stay tuned.

]]>
https://www.codeforest.net/cakephp-from-scratch-baking-our-application/feed 5
CakePHP from scratch: Data validation, routes and more https://www.codeforest.net/cakephp-from-scratch-data-validation-routes-and-more?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-data-validation-routes-and-more https://www.codeforest.net/cakephp-from-scratch-data-validation-routes-and-more#comments Thu, 26 Aug 2010 20:46:39 +0000 https://www.codeforest.net/?p=303 In the previous tutorial I showed you how to develop small application using only one database table. We added Model, Controller and Views for listing and adding Categories in our table. Anyway, today we will continue, so open up the files you created in the previous tutorial (or if you did not finish it, go and check it out now).

I would like to touch an issue of data validation first, and then build the rest of functionality for editing and deleting content of our Categories table.

Data validation in CakePHP is done in Model. And it is quite easy to add it. As our table has only one field to validate, we will just add validation that this field can not be empty. So, replace the code in your /app/models/category.php so it looks like this:

[code lang=”php”]
class Category extends AppModel {
var $name = ‘Category’;

var $validate = array(
‘name’ => array(
‘rule’ => ‘notEmpty’
)
);
}
[/code]

The $validate array tells CakePHP how to validate your data when the save() method is called. Here, I’ve specified that name field must not be empty. CakePHP’s validation engine is strong, with a number of pre-built rules (credit card numbers, email addresses, etc.) and flexibility for adding your own validation rules and will be covered in more details when I extend the tutorial to build a Jobs board application.

Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application.

Now that you have your validation rules in place, use the app to try to add a category with an empty name to see how it works. Since we’ve used the input() method of the FormHelper to create our form elements, our validation error messages will be shown automatically.

You can even write your own error messages. Try this in your model file:

[code lang=”php”]
class Category extends AppModel {
var $name = ‘Category’;

var $validate = array(
‘name’ => array(
‘rule’ => ‘notEmpty’,
‘message’ => ‘No, no, this field must not be empty!’
)
);
}
[/code]

Try saving Category without a name and your custom message should appear. Great stuff.

Let us develop our functionality for editing and deleting the categories. First, easy one – deleting. Open up your /app/controllers/categories_controller.php file and add this function in it just below your add function:

[code lang=”php”]
function delete($id) {
$this->Category->delete($id);
$this->Session->setFlash(‘The category with id: ‘.$id.’ has been deleted.’);
$this->redirect(array(‘action’=>’index’));
}
[/code]

As this function only deletes the category and redirects back to index action of the Categories controller, we don’t have to create a view. However, we will change our index view to have links for deleting a specific category. Open up your /app/view/categories/index.ctp file and change to look like this:

[code lang=”php”]

Categories

link(‘Add Category’,array(‘controller’ => ‘categories’, ‘action’ => ‘add’)); ?>

Id Title Actions
link($category[‘Category’][‘name’],
array(‘controller’ => ‘categories’, ‘action’ => ‘edit’, $category[‘Category’][‘id’])); ?>
link(‘Delete’, array(‘action’ => ‘delete’, $category[‘Category’][‘id’]), null, ‘Are you sure?’ )?>

[/code]

Try to delete some categories now. Did you notice that CakePHP automatically generated a Javascript confirm dialog that asks the user Are you sure? . How awesome is that?

Next, we will add function for editing categories in our controller. Add this in your /app/controllers/categories_controller.php file:

[code lang=”php”]
function edit($id = null) {
$this->Category->id = $id;
if (empty($this->data)) {
$this->data = $this->Category->read();
} else {
if ($this->Category->save($this->data)) {
$this->Session->setFlash(‘Your category has been updated.’);
$this->redirect(array(‘action’ => ‘index’));
}
}
}
[/code]

This function first checks for submitted form data. If nothing was submitted, it finds the Category and hands it to the view. If some data has been submitted, try to save the data using Category model (or kick back and show the user the validation errors).

We need a view for this, so create /app/views/categories/edit.ctp file and paste in this code:

[code lang=”php”]

Edit Category

create(‘Category’, array(‘action’ => ‘edit’));
echo $form->input(‘name’);
echo $form->input(‘id’, array(‘type’=>’hidden’));
echo $form->end(‘Save Category’);
?>
[/code]

This view outputs the edit form (with the values populated), along with any necessary validation error messages.

One thing to note here: CakePHP will assume that you are editing a model if the ‘id’ field is present in the data array. If no ‘id’ is present (look back at our add view), Cake will assume that you are inserting a new model when save() is called.

You can now update your index view with links to edit specific categories, so /app/views/categories/index.ctp now looks like this:

[code lang=”php”]

Categories

link(‘Add Category’,array(‘controller’ => ‘categories’, ‘action’ => ‘add’)); ?>

Id Title Actions
link($category[‘Category’][‘name’],
array(‘controller’ => ‘categories’, ‘action’ => ‘edit’, $category[‘Category’][‘id’])); ?>
link(‘Delete’, array(‘action’ => ‘delete’, $category[‘Category’][‘id’]), null, ‘Are you sure?’ )?>
link(‘Edit’, array(‘action’=>’edit’, $category[‘Category’][‘id’]));?>

[/code]

Congratulations, you finished your first CakePHP application!

Let me explain a bit about Routing in CakePHP. For some, CakePHP’s default routing works well enough. Developers who are sensitive to user-friendliness and general search engine compatibility will appreciate the way that CakePHP’s URLs map to specific actions. So we’ll just make a quick change to routes in this tutorial.

By default, CakePHP responds to a request for the root of your site (i.e. http://www.example.com) using its PagesController, rendering a view called “home”. Instead, we’ll replace this with our CategoriesController by creating a routing rule.

Cake’s routing is found in /app/config/routes.php. You’ll want to comment out or remove the line that defines the default root route. It looks like this:

[code lang=”php”]
Router::connect (‘/’, array(‘controller’=>’pages’, ‘action’=>’display’, ‘home’));
[/code]

Now add this line directly below the one you commented:

[code lang=”php”]
Router::connect (‘/’, array(‘controller’=>’categories’, ‘action’=>’index’));
[/code]

This will connect users requesting ‘/’ to the index() action of our CategoriesController. Point your browser to http://localhost/cake (or wherever you have your application) and you will see that it works awesomely.

Make sure your read our previous tutorials in CakePHP series:

Stay tuned as we will continue next time with CakePHP Bake generator.

]]>
https://www.codeforest.net/cakephp-from-scratch-data-validation-routes-and-more/feed 8