Yii - validate custom field - validation

I use model which not contain attribute 'countries' because I'm saving it in relations-model via many-to-many relation. When I'm creating form in view I use multiple select for custom field 'countries'. How can I validate it from model on $model->validate()?

// protected/extensions/validators/CountryValidator.php
class CountryValidator extends CValidator
{
/**
* #inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
/* #var $object CFormModel */
// for example check exist countryId in db or no
// you can use any other logic
$country = Country::model()->findByPk($object->$attribute);
if (null != $country) {
$object->addError($attribute, 'country not found');
}
}
...
// in your model
public function rules()
{
return array(
array('countryId', 'ext.validators.CountryValidator'),
...
// in config
'import' => array(
'ext.validators.*',
...
How to use:
$yourModel = new YourModel();
$yourModel->countryId = -1;
$yourModel->validate();
print_r($yourModel->getErrors()); die();

Related

Laravel Importing to Excel , error when passing a variable

I want to import some categories, but what i need is also the parent category id.
public function importCategory(Request $request, $cat_id){
$import = new CategoryImport($cat_id);
$import->import($request->file);
if ($import->failures()->count() > 0) {
$message = '';
foreach ($import->failures() as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return redirect()->back();
} else {
return redirect()->back()->with('success', sprintf('Success'));
}
}
Here is the CategoryImport.php
class CategoryImport implements WithHeadingRow, WithValidation, SkipsOnFailure,OnEachRow
{
use Importable, SkipsFailures;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
protected $cat_id = null;
public function __construct( $cat_id) {
$category_id = $cat_id;
}
public function onRow(Row $row)
{
$row=$row->toArray();
Category::create([
'name' => $row['name'],
'image' => $row['image'],
'business_category_id' => $this->category_id,
]);
}
}
So here is the error, it says undefined property, and i am trying to figure it out but don't understand.
Undefined property: App\Imports\CategoryImport::$category_id
Inside the constructor you need to assign the correct variable.
class CategoryImport implements WithHeadingRow, WithValidation, SkipsOnFailure,OnEachRow
{
use Importable, SkipsFailures;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
protected $cat_id = null;
public function __construct($cat_id) {
$this->cat_id = $cat_id;
}
I think the line 'business_category_id' => $this->category_id is wrong. You need to use
'business_category_id' => $this->cat_id
because that is the variable you assign in the constructor.
You didn't set cat_id properly. In your CategoryImport you should have :
protected $category_id = null;
public function __construct($cat_id) {
$$this->category_id = $cat_id;
}

Laravel: How do i fix this trait (with attributes) to also work when creating a model?

I'm using a trait to dynamically add e-mail attribute(s) to a model. It gives me the possibility to reuse code amongst many models. However, this code fails when i try to create a new model (but succeeds when i update an existing model).
The issue is the assumption that $this->id is available in Traits/Contact/HasEmails > setEmailTypeAttribute. Id is not yet available, because saving is not finished.
My question: How can i fix this trait to also work when creating a model?
Google, no results
Thinking about something of model events (static::creating($model))
\app\Traits\Contact\HasEmails.php
/*
* EmailGeneric getter. Called when $model->EmailGeneric is requested.
*/
public function getEmailGenericAttribute() :?string
{
return $this->getEmailTypeAttribute(EmailType::GENERIC);
}
/*
* EmailGeneric setter. Called when $model->EmailGeneric is set.
*/
public function setEmailGenericAttribute($email)
{
return $this->setEmailTypeAttribute(EmailType::GENERIC, $email);
}
/*
* Get single e-mail model for model owner
*/
private function getEmailTypeAttribute($emailType) :?string
{
$emailModel = $this->emailModelForType($emailType);
return $emailModel ? $emailModel->email : null;
}
/*
* Update or create single e-mail model for model owner
*
* #return void
*/
private function setEmailTypeAttribute($emailType, $email) :void
{
$this->emails()->updateOrCreate([
'owned_by_type' => static::class,
'owned_by_id' => $this->id,
'type' => $emailType
],['email' => $email]);
}
\app\Models\Email.php
namespace App\Models;
class Email extends Model
{
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email'
];
/*
* Get polymorphic owner
*/
public function ownedBy(): \Illuminate\Database\Eloquent\Relations\MorphTo
{
return $this->morphTo();
}
/*
* Default attributes are prefilled
*/
protected function addDefaultAttributes(): void
{
$attributes = [];
$attributes['type'] = \App\Enums\EmailType::GENERIC;
$this->attributes = array_merge($this->attributes, $attributes);
}
}
\migrations\2019_10_16_101845_create_emails_table.php
Schema::create('emails', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('owned_by_id');
$table->string('owned_by_type');
$table->string('type'); //f.e. assumes EmailType
$table->string('email');
$table->unique(['owned_by_id', 'owned_by_type', 'type'], 'owner_type_unique');
});
I expect a related model to be created/updated, but it fails on creating.
Trick was using a saved model event and also not forgetting to set the fillable attribute on the email model:
/*
* Update or create single e-mail model for model owner
*
* #return void
*/
private function setEmailTypeAttribute($emailType, $email) :void
{
static::saved(static function($model) use($emailType, $email) {
$model->emails()
->updateOrCreate(
[
'owned_by_type' => get_class($model),
'owned_by_id' => $model->id,
'type' => $emailType
],
[
'email' => $email
]);
});
}

How To Insert and Update Data From Same Form using Codeigniter

Can Anyone Help me to write Controller,Model and View From Which There Would Be a Single form(View) That takes the Hidden Id and Controller Checks whether The Request From View have id or not and depending upon that it would insert and update the same.
Basically you just have to check if the hidden id exists in your database or not. If it doesn't then you insert, if it does you update. Generally this is how you do it:
<?php
class some_controller extends CI_Controller {
/**
* Submits the form
*
* #return boolean
*/
public function submit_form() {
$id = $this->input->post('id');
$data = array(
'somedata' => $this->input->post('somedata'),
'someotherdata' => $this->input->post('someotherdata')
);
$this->load->model('some_model');
if (!is_null($id) && $this->some_model->id_exists($id)) {
return $this->db->update('sometable', array('id' => $id), $data);
} else {
// assumes sometable autoincrements id
// otherwise $data = array_merge(array('id' => $id), $data);
return $this->db->insert('sometable', $data);
}
}
}
class some_model extends CI_Model {
/**
* Checks if id exists in sometable
*
* #return boolean TRUE if item with $id exists in sometable
*/
public function id_exists($id) {
$this->db->where('id', $id);
return $this->db->count_all_results('sometable') > 0;
}
}
Please note: good practice would call for moving the insert and update (in fact all queries) into a model. This is just an example.

Do something before saving model to database in Laravel 5.1

How can I do something such as modify some data fields or more validate before writing data to database in Laravel 5.1 model ?
It's document about that problem is hard to use in real application: http://laravel.com/docs/5.1/eloquent#events
My code is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;
class Atoken extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'atoken';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'token',
'user_id',
'role',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
];
public static function newToken($userId, $role){
# Remove all token assoiciate with input user;
Atoken::where('user_id', $userId)->delete();
$params = [
'user_id' => $userId,
'role' => $role,
];
Atoken::insert($params);
$item = Atoken::where('user_id', $userId)->first();
return $item->token;
}
protected static function boot(){
static::creating(function ($model) {
$model->token = 'sometoken';
});
}
}
In this case, I always got error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))
How can I fix it?
class Lunch extends Eloquent
{
protected static function boot()
{
static::creating(function ($model) {
$model->topping = 'Butter';
return $model->validate();
});
}
protected function validate()
{
// Obviously do real validation here :)
return rand(0, 1) ? true : false;
}
public static function newToken($userId, $role)
{
static::where('user_id', $userId)->delete();
return static::create([
'user_id' => $userId,
'role' => $role,
])->token;
}
}
I would recommend to go into EventServiceProvider, and register event listeners
public function boot(DispatcherContract $events)
{
parent::boot($events);
// Register Event Listeners
\App\Product::updating(function ($product) {
$product->onUpdating();
});
...
then create function onUpdating within the model. You also can choose from saving, saved, creating, created, updating, updated..
This documentation has more:
https://laravel.com/docs/5.1/eloquent#events

Laravel 5 FormRequest validator with multiple scenarios

I would like to ask how should I handle validation on multiple scenarios using FormRequest in L5? I know and I was told that I can create saparate FormRequest files to handle different validations but it is very redundant and also noted that I would need to inject it into the controller manually using the use FormRequest; keyword. What did previously in L4.2 is that I can define a new function inside my customValidator.php which then being called during controller validation via trycatch and then the data is being validated by service using the below implementation.
class somethingFormValidator extends \Core\Validators\LaravelValidator
{
protected $rules = array(
'title' => 'required',
'fullname' => 'required',
// and many more
);
public function scenario($scene)
{
switch ($scene) {
case 'update':
$this->rules = array(
'title' => 'required',
'fullname' => 'required',
// and other update validated inputs
break;
}
return $this;
}
}
Which then in my LaravelValidator.php
<?php namespace Core\Validators;
use Validator;
abstract class LaravelValidator {
/**
* Validator
*
* #var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Validation data key => value array
*
* #var Array
*/
protected $data = array();
/**
* Validation errors
*
* #var Array
*/
protected $errors = array();
/**
* Validation rules
*
* #var Array
*/
protected $rules = array();
/**
* Custom validation messages
*
* #var Array
*/
protected $messages = array();
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
/**
* Set data to validate
*
* #return \Services\Validations\AbstractLaravelValidator
*/
public function with(array $data)
{
$this->data = $data;
return $this;
}
/**
* Validation passes or fails
*
* #return Boolean
*/
public function passes()
{
$validator = Validator::make(
$this->data,
$this->rules,
$this->messages
);
if ($validator->fails())
{
$this->errors = $validator->messages();
return false;
}
return true;
}
/**
* Return errors, if any
*
* #return array
*/
public function errors()
{
return $this->errors;
}
}
and then finally this is how i call the scenarios inside services like this
public function __construct(somethingFormValidator $v)
{
$this->v = $v;
}
public function updateSomething($array)
{
if($this->v->scenario('update')->with($array)->passes())
{
//do something
else
{
throw new ValidationFailedException(
'Validation Fail',
null,
$this->v->errors()
);
}
}
So the problem is now since i have migrated to L5 and L5 uses FormRequest, how should I use scenario validation in my codes?
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class ResetpasswordRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'login_email' => 'required',
'g-recaptcha-response' => 'required|captcha',
];
}
public function messages()
{
return [
'login_email.required' => 'Email cannot be blank',
'g-recaptcha-response.required' => 'Are you a robot?',
'g-recaptcha-response.captcha' => 'Captcha session timeout'
];
}
public function scenario($scene)
{
switch ($scene) {
case 'scene1':
$this->rules = array(
//scenario rules
);
break;
}
return $this;
}
}
also how should I call it in the controller?
public function postReset(ResetpasswordRequest $request)
{
$profile = ProfileService::getProfileByEmail(Request::input('login_email'));
if($profile == null)
{
$e = array('login_email' => 'This email address is not registered');
return redirect()->route('reset')->withInput()->withErrors($e);
}
else
{
//$hash = ProfileService::createResetHash($profile->profile_id);
$time = strtotime('now');
$ip = Determinator::getClientIP();
MailProcessor::sendResetEmail(array('email' => $profile->email,
'ip' => $ip, 'time' => $time,));
}
}
I believe the real issue at hand is everything is validated through the form request object before it reaches your controller and you were unable to set the appropriate validation rules.
The best solution I can come up with for that is to set the validation rules in the form request object's constructor. Unfortunately, I am not sure how or where you are able to come up with the $scene var as it seems to be hard-coded in your example as 'update'.
I did come up with this though. Hopefully reading my comments in the constructor will help further.
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TestFormRequest extends Request
{
protected $rules = [
'title' => 'required',
'fullname' => 'required',
// and many more
];
public function __construct()
{
call_user_func_array(array($this, 'parent::__construct'), func_get_args());
// Not sure how to come up with the scenario. It would be easiest to add/set a hidden form field
// and set it to 'scene1' etc...
$this->scenario($this->get('scenario'));
// Could also inspect the route to set the correct scenario if that would be helpful?
// $this->route()->getUri();
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return $this->rules;
}
public function scenario($scene)
{
switch ($scene) {
case 'scene1':
$this->rules = [
//scenario rules
];
break;
}
}
}
You can use laratalks/validator package for validation with multiple scenarios in laravel. see this repo

Resources