Yii dynamical validation. Is there another way? - yii

I have some model. Depending on value of typeId some params should be required
typeId=1 Required: param2 param3 param4 param5 param6 param7 param9
typeId=2 Required: param1 param3 param4 param5
typeId=3 Required: param1 param3 param8 param9
typeId=4 Required: param1 param3
typeId=5 Required: param1 param10
So i solved it in this way:
public function rules()
{
return array(
array('typeId, param1, param2', 'numerical', 'integerOnly'=>true),
array('param3, param4, param5, param6, param7, param8, param9', 'length', 'max'=>20),
array('param10, param11', 'length', 'max'=>255),
array('created, deleted', 'safe'),
array('typeId', 'required', 'on'=>'insert, update'),
array('typeId', 'exist', 'attributeName'=>'id', 'className'=>'Type', 'message'=>'Select {attribute}'),
array('id, typeId, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, created, deleted', 'safe', 'on'=>'search'),
//dynamic rules
array('param1', 'required', 'on'=>'type2, type3, type4, type5'),
array('param1', 'exist', 'attributeName'=>'id', 'className'=>'Param1', 'message'=>'Select {attribute}', 'on'=>'type2, type3, type4, type5'),
array('param2', 'required', 'on'=>'type1'),
array('param2', 'exist', 'attributeName'=>'id', 'className'=>'Param2', 'message'=>'Select {attribute}', 'on'=>'type1'),
array('param3', 'required', 'on'=>'type1, type2, type3, type4'),
array('param4', 'required', 'on'=>'type1, type2'),
array('param5', 'required', 'on'=>'type1, type2'),
array('param6', 'required', 'on'=>'type1'),
array('param7', 'required', 'on'=>'type1'),
array('param8', 'required', 'on'=>'type3'),
array('param9', 'required', 'on'=>'type1, type3'),
array('param10', 'required', 'on'=>'type5'),
);
}
public function validate($attributes=null, $clearErrors=true)
{
if($clearErrors)
$this->clearErrors();
if($this->beforeValidate())
{
foreach($this->getValidators() as $validator)
$validator->validate($this,$attributes);
//validate dynamic rules
if(!$this->hasErrors())
{
$scenario=$this->scenario;
if($this->scenario=$this->getSubscenario($this->signalId))
{
foreach($this->getValidators() as $validator)
$validator->validate($this,$attributes);
}
$this->scenario=$scenario;
}
$this->afterValidate();
return !$this->hasErrors();
}
else
return false;
}
public function getSubscenario($typeId)
{
switch($typeId)
{
case Signal::TYPE_1:
return 'type1';
case Signal::TYPE_2:
return 'type2';
case Signal::TYPE_3:
return 'type3';
case Signal::TYPE_4:
return 'type4';
case Signal::TYPE_5:
return 'type5';
default:
return false;
}
}
Is there another way?

Related

File update laravel 8 Undefined variable: filename and filepath

I want to upload a blogger's profile image but I get an error:
Undefined variable: filename
Undefined variable: filepath
I think it is a controller issue. I don't know why the variable is not defined, though I declared the same variable name.
So please help me out.
public function update(Request $request)
{
$this->validate($request, [
'id' => 'required',
'company' => 'required',
'period' => 'required',
'desc' => 'required',
// 'file' => 'required|mimes:txt,xlx,xls,pdf,jpg,png|max:6048',
]);
$id = $request->id;
$send = Setting_product::findOrFail($id);
if($request->file()) {
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('files/'.$request->company.'/TC', $fileName, 'public');
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc,
'term_condition_file_path' => $filePath,
'term_condition_file' => $fileName,
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}else{
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}
}
public function update(Request $request)
{
$this->validate($request, [
'id' => 'required',
'company' => 'required',
'period' => 'required',
'desc' => 'required',
'file' => 'required|mimes:txt,xlx,xls,pdf,jpg,png|max:6048',
]);
$id = $request->id;
$send = Setting_product::findOrFail($id);
if ($request->hasFile('file')) {
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('files/'.$request->company.'/TC', $fileName, 'public');
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc,
'term_condition_file_path' => $filePath,
'term_condition_file' => $fileName,
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}else{
$send->update([
'company' => $request->company,
'period' => $request->period,
'desc' => $request->desc
]);
if ($send) {
return redirect()
->route('setting_produk.edit', $id)
->with([
'success' => 'New send has been created successfully'
]);
} else {
return redirect()
->back()
->withInput()
->with([
'error' => 'Some problem occurred, please try again'
]);
}
}
}

How to add validation rule with where condition in laravel 8?

$validatedData = $this->validate($request, [
'ldate' => 'required',
'type' => 'required',
'daytype' => 'required',
'employee' => 'required', 'exists:leaves,bemployee' //where condition i need here
'bemployee' => 'required',
'subject' => 'required',
'content' => 'required',
]);
Here is my validation. Tablename is Leaves. employee, bemployee and ldate are fields in table.
How can i check employee exists as bemployee in where ldate= $ldate?
Thanks in Advance
$valid= Validator::make($request, [
'contact'=> ['required',Rule::exists('tableName')->where(function ($query) use ($request) {
$query->where('column',$request->yourField);}),
],
],
);
if($valid->fails()){
// code
}else{
// code
}

How to make array taking data from database in laravel

why this is not working where all my queries are individually working.
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
this works manually like
$data = [
'name' => 'my_name',
'email' => 'my_email',
'phone' => 'my_phone',
'address' => 'my_address',
'gender' => 'my_gender',
];
return $data;
my whole function is given below:
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->get();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->get();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
When using get() it returns a collection not a single object so you can do
public function read($id){
$user=DB::table('users AS t1')
->select('t1.name','t1.email')
->where('t1.id',$id)->first();
$profile=DB::table('profiles AS t1')
->select('t1.phone','t1.gender','t1.occupation','t1.address')
->where('t1.user_id',$id)->first();
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $profile->phone,
'address' => $profile->address,
'gender' => $profile->gender,
];
return $data;
Or if you have relations defined on the models you can use the relation
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
public function read($id)
{
$user = User::with('profile')->findOrFail($id);
$data = [
'name' => $user->name,
'email' => $user->email,
'phone' => $user->profile->phone,
'address' => $user->profile->address,
'gender' => $user->profile->gender
];
return $data;
}

Yii2 right join only returning 2 columns

Working on an API and I have this query:
$query = CallerIdentity::findNonGeo()->join( 'RIGHT JOIN', 'ehadata', 'caller_ids.cidref = ehadata.cidref')
->select('ehadata.*')
->where(['caller_ids.cidref' => $id]);
echo $query->getSQL();die;
The output of the ->getSQL() function is:
SELECT `ehadata`.* FROM `caller_ids` RIGHT JOIN `ehadata` ON caller_ids.cidref = ehadata.cidref WHERE `caller_ids`.`cidref`='256'
and the result of running the query through the function in postman returns:
{
"cidref": 256,
"status": 0
}
However when I run the query in adminer the result is:
Has anyone got any idea why this might be? I am well and truly confused. Any help is massively appreciated.
EhaData model
class EHAData extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ehadata';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['cidref', 'status', 'name', 'premesis', 'thoroughfare', 'locality', 'postcode'], 'required'],
[['cidref', 'status'], 'integer'],
[['modified'], 'safe'],
[['title', 'forename', 'postcode'], 'string', 'max' => 20],
[['name', 'bussuffix'], 'string', 'max' => 50],
[['premesis'], 'string', 'max' => 60],
[['thoroughfare'], 'string', 'max' => 55],
[['locality'], 'string', 'max' => 30],
[['cidref'], 'exist', 'skipOnError' => true, 'targetClass' => CallerIdentity::className(), 'targetAttribute' => ['cidref' => 'cidref']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ehaid' => 'Ehaid',
'cidref' => 'Cidref',
'status' => 'Status',
'title' => 'Title',
'forename' => 'Forename',
'name' => 'Name',
'bussuffix' => 'Bussuffix',
'premesis' => 'Premesis',
'thoroughfare' => 'Thoroughfare',
'locality' => 'Locality',
'postcode' => 'Postcode',
'modified' => 'Modified',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCallerIdentity()
{
return $this->hasOne(CallerIdentity::className(), ['cidref' => 'cidref']);
}
}
Caller Identity model
class CallerIdentity extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'caller_ids';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['custref', 'caller_id', 'start_date'], 'required'],
[['custref', 'status', 'target_index'], 'integer'],
[['type', 'conf_call', 'magrathea', 'outbound_only', 'callrec_outbound', 'callrec_inbound'], 'string'],
[['start_date', 'last_polled', 'last_modified', 'created'], 'safe'],
[['caller_id'], 'string', 'max' => 15],
[['location', 'destination', 'redirect'], 'string', 'max' => 120],
[['country_code'], 'string', 'max' => 3],
[['details'], 'string', 'max' => 180],
[['expiry'], 'string', 'max' => 18],
[['custref'], 'exist', 'skipOnError' => true, 'targetClass' => Customer::className(), 'targetAttribute' => ['custref' => 'custref']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'cidref' => 'Cidref',
'custref' => 'Custref',
'caller_id' => 'Caller ID',
'location' => 'Location',
'destination' => 'Destination',
'redirect' => 'Redirect',
'type' => 'Type',
'conf_call' => 'Conf Call',
'magrathea' => 'Magrathea',
'outbound_only' => 'Outbound Only',
'callrec_outbound' => 'Callrec Outbound',
'callrec_inbound' => 'Callrec Inbound',
'country_code' => 'Country Code',
'details' => 'Details',
'status' => 'Status',
'start_date' => 'Start Date',
'expiry' => 'Expiry',
'target_index' => 'Target Index',
'last_polled' => 'Last Polled',
'last_modified' => 'Last Modified',
'created' => 'Created',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCustref()
{
return $this->hasOne(Customer::className(), ['custref' => 'custref']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEhadata()
{
return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}
/**
* #inheritdoc
* #return BanQuery the active query used by this AR class.
*/
public static function find()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'caller_ids.cidref','custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'caller_ids.status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE caller_ids.status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->with('ehadata')->asArray()->all();
return $query;
}
public static function findNonGeo()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['caller_ids.status' => '1'])
->andWhere(['type' => 'N']);
return $query;
}
public static function findFax()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref','caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['status' => '1'])
->andWhere(['type' => 'F']);
return $query;
}
public static function findConference()
{
$query = new CallerIdentityQuery(get_called_class());
$query->select([
'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
'type', 'redirect', 'destination', 'status', 'start_date',
'statusDesc' => new \yii\db\Expression("CASE status
WHEN 0 THEN 'Deactivated'
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Inactive'
WHEN 3 THEN 'Unregistered'
ELSE 'Permanently Deleted' END")])
->where(['status' => '1'])
->andWhere(['conf_call' => 'y']);
return $query;
}
}
just wild guessing...
there is also a ->joinWith method for your activequery, used for eager loading
add function extraFields() { return ['ehadata']; } to your CallerIdentity model; read more here http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#fields and call your api with &expand=ehadata param
Solved by adding this in to the CallerIdentity model.
public function fields()
{
$fields = parent::fields();
$fields[] = 'ehadata'; //name of relation
return $fields;
}
Output:
{
"cidref": 1234,
"custref": 288,
"caller_id": "01758364762",
"expiry": null,
"conf_call": "n",
"type": "S",
"redirect": null,
"destination": "846285845#sip.example.co.uk",
"status": 1,
"start_date": "2011-11-01",
"last_polled": "2011-11-01 13:59:51",
"ehadata": [
{
"status": 0,
"name": "Blah blah blah",
"bussuffix": "Ltd",
"premesis": "Blah House",
"thoroughfare": "Blah Road",
"locality": "Blahbach",
"postcode": "BLAH BLAH"
}
]
},

How display duplicate attribute error validation message in yii

I need display error message when user register end he input email which exist.I try this in my view:
<?php echo $form->errorSummary($model, NULL, NULL, array("class" => "standard-error-summary")); ?>
and this
if($model->hasErrors())
echo CHtml::errorSummary($model);
But it doesn't work.
There is my rules method of User model
public function rules()
{
return array(
array('status', 'numerical', 'integerOnly'=>true),
array('first_name, last_name, email, password', 'length', 'max'=>255),
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('id, status, first_name, last_name, email, password', 'safe', 'on'=>'search'),
);
}
RegistrationForm Model:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
and my register action:
public function actionRegister()
{
$model = new RegistrationForm;
if(isset($_POST['RegistrationForm']))
{
$model->attributes = $_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->first_name = $model->first_name;
$user->last_name = $model->last_name;
$user->password = $model ->password;
$user->email = $model->email;
$user->save();
}
}
$this->render('register',array('model'=>$model));
}
Such as you validate RegistrationForm model, you must have unique rule in it (not onlu in User model). So you can add this rule in your RegistrationForm model too:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
// THIS RULE CHECKS EMAIL UNIQUE IN RegistrationForm MODEL
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
So not not necessary to add custom rule.
Thanks!
I found solution. I added this method in my RegisterationForm Model
public function uniqueEmail($attribute, $params)
{
if($user = User::model()->exists('email=:email',array('email'=>$this->email)))
$this->addError($attribute, 'Email already exists!');
}
and added
array('email', 'uniqueEmail','message'=>'Email already exists!'),
to the rules method