How to validate Yii2 dynamic model - yii2

I was working on Yii2 and would like to dynamically validate the field, like validate if another field is not selected.
I found below code on Yii2 documentation:
['state', 'required', 'when' => function($model) {
return $model->country == 'USA';
}]
But the thing is that I am using Yii2 dynamic model. How could I achieve the same thing shown above in dynamic model.

As usual model:
$model = new \yii\base\DynamicModel([
'name', 'country', 'state'
]);
$model->addRule(
'state', 'required', ['when' => function($model) {
return $model->country == 'USA';
}
]);

Related

Laravel controller validation Request does not exist

I'm using Laravel 8 validation, and what i'm trying to do is to validate a form with some input name, unique to table Sizes column "name" where it also depends on another column speciesId that the value from $request->speciesId.
The function in Controller is looks like this
public function storeSize(Request $request)
{
$validated = $request->validate(
[
'name' => [
'required', Rule::unique('sizes')->where(function ($query) {
return $query->where('speciesId', $request->speciesId);
})
],
'speciesId' => 'required'
]
);
}
already add use Illuminate\Http\Request; and use Illuminate\Validation\Rule; but still got "ErrorException Undefined variable: request".
when i'm try to var_dump($request) or echo $request->speciesID, the variable and value is present.
my question is, why the validation function doesn't recognize the Request variable?
The error occurs because inside your function call $request is not available. You need to make it available by adding use $request to function ($query):
$validated = $request->validate([
'name' => [
'required', Rule::unique('sizes')->where(function ($query) use ($request) {
return $query->where('speciesId', $request->speciesId);
})
],
'speciesId' => 'required'
]);

Retrieve only necessary data

Here is my store function
public function store(Request $request)
{
$post = new Post();
$post->author()->associate(auth()->user());
$post->fill($request->all());
$post->save();
return response()->json($post);
}
As a response i get:
I don't want all the data so I tried to take only the data I have defined like this:
$post = $post->only([
'id',
'title',
'content',
'published_at',
'author'
]);
And response now is:
Much better, but not completely. I can not define post author data in this way.
The only way is by creating a creepy relationship where you select only necessary data or like this:
$post = [
'id' => $post->id,
'title' => $post->title,
'content' => $post->content,
'published_at' => $post->published_at->toDateTimeString(),
'author' => [
'id' => $post->author->id,
'name' => $post->author->name,
'email' => $post->author->email,
]
];
So my question is... maybe there is more elegant way to achieve this.
Thank you very much!
The simplest way would probably be to just use only with the author as well:
return $post->only('id', 'title', 'content') + [
'author' => $post->author->only('id', 'name', 'email'),
];
If it was going to get any more complicated or reused somewhere else then I would suggest using something like Eloquent Resources
I would add a function to your Post model
public function jsonOutput()
{
$array['id'] = $this->id;
$array['title'] = $this->title;
$array['content'] = $this->content;
$array['author'] = [
'id' => $this->author->id,
'name' => $this->author->id
];
return $array;
}
and then call it like this
return response()->json($post->jsonOutput());

Validation rule unique requires at least 1 parameters. laravel 5.4

I've got problem with my laravel 5.4 I can't save the data
public function rules()
{
return [
'permission_id' => 'required|unique',
'name' => 'required',
'label' => 'required',
];
}
Error
Validation rule unique requires at least 1 parameters.
the unique rule need at least the name of ur database table.
ur rules function should be like this:
public function rules()
{
return [
'permission_id' => 'required|unique:db_table_name',
'name' => 'required',
'label' => 'required',
];
}
for more informations check laravel doc unique rule

Yii2 ActiveForm unique validation not show error message

This is my model contacts,
public function rules()
{
return [
[['fname', 'status','mobile',], 'required'],
[['user_id', 'contact_type','group_type','passport_no','trip_id','group_id','state',], 'integer'],
[['fname', 'mname', 'lname', 'status', 'street', 'location', 'post', 'city', 'district','email','job_title','company_name','source'], 'string', 'max' => 500],
[['department'], 'string', 'max' => 40],
[['pincode'], 'string', 'max' => 15],
[['mobile'],'unique'],
Here the required validation of mobile works and show error message, but unique rule works but it doesn't show any error message
Help me plz.
1) Unique validation work with database.
2) Once form was submitted then validation was checked and model not saved because of unique validation fails.
3) If you want to unique validation on form then use Ajax.
For this, You need to set 'enableAjaxValidation' => true,
$form = ActiveForm::begin([
'id' => 'contact-form',
'enableAjaxValidation' => true,
]);
Controller:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Reference
Maybe you should also set targetClass:
['email', 'unique', 'targetClass' => '\common\models\User']
I am assuming your view page as register.php. So,
register.php (View)
1) Remove use yii\bootstrap\ActiveForm; (if present)
2) Add use yii\widgets\ActiveForm;
3) Add 'enableAjaxValidation' => true in that field (Where you are validating it. Like below)
<?= $form->field($model, 'mobile',['enableAjaxValidation' => true])->textInput(['class'=>'form-control']) ?>
Controller
See below (Add this line wherever I have written //Add This Line)
.
.
use yii\web\Response; // Add This line
use yii\widgets\ActiveForm; //Add This Line
.
.
Class SomeClass
{
.
.
.
public function actionRegister() {
$model = new Candidate();
//Add This For Ajax Mobile Exist Validation
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post())) {
.
// Your code
.
.
}
}
}
Model
[['mobile'],'unique','message'=>'Mobile No Already Exist'],
For Reference - Click Validate unique value from database in Yii2
if ($model->validate()) {
//SAVE YOUR DATA
} else {
// HERE YOU CAN PRINT THE ERRORS OF MODEL
$data = $model->getErrors();
Yii::$app->session->setFlash('message', $data['password'][0]);// its dislplays error msg on your form
}
This rule in my model worked for me:
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\app\models\Student', 'message' => 'This email address has already been taken.'],

yii2: get relation data in kartik editable widget

I am using kartik yii2 editable extension to edit inline in gridview.
The extension is working fine.
Please refer this screen-shot link [http://awesomescreenshot.com/00753dvb73][1]
In this screen-shot the source field is a dropdown and I want the value of source instead id its id
My View
use kartik\editable\Editable;
[
'attribute'=>'source',
'format'=>'raw',
'value'=> function($data){
//$s = $data->getBacklog_source();//var_dump($s);exit;
return Editable::widget([
'name'=>'source',
'model'=>$data,
'value'=>$data->source,
'header' => 'Source',
'type'=>'primary',
'size'=> 'sm',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=>$data->getSource(), // any list of values
'options' => ['class'=>'form-control', 'prompt'=>'Select Source'],
'editableValueOptions'=>['class'=>'text-danger'],
'afterInput' => Html::hiddenInput('id',$data->id),
]);
}
],
The relation I made is:
public function getSource()
{
$source = BacklogSource::find()->all();
return ArrayHelper::map($source, 'id', 'Source');
}
public function getBacklog_complexity()
{
return $this->hasOne(BacklogComplexity::className(), [
'id' => 'complexity'
]);
}
Thanks for help in advance
I got the solution something like this:
[
'attribute'=>'status',
'format'=>'raw',
'value'=> function($data){
$s = BacklogStatus::findOne($data->status);
return Editable::widget([
'name'=>'status',
'model'=>$data,
'value'=>$s->Status,
'header' => 'Status',
'type'=>'primary',
'size'=> 'sm',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=>$data->getStatus(), // any list of values
'options' => ['class'=>'form-control', 'prompt'=>'Select Source'],
'editableValueOptions'=>['class'=>'text-danger'],
'afterInput' => Html::hiddenInput('id',$data->id),
]);
}
],