My controller action is:
function add() {
if (!empty($this->data)) {
$this->Customer->create();
if ($this->Customer->save($this->data)) {
$this->Session->setFlash('A new Customer has been added');
$this->redirect(array('action'=>'index'));
}
else {
$this->Session->setFlash('The customer cannot be added this time. Try again later.');
$this->redirect(array('action'=>'index'));
}
}
}
My model is:
class Customer extends AppModel {
var $name = 'Customer';
var $validate = array(
'name' => array(
'length'=> array(
'rule' => array('between', 4,50),
'message' => 'Name must be minimum 4 and maximum 50 characters long.'
),
'checkUnique'=> array(
'rule' => 'isUnique',
'message' => 'This Name is already registered'
)
));
and this is my view:
<div class="customers form">
<?php echo $form->create('Customer',array('action'=>'add'));?>
<fieldset>
<legend><?php __('Add Customer');?></legend>
<?php
echo $form->input('Customer.name');
echo $form->input('Customer.balance',array('type'=>'hidden','default'=>0));
?>
</fieldset>
<?php echo $form->end('Submit');?>
</div>
every time I submit the form it splashes:
The customer cannot be added this time. Try again later.
For the hidden input field use 'value' instead of 'default' in your view:
$form->input('Customer.balance', array('type' => 'hidden', 'value' => 0));
Related
I have an Up which has to do a lot with pictures. I have a problem. I know might seems stupid, and even i know that im missing something, but i havent found out yet. So in few words. Let's say I have an Item. |id|name|price|condition|location|picture|
picture is the picture path that i save to DB. So when i create a new Item all the field are required. Till here everything works Fine.Now lets say i open Item x to edit. I edit only the name and the price and other i leave them as they are, and i press save, browse button, of the picture field is still required and i have to open galerry find the pic again in order to save. So my question is this: How can i do a picture upload only if i browse for the picture, but not to forget that on creation must not be empty. To Ilustrate it here is some code:
<?php
App::uses('AppModel', 'Model');
class Item extends AppModel {
public $name = 'Item';
public $primaryKey = 'id';
public $displayField = 'title';
public $validate = array(
'id' => array(
'blank' => array(
'rule' => 'blank',
'on' => 'create',
),
),
'title' => array(
'words' => array(
'rule' => array('custom', '/[0-9A-Za-z\._-]/'),
'message' => 'The Item name can only contain letters, numbers and spaces.',
),
'maxLength' => array(
'rule' => array('maxLength', 100),
'message' => 'The Item name must not be longer than 100 characters.',
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'The Item name must not be empty.',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This Item name already exists.',
),
),
'picture' => array(
'uploadError' => array(
'rule'=>'uploadError',
'message' => 'The File Did NOT Upload. Please Try Again!',
),
'fileSize'=>array(
'rule'=>array('fileSize','<=','30MB'),
'message'=>'File Size should be less then 30MB',
),
'processMediaUpload'=>array(
'rule' =>'processMediaUpload',
'message'=>'Uploading File Failed!',
),
),
'item_location_id' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'You Must Choose a Location',
),
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
),
),
'address' => array(
'words' => array(
'rule' => array('custom', '/[0-9A-Za-z\._-]/'),
'message' => 'The Item Address can only contain letters, numbers and spaces.',
),
'maxLength' => array(
'rule' => array('maxLength', 150),
'message' => 'Address can not be longer then 150 characters long',
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'You Should Put an Address',
),
),
);
public $belongsTo = array(
'ItemLocation' => array(
'className' => 'ItemLocation',
'foreignKey' => 'item_location_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
public function processMediaUpload($mediacheck = array()) {
$dir = 'img/uploads/item/media/';
if (isset($mediacheck['media_path']['name'])) {
if(is_uploaded_file($mediacheck['media_path']['tmp_name'])) {
if (trim($mediacheck['media_path']['name'])!=""){
// here we delete if the image exist and replace it.
if (file_exists(WWW_ROOT . $dir . $mediacheck['media_path']['name'])) {
unlink(WWW_ROOT . $dir . $mediacheck['media_path']['name']);
return true;
}
}
$allowedExts = array('jpeg', 'png', 'jpg', 'gif');
$extension=strtolower(end(explode(".", $mediacheck['media_path']['name'])));
if (($mediacheck['media_path']['size'] < 55000000)) {
if(in_array($extension, $allowedExts)){
if ($mediacheck['media_path']["error"] > 0) {
$this->invalidate('media_path', $mediacheck['media_path']['error']);
return false;
} else {
if (file_exists( WWW_ROOT . $dir) && is_dir( WWW_ROOT . $dir)) {
if (file_exists( WWW_ROOT . $dir . $mediacheck['media_path']['name'])) {
$this->invalidate('media_path', 'File Allredy Exists!');
return false;
} else {
move_uploaded_file($mediacheck['media_path']['tmp_name'], WWW_ROOT . $dir . mktime() . $mediacheck['media_path']['name']);
$this->data[$this->alias]['media_path'] = mktime() . $mediacheck['media_path']['name'];
return TRUE;
}
} else { // in this case the directory doesent exist so we create it
mkdir($dir, 0777, true);
move_uploaded_file($mediacheck['media_path']['tmp_name'], WWW_ROOT . $dir . mktime() . $mediacheck['media_path']['name']);
$this->data[$this->alias]['media_path'] = mktime() . $mediacheck['media_path']['name'];
return TRUE;
}
}
}else { $this->invalidate('media_path', 'Invalid File Format! '); return false;}
} else { $this->invalidate('media_path', 'File size is To big!'); return false; }
} else { $this->invalidate('media_path', 'You must upload a file before you Submit!'); return false; }
} else { $this->invalidate('media_path', 'You must upload a file before you Submit!'); return false; }
// better safe then sorry!
return false;
}
Add Form:
<div class="items form">
<?php echo $this->Form->create('Item', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Add New Item'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('title');
echo $this->Form->input('item_description');
echo $this->Form->input('location_description');
echo $this->Form->input('media_path', array('label'=>'Media','type'=>'file'));
echo $this->Form->input('item_location_id', array('label'=>'Location'));
echo $this->Form->input('item_characteristic_id', array('label'=>'Characteristics'));
echo $this->Form->input('address', array('id' => 'address'));
echo "<div id=\"map_canvas\" style=\"width:98%; height:400px;\"> </div>";
echo $this->Form->input('longitude', array('id'=>'longitude', 'readonly'=>'readonly'));
echo $this->Form->input('latitude', array('id'=>'latitude', 'readonly'=>'readonly'));
echo $this->Form->input('first_seller_id');
echo $this->Form->input('second_seller_id');
echo $this->Form->input('brochure_path', array('label'=>'Broshure','type'=>'file'));
echo $this->Form->input('seo_title');
echo $this->Form->input('seo_description' , array('label' => 'SEO Description'));
echo $this->Form->input('seo_url' , array('label' => 'SEO Url'));
echo $this->Form->input('seo_keywords' , array('label' => 'SEO Keywords'));
?>
</fieldset>
Edit Form:
<div class="items form">
<?php echo $this->Form->create('Item', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Edit Item'); ?></legend>
<?php
$dir = "/img/uploads/item/media/";
echo $this->Form->input('id');
echo $this->Form->input('title');
echo $this->Form->input('item_description');
echo $this->Form->input('location_description');
echo $this->Form->input('media_path', array('label'=>'Media','type'=>'file'));
echo $this->Form->input('hiddenimage', array('type'=>'hidden','value'=> $this->Form->value('media_path') ));
$Image = $this->Form->value( 'media_path');
if(empty($Image) || $Image==NULL)
{$Image = "/img/uploads/noimg.jpg";}
else {$Image = $dir . $Image; }
echo $this->Html->image($Image,array('align'=>'absbottom','style'=>'max-height:100px'));
echo "<h3> Test: ". $this->Form->value('media_path') . "</h3>";
echo $this->Form->input('item_location_id', array('label'=>'Location'));
echo $this->Form->input('item_characteristic_id', array('label'=>'Characteristics'));
echo $this->Form->input('address', array('id' => 'address'));
echo "<div id=\"map_canvas\" style=\"width:98%; height:400px;\"> </div>";
echo $this->Form->input('longitude', array('id'=>'longitude', 'readonly'=>'readonly'));
echo $this->Form->input('latitude', array('id'=>'latitude', 'readonly'=>'readonly'));
echo $this->Form->input('first_seller_id');
echo $this->Form->input('second_seller_id');
echo $this->Form->input('brochure_path', array('label'=>'Broshure','type'=>'file'));
echo $this->Form->input('seo_title');
echo $this->Form->input('seo_description' , array('label' => 'SEO Description'));
echo $this->Form->input('seo_url' , array('label' => 'SEO Url'));
echo $this->Form->input('seo_keywords' , array('label' => 'SEO Keywords'));
?>
</fieldset>
Look at adding the on parameter to your rules.
'on' => 'create'
Will only trigger the validation on an insert (i.e. a new record).
If a rule has defined ‘on’ => ‘create’, the rule will only be enforced
during the creation of a new record. Likewise, if it is defined as
‘on’ => ‘update’, it will only be enforced during the updating of a
record.
In your edit action could you not just check the field and remove it if it's empty? Is that what you mean? Like:
if (empty($this->request->data['Item']['media_path'])) {
unset($this->request->data['Item']['media_path']);
}
It would probably be more complicated than that, checking to see if it's valid upload I guess, but would something like that work?
I'm using the cakephp uploader plugin by Miles Johnson. I like the plugin and I've got it working to be able to upload photos for a photo model.
The problem I'm running into is that when I try to edit an existing record, instead of replacing the photo associated with the record I'm editing a new record is created. The new record has all the same information with the exception of the new photo that's been uploaded.
Here's how the photo model looks:
'Uploader.Attachment' => array(
'imgPath' => array(
// 'name' => '', // Name of the function to use to format filenames
'baseDir' => '', // See UploaderComponent::$baseDir
'uploadDir' => 'files/uploads/', // See UploaderComponent::$uploadDir
'dbColumn' => 'imgPath', // The database column name to save the path to
'maxNameLength' => 60, // Max file name length
'overwrite' => false, // Overwrite file with same name if it exists
'stopSave' => true, // Stop the model save() if upload fails
'allowEmpty' => true, // Allow an empty file upload to continue
'transforms' => array( // What transformations to do on images: scale, resize, etc
array(
'method' => 'resize',
'width' => 50,
'height' => 50,
'append' => '_thumb',
'dbColumn' => 'imgPathThumb',
)
)
)
)
This is the photo admin edit view form:
<?php echo $this->Html->script('ckeditor/ckeditor');?>
<?php echo $this->Form->create('Photo', array('type' => 'file'));?>
<fieldset>
<legend><?php echo __('Admin Edit Photo'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('caption', array('class'=>'ckeditor'));
echo $this->Form->input('imgPath', array('type' => 'file'));
echo $this->Form->input('alt_tag');
echo $this->Form->input('type', array( 'label' => 'Choose a type of photo', 'options' => array(
'gallery'=>'gallery',
'news'=>'news',
'post'=>'post',
)));
echo $this->Form->input('active', array( 'label' => 'Make active', 'options' => array('yes'=>'yes','no'=>'no' )));
echo $this->Form->input('gallery_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is the controller admin edit code:
public function admin_edit($id = null) {
$this->layout = 'admin';
if (!$this->Photo->exists($id)) {
throw new NotFoundException(__('Invalid photo'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Photo->save($this->request->data)) {
$this->Session->setFlash(__('The photo has been saved.'), 'success');
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The photo could not be saved. Please, try again.'), 'error');
}
} else {
$options = array('conditions' => array('Photo.' . $this->Photo->primaryKey => $id));
$this->request->data = $this->Photo->find('first', $options);
}
$galleries = $this->Photo->Gallery->find('list');
$this->set(compact('galleries'));
}
Have I overlooked something obvious?
Cheers, Paul
When You editing record, You must set ID of this record.
Add to form $this->Form->input('id') or set ID in controller before save() action
I have a a form which adds first_name and last_name of user in cakephp.
here is the code
code for view (add.ctp)
<?php
echo $this->Form->create('User');
echo $this->Form->input('first_name',array('label'=>'First Name'));
echo $this->Form->input('last_name',array('label'=>'Last Name'));
echo $this->Form->end('Add User');
?>
code for UserController (UsersController.php)
<?php
public function add(){
if($this->request->is('post')){
$addData = $this->request->data;
$this->User->create();
if($this->User->save($addData)){
$this->Session->setFlash('User has been added successfully');
$this->redirect(array('action'=>'index'));
}
}
}
?>
view code for User Model (UserModel.php)
<?php
class UserModel extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
This is the code I am using, I have seen on cakebook as well and used various other rules, but no validation is working for my form. Can some please help me what could be the reason ?
Thanks in advance!
Your model filename is incorrect. It should be User.php not UserModel.php
please change your file name to user.php if your using table name in mysql as users instead of UserModel.php
and your classname must be like below
<?php
class User extends AppModel{
var $name = 'User';
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
?>
Your model name should be User (as your table name and controller name is users).
So try this in your model file(User.php)
<?php
App::uses('AppModel', 'Model');
class User extends AppModel{
public $validate = array(
'first_name' => array(
'rule' => 'notEmpty',
'message' => 'first name should not be empty.'
),
'last_name' => array(
'rule' => 'notEmpty',
'message' => 'last name should not be empty.'
)
);
}
I have tried to set up a login page, but when I try to log in, even with a wrong username/password, cake redirects to the login page (the logout function redirects correctly). Even if I plug in the wrong info, I get no error flashes at all, I don't get it. Here is my controller code:
class UsersController extends AppController {
public $name='Users';
public $layout='pagelayout';
public $uses=array('User');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout', 'overview');
}
public function login() {
$this->set('title', 'Log in to your Gulf Shores 4 Less account');
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
and here is my model:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
public $name='User';
public $hasMany=array('Unit', 'Complex', 'Coupon', 'Location', 'Image', 'Charter', 'Course', 'Nightclub', 'Store');
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'advertiser')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
?>
Here is the code from AppController:
<?php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'overview'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index')
)
);
function beforeFilter() {
$this->Auth->allow('login','index', 'view', 'condos', 'houses', 'hotels_and_motels', 'print_all_coupons', 'print_coupon', 'search', 'golf', 'charters', 'events', 'nightlife', 'shopping', 'visitors_info', 'contact_us');
}
}
?>
and here is the view code:
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login'));?>
</div>
As you can see, I pretty much copy and pasted what was in the Cakephp-2.0 manual for this. The only difference between my db table and the manual's is that my password is stored as an MD5 hash in my users table. i can't figure out where this has derailed.
Make sure that your passwords are stored using the Auth component hash. AFAIK, there is no support for 'plain' md5 passwords. The hashes Cake generates are more complex than md5.
See the documentation for info on how to hash your passwords. If you are migrating from an app that used md5 hashing, you'll have to reset all the passwords to something random for all your users.
You can try to use the following codes on your AppController.php file
AppController.php
$this->Auth->authenticate = array(
AuthComponent::ALL => array('userModel' => 'User'),
'Form' => array(
'fields' => array('username' => 'email')
)
);
$this->Auth->authorize =false;
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->loginRedirect = array('controller' => 'media', 'action' => 'index/');
$this->Auth->logoutRedirect = '/logout';
$this->Auth->loginError = 'Invalid e-mail / password combination. Please try again';
I currently have this:
Hotels Controller
class HotelsController extends AppController {
var $name = 'Hotels';
function admin_add() {
$this->set('hotel_categories', $this->Hotel->HotelCategory->find('list'));
if ( ! empty($this->data)) {
$this->data['Page']['title'] = $this->data['Hotel']['title'];
$this->data['Page']['layout'] = 'index';
if ($this->Hotel->saveAll($this->data)) {
$this->Session->setFlash('Your hotel has been saved', 'flash_good');
$this->redirect(array('action' => 'admin_add'));
}
}
}
HotelCategory Model
class HotelCategory extends AppModel {
var $name = 'HotelCategory';
var $hasAndBelongsToMany = array(
'Hotel' => array(
'className' => 'Hotel'
)
);
Hotel Model
class Hotel extends AppModel {
var $name = 'Hotel';
var $hasAndBelongsToMany = array(
'HotelCategory' => array(
'className' => 'HotelCategory'
)
);
View
<div id="main">
<h2>Add Hotel</h2>
<?php echo $this->Session->flash();?>
<div>
<?php
debug($hotel_categories);
echo $this->Form->create('Hotel');
echo $this->Form->input('Hotel.title');
echo $this->Form->input('HotelCategory', array('options' => 'select', 'multiple' => 'checkbox'));
echo $this->Form->input('Hotel.body', array('rows' => '3'));
echo $this->Form->input('Page.meta_keywords');
echo $this->Form->input('Page.meta_description');
echo $this->Form->end('Save Hotel');
?>
</div>
<!-- main ends -->
</div>
I can confirm that when I debug($hotel_categories); that there are values.
The problem I am having is that the $this->Form->input('HotelCategory', array('options' => 'select', 'multiple' => 'checkbox')) doesn't produce any options.
That should be:
echo $this->Form->input('HotelCategory', array(
'type' => 'select',
'multiple' => 'checkbox',
'options'=>$hotel_categories));
try explicitly setting the options list in the view
<?php echo $this->Form->input('HotelCategory', array(
'type'=>'select',
'options' => $hotel_categories,
'multiple' => true)); ?>