I was trying to validate my YII2 register form but it not work. In view:
$form = ActiveForm::begin([
'id' => 'register',
'options' => ['accept-charset'=>'utf-8'],
'validateOnChange' => false,
'enableAjaxValidation' => true,
'validateOnSubmit' => true,
])
In controller:
$model = new MUser();
if($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax)
{
$model->refresh();
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
elseif($model->load(Yii::$app->request->post()) && $model->save())
{
\\do something
}
In Model:
public function rules()
{
return [
[
'username',
'unique',
'targetClass' => 'com\modules\admin\models\MUser',
'message' => 'Username exist',
]
];
}
Can anyone let me know what wrong I am doing?
change
return ActiveForm::validate($model)
TO
echo json_encode(ActiveForm::validate($model));
\Yii::$app->end();
ActiveForm::validate($model) is an array it needs to be represented in json form which is done by json_encode and \Yii::$app->end(); is making sure that the application stop on just checking.Also make sure you have after the namespace :
use yii\web\Response;
use yii\widgets\ActiveForm;
But By doing so the submission via ajax of your form will not work the perfect way is using validationUrl.
Related
I am humbly seeking a help on how to go about displaying error message in CI4. i have create a controller like this:
public function login()
{
$validation = \config\services::validation();
$errors = array('email' => 'bad email',
'pass' => 'bad pass ');
if(!$this->validate(array('email' => 'required',
'pass' => 'required')))
{
echo view('login', array('validation' => $this->validator));
}
else
{
print 'success';
}
}
while a tested each of the error reporting function below:
$validation->listErrors();
$validation->listErrors('list');
$validation->showError();
$validation->showError('sigle');
$validation->showError('email');
but non of these function work, if i entered correct data it print success as assign but upon wrong data it all show the same error message which is:
Call to a member function listErrors() on null.
Call to a memberfunction listErrors() on null.
Call to a member function showError()on null.
Call to a member function ShowError() on null.
call form helper in your controller before your validation start
helper('form');
and i re-arrange ur code like this
public function login()
{
$data = [
'validation' => \config\services::validation()
];
if ($this->request->getMethod() == "post") { // if the form request method is post
helper('form');
$rules = [
'email' => [
'rules' => 'required',
'errors' => [
'required' => 'bad email'
]
],
'pass' => [
'rules' => 'required',
'errors' => [
'required' => 'bad pass'
]
]
];
if (!$this->validate($rules)) {
echo view('login', array('validation' => $this->validator));
} else {
// whatever you want todo
}
}
echo view('login', $data);
}
in your login view, if you want to call all error list you got use this method $validation->listErrors();
if you want to call a specific error use this method $validation->listErrors('email');
if you want to check is the specific field returning an error use this method $validation->hasError('email'))
i hope this help you to solve your problem
I make form by React. After submitted form, I need to validate data from Laravel. Problem is that sending data is diffrent than normal form. So any values from dorm is in array data.
//normal form
$request->title
//sending from React
$request->data['title']
So, look at this code
class articleRequest extends Request
{
public function rulse(){
return [
'title' => 'required',
//other rules
];
}
}
class ArticleController extends Controller
{
public function atoreArticle(articleRequest $request){
Textads::create([
'title'=> $request->data['title'],
//other
]);
}
}
But I have an error that title field is required. Without valdiation everything is ok. How I can solve my problem?
You can try this -
$rules = [
'title' => 'required',
//other rules
];
Validator::make($request->all(), $rules)->validate();
will this work? or $request->all()->data ?
$validator = Validator::make($request->data, [
title'' => 'required'
],[
//custom error message if needed
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'data' => $validator->messages(),
'message' => "error"
], 422);
}
I have a field in my FormType that I'm trying to get the value of at the time it's being successfully submitted and pass it to my controller. I set the value of the field by passing a variable to the form and using the attr of the textbox to set it to the corresponding value in $options, the end result of the html is <input type="hidden" id="listing_editId" name="listing[editId]" required="required" value="1288701182" readonly="readonly">
ListingType.php
->add('editId', HiddenType::class, [
'required' => true,
'disabled' => false,
'mapped' => true,
'attr' => [
'value' => $options['editId'],
'readonly' => true,
]
])
I've tried $form->get('editId'); but it doesn't return the value, I've also tried $request->get('editId'); to no avail.
ListingController.php
/**
* #Route("/account/listings/create", name="listing_create")
*/
public function createAction(Request $request)
{
$r = sprintf('%09d', mt_rand(0, 1999999999));
$form = $this->createForm(ListingType::class, null, [
'currency' => $this->getParameter('app.currency'),
'hierarchy_categories' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Category'), 'category', 'categories'),
'hierarchy_locations' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Location'), 'location', 'locations'),
'editId' => $r,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$listing = $form->getData();
$listing->setUser($this->getUser());
try {
$em = $this->getDoctrine()->getManager();
$em->persist($listing);
// I'd like to be able to get the value of an input field that is "editId" here
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('Listing has been successfully created.'));
} catch (\Exception $e) {
$this->addFlash('danger', $this->get('translator')->trans('An error occurred when creating listing object.'));
}
return $this->redirectToRoute('listing_my');
}
return $this->render('FrontBundle::Listing/create.html.twig', [
'form' => $form->createView(),
'editId' => $r]);
}
Try $form->get('editId')->getData() or $request->request->get('editId') or $form->getData()['editId']
I have ajax validation on unique on create it work fine but when I want to update i cant becouse this show message that this name is already used but i not owerwrite this name it is name from database on update click. Its does not matter whcich record i want to update it always show me message that name is already used. Whan can i do to disable message when i not change my input to name which is in base. Now it is so update action automatically filed my inputs but when i not change anythink i have this error on save
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], 'id'=>$model->formName(), 'enableAjaxValidation'=>true, 'validationUrl'=>Url::toRoute('category/validation')]) ?>
My controller:
public function actionValidation(){
$model= new SmCategory;
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format='json';
return ActiveForm::validate($model);
}
}
my rules:
public function rules()
{
return [
[['Name'], 'required'],
['Name', 'unique', 'targetClass' => 'common\models\Smcategory', 'message' => 'This name has already been taken.'],
[['Rel_Category', 'IsDeleted'], 'integer'],
[['File'],'file'],
[['Name', 'Label'], 'string', 'max' => 45],
[['Picture'], 'string', 'max' => 255]
];
}
The problem is here :
$model= new SmCategory;
This code is ok for create, not for update since it will not use the existing model for validation, it could be (just an example and assuming id is the primary key) :
public function actionValidation($id = null)
{
$model = $id===null ? new SmCategory : SmCategory::findOne($id);
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format='json';
return ActiveForm::validate($model);
}
}
And you could update validationUrl in your view :
$validationUrl = ['category/validation'];
if (!$model->isNewRecord)
$validationUrl['id'] = $model->id;
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
'id' => $model->formName(),
'enableAjaxValidation' => true,
'validationUrl' => $validationUrl,
]);
I have the following error
Class 'app\controllers\ActiveForm' not found
when submit the following ActiveForm (kartik\widgets\ActiveForm)
$form = ActiveForm::begin([
'type'=>ActiveForm::TYPE_VERTICAL,
'action' => 'incarico/update/'.$model->id,
'enableAjaxValidation' => true,
'enableClientValidation' => false,
]);
My controller has this action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
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->render('update', [
'model' => $model,
]);
}
}
The error refers to this line
return ActiveForm::validate($model);
Because you haven't include ActiveForm namespace yet.
add this in the use section (in the beginning of that file)
use kartik\widgets\ActiveForm;