Add a link to add a post to the page that lists all blogs.

Here is the new view code.

application/views/blog/posts.tpl

  <html>
  <body>
      <h1>{$title}</h1>
 
      <table border="1">
              <tr><th>ID</th><th>Title</th><th>Created</th></tr>
 
          {foreach from=$posts item=post}
              <tr><td>{$post->post_id}</td><td><a href="/blog/view/{$post->post_id}">{$post->title}</a></td><td>{$post->time|date_format:"%A %b. %e %Y %l:%M %p"}</td></tr>
 
          {/foreach}
      </table>
 
      <a href="/blog/post">Add a post .</a>
  </body>
  </html>
|

Create a new Smarty template for the add post form.

Here is the new template.

application/views/blog/edit.tpl

  <html>
  <body>
      <h3>Add a post</h3>
 
      <form action="" method="POST">
          Title: <br/>
          <input type="text" name="aTitle" id="aTitle" value="{$aTitle}" /> <span style="color: #FF0000;">{$aTitleErr}</span>
 
          <br/>
          Body: <br/>
          <textarea name="aBody" id="aBody">{$aBody}</textarea> <span style="color: #FF0000;">{$aBodyErr}</span>
 
          <br/>
          <input type="submit" name="submit" id="submit" value="Submit" />
 
      </form>
 
  </body>
  </html>

This is a pretty standard form.

The default form element values must match their form element names and ids. This allows form input to be easily pre-populated upon edit, or re-populated upon form invalidation.

The form validation error messages must adhere to the convention where the Smarty tag for the error message must be named the field name plus Err. So the aTitle input will have a corresponding validation error tag called $aTitleErr.

Create a new controller action for adding a post.

Here is the new action.

application/controllers/BlogController.php

  public function post()
      {
          if (empty($_POST))
          {
              $this->view->display('blog/edit.tpl');
          }
          else
          {
              $validators = array(
                  'aTitle' => array(
                      'NotEmpty',
                      'messages' => 'Title is required'
                  ),
                  'aBody' => array(
                      'NotEmpty',
                      'messages' => 'Body is required'
                  )
              );
 
              $form = new Form($validators, $_POST);
 
              if (! $form->isValid())
              {
                  $this->view->assign($_POST);
                  $this->view->assign($form->getMessages());
                  $this->view->display('blog/edit.tpl');
              }
              else
 
              {
                  $post = Zend_Registry::get('factory')->get('Post');
                  $post->title = $form->getHTMLEntities('aTitle');
                  $post->body = $form->getHTMLEntities('aBody');
                  $post->create_dt_tm = date('Y-m-d H:i:s');
                  $post->save();
                  header('Location: /blog');
                  exit;
              }
          }
      }

The first time the form is loaded in the browser, “$_POST” is empty, so the form is displayed. If the form is submitted, a form object is created and validated. If the form fails validation, it is re-displayed with the submitted data re-populated, and any error messages are shown. If the form succeeds, form data is used to populate a new “Post” business object, and the object is saved.

The Form class extends the Zend_Filter_Input class with slightly modified behavior.

Validation:

To validate, create an array as shown in the above code where the array contains form fields to be validated, where each field name points to another array containing a Zend validator and a message for if that validator fails. You can use multiple validators and multiple messages as long as the index for the validators corresponds to the index of its message in the “messages” array.

There is a difference between a form input that is empty, and a form input that is missing. If a text input is submitted blank, the input will be in $_POST with an empty value. If a checkbox is submitted unchecked, it will not show up in $_POST at all. To mandate the presence of a field like a checkbox, use the following:

$validators = array(
   'myCheckbox' => array(
       'presence' => 'required',
       'messages' => 'myCheckbox is required'
   )
);

Note that this differs from the Zend_Filter_Input way of handling missing fields.

If the form fails, you can assign the return value of $form→getMessages() provided your Smarty error tags were named as described above.

If the form passes:

In the interest of security, an Inspekt cage is created around the $_POST data and $_POST is destroyed. Then the only way to access form data is via an Inspekt filter method. This encourages thinking about filtering all input, and not using unfiltered input (though that is still possible). In the code above, the aTitle and aBody fields are HTML escaped first, in case the user entered any Javascript or markup into the blog post (and assuming we don't want that.)

The statement $post→title = “A Title” sets a field in the new Post business object.

Create a method to save a "Post" business object.

Here is the code.

application/models/Post.php

  public function save()
  {
      $sql = "insert into posts
                  (post_id, title, body, create_dt_tm)
                  values
                  (null, ?, ?, ?)";
 
      $bind = array($this->_data['title'],
                    $this->_data['body'], 
                    $this->_data['create_dt_tm']);
 
      Zend_Registry::get('db')->query($sql, $bind);
  }

This is pretty standard code to insert a new row into a database. Note that the fields have already been populated by statements such as “$post→title = “A Title””.

Here is a screenshot of my add post form.

Here is a screenshot after hitting submit without entering any data.

After filling in the fields and hitting submit, I am redirected back to the blog post listing page.

Now we can add posts. What if we write something we don't like? Let's see how to Edit a blog post.

pox-php/create_a_blog_post.txt · Last modified: 2010/05/09 20:54 by gerard
 
 
© 2010 Straylightrun.net under Creative Commons Attribution
Green hosting by Dreamhost.com | Powered by DokuWiki