After adding new column "name" to user table in yii2 advanced, data not getting saved in it - yii2-advanced-app

After assigning all required values to user model (column which i have added also). When I am using $model->save() data for all default attributes getting saved except the one I have added. I trying insert via REST call. If there is any other way to do please let me know. I have also followed this link https://github.com/dektrium/yii2-user/blob/master/docs/adding-new-field-to-user-model.md which is of no use.
this is my rules method in users model
public function rules()
{
return [
[['username', 'email'], 'filter', 'filter' => 'trim'],
[['username', 'email', 'status','name'], 'required'],
['email', 'email'],
['username', 'string', 'min' => 2, 'max' => 255],
// password field is required on 'create' scenario
['password', 'required', 'on' => 'create'],
// use passwordStrengthRule() method to determine password strength
$this->passwordStrengthRule(),
['username', 'unique', 'message' => 'This username has already been taken.'],
['email', 'unique', 'message' => 'This email address has already been taken.'],
];
}
Thank you.

User model which I was using extended from UserIdentity So I have added rules method in UserIdentity class but after adding new column to users table, that column should be specified in rules method of users model only which ever it might be extending. Previously there was no need of adding like this till Yii v2.1.0 may be in Yii 2.2.0 it has to be.

Related

Laminas / ZF3: Add manually Error to a field

is it possible to add manually an Error Message to a Field after Field Validation and Input Filter ?
I would need it in case the Username and Password is wrong, to mark these Fields / Display the Error Messages.
obviously in ZF/ZF2 it was possible with $form->getElement('password')->addErrorMessage('The Entered Password is not Correct'); - but this doesnt work anymore in ZF3/Laminas
Without knowing how you do your validation (there are a few methods, actually), the cleanest solution is to set the error message while creating the inputFilter (and not to set it to the element after it has been added to the form).
Keep in mind that form configuration (elements, hydrators, filters, validators, messages) should be set on form creation and not in its usage.
Here the form is extended (with its inputfilter), as shown in the documentation:
use Laminas\Form\Form;
use Laminas\Form\Element;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
class Password extends Form implements InputFilterProviderInterface {
public function __construct($name = null, $options = []) {
parent::__construct($name, $options);
}
public function init() {
parent::init();
$this->add([
'name' => 'password',
'type' => Element\Password::class,
'options' => [
'label' => 'Password',
]
]);
}
public function getInputFilterSpecification() {
$inputFilter[] = [
'name' => 'password',
'required' => true,
'validators' => [
[
'name' => NotEmpty::class,
'options' => [
// Here you define your custom messages
'messages' => [
// You must specify which validator error messageyou are overriding
NotEmpty::IS_EMPTY => 'Hey, you forgot to type your password!'
]
]
]
]
];
return $inputFilter;
}
}
There are other way to create the form, but the solution is the same.
I also suggest you to take a look at the laminas-validator's documentation, you'll find a lot of useful informations
The Laminas\Form\Element class has a method named setMessages() which expects an array as parameter, for example
$form->get('password')
->setMessages(['The Entered Password is not Correct']);
Note that this will clear all error messages your element may already have. If you want to add your messages as in the old addErrorMessage() method you can do like so:
$myMessages = [
'The Entered Password is not Correct',
'..maybe a 2nd custom message'
];
$allMessages = array_merge(
$form->get('password')->getMessages(),
$myMessages);
$form
->get('password')
->setMessages($allMessages);
You can also use the error-template-name Laminas uses for its error messages as key in your messages-array to override a specific error message:
$myMessages = [
'notSame' => 'The Entered Password is not Correct'
];

Set unique rule to a field on update action on yii2 rest

I am creating a rest api with yii2 to create and update user information. Below is the rule function in the model class.
public function rules()
{
return [
[['name', 'emailId', 'contactNumber'], 'required'],
[['name', 'emailId', 'contactNumber'], 'string', 'max' => 255]
[['emailId', 'username', 'contactNumber'], 'unique'],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]]
];
}
Here I mentioned emailId, username, contactNumber fields should be unique. When I try to create, it is checking whether the field is unique or not. if unique it is throwing the error else it is saving. That is fine.
But when I try to update the value there also it is checking the particular value for the field is unique or not. But it should not be like that. The unique validation should not work on update action. So I updated the rule with 'on'=>'update' as like Yii 1. Check the below function.
public function rules()
{
return [
[['name', 'emailId', 'contactNumber'], 'required'],
[['name', 'emailId', 'contactNumber'], 'string', 'max' => 255]
[['emailId', 'username', 'contactNumber'], 'unique', 'on'=>'update'],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]]
];
}
But when i check the official documentation there is no option like on to check the particular action. When i use 'on'=>'update', both(while creating and update) places it is not validating. Might be because of the on. Just leave that. I need to add unique validation for those fields in create action only not in update action.
So, Please anybody help me with how to add unique validation to those fields only in create action.
Thanks.
You can set scenario for your REST actions in your ActiveController:
public function actions()
{
$actions = parent::actions();
$actions['update']['scenario'] = 'update';
$actions['create']['scenario'] = 'create';
return $actions;
}
And then use it in rules:
[['emailId', 'username', 'contactNumber'], 'unique', 'on'=>'create']
Also you must specify list of active attributes for each scenario in the particular model class:
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['update'] = ['type', 'title', 'description'];
$scenarios['create'] = ['type', 'title', 'description', 'affiliate_id'];
return $scenarios;
}

Adding new fields to Admin User Info in magento

By default when you try to add a new User in magento, it accepts only the following fields:
Username, FirstName, LastName, Email, New Password and Password Confirmation.
I want to add some more field here, e.g. About Me, PhoneNumber, etc where we will add additional information about this role specific users we add to magento.
Has anyone already done this? How should I go about doing this?
I know additional fields will need to be created in the database. The adminhtml userinfo.phtml doesn't mention fields like Username, FirstName etc, so where it is picking it up from?
Please advice.
Thanks,
Neet
You can start with following tutorial to create registration field
http://www.magentocommerce.com/wiki/5_-_modules_and_development/customers_and_accounts/registration_fields
a) Adding new fields to Admin User Info in magento
b) Adding new fields to Admin User Info in Magento
You will need to add a column to the admin_user table. Make a table with the following code:
<?php
$installer->getConnection()->addColumn($installer->getTable('admin/user'),
'location', array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'length' => 256,
'nullable' => true,
'default' => null
));
?>
Then, if you want to add/edit this field from the backend you need to
rewrite the method Mage_Adminhtml_Block_System_Account_Edit_Form::_prepareForm and add a new
element in there:
<?php
$fieldset->addField('location', 'select', array(
'name' => 'location',
'label' => Mage::helper('adminhtml')->__('Location'),
'id' => 'location',
'title' => Mage::helper('adminhtml')->__('Location'),
'class' => 'input-select',
'style' => 'width: 80px',
'options' => array('1' =>
Mage::helper('adminhtml')->__('Russia'), '0' =>
Mage::helper('adminhtml')->__('India')),
));
?>
Clear the cache and run the code. You can add new fields to Admin User Info in Magento.

Duplicate Validation on Combined Fields in zend form

Hi there I have a table in which combination of three fields is unique. I want to put the check of duplication on this combination. Table looks like
I know how to validate single field, But how to validate the combination is not know. To validate one field I use the following function
public function isValid($data) {
// Options for name field validation
$options = array(
'adapter' => Zend_Db_Table::getDefaultAdapter(),
'table' => 'currencies',
'field' => 'name',
'message'=> ('this currency name already exists in our DB'),
);
// Exclude if a id is given (edit action)
if (isset($data['id'])) {
$options['exclude'] = array('field' => 'id', 'value' => $data['id']);
}
// Validate that name is not already in use
$this->getElement('name')
->addValidator('Db_NoRecordExists', false, $options
);
return parent::isValid($data);
}
Will any body guide me how can I validate duplication on combined fields?
There is no ready to use validator for this, as far as I know. You have either to write your own, or do a check with SQL-query with three conditions (one for each field).
you have to Apply a validation on name element of zend form.
Here is code for add validation on name field.
$name->addValidator(
'Db_NoRecordExists',
true,
array(
'table' => 'currencies',
'field' => 'name',
'messages' => array( "recordFound" => "This Currency Name already exists in our DB") ,
)
);
And you must set required true.

Customize errors symfony

There are some "best practice" in Symfony to customize form errors?
For exemple, if i would to show "Campo obligatorio" when the field is required.
1)How can i do that better way and independent from what forms call it?
2)How can i customize message 'An object with the same "%namefield" already exist.' ?
Thanks
updated
sorry, but if i try to do 'invalid' how you said me... it print me the same error
$this->setValidator('urlres', new sfValidatorString(array(
'min_length' => 6,
), array(
'min_length' => 'URL must be longer',
'required' => 'Required field',
'invalid' => 'URL exist'
)));
prints me:
* An object with the same "urlres" already exist.
updated
Felix, your solution is fantastic but it prints me this error:
"urlres: that url already exists"
Are there some way to delete "field:" ??
Thanks
Maybe this form post helps you:
Put the code
sfValidatorBase::setDefaultMessage('required', 'Field required');
in the "configure" of you application configuration apps/youApp/config/yourAppConfiguration.class.php.
You should be able to set the default value for every error message type this way.
If you want to set certain error messages for certain fields, think about to create a form class that defines all this and let all other forms inherit from this one.
The subclasses then only specify which fields should be displayed (and maybe custom validation logic).
You can find an example how to do this in the Admin Generator chapter of the symfony book.
This is the cleanest approach IMHO.
Edit:
If you want leave fields blank, you have to add the required => false option:
'email' => new sfValidatorEmail(array('required' => false))
Regarding the error message: This sounds like the urlres is marked as unique in the database table and the value already exists. Maybe you should check the database schema definition.
Edit 2:
To test both, length and uniqueness, you should use sfValidatorAnd and sfValidatorDoctrineUnique:
$this->setValidator('urlres', new sfValidatorAnd(
array(
new sfValidatorString(
array( 'min_length' => 6, ),
array( 'required' => 'Required field',
'min_length' => 'URL must be at least %min_length% chars long.' )
),
new sfValidatorDoctrineUnique(
array( 'model' => 'yourModel',
'column' => 'theColumn',
'primary_key' => 'thePrimaryKeyColumn',
'throw_global_error' => false),
array('invalid' => "That URL already exists")
)
));
Also your use of the invalid error code in the string validator is not correct. You set the invalid message to
URL exists but how can a string validator know this? It only checks whether the given string meets the min_length, max_length criteria or not.
Btw I assumed that you use Doctrine but I think the same validators are available for Propel.
Edit 3:
Set the option 'throw_global_error' => false. But I am not sure if that works.
You can also have a look at the source code if it helps you.
Let me try to help you.
You can easily customize standard form errors in configure method of your form class. Here is an example:
1)
<?php
class myForm extends BaseMyForm
public function configure(){
parent::configure();
$this->setValidator(
'my_field' => new sfValidatorString(
array('min_length'=>3, 'max_length'=>32, 'required'=>true),
array('required' => 'Hey, this field is required!')
)
);
}
2) Just change a message that has a code 'invalid'.
All you need is just find a valid message code to customize particular default messages. More info - Symfony Forms in Action: Chapter 2 - Form Validation
Updated:
And if you don't want to customize error messages in all your form classes, just create your own base validator class:
abstract class myBaseValidator extends sfValidatorBase
and there redefine default 'required' and 'invalid' messages.
Are there some way to delete "field:"
??
Yes: throw_global_error => true