I am facing issue about id field in the regular http://localhost/bekzcart/admin/users/edit/6 structure.
I have 6 fields for user, all are validated as 'non empty' through model. While editing one user I put one hidden field.
On submitting the form, naturally it gives me error (coming from model) saying 'non empty'. Without entering anything in that field, I hit submit again, now I face the issue.
What happens this time is that 'id' field from the url is now gone, http://localhost/bekzcart/admin/users/edit) and there is a new entry in database (ideally it should update though).
What might be the error?
My Users Controller:
class UsersController extends AppController {
var $name = 'Users';
function admin_edit($id) {
$this->User->id = $id;
$userLevels = $this->User->Level->find('list', array('fields' => array('LEVEL_ID', 'lEVEL_NAME')));
$this->set('levels', $userLevels);
if (empty($this->data)) {
$this->data = $this->User->read();
} else {
$this->User->set($this->data);
if ($this->User->validates(array('fieldList' => array('USER_LOGIN', 'USER_NAME', 'USER_EMAIL', 'USER_ADDRESS', 'USER_PHONE')))) {
$this->data['User']['USER_MODIFIED'] = DboSource::expression('NOW()');
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('Edit User Success.', true));
} else {
$this->Session->setFlash(__('Something wrong with the query', true));
}
}
}
}
}
User Model:
class User extends AppModel {
var $name = 'User';
var $primaryKey = 'USER_ID';
// Validation in here
// Association in here
}
My related view: admin_edit.ctp
$this->Form->input('id', array('type' => 'hidden')) // The Hidden Id Not Work
Many-many thanks for advance,
regrad
Brian ...
what version of cake are you using? update to the latest one, echo $this->Form->input('id'); will automatically be hidden.
And post the full code that generates the form, the output form should be something like this:
<form id="AdminUserEditForm" accept-charset="utf-8" action="/admin/users/edit/1" method="post">
One more suggestion: add 'created' and 'modified' fields to your users table (type datetime). Cake will keep track of these fields for you.
The field id must be replaced by the primary key used by the related table, in this case is USER_ID
$this->Form->input('USER_ID', array('type' => 'hidden'))
Related
I've created a form which adds a category of product in a Categories table (for example Sugar Products or Beer), and each user has their own category names.
The Categories table has the columns id, category_name, userId, created_At, updated_At.
I've made the validation and every thing is okay. But now I want every user to have a unique category_name. I've created this in phpMyAdmin and made a unique index on (category_name and userId).
So my question is this: when completing the form and let us say that you forgot and enter a category twice... this category exist in the database, and eloquent throws me an error. I want just like in the validation when there is error to redirect me to in my case /dash/warehouse and says dude you are trying to enter one category twice ... please consider it again ... or whatever. I am new in laravel and php, sorry for my language but is important to me to know why is this happens and how i solve this. Look at my controller if you need something more i will give it to you.
class ErpController extends Controller{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('pages.erp.dash');
}
public function getWarehouse()
{
$welcome = Auth::user()->fName . ' ' . Auth::user()->lName;
$groups = Group::where('userId',Auth::user()->id)->get();
return view('pages.erp.warehouse', compact('welcome','groups'));
}
public function postWarehouse(Request $request)
{
$input = \Input::all();
$rules = array(
'masterCategory' => 'required|min:3|max:80'
);
$v = \Validator::make($input, $rules);
if ($v->passes()) {
$group = new Group;
$group->group = $input['masterCategory'];
$group->userId = Auth::user()->id;
$group->save();
return redirect('dash/warehouse');
} else {
return redirect('dash/warehouse')->withInput()->withErrors($v);
}
}
}
You can make a rule like this:
$rules = array(
'category_name' => 'unique:categories,category_name'
);
I'd like to ask, is it possible to change the original posted attributes in actionCreate()?
For example I have 3 attributes: name, phNumber, address
In the _form.php, it automatically posts these 3 attributes. BUT what if I want to change the posted name attribute to all Uppercases? Do I need to create my own method of creating a record just to change how the name will be recorded OR is there something that I can do in actionCreate() so that it only changes the name attribute?
For example, user types in
adam michael
for the name textbox, and I want to change only this attribute to
ADAM MICHAEL
to be recorded in the database instead of having to create another method.
Code below:
public function actionCreate() {
$model = new Masseuse;
if (isset($_POST['Masseuse'])) {
$model->setAttributes($_POST['Masseuse']);
if ($model->save()) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('servicemasseuse/create', 'mid' => $model->id));
}
}
$this->render('create', array( 'model' => $model));
}
Just simply do a $model->name=strtoupper($model->name);
Refer here
You must alter the user input prior to saving the data. You do this by creating an overwritten function in your model.
class Masseuse extends CActiveRecord {
// ...
public function beforeSave()
{
$this->name = strtoupper($this->name)
}
}
I have the following code for updating a Yii model:
public function actionSettings($id) {
if (!isset($_POST['save_hostname']) && isset($_POST['Camera']) && isset($_POST['Camera']['hostname'])) {
$_POST['Camera']['hostname'] = '';
}
$model = $this->loadModel($id);
$model->setScenario('frontend');
$this->performAjaxValidation($model);
if (isset($_POST['Camera'])) {
$model->attributes = $_POST['Camera'];
unset($model->api_password);
if ($model->save()) {
Yii::app()->user->setFlash('success', "Camera settings has been saved!");
} else {
Yii::app()->user->setFlash('error', "Unable to save camera settings!");
}
}
$this->render('settings', array(
'model' => $model,
));
}
This works fine, except in my model I have code like this:
<h1>Settings For: <?php echo CHtml::encode($model->name); ?></h1>
The problem is that, even when the user input fails validation, the h1 tag is having bad input echoed out into it. If the input fails the validation, the h1 attribute should stay the same.
I can 'reset' the $model variable to what is in the database before the view is returned, but this then means I don't get any error feedback / validation failed messages.
Is my only option to have 2 $models ($model and $data perhaps), one used for handling the form and the other for sending data to the page? Or does someone have a more elegant solution?
performAjaxValidation assigns all save attributes to the model so this behavior is normal.
I would reload model if save fails.
$model->refresh();
My app works with other models, but for some reason the "Vote" model cannot connect to the db table when I try to save to it. I've been at this for a couple days and I feel like I've tried everything!
here is my controller VoteController.php that calls the model (edited down for readability):
<?php
class VoteController extends AppController {
var $uses = array('Track', 'Vote');
function upvote() {
$this->autoRender = false;
$User = $this->auth();
if ($User) {
$track_id = #$this->params['id'];
$this->Vote->upvote($track_id, $User['User']['id']);
}
}
}
?>
here is the model vote.php:
<?php
App::uses('AppModel', 'Model');
class Vote extends AppModel {
var $name = 'Vote';
function upvote($id, $user_id) {
$VoteObject = array('Vote' => array(
'u_id' => $user_id,
't_id' => $id,
'upvote' => 1,
'downvote' => 0
));
$this->save($VoteObject);
}
}
?>
And of course, in my database, I have a table "votes" with columns id, u_id, t_id, upvote, and downvote.
After everything executes, I get this error:
Missing Database Table
Error: Table votes for model Vote was not found in datasource default.
I've tried deleting the files in tmp, as well as renaming everything, printing out queries, etc, and I can't seem to get anywhere. Any help would be greatly appreciated!
try removing this line
App::uses('AppModel', 'Model');
and adding this to the class
var $useTable = 'votes';
It looks like it's trying to use the correct name. so that might not be an issue. Can you verify that your data source is setup correctly.
Try clearing the tmp/cache directory.
Fixed for me.
According to CakePhp Conventions, your controller should be pluralized with the word Controller in the end, also make sure you named your controller as VotesController.php
<?php
class VotesController extends AppController {
}
?>
On the Model you are using:
var $name = 'Vote';
and you should use: var $name = 'Votes'; (Plural) and make sure your model name is Vote.php (Singular).
Also you should be doing:
function upvote($id, $user_id) {
$VoteObject = array('Vote' => array(
'u_id' => $user_id,
't_id' => $id,
'upvote' => 1,
'downvote' => 0
));
$this->save($VoteObject);
}
inside your Controller not into the model.
There is a 'main.php' view that contains a form with email and name fields and a submit button. Eveyrthing works fine with action_index (the code is below), but I'm curious how to modify the code below so it validates if the email was entered correctly. It should not put values in the database if the email field is not valid. I hope it is possible to made using ->rule. Is it? If yes, then how where to add the validation? (I had no luck trying it in different ways).
public function action_index()
{
if ( !empty($_POST) ) {
$model = ORM::factory('tbl1'); // create
$model->values($_POST); // load values to model
if ($model->check()) {
$model->save(); // save the model
} else {
//show errors
}
}
$this->response->body(View::factory('main'));
}
Thank you.
Use rules function in your ORM model:
public function rules()
{
return array(
'email' => array(
array('email', array(':value')),
),
);
}