How to avoid instant saving of the model with ajax validation? - yii2

I want to add Ajax validation to check the form before updating. In the view, added to the required field
['enableAjaxValidation' => true]
In the controller in the actionUpdate
if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
if ($modelForm->validate()) {
$model->setAttributes($modelForm->getAttributes());
if ($model->save()) {
return $this->redirect([my way]);
}
if ($model->hasErrors()) {
return ActiveForm::validate($model);
} else {
return ['success' => 1, 'html' =>
$this->renderPartial('view', [my data];
}
} else {
return ActiveForm::validate($modelForm);
}
}
The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

In controller try it like this:
$model = new ExampleForm;
// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Add this before your if statement, and remove Yii::$app->request->isAjax from your if statement.

Add some thing like below in your form
$form = ActiveForm::begin([
'id' => 'example',
'action' => ['your_action'],
'validateOnSubmit' => true,
'enableAjaxValidation' => true,
])

Related

croogo 2 Request blackholed due to "auth" violation

I have a problem with my old website. Now I try to move it to new server (php5.6) and when i try to save data I have error:
Request blackholed due to "auth" violation.
I serach the place whose do it this error:
if ($this->Node->saveWithMeta($this->request->data)) {
Croogo::dispatchEvent('Controller.Nodes.afterAdd', $this, array('data' => $this->request->data));
$this->Session->setFlash(__('%s has been saved', $type['Type']['title']), 'default', array('class' => 'success'));
if (isset($this->request->data['apply'])) {
$this->redirect(array('action' => 'edit', $this->Node->id));
} else {
$this->redirect(array('action' => 'index'));
}
}
I think error do function saveWithMeta(). This function view like:
public function saveWithMeta(Model $model, $data, $options = array()) {
$data = $this->_prepareMeta($data);
return $model->saveAll($data, $options);
}
Can I replace/edit this function so that it starts to work?
edit
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
These lines cause an error.

No form errors shown in JsonResponse - Symfony

I have a registration form with fields that are validated in User entity class. The validation works fine, however I can't return JsonResponse with form error messages in it.
My registration form controller method looks like this:
/**
* #Route("/register", name="register")
*/
public function registerAction(Request $request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
$errors = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new JsonResponse(
array(
'message' => 'Success! User registered!',
), 200);
}
else
{
$errors = ($this->get('validator')->validate($form));
return new JsonResponse(
array(
'message' => 'Not registered',
'errors' => $errors,
), 400);
}
}
return $this->render(
'ImmoBundle::Security/register.html.twig',
array('form' => $form->createView(), 'errors' => $errors)
);
}
I get the following json response when I submit the registration form with invalid data:
{"message":"Not registered","errors":{}}
Actually I'm expecting that "errors":{} will contain some error fields, but it doesn't. Does anyone know what the problem here is?
UPD:
My RegistrationType looks like this:
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat password'),
'invalid_message' => "Passwords don't match!",
))
->add('register', SubmitType::class, array('label' => 'Register'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ImmoBundle\Entity\User',
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'authenticate',
));
}
}
UPD2: Found the solution. I needed to do this iteration and then call for getMessage():
$allErrors = ($this->get('validator')->validate($form));
foreach ($allErrors as $error)
{
$errors[] = $error->getMessage();
}
Form validated when you call $form->handleRequest($request);
To get form errors use getErrors method
$errors = $form->getErrors(true); // $errors will be Iterator
to convert errors object to messages array you can use code from this response - Handle form errors in controller and pass it to twig
This is exapmle how i'm process errors in one of my projects
$response = $this->get('http.response_formatter');
if (!$form->isValid()) {
$errors = $form->getErrors(true);
foreach ($errors as $error) {
$response->addError($error->getMessage(), Response::HTTP_BAD_REQUEST);
}
return $response->jsonResponse(Response::HTTP_BAD_REQUEST);
}
It's worked for me.
And also this can help you - Symfony2 : How to get form validation errors after binding the request to the form
You must set error_bubbling to true in your form type by explicitly setting the option for each and every field.

Yii2 framework - Email Validation in Ajax Form

I'm having an issue validation whether a submitted Email Address is Unique in the database.
When the User registers I need to validate whether the email address exists all of the other validation is working fine.
Is there a step missing when you are validating a using an Ajax form in Yii 2.
A User clicks on CTA to register on site/index
use yii\bootstrap\Modal;
use frontend\models\Register;
use yii\helpers\Html;
use yii\helpers\Url;
...
Modal::begin([
'id' => 'modal',
'size'=>'modal-lg',
'clientOptions' => ['backdrop' => 'static', 'keyboard' => FALSE],
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?= Html::button('Register', ['value' => Url::to(['register/create']), 'title' => 'Register', 'class' => 'btn btn-success','id'=>'modalButton']); ?>
This opens up a modal (register/create)
Model Register
class Register extends User
{
...
public function rules()
{
return [
['Email', 'filter', 'filter' => 'trim'],
['Email', 'required'],
['Email', 'email'],
['Email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
];
}
public function signup()
{
$user = new User();
if ($this->validate()) {
$user->Email = $this->Email;
if ($user->save()) {
return $user;
}
} else {
return;
}
}
Register Controller
public function actionCreate()
{
$model = new Register(['scenario' => 'signup']);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::error($model);
return $model->validate();
}
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->renderAjax('create', [
'model' => $model,
]);
}
The View file
<?php $form = ActiveForm::begin(['id'=> 'register', 'enableClientValidation'=>true, 'enableAjaxValidation'=>true, 'validateOnChange'=> true, 'validationUrl' => Url::to(['register/create'])] ); ?>
<div class="form-group">
<?= $form->field($model, 'Email') ?>
</div>
Javascript file
$script = <<< JS
$('body').on('beforeSubmit', 'form#register', function (event, jqXHR, settings) {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length) {
return false;
}
// submit form
$.ajax({
url: form.attr('action'),
type: 'GET',
data: form.serialize(),
success: function (response) {
// do something with response
$(document).find('#modal').modal('hide');
}
});
return false;
});
JS;
$this->registerJs($script);
I was facing a similar issue where my email field was not triggering the "unique" rule in the javascript validation, but the "unique" rule was getting triggered on the form submit.
It's awesome that you came up with a solution for your question that gets the job done, but I think what I just learned could also shed some insight on this question for others.
The key for me was learning/realizing that the "unique" validation rule must use a database lookup to verify if the user input is unique, thus it must use ajax. Other validation rules, such as "required" or "email" don't need ajax to validate. They just use javascript in the client to validate, so they are client validation, whereas the "unique" validator is actually ajax validation.
Note: my code below is not really addressing your code directly, but is intended to communicate the overall understanding and code structure that is needed to answer your question. Some of these steps you already have, but some are missing :)
First, you need a model with a field that requires a 'unique' rule, such as an email address for a user account.
In your Model
public function rules()
{
$rules = [
[['email'], 'unique'],
// ... and all your other rules ...
];
}
When using \yii\widgets\ActiveForm, client validation is enabled by default, but ajax validation is not.
So, next you need to directly turn on ajax validation in the view. This can be done either for the entire form, or just for a single field. The Yii2 Validation docs explain this best, but in my case, I chose to just enable ajax validation on my email field.
In your View
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($user, 'email', ['enableAjaxValidation' => true])->textInput();
//... other form fields and such here ...
<?php ActiveForm::end(); ?>
Next, you also need to handle the ajax validation in your controller, so your controller method could look something like this:
public function actionRegister()
{
$user = new User();
$post = Yii::$app->request->post();
$userLoaded = $user->load($post);
// validate for ajax request
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($user);
}
// vaidate for normal request
if ($userLoaded && $user->validate()) {
$user->save();
return $this->redirect(['view', 'id' => $user->id]);
}
// render
return $this->render('create', ['user' => $user]);
}
And then here's the catch ... everything above is what you would need when working with a normal (non-ajax) form. In your question, you are working on a form in a modal window that is being submit via ajax, so the above controller method will not work. With ajax forms, it becomes pretty tricky to handle the ajax form validation and the ajax form submit in the same controller method.
As usual, Yii has this all figured out for us, and the validationUrl form parameter will save the day. All you have to do is create a new method in your controller that is specifically for ajax validation, and reference the controller/action URL in your form. Something like this should do the trick:
In your View
<?php $form = ActiveForm::begin([
'id' => 'form-id', // always good to set a form id, especially when working with ajax/pjax forms
'validationUrl' => ['user/validate-email'], //['controller/action'],
]); ?>
In your Controller
public function actionRegister()
{
$user = new User();
$post = Yii::$app->request->post();
// vaidate for normal request
if ($user->load($post) && $user->validate()) {
$user->save();
return $this->redirect(['view', 'id' => $user->id]);
}
// render
return $this->render('create', ['user' => $user]);
}
public function actionValidateEmail()
{
// validate for ajax request
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
$user = new User();
$post = Yii::$app->request->post();
$user->load($post);
return ActiveForm::validate($user);
}
}
Cheers!
I managed to solve this myself by using Javascript to make an Ajax request and PHP to receive the quest and check whether the Email already exists in the database.
function checkEmail(){
var email_check;
// Get the value of the email input field
var input_value = document.getElementById('register-email').value;
// Send the value to a PHP page to check
$.ajax({
url: 'checkemail.php/',
type: 'POST',
data: {
email_check: input_value
},
success: function(response) {
// If we have a repsonse we need to check whether it is True or False
email_check = response;
if (email_check == 1) {
// If True add error class
$('.field-register-email').addClass('has-error');
$('.field-register-email .help-block').text('The email supplied has already been used');
} else {
$('.field-register-email').removeClass('has-error');
$('.field-register-email .help-block').text(' ');
}
}
});
};
This will send a POST request to the checkemail.php which will check whether the email address is in the database

yii2 disable the rules if a checkbox is selected

In the active form, I have 3 textinput and one checkbox.
All the 3 textinputs have rules that says cannot be empty. What I want is if the checkbox is clicked, It will disable the rules and will save the empty record in the database.
here is screen shot of the active form..
You could define the rules that way (using when):
public function rules()
{
return [
['cancelled', 'boolean'],
['checkNumber', 'required'],
['payee', 'required', 'when' => function ($model) {return !$model->cancelled;}],
['particulars', 'required', 'when' => function ($model) {return !$model->cancelled;}],
];
}
You may want to add whenClient as well to let the browser check this before it submits the form.
You can do something like this:
$model = new SomeForm();
if ($model->load(Yii::$app->request->post())){
if ($model->checkbox == true) $model->scenario = 'checked';
}
// your model rules:
[['name', 'email', 'subject', 'body'], 'safe', 'on' => 'checked']
or alternatively You can do this:
if ($model->checkbox == true) $model->save(false); //this will disable any validation so be carefull
edit:
if You need cliend side validation switch, You have to use this:
[['name', 'email', 'subject', 'body'], 'required', 'when' => function ($model) {
return $model->cancelled == '0';
}, 'whenClient' => new JsExpression("function (attribute, value) { return $('#mailform-cancelled').val() == '0';}")]

I am trying to find a "simple" way to store images (and data about them) using CakePHP and MySQL.This code has got me a bit confused

I went through this article to make a file uploading site with Cakephp,
http://www.tuxradar.com/content/cakephp-tutorial-build-file-sharing-application
I suppose the relevant code to this question is this, a download and an upload function,
function add() {
if (!empty($this->data)) {
$this->Upload->create();
if ($this->uploadFile() && $this->Upload->save($this->data)) {
$this->Session->setFlash(__('The upload has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
}
}
$users = $this->Upload->User->find('list');
$users = $this->Upload->User->find('list');
$this->set(compact('users', 'users'));
}
function uploadFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$id = String::uuid();
if (move_uploaded_file($file['tmp_name'], APP.'uploads'.DS.$id)) {
$this->data['Upload']['id'] = $id;
$this->data['Upload']['filename'] = $file['name'];
$this->data['Upload']['filesize'] = $file['size'];
$this->data['Upload']['filemime'] = $file['type'];
return true;
}
}
return false;
}
function download($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->Upload->bindModel(array('hasOne' => array('UploadsUser')));
$upload = $this->Upload->find('first', array(
'conditions' => array(
'Upload.id' => $id,
'OR' => array(
'UploadsUser.user_id' => $this->Auth->user('id'),
'Upload.user_id' => $this->Auth->user('id'),
),
)
));
if (!$upload) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->view = 'media';
$filename = $upload['Upload']['filename'];
$this->set(array(
'id' => $upload['Upload']['id'],
'name' => substr($filename, 0, strrpos($filename, '.')),
'extension' => substr(strrchr($filename, '.'), 1),
'path' => APP.'uploads'.DS,
'download' => true,
));
}
I am not quite sure what all that code is doing actually, but I am trying to make a page so I can display one of the images instead of downloading them. If make this statement,
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>
My webpage displays my image but I don't actually have a download folder, I added that extension because it appears that the download function adds it for some reason. If someone could explain what is happening there, that would be great.
You need to make a new controller method to view your images individually, something like this:
public function view($id = null) {
if (!$this->Upload->exists($id)) {
throw new NotFoundException(__('Invalid upload'));
}
$options = array('conditions' => array('Upload.' . $this->Upload->primaryKey => $id));
$this->set('upload', $this->Upload->find('first', $options));
}
And then display the image in your /View/Uploads/view.ctp:
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>