cakephp3 isUnique rule need to use entered value in error message - cakephp-3.0

I need to show the validation message along with the entered value in isUnique rule.
public function buildRules(RulesChecker $rules)
{
$rules->add(
$rules->isUnique(
['user_name'],
'This User Name is already in use'
)
);
return $rules;
}
Above code will display error message 'This User Name is already in use' when the user name is a duplicate one. But I want the message as "User name -entered name- is already in use"

I don't know if there is a cakephp way of doing this.
but you could try:
public function buildRules(RulesChecker $rules)
{
$rules->add(
$rules->isUnique(
['user_name'],
'This User Name ' . $_POST['user_name'] . ' is already in use'
)
);
return $rules;
}
it works for me when I use it like:
public function validationDefault(Validator $validator)
{
$validator->add['user_name', 'unique' [
'rule'=> 'validateUnique',
'provider' => 'table',
'message' => 'Username ' $_POST['user_name'] . ' is already in use'
]);
return $validator;
}

Related

checkbox data not insert in mysql using codeigniter

I try to insert my checkbox data in CodeIgniter. but data did not inserted in the database.
here is my view file:
<input type="checkbox" name="feature[]" value="WIFI" >
<input type="checkbox" name="feature[]" value="TV">
I am trying to use implode to convert the array into the string, but then I don't how to add in $data array, so they inserted in together
here is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$fea=array(
'feature'=>json_encode(implode(",",$feature))
);
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code')
);
if($this->Partner_model->save($user_data,$fea))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
& here is my model:
public function save($data,$fea)
{
return $this->db->insert('property', $data,$fea);
}
Your model is faulty.
You are passing three arguments to insert() but the third you use is not appropriate.
That argument should be a boolean that indicates whether to escape values and identifiers or not. You need to incorporate $fea into $data which should probably be done in the controller.
There is an easier way to create the array $user_data since it is essentially a copy of $_POST just use $this->input->post().
Also, there is no obvious reason why you use json_encode. Unless you need it that way when you retrieve it from the DB there is no reason to bother with it. Consider removing json_encode.
First, change the model
public function save($data)
{
return $this->db->insert('property', $data);
}
Here's a revised save method
public function save()
{
$this->load->model('Partner_model');
$user_data = $this->input->post(); //makes a copy of $_POST
$feature = $this->input->post('feature');
if($feature) //because $feature will be null if no boxes are checked
{
$user_data['feature'] = json_encode(implode(",", $feature));
}
$msg = $this->Partner_model->save($user_data) ? "save sucesss" : "not save";
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
An explanation as requested via comments.
A call to $this->input->post('pname') returns the value of $_POST['pname'] if it is exists, but returns null if it does not exist.
When you create $user_data you make six calls to $this->input() with a different "key" each time to make a copy of $_POST.
$this->input->post() without any arguments returns the whole $_POST array. (See documentation)
$user_data = $this->input->post();
Makes a copy of $_POST using one line of code. It will include $_POST['feature'] if any boxes are checked, but $_POST['feature'] will not be set if no boxes are checked.
There are two ways to test if any boxes were checked. First we can test if isset($_POST['feature']) == true or we can test if $this->input->post('feature') == true. I use the second with the call
if($feature)
Which is pretty much the same as any of the following lines
if($feature != false)...
if($feature != null)...
if( ! empty($feature))...
if( ! is_null($feature))...
In other words, if($feature) evaluates as true if $feature is set and is anything except null, false, 0, "0", "" (an empty string), array() (an empty array)
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'feature'=>json_encode(implode(",",$feature))
);
if($this->Partner_model->save($user_data)){
$msg = "save sucesss" ;
}else{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
model file should be :
public function save($data) {
return $this->db->insert('property', $data);
}

How to force data update on laravel validation custom unique

I'm new in laravel. I have a table with menu_id and title I tried to make this title field unique when have the same menu_id. I found the solution here
But I got problem when update it. Can anyone help please?
My code
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
public function updateSubmenu( Request $request) {
$this->validate( $request, [
'menu_id' => 'required',
'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
'order_by' => 'required|integer',
'description' => 'required'
],
[
'title.unique_custom' => 'This title already token'
]
);
}
Can you explain what problem have you got on update? Some exception?
Edit:
If you couldn't update record if title not changes, you need to add one condition to Validator:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// If old value not changed, don't check its unique.
$current = \DB::table($table)->where('title')->first();
if( $current->{$field} == $value) {
return true;
}
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

how to add data from Employee table to user table in YII2 advanced

I am working on my collage project i.e. Employee Management. I have Employee table in sql(crud is also generated from gii). only Admin is having rights to create Employee (there is no Signup).
My Problem: when I am creating employee then I am not able to save data in user table also, please help me to save data in both Employee and user table.
Thanks in advance
Update:
Below is the code:
public function actionCreate() {
$model1=new Employee;
$model2=new User;
if(isset($_POST['Employee']) && isset($_POST['User']))
{
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save();
$model2->save();
echo 'data is saved in both tables';
}
$this->render('create',array('model1'=>$model1,model2'=>$mod‌​‌​el2));
}
could be you have some validation problem
try check this way
......
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
if ($model1->validate() && $model2->validate() ) {
$model1->save();
$model2->save();
} else {
$errors1 = $model1->errors;
$errors2 = $model2->errors;
var_dump($errors1);
var_dump($errors2);
exit();
}
then just for debug try using
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save(false);
$model2->save(false);
and check in db if the value are saved ..
You can try this example,
public function actionCreate()
{
$model = new Employee();
$user = new User();
if ($model->load(Yii::$app->request->post()) && $user->load(Yii::$app->request->post())) {
if($model->save() && $user->save()) {
Yii::$app->session->setFlash('success', 'Record saved successfully.');
} else {
//var_dump($model->getErrors());
//var_dump($user->getErrors());
Yii::$app->session->setFlash('error', 'Record not saved.');
}
return $this->redirect(['index']);
} else {
var_dump($model->getErrors());
var_dump($user->getErrors());
die();
}
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Follow the instruction given in below link . This should work
how to insert data to 2 tables i.e Employee and User(migrated) from single form(Employee Create) and controller in yii2

QueryException - Integrity constraint violation: 1062 Duplicate entry when I hit the route 'logout'

I get the above error when I try and logout by hitting the route /logout. The table that is referenced in the screenshot is mdbids. It stores all of my IDs (strings, 16 characters in length).
When a user is created their MDBID (id) is stored in the mdbids table.
routes.php
<?php
Route::get('login', ['as' => 'login', 'uses' => 'SessionsController#create']);
Route::get('logout', ['as' => 'logout', 'uses' => 'SessionsController#destroy']);
SessionsController.php
<?php
use MDB\Forms\LoginForm;
class SessionsController extends \BaseController {
protected $loginForm;
function __construct(LoginForm $loginForm)
{
$this->loginForm = $loginForm;
}
public function create()
{
if(Auth::check()) return Redirect::to("/users");
return View::make('sessions.create');
}
public function store()
{
$this->loginForm->validate($input = Input::only('email','password'));
if (Auth::attempt($input)) {
Notification::success('You signed in successfully!');
return Redirect::intended('/');
}
Notification::error('The form contains some errors');
return Redirect::to('login')->withInput()->withFlashMessage("The form contains some errors");
}
public function destroy()
{
Auth::logout();
return Redirect::home();
}
}
The following is taken from my User.php (model) file. It isn't the whole file as it is fairly big, but this is the only part where IDs are mentioned.
User.php (model)
<?php
public function save(array $options = array())
{
$this->mdbid = $this->mdbid ?: str_random(16);
$this->key = $this->key ?: str_random(11);
Mdbid::create([
'mdbid' => $this->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
parent::save($options);
}
I don't know where to start to look. Any help is greatly appreciated.
Your issue is that the logout is actually causing save() to run, and therefor you are causing Mdbid::create to run with an already added key (presumably when you logged in, or somewhere else in your User model?).
Solution #1:
You could add a logout() function to the User model that you have. Something similar to
function logout()
{
$this->mdbid = null;
return Auth::logout()
}
This will stop two of the same keys being added to the logout function.
Solution #2
If what you are trying to accomplish is adding a row upon a successful login, then you should not be using the User::save() function, rather, you should be listening for the auth.login event.
Inside app/start/global.php, add the following code:
Event::listen('auth.login', function($user)
{
$user->mdbid = $user->mdbid ?: str_random(16);
$user->key = $user->key ?: str_random(11);
Mdbid::create([
'mdbid' => $user->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
});
This will ensure only one row gets added to Mdbid per successful login, instead of adding a new row (with the same id) each time the User model is updated.
Solution #3 (a.k.a. what was really wanted)
Each table has mdbid as a primary key. Each primary key needs to be added to the Mdbid table each time a new row is inserted.
The way that this should be done is with an Observer. The first part is adding a new Observer class that will be used for all of the models we want to add the mdbid into:
class MdbidObserver
{
/**
* Observe new rows being added into the database
*/
public function creating($model)
{
// note that $model could be any model
$model->mdbid = $model->mdbid ?: str_random(16);
$model->key = $model->key ?: str_random(11);
Mdbid::create([
'mdbid' => $model->mdbid,
'table_number' => 7,
'table_name' => 'users',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
}
}
The second part is adding the Observer to all the models that we want the mdbid added to (inside app/start/global.php):
User::observe(new MdbidObserver);
Artist::observe(new MdbidObserver);
Album::observe(new MdbidObserver);
To stop any issues with mdbid not actually being random already being used, you might want to add a loop just before $model->mdbid. Something similar to:
$isUnique = false;
while (!$isUnique)
{
$unqiueId = str_random(16);
$row = Mdbid::where('mdbid', $uniqueId);
if (is_object($row))
$isUnique = true;
}
$model->mdbid = $uniqueId;

Getting error while updating User data in cakephp2.4.0

I am getting error on saving the edited data. Actually User clicked on the edit button User is redirected to edit data page at the end (after) editing the data when user wants to save the edited data cakephp gives error sql integrity violation code 1062. The code for edit is default code generated by the cake bake. the code is
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
i also tried savefield instead of save but that is adding new user with all null fields.
You should set the id property on the user before you save it:
$this->User->id = $id;
Or make sure that in your $this->request->data;, the id of the object your are editing is present, $this->request->data['User']['id']; in this particular case, the absence of the user id on the request data is causing the problem.