When we create web applications, we will certainly have to deal with creating content. Of course, we can create it with pure text or HTML, but text is often too simple and HTML is too complex and insecure. That is why special markup languages, such as BBCode, Textile, and markdown are used.
In this recipe, we will learn how to create a model that will automatically convert markdown to HTML when it is being saved.
yiic webapp
as described in the official guide at the following URL:http://www.yiiframework.com/doc/guide/en/quickstart.first-app
post
as follows:DROP TABLE IF EXISTS `post`; CREATE TABLE IF NOT EXISTS `post` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NOT NULL, `text` TEXT NOT NULL, `html` TEXT NOT NULL, PRIMARY KEY (`id`) );
Post
model using Gii.protected/models/Post.php
file and add the following method:protected function beforeValidate() { $parser=new CMarkdownParser(); $this->html=$parser->transform($this->text); return parent::beforeValidate(); }
Post
model can be used transparently. Create protected/controllers/TestController.php
as follows:<?php class TestController extends CController { function actionIndex() { $post = new Post(); $post->title = "I promise to share my opinion on Yii framework"; $post->text = "Recently I've started using [Yii framework](http://www.yiiframework.com/) and definitely will share my opinion as soon as I'll have some more free time."; $post->save(); echo "<h1>$post->title</h1>"; echo $post->html; } }
test/index
. You should get the following:The text marked up with markdown that you have set for the text
value will be automatically converted to HTML, ready to be displayed, and will be saved in the html
database field. Therefore, html
should be used at the display post screen and the markdown text should be used at the create post or edit post screens.
In the preceding code we override CActiveRecord::beforeValidate
to preprocess the data we have obtained from the user input. This method is executed just before the validation that is called when we use $post->save()
.
Yii includes a wrapper around the PHP Markdown Extra markdown parser. The CMarkdownParser
function is used mainly in the Yii documentation and we can surely use it in our applications.
Converting text from one format to another requires more CPU and memory resources, so should be avoided if possible. That is why we are not applying markdown on the fly, and instead only doing it one time when saving a post.
When we edit post
, we need to get the markdown source somehow. For this reason, we save both the markdown source and the produced HTML into a database. Alternatively, we can use a markdown parser on viewing post
and cache results until post
is altered.
3.141.31.240