Form validation problem with CodeIgniter - forms

I have this view:
<?php echo form_open(); ?>
<?php echo form_input('username', '', ''); ?>
<?php echo form_submit('submit', 'Submit'); ?>
<?php echo form_close(); ?>
<?php echo validation_errors(); ?>
and this controller method:
function test() {
$username = $this->input->post('username');
$this->form_validation->set_rules($username, 'Username', 'required|min_length[4]');
if ($this->form_validation->run() !== FALSE) {
echo 'Tada!';
}
$this->load->view('test');
}
but when I leave the username field blank, nothing happens. However, if I type in something in it will tell me the field is required. I've downloaded and given CI a fresh install almost ten times now, trying to load with and without different helpers etc. It's becoming really frustrating, please help.

Try using this:
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');

The problem lies in the first parameter of set_rules, which is the field name.
The $username you're passing is basically setting the field name to validate as whatever the user puts in the input field. If you were to type 'username' into the input box, you'd see that your form validates.
Change the line
$this->form_validation->set_rules($username, 'Username', 'required|min_length[4]');
to
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');

Maybe is the problem of this line
<?php echo form_open(); ?>
If you leave it blank it basically send back to the controller itself and calling the construct and index function only. In this case your function dealing with form processing is "test()"
try this
<?php echo form_open('yourControllerName/test'); ?> //test is the function dealing with
if it is not working try on this
<?php echo form_open('test'); ?>

Related

How to set validation rules for custom CActiveRecord attributes in Yii?

I'm working on a Yii project with a database, that contains a table, where almost all it's data is saved in a field as JSON (it's crazy, but it is so as it is):
id INTEGER
user_id INTEGER
data LONGTEXT
This "JSON field" data has following structure and contains inter alia an image:
{
"id":"1",
"foo":"bar",
...
"data":{
"baz":"buz",
...
}
}
Displaying it is no problem, but now I want to make the data ediable. My form looks like this:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'my-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
));
?>
<div class="row">
<?php echo $form->labelEx($model, 'foo'); ?>
<?php
echo $form->textField($model, 'foo', array(...));
?>
<?php echo $form->error($model, 'foo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'baz'); ?>
<?php
echo $form->textField($model, 'data[baz]', array(...));
?>
<?php echo $form->error($model, 'data[baz]'); ?>
</div>
It works. But there are multiple problems, that seem to be caused by the same thing -- that he form fields are not referenced to the model attributes/properties:
When I make fields foo and baz required (public function rules() { return array(array('foo, baz', 'required')); } -- the property $foo is defined) foo bahaves as wished, but baz causes an "foo cannot be blank" error. So I cannot set a data[*] as required.
If the form is not valid and gets reloaded, all the data[*] fields are empty.
The data[*] fields are not marked as required.
Is there a to solve this without to change the datase structure? There will not be a correct way for it, but maybe a workaround.
It's impossible to validate fields in such way. First of all if you are using field in model it must be defined or exist in table for active record. So if you want to validate such structure the only right way to do it:
class Model extends CActiveRecord {
// Define public varialble
public $data_baz;
public function rules(){
return array(
// Add it to rules
array( 'data_baz', 'required' )
);
}
public function attributeLabels(){
return array(
// Add it to list of labels
'data_baz' => 'Some field'
);
}
protected function beforeSave(){
if ( !parent::beforeSave() ) {
return false;
}
// Also you may create a list with names to automate append
$this->data['baz'] = $this->data_baz;
// And serialize data before save
$this->data = serialize( $this->data );
return true;
}
}
And your form should looks like
<div class="row">
<?php echo $form->labelEx($model, 'data_baz'); ?>
<?php echo $form->textField($model, 'data_baz'); ?>
<?php echo $form->error($model, 'data_baz'); ?>
</div>

Why is CakePHP 2.3.0 adding a '1' to my Form Post Values?

I'm using cakephp 2.3.0. I searched in the manual for quite awhile, but I haven't found the answer. Also, I've searched the Internet, but still haven't found what I'm looking for. SO, I'm posting my question here. Note, I'm fairly new to cakephp.
Scenario:
I have a simple form with two fields: activity and zip code.
I'm using POST on the form.
When I type in some value in those fields and submit, I echo those 'post' values/parameters and display in the browser screen. What I typed in, I can see on the screen, but the number '1' is added to the end of what I typed in the form.
Here is an example. I type in these values in the form, 'walk' and '44555'. Then I click 'Submit'. The post goes to my controller's action, which then calls my view. My view is displayed on the browser screen and I echo out those 'post' values. The results on screen are 'walk1' and '445551'.
Example #2: If I follow the steps above and don't enter any values in my form (I'll add error checking later), what I see on the browser screen is '1' and '1'.
I am unable to figure out why I am getting the value of '1' added to my form's POST values?
I'll be glad to include any other additional php code to this posting, if requested by someone trying to help.
Here is my FORM code (from my view)...I know there are DIV helpers, but I'll get to that later:
echo $this->Form->create(null, array('url' => array('controller'=>'activities', 'action'=>'results'))); ?>
<div class="box1" style="position:relative; top:10px; left:10px; float: left;">
Search here.... <br>
<hr>
<?php echo $this->Form->input('activityName', array('size'=>'30',
'label'=>'Activity Name:', 'value'=>'i.e. walking, etc.'));?>
<br>
<?php echo $this->Form->input('zip', array('size'=>'7', 'label'=>'Postal Code:')); ?>
<br>
</div>
<div class="box1" align="right">
<?php echo $this->Form->end('Go Search');?>
</div>
Here is my controller code:
<?php
class ActivitiesController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
//other code....
}
public function results() {
$this->layout = 'second';
$name = $this->request->data['Activity']['activityName'];
$pCode = $this->request->data['Activity']['zip'];
$this->set('theName', $name);
$this->set('theZip', $pCode);
$this->set('results', $this->Activity->
find('all', array('conditions' => array('name' => $name, 'postal_code' => $pCode))));
$this->set('title_for_layout', 'Results');
$this->render();
}
}
?>
My final view code. I left off some of the code...just showing the part that matters:
<div style="position:relative; top:10px; left:5px; ">
<?php echo print_r($theName); ?>
<br>
<?php echo print_r($theZip); ?>
Thanks
The 1 comes from printing the return value of print_r() which is true (i.e. 1).
In other words: you shouldn't do echo print_r(), just do print_r(). The function handles the printing by itself, you don't have to print the results manually.
(Also, print_r() is almost never the best choice to print out values except when debugging and even then CakePHP's debug() is much more suitable.)

How to prevent html content that's passed into sfFormField::renderRow() from getting escaped?

In a symfony 1.4 view I'm attempting to pass some html/javascript in the "attributes" parameter of the sfFormField::renderRow function:
<?php echo $form['ownership_status_id']->renderRow(array('onFocus' => 'displayHelp("<p>help text</p>");'), 'Own/Rent')?>
Unfortuantely the when the page gets rendered, all of the javascript/html output is escaped:
<select name="address[ownership_status_id]" onFocus="displayHelp("("<p>help text</p>");" id="address_ownership_status_id">
I'm not clear on how to prevent this content from being escaped, can someone help?
Try to unescape the $form variable as so:
sfOutputEscaperGetterDecorator::unescape($form);
Then call renderRow():
<?php echo $form['ownership_status_id']->renderRow(array('onFocus' => 'displayHelp("<p>help text</p>");'), 'Own/Rent'); ?>
I had to use this:
<?php echo sfOutputEscaperGetterDecorator::unescape($form['ownership_status_id']->renderRow(array('onFocus' => 'displayHelp("<p>help text</p>");'), 'Own/Rent')); ?>

symfony 1.2 forms renderRow error message problem

Im trying to render a row field in a template with some extra styles, like this:
<?php echo $form['email']->renderRow(array('class' => 'text')) ?>
<?php echo $form['email']->renderError() ?>
The problem occurs when my form doesnt validate on this field... then it displays the error message 2 times!, i.e the renderRow renders one errorMsg string, and the renderError does it again... How can i stop renderRow from displaying the error message?
If I just do this, then it works:
<?php echo $form['email'] ?>
But in that case I cant style the field as I want....
thanks!
I am pretty sure this is also valid for 1.2. Instead of using renderRow, use something like this:
<?php echo $form['FormElementName']->renderLabel() ?> //display form element label
<?php echo $form['FormElementName']->renderError() ?> //display form element error (if exist)
<?php echo $form['FormElementName']->render(array('class' => 'text')); ?> //display form element
renderRow does them all at once.
EDIT From comments (Flask) - added ->render(array('class' => 'text'));

Problem passing URL variables in post form submission with CakePHP FormHelper

I'm writing my first CakePHP application and am just writing the second part of a password reset form where a user has received an email containing a link to the site and when they click it they're asked to enter and confirm a new password.
The url of the page is like this:
/users/reset_password_confirm/23f9a5d7d1a2c952c01afacbefaba41a26062b17
The view is like:
<?php echo $form->create('User', array('action' => 'reset_password_confirm')); ?>
<?php
echo $form->input('password', array('label' => 'Password'));
echo $form->input('confirm_password', array('type' => 'password', 'label' => 'Confirm password'));
echo $form->hidden('static_hash');
?>
<?php echo $form->end('Reset password'); ?>
However this produces a form like:
<form id="UserResetPasswordConfirmForm" method="post" action="/users/reset_password_confirm/8">
The problem is the user id (8 in this case) is being added to the form action. It's not really a problem here, but when I want to pass through the hash to my controller:
function reset_password_confirm($static_hash=null) {
// function body
}
$static_hash is now populated with 8 rather than the hash from the URL.
I know I could sort this out by creating the form tag myself rather than using $form->create but is there a more cakey way of doing this?
$form->create('User', array('action' => '…', 'id' => false));
Just explicitly set params you don't want passed to null or false. This is unfortunately a case where Cake tries to be a little too intelligent for its own good. ;o)
You could probably also do something like this to POST to the same URL again:
$form->create('User', $this->here);
How about passing it as a parameter instead of form data :
<?php
echo $form->create('User', array('action' => 'reset_password_confirm', $static_hash));
echo $form->input('password', array('label' => 'Password'));
echo $form->input('confirm_password', array('type' => 'password', 'label' => 'Confirm password'));
echo $form->end('Reset password');
?>
and in the controller :
function reset_password_confirm($static_hash = null) {
// Check if form is submitted
if (!empty($this->data)) {
// if it submitted then do your logic
} else {
$this->set('static_hash', $static_hash); // Else, pass the hash to the view, so it can be passed again when form is submitted
}
}
Hope this help :)