diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..619d7bf --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,47 @@ +# (MODX)EvolutionCMS.plugins.ManagerManager.mm_requireFields changelog + + +## Version 1.2.6 (2023-04-27) +* \* Attention! PHP >= 5.4 is required. +* \* Attention! (MODX)EvolutionCMS.plugins.ManagerManager >= 0.7 is required. +* \* Refactoring, the widget now uses “named” parameters, see README → Examples (with backward compatibility). +* \* Refactoring, compatibility with PHP >= 7.4. +* \+ README, README_ru. +* \+ CHANGELOG, CHANGELOG_ru. +* \+ Composer.json. + + +## Version 1.2.5 (2014-02-13) +* \+ Support for the `alias_visible` field has been added (for MODX > 1.0.11). + + +## Version 1.2.4 (2013-10-18) +* \* Support for `email` type of TVs has been added. + + +## Version 1.2.3 (2013-07-14) +* \* The check for definition of the TinyMCE variable was replaced by typeof(tinyMCE). + + +## Version 1.2.2 (2013-05-28) +* \* The problem with TinyMCE (it used to prevent documents save) has been solved. + + +## Version 1.2.1 (2013-05-16) +* \* The content field asterisk bug fix. + + +## Version 1.2 (2013-02-11) +* \* The tv using check in the current template was added. The document saving error is now not shown when a tv was not added to the document. + + +## Version 1.1 (2012-11-13) +* \* Minor code changes. + + +## Version 1.0 (2011) +* \+ The first release. + + + + \ No newline at end of file diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md new file mode 100644 index 0000000..afe044a --- /dev/null +++ b/CHANGELOG_ru.md @@ -0,0 +1,47 @@ +# (MODX)EvolutionCMS.plugins.ManagerManager.mm_requireFields changelog + + +## Версия 1.2.6 (2023-04-27) +* \* Внимание! Требуется PHP >= 5.4 is required. +* \* Внимание! Требуется (MODX)EvolutionCMS.plugins.ManagerManager >= 0.7. +* \* Параметры: Виджет теперь использует «именованные» параметры, см. README → Примеры (обратная совместимость сохранена). +* \* Рефакторинг, совместимость с PHP >= 7.4. +* \+ README, README_ru. +* \+ CHANGELOG, CHANGELOG_ru. +* \+ Composer.json. + + +## Версия 1.2.5 (2014-02-13) +* \+ Добавлена поддержка поля `alias_visible` (для MODX > 1.0.11). + + +## Версия 1.2.4 (2013-10-18) +* \* Добавлена поддержка TV типа `email`. + + +## Версия 1.2.3 (2013-07-14) +* \* Проверка на существование переменной TinyMCE переделана на typeof(tinyMCE). + + +## Версия 1.2.2 (2013-05-28) +* \* Исправлена проблема с TinyMCE (раньше лишний раз ругался, что поле не заполнено). + + +## Версия 1.2.1 (2013-05-16) +* \* Добавлена обработка поля content (звёздочка теперь добавляется и название в сообщении об ошибке выводится). + + +## Версия 1.2 (2013-02-11) +* \* Добавлена проверка использования tv в текущем шаблоне. Теперь наконец-то он не будет ругаться, если этой tv здесь в принципе не существует. + + +## Версия 1.1 (2012-11-13) +* \* Незначительные изменения кода. + + +## Версия 1.0 (2011) +* \+ Первый релиз. + + + + \ No newline at end of file diff --git a/README.md b/README.md index a49efb9..0e0c552 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,96 @@ -# mm_requireFields +# (MODX)EvolutionCMS.plugins.ManagerManager.mm_requireFields -Visit the following [link](http://code.divandesign.biz/modx/mm_requirefields) to read the documentation, instructions & changelog. \ No newline at end of file +A widget for ManagerManager plugin that allows document fields (or TVs) to become required. +The widget appends a red asterisk to a field to indicate it is required, and alerts users if they save the document without completing all required fields. + + +## Requires + +* PHP >= 5.4 +* [(MODX)EvolutionCMS.plugins.ManagerManager](https://code.divandesign.ru/modx/managermanager) >= 0.7 + + +## Installation + +To install you must unzip the archive to `/assets/plungins/managermanager/widgets/mm_requirefields/`. + + +You may also read this documentation: +* [(MODX)EvolutionCMS.plugins.ManagerManager](https://code.divandesign.ru/modx/managermanager). +* [(MODX)EvolutionCMS.modules.ddMMEditor](https://code.divandesign.ru/modx/ddmmeditor). + + +## Parameters description + +* `$params` + * Desctription: Parameters, the pass-by-name style is used. + * Valid values: + * `stdClass` + * `arrayAssociative` + * **Required** + +* `$params->fields` + * Desctription: The name(s) of the document fields (or TVs) that are required. + * Valid values: + * `stringCommaSeparated` + * `array` + * **Required** + +* `$params->fields[$i]` + * Desctription: The name of the document field or TV. + * Valid values: `string` + * **Required** + +* `$params->roles` + * Desctription: The CMS user roles that the widget is applied to. + * Valid values: + * `array` + * `stringCommaSeparated` + * `''` — when this parameter is empty then widget is applied to the all roles + * Default value: `''` + +* `$params->roles[$i]` + * Desctription: CMS user role ID. + * Valid values: `integer` + * **Required** + +* `$params->templates` + * Desctription: Document templates IDs for which the widget is applied to. + * Valid values: + * `array` + * `stringCommaSeparated` + * `''` — empty value means the widget is applying to all templates + * Default value: `''` + +* `$params->templates[$i]` + * Desctription: Template ID. + * Valid values: `integer` + * **Required** + + +## CMS events + +* `OnDocFormRender` + + +## Examples + + +### Make the page title and publication date fields required for all docs and users + +```php +mm_requireFields([ + 'fields' => 'pagetitle,pub_date' +]); +``` + + +## Links + +* [Home page](https://code.divandesign.ru/modx/mm_requirefields) +* [Telegram chat](https://t.me/dd_code) +* [Packagist](https://packagist.org/packages/dd/evolutioncms-plugins-managermanager-mm_requirefields) +* [GitHub](https://github.com/DivanDesign/EvolutionCMS.plugins.ManagerManager.mm_requireFields) + + + \ No newline at end of file diff --git a/README_ru.md b/README_ru.md new file mode 100644 index 0000000..81ee8bc --- /dev/null +++ b/README_ru.md @@ -0,0 +1,96 @@ +# (MODX)EvolutionCMS.plugins.ManagerManager.mm_requireFields + +
Виджет для плагина ManagerManager, позволяющий сделать поля документа или TV обязательными для заполнения. +Добавляет звёздочку красного цвета рядом с именем обязательного для заполнения поля, выдаёт сообщение при попытке сохранить не заполнив обязательные поля, предотвращая сохранение. + + +## Использует + +* PHP >= 5.4 +* [(MODX)EvolutionCMS.plugins.ManagerManager](https://code.divandesign.ru/modx/managermanager) >= 0.7 + + +## Установка + +Для установки распакуйте архив в `/assets/plungins/managermanager/widgets/mm_requirefields/`. + + +Смотрите также документацию: +* [(MODX)EvolutionCMS.plugins.ManagerManager](https://code.divandesign.ru/modx/managermanager). +* [(MODX)EvolutionCMS.modules.ddMMEditor](https://code.divandesign.ru/modx/ddmmeditor). + + +## Описание параметров + +* `$params` + * Описание: Параметры, используется стиль именованных параметров. + * Допустимые значения: + * `stdClass` + * `arrayAssociative` + * **Обязателен** + +* `$params->fields` + * Описание: Поля документа (или TV), которые должны быть обязательными. + * Допустимые значения: + * `stringCommaSeparated` + * `array` + * **Обязателен** + +* `$params->fields[$i]` + * Описание: Название поля документа или TV. + * Допустимые значения: `string` + * **Обязателен** + +* `$params->roles` + * Описание: Роли пользователей CMS, для которых необходимо применить виждет. + * Допустимые значения: + * `array` + * `stringCommaSeparated` + * `''` — применяется для всех ролей при пустом значении + * Значение по умолчанию: `''` + +* `$params->roles[$i]` + * Описание: Роль пользователя CMS. + * Допустимые значения: `integer` + * **Обязателен** + +* `$params->templates` + * Описание: ID шаблонов документов, для которых необходимо применить виджет. + * Допустимые значения: + * `array` + * `stringCommaSeparated` + * `''` — применяется для всех шаблонов при пустом значении + * Значение по умолчанию: `''` + +* `$params->templates[$i]` + * Описание: ID шаблона документа. + * Допустимые значения: `integer` + * **Обязателен** + + +## События CMS + +* `OnDocFormRender` + + +## Примеры + + +### Сделать обязательным для заполнения заголовки и даты публикации всех документов и пользователей + +```php +mm_requireFields([ + 'fields' => 'pagetitle,pub_date' +]); +``` + + +## Ссылки + +* [Home page](https://code.divandesign.ru/modx/mm_requirefields) +* [Telegram chat](https://t.me/dd_code) +* [Packagist](https://packagist.org/packages/dd/evolutioncms-plugins-managermanager-mm_requirefields) +* [GitHub](https://github.com/DivanDesign/EvolutionCMS.plugins.ManagerManager.mm_requireFields) + + + \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..22b4252 --- /dev/null +++ b/composer.json @@ -0,0 +1,47 @@ +{ + "name": "dd/evolutioncms-plugins-managermanager-mm_requirefields", + "version": "1.2.6", + "description": "A widget for ManagerManager plugin that allows document fields (or TVs) to become required.", + "keywords": [ + "modx", + "modx evo", + "modx evolution", + "evo", + "evo cms", + "evolutioncms", + "evolution cms", + "dd group", + "dd studio", + "divandesign", + "managermanager", + "mm", + "mm widget", + "mm_requirefields", + "require document field", + "require tv" + ], + "homepage": "https://code.divandesign.ru/modx/mm_requirefields", + "support": { + "chat": "https://t.me/dd_code" + }, + "authors": [ + { + "name": "Ilyas Ronef", + "email": "ilyas@DivanDesign.ru", + "homepage": "https://ronef.ru", + "role": "Owner" + }, + { + "name": "ncrossland", + "role": "Developer" + }, + { + "name": "Jelle Jager AKA TobyL", + "role": "Creator" + } + ], + "require": { + "php": ">=5.4.0", + "dd/evolutioncms-plugins-managermanager": ">=0.7.0" + } +} \ No newline at end of file diff --git a/mm_requirefields/index.html b/index.html similarity index 100% rename from mm_requirefields/index.html rename to index.html diff --git a/mm_requirefields.php b/mm_requirefields.php new file mode 100644 index 0000000..f6f25f2 --- /dev/null +++ b/mm_requirefields.php @@ -0,0 +1,205 @@ + 1 || + !is_array($params) && + !is_object($params) + ){ + //Convert ordered list of params to named + $params = \ddTools::orderedParamsToNamed([ + 'paramsList' => func_get_args(), + 'compliance' => [ + 'fields', + 'roles', + 'templates', + ] + ]); + } + + //Defaults + $params = \DDTools\ObjectTools::extend([ + 'objects' => [ + (object) [ + 'fields' => '', + 'roles' => '', + 'templates' => '' + ], + $params + ] + ]); + + if ( + !useThisRule( + $params->roles, + $params->templates + ) + ){ + return; + } + + global + $mm_fields, + $modx + ; + + if ($modx->Event->name == 'OnDocFormRender'){ + $params->fields = getTplMatchedFields($params->fields); + + if (empty($params->fields)){ + return; + } + + $output = '//---------- mm_requireFields :: Begin -----' . PHP_EOL; + + $output .= ' + $j("head").append(""); + var requiredHTML = "*"; + '; + + $submit_js = ''; + $load_js = ''; + + foreach ( + $params->fields as + $field + ){ + //Ignore for now + switch ($field){ + //Fields for which this doesn't make sense + case 'keywords': + case 'metatags': + case 'hidemenu': + case 'which_editor': + case 'template': + case 'menuindex': + case 'show_in_menu': + case 'parent': + case 'is_folder': + case 'alias_visible': + case 'is_richtext': + case 'log': + case 'searchable': + case 'cacheable': + case 'clear_cache': + case 'content_type': + case 'content_dispo': + $output .= ''; + break; + + //Pub/unpub dates don't have a type attribute on their input tag in 1.0.2, so add this. Won't do any harm to other versions + case 'pub_date': + case 'unpub_date': + $load_js .= ' + //Cant use jQuery attr function as datepicker class clashes with jQuery methods + $j("#pub_date, #unpub_date").each(function(){this.type = "text";}); + '; + //No break, because we want to do the things below too. + + //Ones that follow the regular pattern + default: + //What type is this field? + $fieldname = $mm_fields[$field]['fieldname']; + + //What jQuery selector should we use for this fieldtype? + switch ($mm_fields[$field]['fieldtype']){ + case 'textarea': + $selector = 'textarea[name=' . $fieldname . ']'; + break; + + //If it's an input, we only want to do something if it's a text field + case 'input': + $selector = 'input[type=text][name=' . $fieldname . '],input[type=email][name=' . $fieldname. ']'; + break; + + //All other input types, do nothing + default: + $selector = ''; + break; + } + + //If we've found something we want to use + if (!empty($selector)){ + if ($field == 'content'){ + $label = '$j("#content_header")'; + $tinymcefix = 'if (typeof(tinyMCE) != "undefined" && typeof(tinyMCE.triggerSave) != "undefined"){tinyMCE.triggerSave();}'; + }else{ + $label = '$sel.parents("td:first").prev("td").children("span.warning")'; + $tinymcefix = ''; + } + + $submit_js .= ' + +// The element we are targetting (' . $fieldname . ') +var $sel = $j("' . $selector . '"); + +' . $tinymcefix . ' +// Check if its valid +if($j.trim($sel.val()) == ""){// If it is empty + // Find the label (this will be easier in Evo 1.1 with more semantic code) + var lbl = ' . $label . '.text().replace($j(requiredHTML).text(), ""); + + // Add the label to the errors array. Would be nice to say which tab it is on, but no + // easy way of doing this in 1.0.x as no semantic link between tabs and tab body + errors.push(lbl); + + // Add an event so the hilight is removed upon focussing + $sel.addClass("mmRequired").focus(function(){ + $j(this).removeClass("mmRequired"); + }); +} + '; + + $load_js .= ' + +// Add an indicator this is required (' . $fieldname . ') +var $sel = $j("' . $selector . '"); + +// Find the label (this will be easier in Evo 1.1 with more semantic code) +var $lbl = ' . $label . '.append(requiredHTML); + + '; + } + break; + } + } + + $output .= $load_js . ' +$j("#mutate").submit(function(){ + var errors = []; + +' . $submit_js . ' + + if(errors.length > 0){ + var errMsg = errors.length + " required fields are missing:\n\n "; + + for (var i = 0; i < errors.length; i++){ + errMsg += " - " + errors[i] + " \n"; + } + errMsg += " \nPlease correct the indicated fields."; + + alert(errMsg); + return false; + }else{ + return true; + } +}); + '; + + $output .= '//---------- mm_requireFields :: End -----' . PHP_EOL; + + $modx->Event->output($output); + } +} +?> \ No newline at end of file diff --git a/mm_requirefields/mm_requirefields.php b/mm_requirefields/mm_requirefields.php deleted file mode 100644 index 1ddd542..0000000 --- a/mm_requirefields/mm_requirefields.php +++ /dev/null @@ -1,176 +0,0 @@ -Event; - - // if the current page is being edited by someone in the list of roles, and uses a template in the list of templates - if ($e->name == 'OnDocFormRender' && useThisRule($roles, $templates)){ - // if we've been supplied with a string, convert it into an array - $fields = makeArray($fields); - - if (count($fields) == 0) return; - - $output = "\n// -------------- mm_requireFields :: Begin ------------- \n"; - - $output .= ' - $j("head").append(""); - var requiredHTML = "*"; - '; - - $submit_js = ''; - $load_js = ''; - - foreach ($fields as $field){ - //ignore for now - switch ($field){ - // fields for which this doesn't make sense - in my opinion anyway :) - case 'keywords': - case 'metatags': - case 'hidemenu': - case 'which_editor': - case 'template': - case 'menuindex': - case 'show_in_menu': - case 'parent': - case 'is_folder': - case 'alias_visible': - case 'is_richtext': - case 'log': - case 'searchable': - case 'cacheable': - case 'clear_cache': - case 'content_type': - case 'content_dispo': - case 'which_editor': - $output .= ''; - break; - - // Pub/unpub dates don't have a type attribute on their input tag in 1.0.2, so add this. Won't do any harm to other versions - case 'pub_date': - case 'unpub_date': - $load_js .= ' - $j("#pub_date, #unpub_date").each(function() { this.type = "text"; }); // Cant use jQuery attr function as datepicker class clashes with jQuery methods - '; - // no break, because we want to do the things below too. - - // Ones that follow the regular pattern - default: - //if it's tv & it's not used in current template - if ($mm_fields[$field]['tv'] && tplUseTvs($mm_current_page['template'], $field) === false){ - //Go to next field - continue; - } - - // What type is this field? - $fieldname = $mm_fields[$field]['fieldname']; - - // What jQuery selector should we use for this fieldtype? - switch ($mm_fields[$field]['fieldtype']){ - case 'textarea': - $selector = "textarea[name=$fieldname]"; - break; - - case 'input': // If it's an input, we only want to do something if it's a text field - $selector = "input[type=text][name=$fieldname],input[type=email][name=$fieldname]"; - break; - - default: // all other input types, do nothing - $selector = ''; - break; - } - - // If we've found something we want to use - if (!empty($selector)){ - if ($field == 'content'){ - $label = '$j("#content_header")'; - $tinymcefix = 'if (typeof(tinyMCE) != "undefined" && typeof(tinyMCE.triggerSave) != "undefined"){tinyMCE.triggerSave();}'; - }else{ - $label = '$sel.parents("td:first").prev("td").children("span.warning")'; - $tinymcefix = ''; - } - - $submit_js .= ' - -// The element we are targetting ('.$fieldname.') -var $sel = $j("'.$selector.'"); - -'.$tinymcefix.' -// Check if its valid -if($j.trim($sel.val()) == ""){// If it is empty - // Find the label (this will be easier in Evo 1.1 with more semantic code) - var lbl = '.$label.'.text().replace($j(requiredHTML).text(), ""); - - // Add the label to the errors array. Would be nice to say which tab it is on, but no - // easy way of doing this in 1.0.x as no semantic link between tabs and tab body - errors.push(lbl); - - // Add an event so the hilight is removed upon focussing - $sel.addClass("mmRequired").focus(function(){ - $j(this).removeClass("mmRequired"); - }); -} - '; - - $load_js .= ' - -// Add an indicator this is required ('.$fieldname.') -var $sel = $j("'.$selector.'"); - -// Find the label (this will be easier in Evo 1.1 with more semantic code) -var $lbl = '.$label.'.append(requiredHTML); - - '; - } - break; - } - } - - $output .= $load_js.' -$j("#mutate").submit(function(){ - var errors = []; - -'.$submit_js.' - - if(errors.length > 0){ - var errMsg = errors.length + " required fields are missing:\n\n "; - - for (var i = 0; i < errors.length; i++){ - errMsg += " - " + errors[i] + " \n"; - } - errMsg += " \nPlease correct the indicated fields."; - - alert(errMsg); - return false; - }else{ - return true; - } -}); - '; - - $output .= "\n// -------------- mm_requireFields :: End ------------- \n"; - - $e->output($output . "\n"); - } -} -?> \ No newline at end of file