I'm developing simple module for prestashop.in my admin controller i have input text called username.i want user to enter his user name without space.
what i tried
i have added below code in to Validate.php and tried to access it from Module class.but its not working.
Validate.php
public static function checkWhiteSpace($var){
return preg_match('/\s/',$var);
}
Model class
class User extends ObjectModel
{
public $id_user;
public $username;
public static $definition = array(
'table' => 'Users',
'primary' => 'id_user',
'multilang' => false,
'fields' => array(
'username' => array(
'type' => self::TYPE_STRING,
'required' => true,
'validate' => 'checkWhiteSpace',
),
),
);
}
Try to invert your result from Validate. Because when your field is invalid it shows true and opposite when valid. So try this
public static function checkWhiteSpace($var){
return !preg_match('/\s/',$var);
}
It should work within your Model class, you don't need to change Validate.php.
Related
I have a Zend\Form\Form for one of my entities that uses the DoctrineModule\Form\Element\ObjectSelect element to enable the user to select a referenced entity.
class MyEntityForm extends Zend\Form\Form
{
public function __construct()
{
// ...
$this->add([
'name' => 'referenced_entity',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => [
'object_manager' => $object_manager,
'target_class' => 'MyOtherEntity',
'property' => 'id',
'display_empty_item' => true
],
]);
// ...
}
}
The referenced entity may be empty (= the foreign key field in the database can be NULL). I just can't get the form to validate if no referenced entity has been selected. I would like my form to validate even if the given referenced_entity is empty (null or "") or not present at all (key referenced_entity missing from the data array).
I tried a variety of different input filter specifications, the last setup looked as follows
class MyEntityForm
extends Zend\Form\Form
implements Zend\InputFilter\InputProviderInterface
{
// ...
public function getInputSpecification()
{
return [
// ...
'referenced_entity' => [
'required' => false,
'allow_empty' => true,
'continue_if_empty' => false
],
// ...
}
// ...
}
But to no avail, the validation error stays the same (excerpt of var_dump of $form->getMessages() after $form->isValid())
'referenced_entity' =>
array (size=1)
'isEmpty' => string 'Value is required and can't be empty' (length=36)
Do I have to extend the ObjectSelect form element to change its input filter specification and remove the isEmpty validator or is there an easier solution?
If I remember well, if you want to provide input filter configuration into your Form class, then you must implement the InputFilterProviderInterface interface.
If you want to configure it at the element level then your Element class must implement the InputProviderInterface interface
So it would mean that your form class has to be like that:
class MyEntityForm
extends Zend\Form\Form
implements
// this...
// Zend\InputFilter\InputProviderInterface
// must be this!
Zend\InputFilter\InputFilterProviderInterface
{
// ...
public function getInputFilterSpecification()
{
return [
// ...
'referenced_entity' => [
'required' => false,
'validators' => [],
'filters' => [],
],
// ...
}
// ...
}
DoctrineModule\Form\Element\ObjectSelect inherits Zend\Form\Element\Select and it includes automaticatilly a input especification with a validator for itself.
I didn't test myself, but an way to solve this is remove this validator by adding 'disable_inarray_validator' key in options:
public function __construct()
{
// ...
$this->add([
'name' => 'referenced_entity',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => [
'object_manager' => $object_manager,
'target_class' => 'MyOtherEntity',
'property' => 'id',
'display_empty_item' => true,
'disable_inarray_validator' => true
],
]);
// ...
//or via method
$this->get('referenced_entity')->setDisableInArrayValidator(true);
}
I've created an admin module based off of the tutorial here. I'm attempting to change two of my form inputs to wysiwyg editors based off of information found here. However, whenever I load the edit page I get an error Call to a member function setCanLoadTinyMce() on a non-object. $this->getLayout()->getBlock('head') var_dumps to false.
Namespace/Slides/Block/Adminhtml/Slide/Edit.php looks as follows
class Namespace_Slides_Block_Adminhtml_Slide_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}
protected function _construct()
{
//... Construction stuff
}
}
Namespace/Slides/Block/Adminhtml/Slide/Edit/Form.php
class Cfw_Slides_Block_Adminhtml_Slide_Edit_Form
extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
//...Do some things first, like create the fieldset..
//Add the editable fields
$this->_addFieldsToFieldset($fieldset, array(
'foreground_image' => array(
'label' => $this->__('Foreground Image'),
'input' => 'image',
'required' => false,
),
'background_image' => array(
'label' => $this->__('Background Image'),
'input' => 'editor',
'required' => true,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
),
'description' => array(
'label' => $this->__('Text Overlay'),
'input' => 'editor',
'required' => false,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
)
));
return $this;
}
protected function _addFieldsToFieldset(
Varien_Data_Form_ElementFieldset $fieldset, $fields)
{
$requestData = new Varien_Object($this->getRequest()->getPost('slideData'));
foreach ($fields as $name => $_data) {
if ($requestValue = $requestData->getData($name)) {
$_data['value'] = $requestValue;
}
//Wrap all fields with slideData group
$_data['name'] = "slideData[$name]";
//Generally, label and title are always the same
$_data['title'] = $_data['label'];
//If no new value exists, use the existing slide data.
if (!array_key_exists('value', $_data)) {
$_data['value'] = $this->_getSlide()->getData($name);
}
//Finally, call vanilla funcctionality to add field.
$fieldset->addField($name, $_data['input'], $_data);
}
return $this;
}
}
I'm not sure if you need it, but here's my file structure as well
Namespace
-Slides
--Block
---Adminhtml
----Slide
-----Edit
------Form.php
-----Edit.php
-----Grid.php
----Slide.php
--controllers
---Adminhtml
----SlideConroller.php
--etc
---config.xml
--Helper
---Data.php
--Model
---Resource
----Slide
-----Collection.php
----Slide.php
---Slide.php
--sql
---namespace_slides_setup
----install-0.0.1.php
The issue is that Magento cannot find your head block.
Instead of using:
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
Try calling it like this:
Mage::app()->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
If that doesn't work, it's a different issue but the problem is still that Magento can't find the head block.
I imagine you no longer need a solution for this, but I ran into the same issue using the same tutorial that you did.
The 'head' block (and thus setCanLoadTinyMce()) was unavailable in the Edit.php and the Form.php via the _prepareLayout() function.
The 'head' block was available in the controller(SlideController.php in your case) between $this->loadLayout() and $this->renderLayout within the editAction() function.
In SlideController.php change
$this->loadLayout()
->_addContent($brandBlock)
->renderLayout();
to
$this->loadLayout() ;
$this->_addContent($brandBlock);
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
$this->renderLayout();
I'm using CakePHP 2.2.4, and I have started to work with Atuh Componenet.
This is my AppController:
class AppController extends Controller {
public $components = array('Auth', 'Session');
public function beforeFilter() {
$this->Auth->authorize = array('Controller');
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('User.active' => 1),
'fields' => array('username' => 'email', 'password' => 'password'),
)
);
}
public function isAuthorized($user) {
debug($user);
return true;
}
}
This is my User.php model
class User extends AppModel {
public $name = 'User';
/* Relazioni */
public $hasOne = 'Profile';
public $belongsTo = 'Role';
public $hasMany = array(
'Lead' => array(
'className' => 'Lead'
)
);
}
and this is my UserController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController
{
public $name = 'Users';
public $uses = array();
public function beforeFilter()
{
parent::beforeFilter();
}
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
debug('Logged');
}
else
{
$this->Session->setFlash('Login non autorizzato', 'default', array('class' => 'errore'), 'login');
}
}
}
public function logout()
{
$this->redirect($this->Auth->logout());
}
}
I have a strange problem using Auth Component, because at the end of the layout I have sql_dump element, that prints NO QUERY.
However, If i put correct values I do not login
Why does Auth component is not working ?
EDIT:
The data of the request is:
Array
(
[User] => Array
(
[email] => test#test.it
[pwd] => abc
)
)
Your code in AppController is wrong
public function beforeFilter() {
$this->Auth->authorize = array('Controller');
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('User.active' => 1),
// password != pwd as you post it
'fields' => array('username' => 'email', 'password' => 'password'),
)
);
}
Change it to
'fields' => array('username' => 'email', 'password' => 'pwd'),
or make sure to post password instead of pwd in your form
Please see https://github.com/cakephp/cakephp/blob/master/lib/Cake/Controller/Component/Auth/FormAuthenticate.php for documentation on the matter
I'd like to post-fix this answer for anyone arriving here, who is unable to get logged in using Auth for which this example does not DIRECTLY Apply.
An important thing to remember is that Auth is expecting the underlying database columns to be "username" and "password". If for whatever reason you defer from this, for example if you want to validate on a users email (very common) and you change the table's column name to reflect this, than you must tell Auth about this.
The reason is because the underlying query will fail. Ultimately all that's happening behind the scene is a simply query matching the specified fields. For example (not exact - simply for demonstration purposes -- select *'s are bad):
SELECT * FROM users WHERE username = 'blahblahblah' AND password = 'someInsan31yh4sh3dpassw0rd'
If your underlying table is missing a "username" column in loo of an "email" column, than this query will obviously fail. Resulting in the inability to login and usually with no indication that the query failed (it is even omitted from the SQL dump). The following code in your AppController however will solve you issues:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'columnUsedForValidatingUsername', 'password' => 'columnUserForValidatingPassword')
)
)
)
);
Jippi's answer was completely correct in this case. But I feel as though as an answerER on StackOverflow you owe it to anyone finding this to explain WHY the problem is occurring and provide an unspecific answer.
Cheers
I want to add a new form to the edit customer page, so far so good, using rewrites to customer_edit_tabs i was able to add a tab and my admin form to the page. Code looks like this.
protected function _beforeToHtml()
{
$this->addTab('extraoptions', array(
'label' => Mage::helper('customer')->__('Extra options'),
'class' => 'ajax',
'url' => $this->getUrl('module/adminhtml_tabs/info', array('_current' => true)),
));
This adds my tab corrently. From there the link on the tabs controller:
public function infoAction()
{
$this->_init();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('module/adminhtml_tabs_edit')->toHtml()
);;
}
This links to my form container on Block/Adminhtml/Tabs/Edit.php
class Namespace_Module_Block_Adminhtml_Tabs_Edit extends Mage_Adminhtml_Block_Widget_Form_Container{public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_mode = 'edit';
$this->_blockGroup = 'module';
$this->_controller = 'adminhtml_tabs';
$this->_updateButton('save', 'label', Mage::helper('module')->__('Save'));
}
public function getHeaderText()
{
return Mage::helper('module')->__('Extra Options');
}
}
My Block/Adminhtml/Tabs/Edit/Form.php
class Namespace_Module_Block_Adminhtml_Tabs_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
public function __construct()
{
parent::__construct();
}
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'info_form',
'action' => $this->getUrl('module/adminhtml_tabs/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$fieldset = $form->addFieldset('extra_options', array('legend' => Mage::helper('module')->__('Extra Options Fieldset')));
$fieldset2->addField('extra', 'text', array(
'name' => 'zip',
'title' => Mage::helper('module')->__('extra'),
'label' => Mage::helper('module')->__('extra data'),
'maxlength' => '250',
'required' => false,
));
$form->setUseContainer(true);
}
protected function _prepareLayout()
{
return parent::_prepareLayout();
}
Everything is fine, I have a new button below the default save customer buttons, but this save button does not update the action, so if i click it, it goes to the default customer/edit/save action, it does not tell me the method does not exist which it should. My guess is that there is something wrong with the container but i have tried three tutorials with little differences to no avail, hope someone can help and even maybe someone will find my code helpful.
In this line of code:
'action' => $this->getUrl('module/adminhtml_tabs/save')
You are telling Magento to look for a module named module, a controller aliased adminhtml_tabs, and a saveAction() method within that file.
You need to figure out where you want to send the user when a save needs to be performed, and then place it there (e.g. the route to your controller->saveAction() method).
I decided to create a new button to save with a custom action. On the container:
$this->_addButton('save', array(
'label' => Mage::helper('adminhtml')->__('Save Extras'),
'onclick' => 'document.myform.submit();',
'class' => 'save',
),-1,5);
This did the trick.
i try to program a LdapAuthentication and i need some help.
First i need to configure the "$components" in /app/Controller/
Component/AppController.php
<?php
class AppController extends Controller {
var $components = array('Auth' => array(
'Ldap',
'authError' => 'Not allowed here',
'authenticate' => array('Form' => array(
'fields' => array(
'username' => 'username',
'password' => 'password',
'domain' => 'domain'
)
)
),
'authorize' => true,
), 'Session');
}
?>
Then i create a LdapAuthorize.php like
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#creating-custom-authorize-objects
<?php
App::uses('BaseAuthorize', 'Controller/Component/Auth');
class LdapAuthorize extends BaseAuthorize {
public function authorize($user, CakeRequest $request) {
echo "test";
}
}
?>
But when i try to login with
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'),
'default', array(), 'auth');
}
cakephp doesn't use my authorize function.
What i do wrong? Please help.
Here is a working Ldap Auth class for 2.0.x
https://github.com/analogrithems/idbroker/tree/dev_cake2.0
with a blog post detailing it here:
http://www.analogrithems.com/rant/2012/01/03/cakephp-2-0-ldapauth/
** ALSO **
Your Auth configuration is wrong - the authorize key takes a string or array - a boolean true isn't going to do anything.
If you want it to check an isAuthorized action in the controller - set it like so:
<?php
...
public $components = array( 'Auth' => array(
...
'authorize' => array( 'Controller' ),
...
));
?>
You are passing a boolean parameter here, and have no isAuthorized function in your AppController. Also, you are using old php4 syntax to declare your member variables (use public, protected or private instead of "var")