This module helps to add comments to any instance of CActiveRecord.
Requirements ¶
tested on Yii 1.1.8
Usage ¶
You must create table
[sql]
CREATE TABLE IF NOT EXISTS `tbl_comments` (
`owner_name` varchar(50) NOT NULL,
`owner_id` int(12) NOT NULL,
`comment_id` int(12) NOT NULL AUTO_INCREMENT,
`parent_comment_id` int(12) DEFAULT NULL,
`creator_id` int(12) DEFAULT NULL,
`user_name` varchar(128) DEFAULT NULL,
`user_email` varchar(128) DEFAULT NULL,
`comment_text` text,
`create_time` int(11) DEFAULT NULL,
`update_time` int(11) DEFAULT NULL,
`status` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`comment_id`),
KEY `owner_name` (`owner_name`,`owner_id`)
)
To add a comment to the model, you need to perform two steps. First step - configure the module in app config:
'modules'=>array(
...
'comments'=>array(
//you may override default config for all connecting models
'defaultModelConfig' => array(
//only registered users can post comments
'registeredOnly' => false,
'useCaptcha' => false,
//allow comment tree
'allowSubcommenting' => true,
//display comments after moderation
'premoderate' => false,
//action for postig comment
'postCommentAction' => 'comments/comment/postComment',
//super user condition(display comment list in admin view and automoderate comments)
'isSuperuser'=>'Yii::app()->user->checkAccess("moderate")',
//order direction for comments
'orderComments'=>'DESC',
),
//the models for commenting
'commentableModels'=>array(
//model with individual settings
'Citys'=>array(
'registeredOnly'=>true,
'useCaptcha'=>true,
'allowSubcommenting'=>false,
//config for create link to view model page(page with comments)
'pageUrl'=>array(
'route'=>'admin/citys/view',
'data'=>array('id'=>'city_id'),
),
),
//model with default settings
'ImpressionSet',
),
//config for user models, which is used in application
'userConfig'=>array(
'class'=>'User',
'nameProperty'=>'username',
'emailProperty'=>'email',
),
),
...
),
Second step - display ECommentListWidget in view for displaying commentable models
$this->widget('comments.widgets.ECommentsListWidget', array(
'model' => $model,
));
To manage all comments go to http://yoursite.com/comments.
Damn crazy world...
I just created an extension for exactly the same approach yesterday! :-)
https://github.com/yiiext/comment-module
Edit: it is now here: /extension/comment-module
great! heheeheh actually i recently do the same thing as both of you (cebe and segoddnja)
congrats !
this is badly needed for almost every projects , but need a well wrapper module ,and make it a module is the best way when using it just use a widget as interface. in yiiext early i noticed that there is a commentable behavior but it is needed to inject to models. i don't think it is a good idea.
and here is my comment schema:
CREATE TABLE comment ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, uid INTEGER NOT NULL DEFAULT 0, parent_id BIGINT NOT NULL DEFAULT 0, object_class VARCHAR(50) NOT NULL, object_id INTEGER NOT NULL, content TEXT NOT NULL, ctime INTEGER NOT NULL, replies INTEGER NOT NULL DEFAULT 0, author VARCHAR(50) NOT NULL, author_email VARCHAR(50) NOT NULL DEFAULT '', author_url VARCHAR(200), author_ip VARCHAR(100), status TINYINT NOT NULL DEFAULT 0, user_agent VARCHAR(255) NOT NULL, PRIMARY KEY (id) ) ;
by the way , @CeBe did you use the smarty as view render. i read your comment-module in github. what if some project use another viewRender ? i thought yours is more complex for using .
another one
I also have created a comments module, but havent posted it yet :) I has similar approach, but has ajax support ;) It also has callback support, if you want to know when a comment is inserted.
comment module
I've just completed a similar comment module and.. hehe no just kidding..
Nice approach though, linking comments to a class.
A couple of questions
Error
Получаю ошибку
TypeError: jQuery("#yw0").commentsList is not a function
В FireBug вижу что скрипт подключен
В чем может быть дело?
Thanks
9343 Porcelanosa
Скорее всего, у тебя на странице есть еще как минимум один CHtml::ajax элемент. В этом случае получаем 2 (или больше) элемента с одинаковыми id, а именно с #yw0. Решение: генерируй уникальные id для всех CHtml::ajax-элементов, например с помощью uniqid().
Решение
на 75 строке базового виджета ECommentsBaseWidget
Исправила
$cs->registerScriptFile($assets . '/comments.js?'.time(),** CClientScript::POS_END**);
Вроде бы заработало.
А можно ли с помощью настроек убрать email из имен? Или надо править view?
9345 Porcelanosa
Вот кусок моего файла настроек этого модуля:
//config for user models, which is used in application 'userConfig'=>array( 'class'=>'User', 'nameProperty'=>'link', // 'emailProperty'=>'email', ),
где модель User имеет геттер getLink(), который выводит фото пользователя с его ником сразу в виде ссылки. Email не отображается.
Модели с составными ключами
Подскажите пожалуйста как использовать этот модуль в моделях с составными ключами.
По исходникам, как я понимаю, это возможно.
А вот как связать в конфиге - непонятно
use comments-module as sub modules
When your module use as child module, it doesn't works. I post the problems and my solution here:
http://www.yiiframework.com/forum/index.php/topic/37855-problems-with-nested-modules/
just love it
segoddnja you made my day, this module is just great
Thanks
Great!
Where to extract
For beginners - it would have been great if you had mentioned the folder where we need to extract this module.
Does this go into the modules or extension folder ?
thanks for replying and thanks for the module!
Re: Where to extract
Place it in module folder.
How to use widget by ajax request.
I want call the widget in view and load this view file by ajax request.
The problem is How to register js by creating unique Id like the widget is doing,
$js = "jQuery('#{$this->id}').commentsList($options);"; Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$this->id, $js);
Can anyone please tell me how can i achieve it?
Thanks in advance
Problem while using this module
Hi everyone! I am trying to use this module and I get a CDbException:
CDbException
Description
The table "{{comments}}" for active record class "Comment" cannot be found in the database.
Source File
C:\wamp\www\yii\framework\db\ar\CActiveRecord.php(2049)
02037: private $_model;
02038:
02039:
Using ECommentsListWidget in a Form
Hello,
very nice extension!
I use the ECommentsListWidget in a AR detail view without problems.
Now I want to use the widget in the record's form view also.
When I put the widget below the form, I always get a JavaScript error
Uncaught TypeError: undefined is not a function
onjQuery('#yw4').commentsList({'dialogTitle':'Add comment','deleteCo...
.There is no error when I put the widget before the form.
Any ideas greatly appreciated...
Regards,
Joachim
Patchs
I am set db in config/main.php:
'tablePrefix'=>'tbl_',
Captcha not showed without this two patches:
Inside file models/Comment.php this line
replace to
Inside file widgets/views/ECommentsFormWidget.php this line
'captchaAction'=>Yii::app()->urlManager->createUrl(CommentsModule::CAPTCHA_ACTION_ROUTE),
replace to
'captchaAction'=>CommentsModule::CAPTCHA_ACTION_ROUTE,
I am used this view to test widget on default yii site:
Yii::app()->user->setId(1); $post = Post::model()->findByPk(1); $this->widget('comments.widgets.ECommentsListWidget', array( 'model' => $post, ));
This module use sql tree like Adjacency list.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.