• Aucun résultat trouvé

Adding Posts

Dans le document Fichier PDF cake-manual.pdf (Page 127-130)

A. The Cake Blog Tutorial

A.9. Adding Posts

var $name = 'Posts';

function index() {

$this->set('posts', $this->Post->findAll());

}

function view($id = null) {

$this->Post->id = $id;

$this->set('post', $this->Post->read());

} }

?>

The set() call should look familiar. Notice we're using read() rather than findAll() because we only really want a single post's information.

Notice that our view action takes a parameter. This parameter is handed to the action by the URL called. If a user requests /posts/view/3, then the value '3' is passed as $id.

Now let's create the view for our new 'view' action and place it in / app/views/posts/view.thtml.

Example A.6. /app/views/posts/view.thtml

<h1><?php echo $post['Post']['title']?></h1>

<p><small>Created: <?php echo

$post['Post']['created']?></small></p>

<p><?php echo $post['Post']['body']?></p>

Verify that this is working by trying the links at /posts/index or manually requesting a post by accessing /posts/view/1.

A.9. Adding Posts

reading from the database and showing us the posts is fine and dandy, but let's allow for the adding of new posts.

First, start with the add() action in the PostsController:

Example A.7. /app/controllers/posts_controller.php (add action added)

<?php

class PostsController extends AppController {

var $name = 'Posts';

function index()

{

$this->flash('Your post has been saved.','/posts');

} } } }

?>

Let me read the add() action for you in plain English: if the form data isn't empty, try to save the post model using that data. If for some reason it doesn't save, give me the data valida-tion errors and render the view showing those errors.

When a user uses a form to POST data to your application, that information is available in

$this->params. You can pr() that out if you want to see what it looks like. $this->data is an alias for $this->params['data'].

The $this->flash() function called is a controller function that flashes a message to the user for a second (using the flash layout) then forwards the user on to another URL (/posts, in this case). If DEBUG is set to 0 $this->flash() will redirect automatically, however, if DE-BUG > 0 then you will be able to see the flash layout and click on the message to handle the redirect.

Calling the save() method will check for validation errors and will not save if any occur.

There are several methods available so you can check for validation errors, but we talk about the validateErrors() call in a bit, so keep that on the back burner for a moment while I show you what the view looks like when we move on to the section about data validation.

A.10. Data Validation

Cake goes a long way in taking the monotony out of form input validation. Everyone hates coding up endless forms and their validation routines, and Cake makes it easier and faster.

To take advantage of the validation features, you'll need to use Cake's HtmlHelper in your views. The HtmlHelper is available by default to all views at $html.

Here's our add view:

Example A.8. /app/views/posts/add.thtml

<h1>Add Post</h1>

<form method="post" action="<?php echo $html->url('/posts/add')?>">

<p>

Title:

<?php echo $html->input('Post/title', array('size' =>

'40'))?>

<?php echo $html->tagErrorMsg('Post/title', 'Title is required.') ?>

<?php echo $html->tagErrorMsg('Post/body', 'Body is required.') ?>

</p>

<p>

<?php echo $html->submit('Save') ?>

</p>

</form>

As with $html->link(),$html->url()will generate a proper URL from the controller and action we have given it. By default, it prints out a POST form tag, but this can be modi-fied by the second parameter. The $html->input() and $html->textarea() func-tions spit out form elements of the same name. The first parameter tells Cake which mod-el/field they correspond to, and the second param is for extra HTML attributes (like the size of the input field). Again, refer to Chapter "Helpers" [ht-tp://manual.cakephp.org/chapter/helpers] for more on helpers.

ThetagErrorMsg()function calls will output the error messages in case there is a valid-ation problem.

If you'd like, you can update your/app/views/posts/index.thtml view to include a new "Add Post" link that points to www.example.com/posts/add.

That seems cool enough, but how do I tell Cake about my validation requirements? This is where we come back to the model.

Example A.9. /app/models/post.php (validation array added)

<?php

class Post extends AppModel {

var $name = 'Post';

var $validate = array(

'title' => VALID_NOT_EMPTY, 'body' => VALID_NOT_EMPTY );

}

?>

The $validatearray tells Cake how to validate your data when the save()method is called. The values for those keys are just constants set by Cake that translate to regex matches (see /cake/libs/validators.php). Right now Cake's validation is regex based, but you can also use Model::invalidate() to set your own validation dynamically.

Now that you have your validation in place, use the app to try to add a post without a title or body to see how it works.

Dans le document Fichier PDF cake-manual.pdf (Page 127-130)