Disabling validation for specific form (user login) - validation

The problem
I have a login form available on every page (in the right menu). The problem is that when the user is on the register page, the fields from the login form are validated. I have username and password fields in both forms, and both are validated.
Ideas:
Different field names for registration form (register_username, register_password, register_email) and then set normal names before saving.
Different model (but albo using the users table) for login form?
Anyway, I just wonder what is the best way to solve this.

I'm guessing that both forms would submit to different actions, with the registration form submitting to Users->register() and the login form submitting to Users->login().
I would suggest that when you're in the register() action, you could try copying the relevant variable into another associative array and then validating and saving that, rather than validating and saving the $this->data variable.

Your second option is correct. I had encountered this problem before and wrote an article about it at the Bakery: Multiple Forms per page for the same model
The basic idea is to create separate models for each form extending the original model:
class RegisterForm extends User {
}
Then, load these forms in your controller however you please:
$this->loadModel('RegisterForm');
Then call validation as usual:
$this->RegisterForm->save($this->data);
For your particular case, you might not want to create the LoginForm model, and have only the RegisterForm model. This will let you take advantage of whatever magic the AuthComponent has.
HTH.

I haven't tried two forms with the same inputs, but this works for two forms with different inputs. I don't see why it shouldn't work for your needs.
View:
Make sure each submit button has a name value so that $this->params can identify it.
//first form ...
<?php
$profile_options = array('label' => 'edit profile',
'name' => 'form1');
echo $this->Form->end($profile_options);
?>
//second form ...
<?php
$password_options = array('label' => 'edit password',
'name' => 'form2');
echo $this->Form->end($password_options);
?>
Controller action:
Use $this->params to test for each form submission
if(isset($this->params['form']['form1'])){
$this->User->set($this->data); //necessary to specify validation rules
if($this->User->validates(array('fieldList' => array('email')))){
$this->User->saveField('email', $this->data['User']['email']);
}
}
elseif(isset($this->params['form']['form2'])){
//same deal for second form
}

It may be desirable to validate your model only using a subset of the validations specified in your model. For example say you had a User model with fields for first_name, last_name, email and password. In this instance when creating or editing a user you would want to validate all 4 field rules. Yet when a user logs in you would validate just email and password rules. To do this you can pass an options array specifying the fields to validate:
if ($this->User->validates(array('fieldList' => array('email', 'password')))) {
// valid
} else {
// invalid
}

Related

Customized validation rule on laravel form request validation

I do have a registration form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.
The user input fields in the form are 'quantity', 'rate' and 'discount'.
The populated fields are 'total' and 'bill_amount'.
What i need to validate are :
Check 'total' equal to 'quantity' * 'rate'.
Check 'bill_amount' equal to 'total' - 'rate'
I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.
In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)
Thanks in advance!
After a long time I was able to find this solution.
Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]
public function withValidator($validator)
{
$quanty = $this->request->get("quantity");
$rate = $this->request->get("rate");
$billAmount = $this->request->get("bill_amount");
$validator->after(function ($validator) {
if(($quanty * $rate) != $billAmount) {
$validator->errors()->add('bill_amount', 'Something went wrong with this field!');
}
});
}

Custom Magento Module

So im creating a module in the backend, I have a shell module created (items in admin top menu and a page to visit.) basically I want to have an input field that the admin can type a number into then click a button "add", this will insert a row into an existing table in the database.
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->beginTransaction();
$fields = array();
$fields['name']= 'andy';
$connection->insert('test', $fields);
$connection->commit();
I have a table called "test" within my database. If I put the above code into my Controller file, it successfully adds a row to the database when i visit the admin page. But i need to allow the user to input the data that is inserted.
Would I have to move that code into the Model and somehow send the input data to the Model and let that do the work? or not. If this is correct could someone point me to a good place to research sending data to models? (if thats even possible)
iv tried lots of tutorials but they are all way to big for what I need, I dont need to display anything, I just need to have an input box and a save button.
EDIT
i have created a file block/Adminhtml/Form/Edit/Form.php which contains the following . . .
class AndyBram_Presbo_Block_Adminhtml_Form_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(
array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/test'),
'method' => 'post',
)
);
$form->setUseContainer(true);
$this->setForm($form);
$fieldset = $form->addFieldset('display', array(
'legend' => 'Display Settings',
'class' => 'fieldset-wide'
));
$fieldset->addField('label', 'text', array(
'name' => 'label',
'label' => 'Label',
));
if (Mage::registry('andybram_presbo')) {
$form->setValues(Mage::registry('andybram_presbo')->getData());
}
return parent::_prepareForm();
}
}
then in my controller i have 2 functions like below . . .
public function indexAction()
{
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('presbo/adminhtml_form_edit_form'));
}
public function testAction()
{
echo 'form data here';
$this->loadLayout();
$this->renderLayout();
}
the form is displayed successfully but there is no button to send or say 'do an action'
Further Edit
i have successfully added a submit button to the form that successfully goes to the testAction and echo' "form data here".
how do i then access the data,
iv added the below line
$postData = $this->getRequest()->getPost();
now if i echo $postData, it just puts "array"
if i echo $postData[0] it doesnt put anything just a blank page
any ideas or pointers?
Magento is built as an MVC framework, thus you're right - you need to pass data from controller to the model, and do not do any DB updates directly in a controller's code. The best source for an example is the own Magento code - you can take any controller action, which saves data to DB to see, how it is done. E.g. check app/code/core/Mage/Adminhtml/controllers/NotificationController.php method markAsReadAction().
There you can see, that:
Data is retrieved from the request by calling
$this->getRequest()->getParam('id') - actually this is the answer
to the question, how to get the submitted data
Data is set to model, and then saved to the DB via call to the
$model->setIsRead(1)->save()
It is strongly encouraged to follow the same approach of working with models. This makes codes much better and easier to support.
Note, that "M" letter of "MVC" architecture in Magento is represented by two layers: Models and Resource Models.
Models:
Contain business logic of an entity. E.g. adding ten items to a
Shopping Cart model triggers a discount rule
Represented by classes with a general name of <Your_Module>_Model_<Model_Name>
If need to work with DB, then extend Mage_Core_Model_Abstract and have a Resource
Model, which is responsible for DB communication
Do not need to have basic save/load methods to be implemented, as the ancestor
Mage_Core_Model_Abstract already has all that routines ready to use
Created via call to Mage::getModel('<your_module>/<model_name>')
Resource Models:
Serve as DB abstraction layer, thus save/load data from DB, perform
other DB queries
Extend Mage_Core_Model_Resource_Db_Abstract in order to communicate with DB
Represented by classes with a general name of
<Your_Module>_Model_Resource_<Model_Name>
Automatically created by a corresponding model, when it needs to communicate with DB
So, in a controller you care about creating Models only. Resource Models are created by a Model automatically.
And, according to everything said above, your controller should look like:
public function testAction()
{
$model = Mage::getModel('your_module/your_model');
$model->setName('andy');
$model->save();
}
You can download a fully working example of the thing you need here.
There can be several variations to the code provided, depending on your specific case. But it represents a general approach to implementing the thing you want.

username availability in Yii framework using ajax

the scenario is i have a form in my Yii project that will take the username as input and sends the user a mail containing activation link if he has not received one. the form name is ResendActivationLinkForm which extends the CFormModel class. now at the submission time i wanna check if the username exists or not in the database using AJAX...How to use yii's own classes and functions to accomplish that?
well thanks for replies..but i got it in a simpler fashion.
i just added an array inside the form model ResendActivationLinkForm depicting my rule.. eg..
public function run(){
return array(
.....
.....
array('username','exist','className'=>'User'),
);
}
where username is my attributeName, exist is the validator alias and className is the Model class name whose attribute it should look for...
you can look at http://www.yiiframework.com/wiki/56/ for more details. :) Happy Coding. :)
If Usermodel is the model that has a username attribute, you can do something like this.
if(Usermodel::model()->findByAttributes(
array(),
'username = :inputtedUsername',
array(':inputtedUsername' => $_POST['username'],)))
{
//user found
}else{
//user not found
}
For more information about the various CActiveRecord methods check the website
I'd extend the form model with a custom validator, such as array('username','UsernameExistsValidator'). This validator class should extend CValidator and implement public function validateAttribute($object,$attribute) which can use $this->addError() to flag if the username is not available. See the source for other Yii validators if you need some more input on the bits in there.
The logic from the answer above would fit into validateAttribute,

Codeigniter Grocery Crud update field?

$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
$crud->callback_edit_field('user_password',array($this,'_user_edit'));
$crud->callback_add_field('user_password',array($this,'_user_edit'));
callback function:
function _user_edit(){
return '<input type="password" name="user_password"/> Confirmation password* : <input type="password" name="konfirmpass"/>';
}
My question is how to update if only "password" not blank?
I've installed CI 2.0.3 and GC 1.1.4 to test because at a glance your code looked fine. As it turns out, it is and your code works. I modified the out of the box employees_management method in the examples controller with GC. Added a user_password column to the database and added your code to the controller.
The code both ensures that the password fields match and that they're not empty when submit.
Empty results in "The Password field is required"
Mismatched results in "The Password field does not match the konfirmpass field."
Perhaps if this isn't working for you, you should post your entire method instead of just the rules and callbacks so we can see if there are any other problems.
Edit
To edit the field, only if the password has been edited you need to add
$crud->callback_before_update( array( $this,'update_password' ) );
function update_password( $post ) {
if( empty( $post['user_password'] ) ) {
unset($post['user_password'], $post['konfirmpass']);
}
return $post;
}
This however may mean that you need to remove the validation for empty password depending on which order the callbacks run (if they're before or after the form validation runs). If they run before the form validation, you'll need to also need to run a call to callback_before_insert() and add your validation rules within the two callbacks. Insert obviously will need the required rule, and update won't.
Edit 2, Clarification of Edit 1
Having looked into it, the validation runs before the callbacks, so you can't set validation rules in the callback functions. To achieve this you'll need to use a function called getState() which allows you to add logic based on the action being performed by the CRUD.
In this case, we only want to make the password field required when we are adding a row, and not required when updating.
So in addition to the above callback update_password(), you will need to wrap your form validation rules in a state check.
if( $crud->getState() == 'insert_validation' ) {
$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
}
This will add the validation options if the CRUD is inserting.

CakePHP validation error messages - how to pass them around?

Please note: I'm not trying to do this anymore, because I found an alternative, but it may be useful in the future to know the answer.
I have a form that is in a view (index.ctp) associated with the index() action on a controller. That form should post data to another action, contact(), in the same controller. This second action doesn't have a view, it's just to process the information and redirect the user according to the outcome. This action is doing the validation and redirecting the user to the referer (index in this case) in case of an error, and then the error should be displayed in index. Note that the model doesn't use a database table, but it's used only to define validation rules.
The validation is taking place correctly and reporting the expected errors. In order to retrieve the errors after the redirect, it writes the $this->ModelName->invalidFields() array to a session variable that is retrieved on the index() action after the redirection.
This array is passed on to the $errors variable to the view. Now comes the problem. The errors, although being passed correctly between redirects, aren't getting attached to the respective forms. How can I accomplish this? The form has all the conventional names, so it should be automatic, but it isn't.
Here's part of the relevant code:
Index view:
echo $this->Form->create('Contact', array('url' => '/contacts/contact'));
echo (rest of form) ...
echo $this->Form->end(__('send message', true));
Contacts controller:
function index() {
if ($this->Session->check('Contact.errors')) {
$this->set('errors', $this->Session->read('Contact.errors'));
}
}
function contact() {
if (!empty($this->data)) {
$this->Contact->set($this->data);
if ($this->Contact->validates()) {
(send the email)
}
else {
$this->Session->write('Contact.errors', $this->Contact->invalidFields());
$this->redirect($this->referer);
}
}
}
I don't think it's a good idea to write the validation errors in a session variable. I'm no CakePHP expert, but I don't think that's the way you are supposed to do it. All your forms should point to the same url you are on, so the data that the user has entered will not be lost.
Could you add some code to your question?

Resources