При добалении коментария, мы должны выбирать соответствующий id post. Это неудобно.
Добавим снизу файла modules/post/templates/showSuccess.php :
<?php echo link_to('Add a comment', 'comment/create?post_id='.$post->getId()) ?>
заменим в файле
modules/comment/templates/editSuccess.php строки:
<tr>
<th>Post:</th>
<td><?php echo object_select_tag($comment, 'getPostId', array (
'related_class' => 'Post',
)) ?></td>
</tr>
на:
<?php if ($sf_params->has('post_id')): ?>
<?php echo input_hidden_tag('post_id',$sf_params->get('post_id')) ?>
<?php else: ?>
<tr>
<th>Post*:</th>
<td><?php echo object_select_tag($comment, 'getPostId', array('related_class' => 'Post')) ?></td>
</tr>
<?php endif; ?>
В файле modules/comment/actions/actions.class.php найдем метод executeUpdate(). Изменим его:
public function executeUpdate ()
{
if (!$this->getRequestParameter('id', 0))
{
$comment = new Comment();
}
else
{
$comment = CommentPeer::retrieveByPk($this->getRequestParameter('id'));
$this->forward404Unless($comment);
}
$comment->setId($this->getRequestParameter('id'));
$comment->setPostId($this->getRequestParameter('post_id'));
$comment->setAuthor($this->getRequestParameter('author'));
$comment->setEmail($this->getRequestParameter('email'));
$comment->setBody($this->getRequestParameter('body'));
$comment->save();
return $this->redirect('post/show?id='.$comment->getPostId());
}
Валидпция форм
Создадим update.yml в /modules/comment/validate/ :
methods:
post: [author, email, body]
get: [author, email, body]
fillin:
enabled: on
names:
author:
required: Yes
required_msg: The name field cannot be left blank
email:
required: No
validators: emailValidator
body:
required: Yes
required_msg: The text field cannot be left blank
emailValidator:
class: sfEmailValidator
param:
email_error: The email address is not valid.
Конроллер будет перенаправлять пользователя в случае ошибки на updateError.php . Для реализации этого добавим метод handleErrorUpdate в класс действий modules/comment/actions/actions.class.php:
public function handleErrorUpdate()
{
$this->forward('comment', 'create');
}
Изменим шаблон modules/comment/templates/editSuccess.php, добавив сверху:
<?php if ($sf_request->hasErrors()): ?>
<div id="errors" style="padding:10px;">
Please correct the following errors and resubmit:
<ul>
<?php foreach ($sf_request->getErrors() as $error): ?>
<li><?php echo $error ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Убираем спецсимволы %20 Редактируем Post.php в /lib/model/ :
public function getStrippedTitle()
{
$result = strtolower($this->getTitle());
// strip all non word chars
$result = preg_replace('/\W/', ' ', $result);
// replace all white space sections with a dash
$result = preg_replace('/\ +/', '-', $result);
// trim dashes
$result = preg_replace('/\-$/', '', $result);
$result = preg_replace('/^\-/', '', $result);
return $result;
}
Создаем действие permalink. Добавим метод в modules/post/actions/actions.class.php:
public function executePermalink()
{
$posts = PostPeer::doSelect(new Criteria());
$title = $this->getRequestParameter('title');
foreach ($posts as $post)
{
if ($post->getStrippedTitle() == $title)
{
$this->getRequest()->setParameter('id', $post->getId());
return $this->forward('post', 'show');
}
}
$this->forward404();
}
Меняем шаблон modules/post/templates/listSuccess.php, удаляя id table header и лоетку, а также заменяя Title с:
<td><?php echo $post->getTitle() ?></td>
на:
<td><?php echo link_to($post->getTitle(), '@post?title='.$post->getStrippedTitle()) ?></td>
Редактируем routing.yml из /config/ добавляя сверзу:
list_of_posts:
url: /latest_posts
param: { module: post, action: list }
post:
url: /weblog/:title
param: { module: post, action: permalink }
Защищаем приложение
В шаблоне modules/post/templates/showSuccess.php удаляем:
<?php echo link_to('edit', 'post/edit?id='.$post->getId()) ?>
Также в modules/post/templates/listSuccess.php удаляем:
<?php echo link_to('create', 'post/create') ?>
Также можно удалить методы из modules/post/actions/actions.class.php:
* executeCreate
* executeEdit
* executeUpdate
* executeDelete
Создаем админку
$ symfony init-app backend
$ symfony propel-init-admin backend post Post
$ symfony propel-init-admin backend comment Comment
Редактируем (apps/backend/templates/layout.php):
<div id="navigation">
<ul style="list-style:none;">
<li><?php echo link_to('Manage posts', 'post/list') ?></li>
<li><?php echo link_to('Manage comments', 'comment/list') ?></li>
</ul>
</div>
<div id="content">
<?php echo $sf_data->getRaw('sf_content') ?>
</div>
Генерирум форму backend/modules/post/config/generator.yml:
generator:
class: sfPropelAdminGenerator
param:
model_class: Post
theme: default
fields:
title: { name: Title }
excerpt: { name: Exerpt }
body: { name: Body }
nb_comments: { name: Comments }
created_at: { name: Creation date }
list:
title: Post list
layout: tabular
display: [=title, excerpt, nb_comments, created_at]
object_actions:
_edit: ~
_delete: ~
max_per_page: 5
filters: [title, created_at]
edit:
title: Post detail
fields:
title: { type: input_tag, params: size=53 }
excerpt: { type: textarea_tag, params: size=50x2 }
body: { type: textarea_tag, params: size=50x10 }
created_at: { type: input_date_tag, params: rich=on }
Редактируем /lib/model/Post.php:
public function getNbComments()
{
return count($this->getComments());
}
Защищаем вход в админку
в apps/backend/modules/post/config/security.yml:
all:
is_secure: on
$symfony init-module backend security
Редактируем apps/backend/modules/security/templates/indexSuccess.php:
<h2>Authentication</h2>
<?php if ($sf_request->hasErrors()): ?>
Identification failed - please try again
<?php endif; ?>
<?php echo form_tag('security/login') ?>
<label for="login">login:</label>
<?php echo input_tag('login', $sf_params->get('login')) ?>
<label for="password">password:</label>
<?php echo input_password_tag('password') ?>
<?php echo submit_tag('submit', 'class=default') ?>
</form>
Добавляем модуль в apps/backend/modules/security/actions/actions.class.php:
public function executeLogin()
{
if ($this->getRequestParameter('login') == 'admin' && $this->getRequestParameter('password') == 'password')
{
$this->getUser()->setAuthenticated(true);
return $this->redirect('main/index');
}
else
{
$this->getRequest()->setError('login', 'incorrect entry');
return $this->forward('security', 'index');
}
}
Редактируем :
public function executeIndex()
{
}
в apps/backend/config/settings.yml добавляем:
all:
.actions:
login_module: security
login_action: index
Проверяем
http://localhost/index.php/
http://localhost/backend.php/
$ symfony cc