Giter Site home page Giter Site logo

yii2-comments's People

Contributors

corpsepk avatar dilden avatar dmitry-semenov avatar gitter-badger avatar gugoan avatar morontt avatar mtangoo avatar nrob81 avatar patroklo avatar satoved avatar seesoft-dev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-comments's Issues

Embedding

Your extensions looks amazing by the way. !!!!
I noticed that I can type in html and iframes etc... This can pose a security risk...
This way people can add malicious scrips to my app

Переход с 1.0.3 на 1.0.4

Здраствуйте после обновления компосером модуля с 1.0.3 на 1.0.4 возникла ошибка из за новго поля в таблице relatedTo (вероятно из за того что в миграции не предусмотрена проверка на существование таблици) + название миграции не позволяет ее накактить снова.
Как решение проблемы хотел бы предложить вместо одной миграции сделдать последовательность миграций.

(Нехотелось создавать еще одно issuse)
Есть следующая проблема, на сайте используеться два модуля комментариев поэтому название модуля (comment) уже занято, есть ли корректный способ передать в модели модуля другое название без переопределения их в каталогах проекта ?
П.С. Спасибо за отличный модуль

Про comment.js и комментирование гостями

Доброго времени суток!
Спасибо за Ваш модуль, среди всех я остановился именно на Вашем продукте. Но есть небольшие предложения и вопросы, которые хотелось бы прояснить.

  1. Предложение: В функции reply и cancelReply в файле comment.js добавить триггер событий, что-то типа 'beforeMoveTextarea' и 'afterMoveTextarea', по которым можно обезопасить перемещение по странице, как-минимум, tinyMCE: поскольку в текущей версии редактор tinyMCE "зависает". В эти события можно было бы повесить собственные функции отключения редактора в момент переноса.
  2. И совершенно необязательный, но желательный вопрос: что Вы думаете о комментировании сущностей гостями сайта? И стоит ли ожидать модернизацию системы комментирования в данном вопросе?
    С уважением!

Jquery и скрипты

Здравствуйте, господа разработчики!
Проблема при использовании вашего чудесного модуля у меня возникает следующая:

  • Не работают кнопки reply, да и вообще весь модуль функционирует абы-как.

Провел расследование, нашел проблему.
Она заключается в том, что я обновляю класс вида по ajax, и вот в этом новом виде и есть комментарии, которые не работают. Если же я вывожу комментарии на Главную, т.е. сразу после загрузки site/index, все отрабатывает великолепно.

Как я могу поправить это, перерегистрируя виджет заново?
В файле вида:

use yii2mod\comments\CommentAsset;
CommentAsset::register($this);

Не помогает..

Не работает ссылка reply в комментариях

При нажатии на ссылку reply (ответить) на комментарии просто перебрасывает на верх страницы. Проще говоря, ссылка работает как обычная ссылка на эту-же страницу. Соответственно, не записывается родительский id . Что может быть. На сколько я понял, за поведение ссылки отвечает comment.js и data атрибуты <?php echo Html::a("<span class='glyphicon glyphicon-share-alt'></span> Ответить", '#', ['class' => 'comment-reply', 'data' => ['action' => 'reply', 'comment-id' => $comment->id]]); ?>
Все это подключается в assets. Возможно ,что-то я упустил?

Возможно jquery плагин где-то нужно включить?

how to use in yii2-advanced

I don't know <?php echo \yii2mod\comments\widgets\Comment::widget([ 'model' => $model, 'relatedTo' => 'User ' . \Yii::$app->user->identity->username . ' commented on the page ' . \yii\helpers\Url::current() // for example ]); ?> about what is the '$model'. Is't a model =new user?

Database Exception

I've been trying to work with this extension but when I try to see comments/index it says "SQLSTATE[42803]: Grouping error: 7 ERROR: column "a.username" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "c"."createdBy", "a"."username" FROM "comment" "c" LE..."
getAuthors()

I'm using Postgresql and I don't know if that's the problem. Thanks for the help.

Pagination

Добрый день! А есть ли возможность вывода постранично разбив комментарии?

Pjax support

Hi, I'm trying to use javascript to reload the comments instead of reloading all the page, I thought that using pjax whould be the simplest way, but I can't think of a way of reloading the widget with the new comment once i have sent the data. Does something come to mind to you to be able to use ajax for this comment system?

Возникли проблемы в использовании модуля

При отправки комментария Pjax container не перезагружаеться а перенаправляет на главную страницу сайта в (возможно связано с тем что в Url-X-Path в хедере ответа приходит не текущая страница а домашняя страница сайта) в качестве хот фикса изменил одну из js функций

` function beforeSubmitForm() {
var $commentForm = $(this),
settings = $commentForm.data('comment');
//Add loading to comment button
$commentForm.find(':submit').prop('disabled', true).text('Loading...');
var pjaxSettings = $.extend({container: settings.pjaxContainerId}, settings.pjaxSettings);
//Send post request

    $.post($commentForm.attr("action"), $commentForm.serialize(), function (data) {
        //If success is status, then pjax container has been reloaded and comment form has been reset
        if (data.status == 'success') {
            $commentForm.find(':submit').prop('disabled', false).text('Comment');
            $commentForm.trigger("reset");
            alert('Your comment while show after moderation');
            // $.pjax(pjaxSettings).done(function () {
            //     $commentForm.find(':submit').prop('disabled', false).text('Comment');
            //     $commentForm.trigger("reset");
            //     //Restart plugin
            //     methods.reset.call($commentForm, settings);
            // });
        }
        //If status is error, then only show form errors.
        else {
            if (data.hasOwnProperty('errors')) {
                $commentForm.yiiActiveForm('updateMessages', data.errors, true);
            }else {
                $commentForm.yiiActiveForm('updateAttribute', 'commentmodel-content', [data.message]);
            }
            $commentForm.find(':submit').prop('disabled', false).text('Comment');
        }
    });

    return false;
}`

настройки pjax использую по умолчанию
<?php Pjax::begin([ 'enablePushState' => false, 'timeout' => 10000, 'id' => $pjaxContainerId ]); ?>

how to get and show avatar

my model User related model UserProfile
code models User

`public static function tableName()
{
return '{{%user}}';
}

public function attributeLabels()
{
return [
'username' => Yii::t('common', 'Username'),
'email' => Yii::t('common', 'Email'),
'status' => Yii::t('common', 'Status'),
'created_at' => Yii::t('common', 'Created at'),
'updated_at' => Yii::t('common', 'Updated at'),
'action_at' => Yii::t('common', 'Last action at'),
];
}

public function getUserProfile()
{
return $this->hasOne(UserProfile::className(), ['user_id' => 'id']);
}`

and code model UserProfile
` public static function tableName()
{
return '{{%user_profile}}';
}

public function behaviors()
{
    return [
        'uploadBehavior' => [
            'class' => UploadBehavior::className(),
            'attributes' => [
                'avatar_path' => [
                    'path' => '@storage/avatars',
                    'tempPath' => '@storage/tmp',
                    'url' => Yii::getAlias('@storageUrl/avatars'),
                ],
            ],
        ],
    ];
}


    public function attributeLabels()
{
    return [
        'firstname' => Yii::t('common', 'Firstname'),
        'lastname' => Yii::t('common', 'Lastname'),
        'birthday' => Yii::t('common', 'Birthday'),
        'avatar_path' => Yii::t('common', 'Avatar'),
        'gender' => Yii::t('common', 'Gender'),
        'website' => Yii::t('common', 'Website'),
        'other' => Yii::t('common', 'Other'),
    ];
}`

JS FormData implementation

Is it possible to change:
var formData = $commentForm.serializeArray();
to FormData object? To make file uploads.

My own model

Доброе время суток. Столкнулся с ошибкой.

Что бы добавить возможность удаления своих комментариев я создал свою модель, в который дописал проверку в методе beforeModeration()

Подключаю модель:

'modules' => [
        'comment' => [
            'class' => 'yii2mod\comments\Module',
            'commentModelClass' => 'app\models\CommentModel',
        ]
    ]

В итоге комментарии подгружаются с использованием моей модели, но при удалении у меня беда:

PHP Recoverable Error 'yii\base\ErrorException' with message 'Argument 1 passed to yii2mod\comments\events\CommentEvent::setCommentModel() must be an instance of yii2mod\comments\models\CommentModel, instance of app\models\CommentModel given, called in /home/admin/web/tasks.inde.pp.ua/public_html/vendor/yiisoft/yii2/base/Object.php on line 157 and defined'

in /home/admin/web/tasks.inde.pp.ua/public_html/vendor/yii2mod/yii2-comments/events/CommentEvent.php:31

Change tableName Comment to comment

class CommentModel extends ActiveRecord
{
    /**
     * @var null|array|ActiveRecord[] Comment children
     */
    protected $_children;

    /**
     * Declares the name of the database table associated with this AR class.
     *
     * @return string the table name
     */
    public static function tableName()
    {
        return '{{%Comment}}'; // change Comment to comment
    }
?>
You should keep your table name as lower case. Because in Windows the case sensitive of table never change. Once you put the script in Linux it 'll change all to lower case.

Unable to override controller.

I've tried the following below to override your controller and it didn't work.


'controllerMap' => [
        'comments' => 'yii2mod\comments\controllers\ManageController'
  ]

Can you explain to me where exactly in the main config file i should place this code?
I see no admin module section in this file. I'm using yii2 advanced .

Thanks.

Migrations

Today I created a new site, with your component... however it still downloaded the old migrations (where the {{% was not yet fixed
Any idea why ?

I18N

My site is multilingual and I want the comments to be visible only on the language that they were made in
So if a user uses the english version of the site, they must not see the german comments
Is that possible ?

How to get decrypted entity value?

We have an entity field in the database with char(10) and when the module name encrypting the length was bigger than it can store, so it`s trimmed. So how i can get fully entity name like "posts", "news" etc ...

Request

Can I make a request for a feature?
Add some custom data to the widget setting
and be able to show only those with that setting

ie

    'model' => $model,
'language' => 'de',
'languageStrict' => TRUE,
    'relatedTo' => 'User...

This stores de in the record field 'language'
if languageStrict== TRUE then it only shows those records where the languageis the same (de)
if languageStrict== FALSE it shows ALL the records (like current)

This way people can easy implement multilingual

I could ofcourse copy your code and modify it...but this way more people can benefit from your work

Проблема при многоразовом использовании виджета на одной странице

Хотелось бы сообщить о возможности возникновения бага при условии многоразово использования модуля на одной странице при рандомном порядке отображения сущностей к которым применяеться модуль, баг связан с логикой работы метода $this->getId(); и Pjax контейнера. Проблема в том что при многоразовом отправлении запросов id контейнера может меняться поскольку порядок присвоения контейнеру id меняеться в соотвецтвии с порядком отображения его на странице и врезультате мы получаем пачку коментариев другой сущности.

Как решение проблемы предлагаю переопределить метод init() в Comment.php и сделать его зависимым от entityId или же сделать возможным определять его ид с точки вызова виджета так же как и $formId (на ваше усмотрение)

Также столкнулся с связаной с этим проблемой решение которой не смог найти (при рандомном отображении сущностей к которым применяеться виджет) тоесть когда Pjax посылает запрпос на туже страницу на подгрузку контейнера с определенным id (но поскольку идет рандомное отображение) то при запросе Pjax его не находит и редиректит на страницу /comment/default для отмены редиректа присвоил ActiveForme следующий параметр 'data-pjax'=>true, в результате в Pjax просто подгружает в свой контейнер ответ со страници /comment/default а именно ['status' => 'success'] что тоже не есть верным результатом в целом буду рад услышать ваше мнение по поводу решения даной проблемы. Спасибо за внимание.

При использовании параметра 'showDeletedComments' => true выдвет Unknown Property по всей видимости вы просто забыли убрать его со страници описания в отделе Basic example: хотя параметр весьма полезный как альтернатива вместо отображения тексту Comment was deleted.

П.С. Спасибо за отличный виджет.

questions / request

  1. Сделать полный перевод расширения, включая кнопки "Удалить" и "Ответить" (которые в данный момент нельзя перевести i18n)
  2. Как правильно подключать свой вид на yii2-advanced
    пробовал:
    ставлю - 'commentView' => '@frontend/views/comments/index'
    получаю - Invalid Parameter – yii\base\InvalidParamException

-- Google Translate ---

  1. Make a full translation of the expansion, including the "Delete" button, and "Reply" (which at the moment can not translate i18n)
  2. How to connect your view of the yii2-advanced
    I tried:
    use - 'commentView' => '@frontend/views/comments/index'
    I get - Invalid Parameter – yii\base\InvalidParamException

how to entry entity , entityId, and relatedTo

when i used this widget ,, the first show error 'The "entityIdAttribute" value for widget model cannot be empty,,, and widgets there are column entity , entitiyId and relatedTo,, how to use entry this column

Internal Server Error

error

exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii2mod\comments\models\CommentModel::url' in C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Component.php:201
Stack trace:
#0 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\db\BaseActiveRecord.php(306): yii\base\Component->__set('url', '/article/fromte...')
#1 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Model.php(698): yii\db\BaseActiveRecord->__set('url', '/article/fromte...')
#2 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Model.php(827): yii\base\Model->setAttributes(Array)
#3 C:\xampp\htdocs\yii2-core\vendor\yii2mod\yii2-comments\controllers\DefaultController.php(86): yii\base\Model->load(Array)
#4 [internal function]: yii2mod\comments\controllers\DefaultController->actionCreate('\xC3\xA7\xC3\x91|\xC3\x82i(q0p\xC3\x9CF...')
#5 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#6 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction->runWithParams(Array)
#7 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Module.php(522): yii\base\Controller->runAction('create', Array)
#8 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module->runAction('comment/default...', Array)
#9 C:\xampp\htdocs\yii2-core\vendor\yiisoft\yii2\base\Application.php(379): yii\web\Application->handleRequest(Object(yii\web\Request))
#10 C:\xampp\htdocs\yii2-core\frontend\web\index.php(32): yii\base\Application->run()
#11 {main}

How can i get the user id ?

Hi thanks for the code I works fine and the readme helps a lot to implement it.

I am overriding the _list.php to add a link to the user profile.
in the model i can get the updateBy but is not always correspond the user who made the comment.

I manage to add the getAvatar and getAuthorName but i can't manage to get the user id is it any method to do that?

Thaks again

malformed utf-8 characters possibly incorrectly encoded php

When add a comment
gives me
malformed utf-8 characters possibly incorrectly encoded

and i resolved it by

  $decryptEntity = Yii::$app->getSecurity()->decryptByKey(utf8_decode($entity), $module::$name);

and

return utf8_encode(Yii::$app->getSecurity()->encryptByKey(Json::encode([
            'entity' => $this->entity,
            'entityId' => $this->entityId,
            'relatedTo' => $this->relatedTo
        ]), Module::$name));

thanks

add permanent link

  • Add anchor to posted date
  • Add view link to comments grid view on the manage comments page.

Нуждаюсь в помощи с конфигурацией

Добрый день! Вопросы могут показаться глупыми, я неопытен и возможно просто упустил какую-то очевидную вещь.
Установил данный модуль через composer на проект, основанный на yii2 advanced
в /common/config/main.php добавил это
image

и в /backend/config/main добавил следующее:
image

почему-то при попытке зайти на site/admin/comments, я получаю ошибку 404. Перепробовал уже все варианты, не получается.

Можете помочь?
Спасибо.

Comment Mailing

Hi ,

Just wondering if you can add the ability to send emails on comment addition or replies to any parent comment within your module.

Sounds like a useful enhancement.

Giving configuration option to disable to enable email to parent comment for replies or comments in general.

what do you think?

Проблема при добавлении коментария

Приветствую, есть такая проблема после добавления каждого 2-ого комментария если не обновлять страницу, получаю JSON такого вида {"status":"success"} вместо того чтобы остаться на той же странице. В чем может быть проблема такого поведения. Собственно actionCreate() в defaultController
содержит данную строку return ['status' => 'success']; но почему первый комментарий добавляется без проблем а второй возвращает данный json.

when I run php yii migrat shell throw error “table already exists”

when i run php yii migrate --migrationPath=@vendor/yii2mod/yii2-comments/migrations,throw some error, Error Info :

rename table {{%Comment}} to {{%comment}} ...Exception 'yii\db\Exception' with message 'SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'blog_comment' already exists
The SQL being executed was: RENAME TABLE `blog_Comment` TO `blog_comment`'

My Developer environment is MAMP,and the MySQL version is 5.5.42。

so I modified the my.conf file and restart mysqld server.

[mysqld]
lower_case_table_names = 0

the bug is aways ready exists,please tell me some idea to solve it.

Отображаются не все комментарии

Здравствуйте. Подскажите пожалуйста, в чем может быть такая проблема. Установил модуль по инструкции, комменты добавляются и выводятся. Но не все. То есть если я зайду на страницу, напишу пару комментов, все окей. Но если перезайду на другого юзера, то добавленные им комменты не выводятся или выводятся иногда. Как на скрине http://joxi.ru/82QM48Of0RYg2d , комментов 6, а выводится 2. И выводится они, как я понял, должны с последнего, но они так не делают. Использую такой вывод:

<?php echo \yii2mod\comments\widgets\Comment::widget([
                'model' => $comp,
                'relatedTo' => 'User ' . \Yii::$app->user->identity->username . ' commented on the page ' . \yii\helpers\Url::current(),
                'maxLevel' => 5,
                // set `pageSize` with custom sorting
                'dataProviderConfig' => [
                    'sort' => [
                        'attributes' => ['id'],
                        'defaultOrder' => ['id' => SORT_DESC],
                    ],
                    'pagination' => [
                        'pageSize' => 10
                    ],
                ],
                // your own config for comments ListView, for example:
                'listViewConfig' => [
                    'emptyText' => Yii::t('app', 'No comments found.'),
                ]
            ]); ?>

Multiple widget on same page

Hi , i want to use multiple comment widget on a page , all things works fine but comment form dont work , how i can do this ?

Comments in modal window

I used your extension to load comments in a modal window. It worked fine and the page is rendered correctly but after submitting new comment and after a "success" response the whole page is reloaded.

As far as I can say it happens because of the PJAX reload but I do not understand why the whole page gets reloaded instead of only PJAX container.

Any thoughts on this issue would be appreciated.

Не корректно работае дерево в yii2 advansed

есть проблема с построением дерева комментариев. Подключаю модуль во frontend при использовании комментариев без ветвления( только первый уровень), все работае отлично. Если использовать ветвление(погружение),то как только я делаю ответ на последний опубликованный комментарий, ответ отображается, но перестает отображатся последующие комментарии предидущего уровня, то есть не ответ на комментарий, а комментарий в верхнего уровня. В базу он записыватся, но в виде он не выводится. Можете меня помочь?

Pagination

why there is no navigation through pages, it is not convenient when all comm displayed? (sorry for my English)

How to show only the comments related to this activeRecord / url

Hi Igor,
Sorry to bored you with a silly question but I cant manage to filter the record comments all rest it is looking beautiful.

<?php
echo \yii2mod\comments\widgets\Comment::widget([
    'model' => $book,
    'commentView' => '@frontend/views/comments/index', // path to your template
    //'relatedTo' => 'User ' . \Yii::$app->user->identity->username . ' commented on the page ' . \yii\helpers\Url::current(),
    'relatedTo' => \yii\helpers\Url::current(),
    'maxLevel' => 2,
    // set `pageSize` with custom sorting
    'dataProviderConfig' => [
        'sort' => [
            'attributes' => ['id'],
            'defaultOrder' => ['id' => SORT_DESC],
        ],
        'pagination' => [
            'pageSize' => 10
        ],
    ],
    // your own config for comments ListView, for example:
    'listViewConfig' => [
        'emptyText' => Yii::t('app', 'No comments found.'),
    ]
]);
?>

I can see that I can change the relatedTo property with any value and this change the db field but I don't understand how the model in my case $book works with the widget

thanks

Is there a way to getChildren works with orderBy

I would like to see the replies of a comment with the oldest at first and the newer at the bottom, like youtube. Is it possible? By default it works the other way around.

Example:
carlos -- Hii 2 days ago
anonymous -- Bye 1 day ago
masteroftea -- Haha 1 minute ago

Change / request

Если соединение интернет не очень хорошее, то, можно нажать много раз на кнопку отправить комментарий и он много раз подряд его отправит.

Нужно блокировать кнопку после первого нажатия до полной отправки комментария.

Google Translate
If Internet connection is not very good , then you can click the button several times to make a comment and he many times in a row it sends .

It is necessary to block the button after the first click to the full post a comment

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.