Validate Yii2 Activeform on simple button click - php

I want to validate my Yii2 activeform on simple button click which is not submitButton. I tried $('#formId').yiiActiveForm("validate") but it is not working.
I also tried - $('#formId').yiiActiveForm('submitForm') it validates form but it also submit it if everything is ok. I don't want to submit that form. I just want to validate it on button click and if everything is ok than i want to open a modal popup.
What are possible ways to validate this activeform on button click

To validate your form perform ajax validation only inside your action as follows. This will only validate your form
public function actionValidateForm() {
$model = new Form();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
Yii::$app->end();
}
}

You have to set enableClientValidation = false, in you'r form's options .

Related

form values lost if captcha error in codeigniter php

I have created a website in php, the website has a signup form and google captcha in it. If the captcha is correct the form will submit successfully. If the captcha is wrong the same page will reload:
$this->session->set_flashdata('message', 'Captcha Error.');
redirect(base_url('signup'), 'Location');
The problem is the page is reloading with empty values, the user entered inputs are gone, can anyone please tell me what am i missing in my code?
Thanks in advance.
You can save your form value in session, and autofill the form based on data in session.
//set formdata to session
$data_session = array(
'name' => $name,
'email' => $email
);
$this->session->set_userdata('form_data', $data_session);
And set the data when you load the register page, and set the value to your view.
//load session data if exist
$data['name'] = null;
$data['email'] = null;
if ($this->session->userdata('form_data') != null)
{
$data['name'] = $this->session->userdata('form_data')['name'];
$data['email'] = $this->session->userdata('form_data')['email'];
}
$this->load->view('register_view',$data);
Dont forget to remove the session if signup is successful.
$this->session->unset_userdata('form_data');
Alternatively you can also use HTTP method and POST / GET the data to the new page (dont use HTTP GET if you want to send the password).

Drupal 8 Form with custom action

I have created a ModalDialog in Drupal contain two forms like as follows,
public function signUpForm() {
$response = new AjaxResponse();
// Get the modal form using the form builder.
$modal_form[] = $this->formBuilder->getForm('Drupal\signup_form\Form\SignupForm');
$modal_form[] = $this->formBuilder->getForm('Drupal\signup_form\Form\SigninForm');
// Add an AJAX command to open a modal dialog with the form as the content.
$response->addCommand(new OpenModalDialogCommand('', $modal_form, ['width' => '800','dialogClass' => 'signup-modal']));
return $response;
}
The forms are rendered, But the problem is ,both forms are submitting to the same function. I am unable to change the action of the form.
Is there any options available to change the form action to a custom url?
You need to alter these forms so that you can add your own submit handlers (and remove the unwanted one), and eventually from there you will be able to set the appropriate redirect, or AjaxResponse.
For example, for each form, implement hook_form_alter from a custom module :
function MODULE_signup_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
$form['actions']['submit']['#submit'][] = 'MODULE_signup_form_ajax_submit';
}
Then add the appropriate submit handlers, eg. :
function MODULE_signup_form_ajax_submit(array $form, FormStateInterface &$form_state) {
$response = new AjaxResponse();
$form-class = '.signup-form'; # using your own selector
$selector = '#drupal-modal' . ' ' . $form-class;
$message = '<div>submitted</div>';
$response->addCommand(new ReplaceCommand($selector, $message));
$form_state->setResponse($response);
}
I assumed you want to update the modal content so that the second form can still be submitted, so here I added the 'use-ajax-submit' class (cf. Drupal.behaviors.AJAX) to the appropriate $form action attributes so that the submit response can be rendered in the modal as well. Also used the ReplaceCommand to replace the submitted form content with a simple message.
If instead the first submitted form should trigger a redirection, then don't use setResponse() (that actually cancels redirect), and use setRedirect() if the base action url is not the one that you want.

Symfony validate entity using form

$userData = (new User())
->setPersonCode(123)
->setPhone('+470002342342342');
$userForm = $this->toolbar->getForm(UserType::class, $userData);
I'm creating form from entity class where is setted data. If now I try use:
$userForm->isValid();
I'm getting true, because form data is not submitted, how I can do validation, without setting manually data to form and submitting ?
If you don't want to submit data to a form, skip forms entirely; use the Validator service directly:
<?php
// (Assuming you're in a controller, otherwise inject the validator some other way.)
$userData = (new User())
->setPersonCode(123)
->setPhone('+470002342342342');
$validator = $this->get('validator');
$errors = $validator->validate($userData);
$isValid = count($errors) === 0;
Your question is worded a little strange and im not sure exactly what you want, If you want to manually set the data like above then call $form->submit() passing the user data.
$userData = (new User())
->setPersonCode(123)
->setPhone('+470002342342342');
$userForm = $this->toolbar->getForm(UserType::class);
$userForm->submit($userData);
if(!$userForm->isValid()){
// handle errors
}
If you want to have the user submit data on a form then do something like this:
public function createUserAction(Request $request)
{
$userForm = $this->toolbar->getForm(UserType::class);
$userForm->handleRequest();
if(!$userForm->isValid()){
// handle errors
}
}
$userForm->handleRequest(); will handle taking data that was submitted from the form on the page.

Symfony 2 Form - refresh protection when form is not valid

first of all sorry for my bad english.
The problem is as follows:
I try to do add and edit post in Blog system.
My pseudocode:
private function getPostForm()
{
$form=$this->createFormBuilder()
->add(...
}
public function addPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// form to create new post
// display form to add - send to updatePost
}
public function editPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// get post id and display form to edit post
// send to updatePost
}
public function updatePost()
{
// get data from post and validate
$form->bind(...
// if validate is true => save
if($form->isValid())....
// if not => get errors and display
else {
// redirect and display errors and post data
}
My problem - when form is not valid, I would like redirect user to add/edit post and display errors thanks to user can't refresh page (eg. F5 key) when data will be sent and not valid.
How to do it correctly?
Maybe, you should do like this. If all is correct do update and redirect, if validation fail display view again
public function updatePost()
{
....
if($form->isValid()){
//yours update logic
return $this->redirect(..);
}
return $this->render('create.html.twig', array(
'form' => $form->createView();
));
}

Submitting form to itself and echoing validation errors in CodeIgniter

I had few forms in my project, they were submitted to public function's like site.com/email => site.com/validate_email, but then I realized that that's not what I want.
Now I need to make them submit to themselfs ,check and display validation errors.
What is the appropriate way to do this? Check for emptyness of $_POST and then call my new _validate_email(//that will return true or false) if post isn't empty?
Or something else not that noobish?:)
for example:
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
//some stuff here
}
else
{
$this->load->view('login'); //or redirect()?
}
view:
<?php $this->load->view('header'); ?>
<div class="form-container">
<?=$this->form_validation->validation_errors();?>
<?php
$form_atr = array(
'id' => 'form-set'
);
echo form_open('main/login_validation', $form_atr);//this should be 'main/login'
?>
<div class="header">
/*
here goes other parts of form
*/
</div><!--END form-container -->`
<?php $this->load->view('footer'); ?>
So, basicaly i need to combine login() and login_validation(), but make it so that when user`s input incorrect i get reloaded page of the same view with the same URL and get validation errors displayed.
I've tried to put code of validation into the same function that displays form, but I can't figure out how to redirect or reload the view to show val.errors if any.
So, I think this way is correct(It really should be):
I made my login_validation() private by adding '_' before it, like so _login_validation()
Than I added an if() statement that contains $_POST form variables and i am cheking them with php isset() function, that way the code can determine when user submitted a form. And after all that I just call _login_validation() if inputs are set or load again my login view if not.
public function login()
{
if(isset($_POST['password']) && isset($_POST['email']))
{
$this->_login_validation();
}
else
{
$this->load->view('login');
}
}
and dont forget to process your form so it would submit to the same URL:
echo form_open('', $form_atr);
Hope that will help someone someday.
First of all, validation_errors() is one kind of flash data, so whenever you redirect the page with error the validation errors will be displayed, if you reload it second time it will not be displayed.
From your question i could not understand, do you want to show the errors or not.
if you want to show the errors:
then just redirect the page to login and in the login view add a alert div.
if you don't want to show the errors:
then just remove the alert div.
*i don't see any alert div in your login view, if validation errors are still displayed then may be alert div is in the header view

Categories