Skip to content

Instantly share code, notes, and snippets.

@phalcon
Last active December 11, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phalcon/4520220 to your computer and use it in GitHub Desktop.
Save phalcon/4520220 to your computer and use it in GitHub Desktop.
<?php
use Phalcon\Forms\Elements\Text as TextElement;
use Phalcon\Forms\Elements\TextArea as TextAreaElement;
use Phalcon\Validation\StringLength;
use Phalcon\Validation\PresenceOf;
class PostsController extends \Phalcon\Mvc\Controller
{
protected function getForm($post)
{
$title = new TextElement('title');
$title
->addValidation(new StringLength([
'minimum' => 5,
'message' => 'The title is too short'
])
->addValidation(new PresenceOf([
'message' => 'The title is required'
]);
$content = new TextAreaElement('content');
$content
->addValidation(new StringLength([
'minimum' => 5,
'message' => 'The content is too short'
]);
return $this->forms->create($post)
->add($title)
->add($content);
}
public function editAction($id)
{
$post = Posts::findFirstById($id);
$this->view->setVar("form", $this->getForm($post));
}
public function saveAction()
{
$form = $this->getForm();
if ($form->isValid($_POST)) {
$post = new Posts();
$post->save($_POST);
$this->flash->success("Post was created successfully");
return $this->response->redirect("posts/index");
}
}
}
<?php echo $form->outputMessages() ?>
<form method="post" action="<?php echo $this->url->get("posts/save") ?>">
<p>
<label for="title">Title</label> <?php echo $form->render("title"); ?>
</p>
<p>
<label for="content">Content</label> <?php echo $form->render("content"); ?>
</p>
<input type="submit" value="Save"/>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment