Validate form by ajax in yii2 - php

I have a form which is opening in popup so I want to validate my form by ajax validation but when i click on submit button my page getting refreshed so I am not getting any validation error
View file:
<?php $form = ActiveForm::begin([
'id' => 'signup-form',
'enableAjaxValidation' => true,
//'action' => Url::toRoute('user/ajaxregistration'),
'validationUrl' => Url::toRoute('user/ajaxregistration')
]); ?>
<div class="col-md-12">
<div class="formbox">
<div class="inputbox signup">
<div class="input-group"> <span class="input-group-addon"><i class="glyphicon name"></i></span>
<?= Html::textInput('userFullName', '', ['placeholder' => "Name",'class'=>'form-control']); ?>
</div>
<?php ActiveForm::end(); ?>
Controller File:
public function actionValidate() {
$model = new SignupForm;
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();
}
}
Model Code:
return [
['userFullName', 'trim'],
['userFullName', 'required'],
];
Please suggest me what should i do so that my page will not get refrsh and I will get the validation error

You are using an ActiveForm without any ActiveFields, this means that the validation rules that have been defined within the model aren’t even being assigned to the text input. I have written an implementation for your problem:
Model:
use Yii;
use yii\base\Model;
class ExampleForm extends Model
{
// this 'virtual attribute' defines a form field
public $userFullName;
// validation rules
public function rules()
{
return [
['userFullName', 'trim'],
['userFullName', 'required'],
];
}
}
Controller:
use models\ExampleForm;
use yii\web\Response;
use yii\widgets\ActiveForm;
public function actionExample()
{
$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);
}
if ($model->load(Yii::$app->request->post())) {
// code to process form data goes here.. This will execute on a form submission.
}
return $this->render('example-form', [
'model' => $model,
]);
}
View:
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$this->title = 'Example';
?>
<div class="exampleForm">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the form.</p>
<!-- this form will submit via POST to the same action that renders it -->
<?php $form = ActiveForm::begin() ?>
<!-- this is an active field. Any validation rules for the 'userFullName' field -->
<!-- that have been defined within the $model object will be applied to this field -->
<!-- the validation has also been set to validate via ajax within the $options array -->
<!-- read more about ActiveFields here: http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html -->
<?= $form->field($model, 'userFullName', ['enableAjaxValidation' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit!', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The best way to see whether ajax requests are being sent off / the form is being validated is to check chromes developer tools, go to the network tab and inspect the activity.

use renderAjax() Method:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}else {
return $this->renderAjax('YourViewFileName', [
'model' => $model,
]);
}

Related

Yii2 Form Submission TroubleShoot

So I'm displaying the logged user's information on a page, followed by a form which can be used to change basic user info, such as e-mail address, username and so on.
In the ProfileController file, I have the Index action, which handles the user info and, theoretically, the form too:
public function actionIndex() {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
if ($user->load(Yii::$app->request->post())) {
$user->save();
//var_dump($user->first_name);die;
}
return $this->render('index', [
'user' => $user,
]);
}
In the index view file, I'm displaying the form as it follows:
<div class="row form">
<div class="user-form col-md-8 col-md-offset-2">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($user, 'last_name')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'first_name')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'email')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'image')->textInput([]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Problem is, whenever I press the submit button beneath the form, the controller receives the post request, but does not update the new values given in the form fields, thus displaying the old info at the var_dump(). What should I do?
Probably validation failed. Proper way of doing this is:
// ...
if ($user->load(Yii::$app->request->post())) {
if ($user->save()) {
// validated and saved, check $user state now
}
}
Method save() calls method validate() automatically. You can call it on your own as well if you want to operate on this model only when it's validated.

Pjax and form submit not woking in yii2

I'm developing a registration page but some part of this page should be submitted alone. I make some research and found Pjax in yii2 ut what I found in the documentation not working properly with mine.
No tag is created...only a hidden element containing csrf.
On submission, All page is reloaded.
View:
<div class="row profileimg">
<?php Pjax::begin(['timeout' => 40000, 'id' => 'myPjax',]); ?>
<?= Html::beginForm(['couple-partner/saveprofileimg'], 'post', ['id' => 'CouplePartnerSumb', 'data-pjax' => true, 'class' => 'form-inline']); ?>
<div class="col-lg-12" onmouseover="onmouseOverImg('FirstPartnerEditButton', 'FirstPartnerDelButton');" onmouseout="onmouseoutImg('FirstPartnerEditButton', 'FirstPartnerDelButton')" id="imgdiv" style="display:inline-block;position: relative;left : 35%;height: 110px;width: 150px;">
<img src="<?= $models != NULL && sizeof($models) > 0 && $models[0]->USER_PROFILE_PIC != NULL ? $models[0]->USER_PROFILE_PIC : "" ?>" style="cursor: pointer;width:100%;height:100% " id="firstPartnerProfilePic" class="img-thumbnail ">
<?= Html::fileInput('imageFile', '') ?>
<?php echo Html::submitButton('Upload', ['class' => 'btn btn-primary', 'id' => 'submit_iddddd',]) ?>
</div>
<?php echo Html::endForm();Pjax::end();?>
</div>
Controller:
public function actionSaveprofileimg() {
$model = new CouplePartner();
if (Yii::$app->request->isAjax) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->renderAjax('index', ['model' => $model]);
}
I can't find what is the problem that Pjax not working properly and why submit button reload all the page when is clicked.
The page reloaded because controller throw 500 error.
You should change
$model->upload()
to
$model->imageFile->upload()
and try catch more issues while controller is processing upload request

Email Validation are not Working in Cakephp 3.0

Email validation is not working and if i take name of the field as email only then it take is email but also not perfect validation like 'a#a' is working if i take it as email otherwise only non-empty is working only.
RecommendTable.php
<?php
namespace App\Model\Table;
use App\Model\Entity\recommend;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\Validation\Validator;
class RecommendTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('recommend');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator = new Validator();
$validator
->requirePresence('name')
->notEmpty('name', 'Please fill this field')
->add('name', [
'length' => [
'rule' => ['minLength', 10],
'message' => 'Titles need to be at least 10 characters long',
]
]);
$validator->add("emai", "validFormat", [
"rule" => ["email"],
"message" => "Email must be valid."
]);
$validator
->requirePresence('yemail')
->notEmpty('yemail', 'Please fill this field..')
->add('yemail', ['length' => ['rule' => ['minLength', 10],'message' => 'Titles need to be at least 10 characters long',]]);
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
}
Recommend.php
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class Recommend extends Entity
{
protected $_accessible = [
'*' => true,
'id' => false,
];
protected function _setPassword($value)
{
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Index.ctp
<?= $this->Form->create($temp) ?>
<div class="row">
<div class="container">
<div class="comment-form">
<div class="row">
<div>
<h2>
<center>
Recommend us to your Friends/Library
</center>
</h2>
</div><fieldset>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<?php
echo $this->Form->input('emai',array('id'=>'emai','label'=>'To ( Receiver’s mail-ID)',"placeholder"=>"Send E-mail to multiple (seperated by commas).")) ?>
</div>
</div>
<div class="col-md-6 col-sm-3">
<div class="input-container">
<?php
echo $this->Form->input('name',array('id'=>'name','label'=>'Name',"placeholder"=>"Name")); ?>
</div>
</div>
<div class="col-md-6 col-sm-3">
<div class="input-container">
<?php
echo $this->Form->input('yemail',array('id'=>'yemail','label'=>'From',"placeholder"=>"From")); ?>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<label>Message</label>
<textarea name="msg" id="msg" style="resize: none;text-align:justify; " disabled placeholder="Hello"></textarea>
</div>
</div>
</fieldset>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<?= $this->Form->button(__('Submit')) ?>
<button type="Reset">Reset</button>
<?= $this->Form->end() ?></div>
Recommend Controller
<?php
namespace App\Controller;
use Cake\ORM\TableRegistry;
use App\Controller\AppController;
use Cake\Mailer\Email;
use Cake\ORM\Table;
use App\Model\Tabel\RecommendTabel;
use Cake\Event\Event;
class RecommendController extends AppController
{
public function index()
{
$temp = $this->Recommend->newEntity();
if ($this->request->is('post')) {
$temp = $this->Recommend->patchEntity($temp, $this->request->data);
if($temp) {
$name=$this->request->data('name');
$receiver_email=$this->request->data('emai');
$Subject_Title='Temp';
$Sender_email=$this->request->data('yemail');
$email = new Email();
$email->template('invite', 'default')
->viewVars(['value' => $name])
->emailFormat('html')
->from($Sender_email)
->to($receiver_email)
->subject($Subject_Title)
->send();
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'add']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('temp'));
$this->set('_serialize', ['temp']);
}
The patchEntity function returns a patched entity. So, the result of this line will always evaluate to true when used in a boolean context.
$temp = $this->Recommend->patchEntity($temp, $this->request->data);
So, to check whether any errors were detected, your if statement cannot just compare the returned value to true, but instead do something like this:
if (!$temp->errors()) {
Cakephp is provide in defult validation library, please find this validation in (i.e. http://book.cakephp.org/2.0/en/models/data-validation.html). Please try to use this code.
public $validate = array('email' => array('rule' => 'email'));
public $validate = array(
'email' => array(
'rule' => array('email', true),
'message' => 'Please supply a valid email address.'
)
);

Yii Framework file input skipOnEmpty validation always fails

I am currently doing a project in PHP Yii framework.
I have a form with file input field called company_logo.For the field I have added the following rule in the model [['company_logo'],'file','skipOnEmpty'=>false]
When I upload file, it shows
Please upload a file.
even if I uploaded a file.
When I remove the
skipOnEmpty
it is uploading the file.I have researched several places for the issue.But couldn't find a solution.
The controller, view and model are given below
View - add_company.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Company</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'company_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'company_address')->textArea(array('class'=>'form-control')); ?>
</textarea>
<div class="form-group">
<?= $form->field($model, 'company_logo')->fileInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_email')->textInput(array('class'=>'form-control','type'=>'email')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_phone_number')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'retype_admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="box-footer">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
</div><!-- /.box-body -->
<?php ActiveForm::end(); ?>
</div>
</div>
Controller - CompanyController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\CompanyModel;
use yii\web\UploadedFile;
global $username;
class CompanyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Companies',
'dash_sub_title'=>'Add new company'
);
$message = array();
$model = new CompanyModel();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
echo "hello";
$model->company_logo = UploadedFile::getInstance($model, 'company_logo');
echo "world";
if ($model->company_logo && $model->validate()) {
$model->company_logo->saveAs('uploads/' . $model->company_logo->baseName . '.' . $model->company_logo->extension);
} else {
echo "Yo Yio ture";
exit;
}
$model->add_company();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added company '.$model->company_name;
}else {
$message = $model->getErrors();
// print_r( $message );
// exit;
}
return $this->render('add-company', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
Model - CompanyModel.php
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false]
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false],//here the comma is missing
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens

I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.
I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.
<a class="list-group-item">
<form role="form">
<div class="form">
<?php $model = new Usuarios; ?>
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'usuarios-form',
'action' => $this->createUrl("usuarios/create"),
'enableAjaxValidation' => false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div style="padding:1px;" class="input-group input-group-sm">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user" style="color:white"></span>
</span>
<?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
<?php echo $form->error($model, 'Nombre'); ?>
</div>
<div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
<center>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
</center>
</div>
<?php $this->endWidget(); ?>
</div>
</form>
</a>
This is what your controller action should look like:
public function actionCreate() {
$model = new Usuarios;
if(isset($_POST['Usuarios'])) {
// Populate the model with values from form
// These attributes must be set to safe in the model rules() function
$model->attributes = $_POST['Usuarios'];
// ->save() will validate the model with the validation rules
// in the Usuarios.php model. If you do not want validation, use ->update()
if($model->save()) {
$this->redirect(array('view', 'id' => $model->primaryKey));
}
}
$this->render('create', array(
'model' => $model, // You pass the model to the view page
));
}
In your model, you need to update the rules() function to accept the fields for saving in the database:
public function rules() {
return array(
array('Nombre', 'safe'),
);
}

Categories