Server side validation in module setting page in backend joomla - joomla

I am using joomla 2.5, i am working on joomla module, i want to perform server side custom form validation at backend setting page in module. I have checked joomla forums , but they all explained according to component , i strictly need to do it in module . I am new in joomla . Please explain the method.

Try this,
First of all you can't do a wide variety of validations like components forms in module params without hacking the core.
the available options are limiting INT,RAW data string only.
you can use the last option of module params called filter. Details take a look at this.
<field name="myintvalue" type="text" default="8" label="Enter some text" description="Enter some description" filter="integer" />
<field name="myhtmlvalue" type="text" default="" label="Enter some text" description="Enter some description" filter="raw" />
Alternate Options.
You can create a custom rule for validation. For example your module name is mod_mymodule:
Add addrulepath attribute to the fieldset in the .xml file:
addrulepath="modules/mod_mymodule"
This will be the path to the custom rule folder.
Add validate attribute to the field with the name of the rule file:
validate="testint"
This will give us the file testint.php.
Create the rule file testint.php and put it to the path specified in the addrulepath attribute. So the full path will be:
administrator/modules/mod_mymodule/testint.php
Here is a simple validation rule class:
class JFormRuleTestint extends JFormRule
{
public function test(&$element, $value, $group = null, &$input = null, &$form = null)
{
return ((int)$value > 0 && (int)$value < 2);
}
}
it should extend JFormRule class and you will need only one method, called test. $value will contain the input from the field. Here we are testing it to be integer between 0 and 2.
Hope its helps..

Related

Ckeditor in Drupal 8 : how to remove <span> tags if they don't have class attributes?

I'm using the "Allowed html tags" filter in Ckeditor - Drupal 8.
I want Ckeditor to keep <span> tags that have specific classes or IDs, and to remove if it has no attribute.
For example :
Keep span: <span class="apple">text sample</span>
Keep span : <span id="fruit">text sample</span>
Remove span : <span>text sample</span> -> text sample
Actually, when I configure a text format, I have this code in the allowed tags field :
<p><sup><sub><span id class="apple"><a href !href accesskey id rel target title>
It keeps <span> with IDs or wanted classes, but I cannot get rid of the unwanted <span> with no attribute.
Is there any way to solve this problem with code input?
Thanks in advance,
Emilie
So here is the custom module I wrote to make it work and to get around this major bug in CKEDITOR :
<?php
use Drupal\editor\Entity\Editor;
function MODULENAME_editor_js_settings_alter(array &$settings) {
foreach ($settings['editor']['formats'] as $name => $value) {
$settings['editor']['formats']['machine_name_of_your_text_editor_profile']
['editorSettings']['allowedContent'] =
'p sup h1 h2 h3' +
'span[!id];
span(!foo);
span(!bar);
span(!jane);
span(!doe);'
;}
}
Result : spans are totally deleted if there is no ID, or if you use a class that is not mentionned in this list (foo, bar, jane or doe). You must declare all elements you need to be displayed, because this config will overwrite all previous inputs in the ACF field.
For this solution, I was inspired by :
The ACF Custom doc : https://ckeditor.com/docs/ckeditor4/latest/examples/acfcustom.html
A tread about hook_editor_js_settings_alter : https://drupal.stackexchange.com/questions/268311/hook-editor-js-setting...
Note : Limit allowed HTML tags and correct faulty HTML filter (in /admin/config/content/formats) does not act consistently with the Ckeditor API. Only a part of the options are really implemented in this field, and uses of "!" don't work. This is why the solution provided uses "hook_editor_js_settings_alter".
function MODULENAME_editor_js_settings_alter(array &$settings) {
$formats = ['basic_html', 'full_html'];
foreach ($formats as $format) {
$settings['editor']['formats'][$format]['editorSettings']['allowedContent']['span']['attributes'] = '!class';
}
}
allowedContent is an array when loaded by Drupal. Instead of replacing it with a string, you can use the ACF rules to specify whether attributes are required. This allows the config from the UI to still apply.

validation giving error in Joomla 2.5

i am using Joomla 2.5 user registration form . manually i added one more field user phone number . and i am doing server side validation .
Code is : registration.xml
<form
addrulepath="/administrator/components/com_user/models/rules"
>
<field
name="pnumber"
type="text"
description="Enter your valid Number"
label="Phone number:"
required="true"
size="30"
hint="EX:080-12345678"
validate="mobile"
/>
and i have created validation file in administrator\components\com_users\models\rules\mobile.php
code is :
<?php
defined('JPATH_BASE') or die;
jimport('joomla.form.formrule');
class JFormRuleMobile extends JFormRule
{
public function mobile(& $element, $value, $group = null, & $input = null, & $form = null)
{
return preg_match("/^\+{0,1}[0-9]{6,14}$/",$value);
}
}
?>
when i submit the form "Validation Rule missing: mobile" error is coming.
what is the problem . where i am doing mistakes
its very simple ...
just use joomla inbuilt rule called "tel" .its very good for validate the phone number
more info joomla document about this
You need to enable the behaviour of validate on your form.
Add form-validate class to your form as well.
you have different classes:-
required
validate-username
validate-password
validate-numeric
validate-email
validate-[custom] -> custom defined
Use this link for Joomla
Or you can easily validate the form using jQuery or HTML's required attribte and pattern attribute.

Add new field in bundle item option in admin section

I am new bie in magento.I am creating a bundle product from admin section .when I add the bundle item there is only the title field for information but I need to add one more field for the description like I created a bundle item for computers but I need to show description about it .
Please help .my requirement is to add new field for description along with the title in bundle item option.
any help will be appreciated .
you can add extra field to magento bundle products by editing app\design\adminhtml\default\default\template\catalog\product\edit\options\type\select.phtml and few database changes.
EDIT:
first we have to add our custom field to catalog_product_option_type_value table in the database, using a instraller script
<?php
/* #var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->getConnection()
->addColumn($installer->getTable('catalog/product_option_type_value'), 'your_custom_field_name’, 'VARCHAR(128) NULL');
$installer->endSetup();
then copy the file in location app\design\adminhtml\default\default\template\catalog\product\edit\options\type\select.phtml
to app\design\adminhtml\default\default\template\companyname\catalog\product\edit\options\type\select.phtml. override the core file
Rewrite: ‘Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Select’ block and replace constructor file in it by indicating our phtml file
public function __construct()
{
parent::__construct();
$this->setTemplate('companyname/catalog/product/edit/options/type/select.phtml');
$this->setCanEditPrice(true);
$this->setCanReadPrice(true);
}
open companyname/catalog/product/edit/options/type/select.phtml ile in OptionTemplateSelect varilable in tag we add the line: under 'sort order' field
'<th class="type-title"><?php echo Mage::helper('catalog')->__('your_custom_field_name') ?></th>'+
Add OptionTemplateSelectRow tag to the variable:
'<td><input type="text" class="input-text select-type-details" id="product_option_{{id}}_select_{{select_id}}_title" name="product[options][{{id}}][values][{{select_id}}][your_custom_field_name]" value="{{your_custom_field_name}}">{{checkboxScopeTitle}}</td>'+
now check in backend you should see the custom field by now. to make it required you can add required-entry class to above input field
now for retrieve values from database re-write the block:
Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Option
In: 'getOptionValues()' method, cycle: foreach ($option->getValues() as $_value) {
add new key: 'your_custom_field_name' to the variable: $value and the value for it: $_value->getYourCustomField();
now custom field will appear in database
In order for the new attribute to appear on the frontend rewrite the class: Mage_Catalog_Block_Product_View_Options_Type_Select and add the newly added attribute to it. But be aware that depending on the type of Custom Options there different kinds of htmls generate.
please refer this article for more details

Where to define a filter function for a form field in my Joomla component's preferences

I am creating a component in Joomla 2.5. This component has some options that are defined in its config.xml, so they can be set in the preferences of the component. Now I would like to apply a filter to one of these option fields, using the attribute filter="my_filter".
In the source code of JForm I saw the following lines at the very end of the implementation of JForm::filterField():
if (strpos($filter, '::') !== false && is_callable(explode('::', $filter)))
{
$return = call_user_func(explode('::', $filter), $value);
}
elseif (function_exists($filter))
{
$return = call_user_func($filter, $value);
}
That's what I needed for using a filter function defined by myself!
I managed to do this for form fields used in the views of my component. I defined the filter function as MyComponentHelper::my_filter(), where MyComponentHelper is a helper class which I always load in the very base of my component. And in the form's xml I added filter="MyComponentHelper::my_filter" to the fields that have to be filtered. However... when I am trying to apply the filter function to a form field in my component's preferences, I am not in my own component, but in com_config instead, so my helper class is not available!
So, therefore, my question: where to define my own filter function in such a way that it can be found and called by JForm::filterField() in com_config?? Help is very much appreciated.
May be it is too late, but this topic is only I found about that trouble. May be my solution will be helpfull to someone.
1) Add to tag of .xml form file the attribute 'addfieldpath' like this:
<fieldset name="basic" addfieldpath="PATH_TO_MY_EXTENSION/models/fields">
2) Modify filtered field description like this:
<field
name="MY_FIELD_NAME"
type="myfildtype"
label="MY_FIELD_LABEL"
description="MY_FIELD_DESC"
filter="JFormFieldMyFieldType::filter"
/>
3) Create the file 'PATH_TO_MY_EXTENSION/models/fields/myfildtype.php':
<?php
defined('JPATH_PLATFORM') or die;
JFormHelper::loadFieldClass('text'); // or other standard Joomla! field type
class JFormFieldMyFieldType extends JFormFieldText // or other standard Joomla! field type class
{
protected $type = 'MyFieldType';
public static function filter($value)
{
// filter code
return $value;
}
}
I had to deal with the same issue today. Here is what I did.
Our form field looks like this:
<field name="verwaltungskosten" type="text" class="form-control" size="40" label="Verwaltungskosten" labelclass="col-sm-2
compojoom-control-label"
filter="MyComponentFilterDouble::filter" required="true"/>
As you can see we have a filter. We've specified
MyComponentFilterDouble as class and filter as a method of this class.
If you have a look at libraries/joomla/form/form.php in the
FilterField function toward the end you'll see that the code will try
to execute our custom filter. Now here comes the tricky part. How does
Joomla know where our filters are located? Well, it doesn't! We have
to load our filters in advance. JForm doesn't come with a utility
class that could load a custom filter. I've decided to load our
Filters in our model in the getForm function. As you know each model
that extends from JModelAdmin should have a getForm function. This
function makes sure that we are loading the correct form from a .xml
file. So in this function just before I load the form I did:
JLoader::discover('MyComponentFilter', JPATH_ADMINISTRATOR . '/components/com_mycomponent/models/forms/filters');
The discover method will make sure to auto load our class when we need
it. This way it will be available to our form.
And there we go! Now when our model validates the form. It actually
always first performs filtering on the data. Now in our custom filter
we can modify the data and pass it back for validation. It's that
easy!
The above text is in quotes because I took it from my blogpost about that same issue over here: https://compojoom.com/blog/entry/custom-filtering-for-jform-fields
I think what you're asking about is actually adding custom validation to one of your form fields. If that's the case you actually need to be looking at adding server-side validation in addition to adding configuration. Pay particular attention to the 'addrulepath' in the example under the heading "Using configuration parameters as default value". You'll most likely end up extending JFormRule, of which I've included a very stripped-down example below.
<?php
/** headers */
defined('JPATH_PLATFORM') or die; // Joomla only
class JFormRuleCustom extends JFormRule
{
public $type = 'Custom';
public function test(&$element, $value, $group = null, &$input = null, &$form = null) {
return /* true for passed validation, false for failed validation */
}
}
When you've got that down you can add the validation "custom" to your form fields like so:
<field
name="pw1"
type="password"
label="COM_NEWUSER_UPDATE_LABEL_PASSWORD1"
description="COM_NEWUSER_UPDATE_DESCRIPTION_PASSWORD1"
message="COM_NEWUSER_UPDATE_ERROR_PASSWORD1"
size="40"
required="true"
validate="custom"
minlength="5"
maxlength="20"
specials="!##$%^&*"
/>
Hopefully that answers your question and didn't go totally off-topic.

Joomla editor strips tags

I'm trying to create a custom component in Joomla 2.5 and struggling to get it to stop it stripping all html tags out of the editor field - links, new lines, p tags - the full works. The form field is below:
<field
name="post"
type="editor"
label="COM_HELLO_WORLD_EDITOR_LABEL"
description="COM_HELLO_WORLD_EDITOR_DESC"
class="inputbox"
filter="JComponentHelper::filterText"
required="true"
default=""
/>
Clearly there are many many posts about this around both SO and Joomla forums. However they generally seem to have two clear themes.
Tiny MCE Settings. I've checked after setting my default editor to "None" (i.e. just a text area) and the tags are all still stripped
Joomla Text filter settings. I'm logged in as a Global Admin with the super users set to "no filtering"
I'm overriding the model's save function for this with:
function store()
{
$row =& $this->getTable();
$input = new JInput();
$data = $input->getArray($_POST);
//Sets Users id as current logged in user if not set
if(!$data['jform']['post_user']) {
$data['jform']['post_user']=JFactory::getUser()->id;
}
// Bind the form fields to the post table
if (!$row->bind($data['jform'])) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Make sure the hello is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the hello table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
My gut instinct is that it's to do with JInput stripping HTML tags. But even adding in the extra line into the save file $data['jform']['post']=$input->getHTML('post'); nothing happened. So I'm not really sure where to go from here. Any ideas?
UPDATE
Just to clarify an issue quickly - I want to use the preset Joomla 'Text Filter' Settings under 'Global Configuration' rather than manually setting each tag in the component!
UPDATE 2
I added filter="raw" to the editor form field. I now see the html <p> tags when I dump out the variable $_POST['jform']['post'], null, 'HTML'). However then when applying just a simple JInput Filter function - let alone applying the Joomla Config values - I'm getting null.
$input = new JInput();
$data = $input->getArray($_POST);
$data['jform']['post']=$input->get($_POST['jform']['post'], null, 'HTML');
Is the sentence here "HTML - Returns a string with HTML entities and tags intact, subject to the white or black lists in the filter." describing the JInput HTML filter referring to the Global Config Text filter settings? Just to confirm?
Try something like this
$input_options = JFilterInput::getInstance(
array(
'img','p','a','u','i','b','strong','span','div','ul','li','ol','h1','h2','h3','h4','h5',
'table','tr','td','th','tbody','theader','tfooter','br'
),
array(
'src','width','height','alt','style','href','rel','target','align','valign','border','cellpading',
'cellspacing','title','id','class'
)
);
$postData = new JInput($_POST,array('filter' => $input_options));
First array it is allowed tags, second array it is allowed attributes.
What is this about? filter="JComponentHelper::filterText"? Did you write a custom filter?
The default filtering like most things in Joomla (also acl for example) is very strict so that if you get xss from not filtering it's a deliberate choice you've made not a security risk in the core. But your core filtering should be being applied ... except that you seem to have perhaps overridden with the unknown filter. So I suspect given this unknown filter it's falling back to very string.
Quite some time later, but just for the record, for anyone encountering the same problem, here my solution.
For me this problem was immediately solved by using JRequest instead of JInput. I believe it's deprecated, but it is still used by Joomla 2.5.14 (most up-to-date Joomla 2.5 at this moment) in the save() function of JControllerForm.

Resources