Cakephp Formhelper : disable required on textarea - cakephp

I am trying to disable the required on that text input in my form.
However, even with
['required' => false], ['allowEmpty' => true]
which remove "required=required" from the HTML, I still get greeted with a 'This field cannot be left empty' when I try to make it be empty.
This string is located in Validator.php from what I see, but even though I tried editing or deleting what I thought was causing this, I did not find my way through.
I'm using cakephp 3.0.2
Here's my little form :
<?php
echo $this->Form->create($schedule);
echo $this->Form->input('year', [array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('month',[array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('text', ['required' => false], ['allowEmpty' => true]);
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
Thanks for the time you'll give me.

How is your model defined? Do you have a
public $validate = array()
defined? Are you sure you did not set required=true there, and did you set 'allowEmpty => true there? Because that's where that validation belongs rather than in the form, so you should first check you're not contradicting yourself.

Related

Cakephp 2.3.9 custom message in model validation not working

I am doing model validation in my admin panel login so there is only two fields username and password. Validation is working but custom message which I have written in my model is not shown.
Model
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please Enter Your Username'
)
),
'password' => array(
'required' => array(
'rule' => array ('notEmpty'),
'message' => 'Please Enter Your Password'
)
)
);
Controller
function login(){
$this->layout = 'admin_login';
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
View
echo $this->Form->create('Admin',array('autocomplete'=>"off"));
echo '<div style="width:294px;float:left;position:relative;">';
echo $this->Form->input('username' , array('label' => '', 'placeholder' =>'Enter your username','div' => false));
echo $this->Form->input('password' , array('label' => '', 'value' =>'', 'div' => false,'placeholder'=>'Enter Your Password'));
echo '</div>';
echo '<div style="padding-left:0px;">';
echo $this->Form->end(__('Login' ,true));
I have already tried a few things like which is mentioned in this link, but it's not working for me.
CakePHP : Validation message not displaying
That looks like a message from the browser and not CakePHP.
CakePHP now adds a required attribute which modern browsers can use to trigger an error.
You can do one of three things here:
One: Set up your form to leave validation to the server:
$this->Form->create(array('novalidate'=>true));
Two: Set a custom validation message in the browser: http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-setcustomvalidity
Three: tolerate it
You get that message because the "username" field is flagged as "required". Maybe you've not defined it in the Form->input() function, but the "required" flag has been automatically added from the Model (due to your validation rules). As timstermatic said, it's a browser validation message caused by the required attribute.
To solve this issue (and show the CakePHP validation message) you've to force for avoiding the addition of the "required" flag on your field:
$this->Form->input('username', array('required' => FALSE));
This will override the Model automatic additions. Happy coding ;)
*Edited => It's important to clarify that the inline override removes only the required flag on the field: you'll take advantage of the Model validation anyway (just because if an empty field is sent to the server, it will not pass the validation rule you entered.
keep this code it will bypass the html5 validation and add your custom validations
view
echo $this->form->create('Post',array('action'=>'add'));
echo $this->form->input('title');
echo $this->form->input('body');
echo $this->form->submit('Save Post',array('formnovalidate'=>true));
echo $this->form->end();//Creates ending form tag
Model
var $validate=array(
'title'=>array(
'title_must_not_be_empty'=>array('rule'=>'notEmpty','message'=>'Please enter a title),
'title_must_be_unique'=>array('rule'=>'isUnique','message'=>'Title name already exists')
),
'body'=>array(
'body_must_not_be_empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter body'
)
)
);
This will work just the way you want

CakePHP update multiple form fields from selectbox change

I'm using CakePHP 2.2. I'm adapting a method of dynamically updating a selectbox which I got from: http://www.willis-owen.co.uk/2011/11/dynamic-select-box-with-cakephp-2-0/#comment-10773 which works without issue. It updates the 'hotels' selectbox contents when the users selects a 'region' from another select box.
On the same form, I want to automatically populate multiple 'team' fields with address details from the 'hotels' model when a user selects a 'hotel' from the selectbox.
The user can then modify the address ... all of this before the user clicks submit on the 'team' add view.
In Team\add.ctp view I have the following code:
echo "<div id='address'>";
echo $this->Form->input('address_1');
echo $this->Form->input('address_2');
echo $this->Form->input('address_3');
echo $this->Form->input('city');
echo $this->Form->input('postcode');
echo $this->Form->input('country');
echo "</div>";
...
$this->Js->get('#TeamHotelId')->event('change',
$this->Js->request(array(
'controller'=>'hotels',
'action'=>'getAddress'
), array(
'update'=> '#address',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
In my HotelsController.php I have:
public function getAddress() {
$hotel_id = $this->request->data['Team']['hotel_id'];
CakeLog::write('debug', print_r($hotel_id, true));
$address = $this->Hotel->find('first', array(
'recursive' => -1,
'fields' => array('hotel.address_1', 'hotel.address_2', 'hotel.address_3', 'hotel.city', 'hotel.postcode', 'hotel.country'),
'conditions' => array('Hotel.id' => $hotel_id)
));
CakeLog::write('debug', print_r($address, true));
$this->set('hotels', $address);
$this->set(compact('address'));
$this->layout = 'ajax';
}
hotels\get_address.ctp:
<?php
echo $this->Form->input('Team.address_1', array('value'=> $address['Hotel']['address_1']));
echo $this->Form->input('Team.address_2', array('value'=> $address['Hotel']['address_2']));
echo $this->Form->input('Team.address_3', array('value'=> $address['Hotel']['address_3']));
echo $this->Form->input('Team.city', array('value'=> $address['Hotel']['city']));
echo $this->Form->input('Team.postcode', array('value'=> $address['Hotel']['postcode']));
echo $this->Form->input('Team.country', array('value'=> $address['Hotel']['country'])); ?>
This now works and the code has been updated.
You can not do in that way as you are trying to accomplish. However, there is a way in which you can update as you want by passing an id from dropdown using ajax and populating all the other fields on the basis of that id. Please make sure in 'update'=>#id you should put the div id of a div containing all the fields you want to show on the page where you want your contents to appear on ajax request.
Note: Please follow the Richard link which you have given i.e. www.willis-owen.co.uk, it will definitely help you that you are trying to do.

Validation problems with multiple checkboxes (HABTM) on CakePHP form

Short version
I have some HABTM checkboxes on a form. Validation is working correctly (at least one checkbox needs to be checked for validation to pass) but the CakePHP error message divs aren't being generated as they should be.
Long Version
I have a from which allows users to fill in their name and email address and then choose from a list of brochures (checkboxes) they'd like to receive.
The form looks like this:
<?php
echo $this->Form->create('Request',array('action' => 'index'));
echo $this->Form->input('id');
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('Brochure',array(
'label' => __('Information Required:',true),
'type' => 'select',
'multiple' => 'checkbox',
'options' => $list,
'selected' => $this->Html->value('Brochure.Brochure'),
));
echo $this->Form->submit('Submit');
echo $this->Form->end();
?>
In my controller, $list is set as like this:
$this->Request->Brochure->find('list',array('fields'=>array('id','name')));
After reading the 2nd answer (posted by user448164) in HABTM form validation in CakePHP on Stack Overflow, I set my Request model up like this:
<?php
class Request extends AppModel {
var $name = 'Request';
function beforeValidate() {
foreach($this->hasAndBelongsToMany as $k=>$v) {
if(isset($this->data[$k][$k]))
{
$this->data[$this->alias][$k] = $this->data[$k][$k];
}
}
}
var $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your full name'
),
'email' => array(
'rule' => 'email',
'message' => 'Please enter a valid email address'
),
'Brochure' => array(
'rule' => array('multiple', array('min' => 1)),
'message' => 'Please select 1'
),
);
?>
This actually works 99% well. If none of the checkboxes are checked, validation fails as it should do. However, the only problem is that Cake isn't setting the "error" class on the <div>, nor is it creating the <div class="error-message">Please select 1</div> as it should.
For name and email, there is no problem - the error divs are being created properly.
So, to clarify, validation is working for my HABTM checkboxes. The only problem is that the error divs aren't being generated.
I'm posting this here as this is actually a much better question than the related question you found.
I was banging my head against a wall trying to handle the same problem of getting the validation error to show up in the page. I'm using CakePHP v1.2 and I hit a similar problem although I have actually split out the HABTM into the individual tables i.e. Request->BrochuesRequest->Brochure. This is because I can't have it deleting and re-adding the joining table rows at will.
Firstly I think the accepted answer from your linked question assumes that you are doing a save / saveAll when the beforeValidate call is triggered, however I was doing it through a validates call. The difference is that you need to call the Request->set method first. It was an article by Jonathan Snook on Multiple Validation Sets pointed me to that issue.
The second issue is actually getting the error message to appear was down to the $field value you use when calling invalidate. For ages I was including the model as well as the field assuming that this was how it matched the invalidate call to the input, i.e. you have $form->input('BrochuresRequest.brochures_id') so you need $this->BrochuresRequest->invalidate('BrochuresRequest.brochures_id').
However that is wrong you just want $this->BrochuresRequest->invalidate('brochures_id').
<?php
// requests/add view
echo $form->input('BrochuresRequest.brochures_id', array('multiple' => true));
// requests_controller
function add() {
if (!empty($this->data)) {
$this->Request->create();
// critical set to have $this->data
// for beforeValidate when calling validates
$this->Request->set($this->data);
if ($this->Request->validates()) {
$this->Request->saveAll($this->data);
}
}
}
// request model
function beforeValidate() {
if (count($this->data['BrochuresRequest']['brochures_id']) < 1) {
$this->invalidate('non_existent_field'); // fake validation error on Project
// must be brochures_id and not BrochuresRequest.brochures_id
$this->BrochuresRequest->invalidate('brochures_id', 'Please select 1');
return false;
}
return true;
}
?>
A few of the other things that I picked up on the way through:
You don't need a separate $form->error in the view
I couldn't for the life of me get the 'multiple' validation rule to work in the model
The accepted answer checks for an isset but I believe that this isn't required and masked the problem of there being no $this->data being passed through.
The beforeValidate should return false if you want it to prevent any save action.

CakePHP - radio button not showing error message

I'm unable to get the error message to show up when creating a radio form using the CakePHP form helper.
This is what I have now.
$options=array('active'=>'Active','inactive'=>'Inactive');
echo $form->input('Status', array(
'type' => 'radio',
'id' => 'EntryStatus',
'name' => 'data[Entry][status]',
'options' => $options
));
What am I missing?
I'm using CakePHP 1.2.7 and this is what I have in the validation
'status' => array(
'notempty' => array(
'rule' => 'notempty',
'required' => true,
'message' => 'yo'
)
)
Tried the answer from Form helper for creating Radio button in Cakephp and it's giving me a select option form instead.
Thanks,
Tee
had same problem, and i fount this, and it works:
http://book.cakephp.org/view/204/Form-Element-Specific-Methods
you need
if ($form->isFieldError('gender')){
echo $form->error('gender');
}
... in your code. this works in case that your field is named as gender.
I had the same issue and I added:
<?php echo $form->error('currentStatus');?>
below the radio button and it worked fine.
Try taking a look at $form->input('Status' ... (capital 'Status') versus the DB column name (which might or might not be capitalized versus 'name' => 'data[Entry][status]' (not capital 'status').
Cake's form helper is picky about inserting error messages when it can't figure out what things go to what.
Have you tried using the explicit $form->radio() method instead of the general input() method?
You need to manually add in an error form helper.
echo $form->error('status');
You need to add error condition in case of radio button
<?php
$options=array('active'=>'Active','inactive'=>'Inactive');
echo $form->input('Status', array(
'type' => 'radio',
'id' => 'EntryStatus',
'options' => $options
)
);
if ($form->isFieldError('Status')){
echo $form->error('Status');
}
?>

File upload error cakephp

When I choose an image and push upload, I get this error in my controller:
Notice (8): Undefined index: File [APP/controllers/garage_car_images_controller.php, line 22]
I've also noticed that the $form->create line shown below does NOT generate form code in the inspected html. This is VERY weird.
Any ideas how to fix this? Thanks!
My view code:
<div class="title_plate">
<h1 id="title_plate_header">add image</h1>
</div>
<div id="overlay_content">
<?php
echo $form->create('GarageCarImage', array('controller' => 'garage_car_images','action' => 'add', 'type' => 'file'));
echo $form->file('File');
echo $form->hidden('garage_car_id', array('value' => $this->params['pass'][0]));
echo "<br><br>";
echo "Make this image the default? " . $form->input('default', array('type' => 'select', 'label' => false, 'options' => array('0' => 'No', '1' => 'Yes')));
echo "<br>";
echo $form->submit('Upload');
echo $form->end();
?>
</div>
My controller code:
if (!empty($this->data) &&
is_uploaded_file($this->data['GarageCarImage']['File']['tmp_name'])) {
$fileData = fread(fopen($this->data['GarageCarImage']['File']['tmp_name'], "r"),
$this->data['GarageCarImage']['File']['size']);
$this->data['GarageCarImage']['type'] = $this->data['GarageCarImage']['File']['type'];
$this->data['GarageCarImage']['user_id'] = $this->Auth->user('id');
$this->GarageCarImage->save($this->data);
}
Are you sure it doesn't generate the form code? If it didn't, I don't think you would even be able to try and submit a form. I believe submitting the form occurs because you seem to issue a request for /garageCarImages/index -- to me, that says that the form is getting generated properly.
If indeed that is the case, you should just change the value of the first parameter to the name of the controller that you want the code to execute in. For me, typically, I use an Attachment controller to do this, so I would put:
echo $form->create( 'Attachment', array(...) );
Your situation will depend on where the code is located to process the upload. Most likely it's the ImageController (guessing here...), but I'm not sure without knowing more details of your system.

Resources