CakePHP validation messages position - validation

Normally, the CakePHP's validation messages from models like:
class User extends AppModel {
public $name = 'User';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
'regexp' => array(
'rule' => '/^[a-z0-9]{3,10}$/i',
'message' => 'Only letters and integers, min 3, max. 10 characters'
)
)
)
}
Are printed below the inputs, I mean that messages: 'message' => 'A username is required'
So it looks like:
|INPUT|
[Message]
How do I can change that so the messages gonna be added to the array:
$errors[] = 'Message';
And then, I would like to use foreach to print them in one place.
Is that possible?

CakePHP has all of the validation errors available to the view in $this->validationErrors. So I loop through them thusly:
<?php if ( !empty($this->validationErrors['Model']) ) { ?>
<div id="errorlist">
<h3>You have errors in your submission. <?php echo $warnimage; ?></h3>
<div>
<ul>
<?php foreach( $this->validationErrors['Model'] as $val ){ ?>
<li><?php echo $val; ?></li>
<?php } ?>
</ul>
</div>
</div>
<?php } ?>
EDIT
Where to place this code?
Place the code in the view where you would like it displayed.
How to disable displaying those errors below inputs?
I don't disable that display but suppose if you wished you could just unset $this->validationErrors['Model']. (untested)
Another solution is to use elements as shown in this article by Miles Johnson.

Related

How to make the Yii-CActiveForm not set a list item to selected?

In a Yii application I have models User and Expert ('expert'=>array(self::BELONGS_TO, 'Expert', 'expert_id'),).
There is a form for creating/editing user data. Now I want to extend it with a drop-down list:
<?php
/**
* #var $experts Expert[]
*/
$expertsDropDownListData = array();
foreach ($experts as $expert) {
$expertsDropDownListData[$expert->id] = $expert->name;
}
?>
<div class="row">
<?php
echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
?>
<?php
echo $form->dropDownList(
$user, 'expert[id]', $expertsDropDownListData,
array(
'empty' => Yii::t('app', 'Please select an expert.'),
// 'options' => array('' => array('selected' => 'selected')),
// 'prompt'=>'Choose One',
)
);
?>
<?php echo $form->error($user, 'expert[id]'); ?>
</div>
I want the drop-down list never to have an expert entry as ould default entry. On page load alwys the empty value should be "selected". It works on pages of users, that don't have a related expert (in the users table the columnt expert_id is NULL). But on the pages of the user, that have an expert, the expert entry of the user gets selected.
How to permit the CActiveForm object selecting an antry and display a form without preselected value irrespective of the tables/objects relationships?
You can fill the attribute $model->expert with null after load.
// Controller
$user = User::model()->findByPk(1);
...your awesome code here...
// never show a default value
$user->expert=null;
if(isset($_POST)) {
// $user->expert will be set here with data from view
$user->attributes = $_POST;
}
...
// View
<div class="row">
<?php
echo $form->labelEx($user, '', array('label' => Yii::t('app', 'Some text...')));
?>
<?php
echo $form->dropDownList(
$user, 'expert', CHtml::listData($experts,'id', 'name'),
array('empty' => Yii::t('app', 'Please select an expert.'),)
);
?>
<?php echo $form->error($user, 'expert'); ?>
</div>

Having trouble with codeigniter check box on remember me button

I am storing the username and password in cookie but i have little trouble with remember me button i want that when user check the check box the cookie store the values else only log in the user but the problem is here when i put the check in my controller it wont work i know the problem is in my if condition please some one sort me out the problem or correct my syntax will be really thankful. Here is my code of controller and view.
function verifying(){
$data=array(
'username'=>$this->input->post('username'),
'password'=>$this->input->post('password')
);
if($this->input->post('remember_me')=="checked")
{
$cookie = array(
'name' => 'username',
'value' => $this->input->post('username'),
'expire' => 86500,
'secure' => false
);
$cookie1 = array(
'name' => 'password',
'value' => $this->input->post('password'),
'expire' => 86500,
'secure' => false
);
}
$this->input->set_cookie($cookie);
$this->input->set_cookie($cookie1);
$result=$this->user->verify("signup",$data);
if($result)
{
$sess_arrau=array();
foreach($result as $row)
{
$sess_arrau=array('username'=>$row->username);
}
$this->session->set_userdata($sess_arrau);
$data['username']=$this->session->userdata('username');
$this->load->view("success",$data);
}
//$this->load->view("success",$sess_array);
else{
redirect("signin");
}
}
Log in page code.
<?php
$username=$this->input->cookie('username', false);
$password=$this->input->cookie('password',false);
if($this->session->userdata('username')!=''){
redirect("index/post");
}
echo form_open("index/verifying");
echo form_input('username',"$username",'placeholder="username"');
echo form_checkbox('remember_me','REMEMBER ME',FALSE);
echo form_label('REMEMBER ME','remember_me');
?>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<?php
echo form_password('password',"$password",'placeholder="password"');
echo form_submit('submit','Signin');
echo form_close();
?>
Your problem is that "checked" won't be the value of the input when it has been checked. Instead the value will be "REMEMBER ME" because this is the second parameter you have passed to the form_checkbox function.
So in your controller rather than do
if($this->input->post('remember_me')=="checked")
{
//Do stuff here...
}
You need to do
if($this->input->post('remember_me')=="REMEMBER ME")
{
//Do stuff here...
}
quite easy the answer above is correct too and the other short approach is like that.
if($this->input->post('remember_me')!="")
And it will work fine too.

Magento form - how to display input fields on the same row?

I have this form:
$form = new Varien_Data_Form();
$costsForm = $form->addFieldset('costs', array(
'legend' => Mage::helper('starmall_config')->__('Shipping costs')
));
$data = array();
$costsArr = Mage::helper("starmall_config")->getShippingWeightRateList();
for ($i=0; $i < count($costsArr); $i++) {
$data["ship_cost_" . $i . "_from"] = $costsArr[$i]["from"];
$data["ship_cost_" . $i . "_to"] = $costsArr[$i]["to"];
// 1st column
$costsForm->addField("ship_cost_" . $i . "_from", 'text', array(
'name' => "ship_cost_" . $i . "_from",
'label' => $costsArr[$i]["label"],
'class' => 'required-entry',
'style' => 'width:50px',
'required' => true,
));
// 2nd column
// how to add a new field on the same row in another column
// 3rd column
// how to add a new field on the same row in another column
// 4th column
// how to add a new field on the same row in another column
}
It looks like this:
I want to add multiple input fields on the same row. Can this be done in Magento 1.7 ?
1) If you add fields directly to the form ( e.g. $form->addField(....) )
\app\design\adminhtml\default\default\template\widget\form\renderer\element.phtml
around line 29:
change:
<span class="field-row">
into:
<span class="field-row <?= $_element->getId();?>">
Now you have access to the form row with a class, and you can play with CSS to achieve what you need.
2) If you add fields to a form fieldset ( e.g. $fieldset->addField(....) )
provide parameter "container_id", for example:
$fieldset->addField('test_field', 'text', array(
'name' => 'test_field',
'label' => $this->__('Test field'),
'required' => false,
'disabled' => false,
'style' => 'width:50px;',
'container_id' => 'some-row-id'
));
After rendering you will see:
<tr id="some-row-id">
And now you can play easily with CSS to get what you need.
Kind Regards,
Janusz
Hello as Magento actually stores one value per path (see core_config_data table) the only way I can think of to achieve this would be to save your data in json or serialized format, then overwrite the renderer to split the information into separate input fields. even easyer would be to just add some javascript that automatically splits the json to separate inputs and then combines it back toghether on submit so you do not have to edit the models and renderers.
Try to use setNoSpan() method.
For example:
$checkbox = $this->addField('is_enabled', 'checkbox', array(
'onclick' => 'this.value = this.checked ? 1 : 0;',
'name' => 'is_enabled',
))->setNoSpan(true);
or
$checkbox = $this->addField('is_enabled', 'checkbox', array(
'onclick' => 'this.value = this.checked ? 1 : 0;',
'name' => 'is_enabled',
'no_span' => true
));
You can see usage of this element in follow file:
app/design/adminhtml/default/default/template/widget/form/renderer/element.phtml
<?php $_element = $this->getElement() ?>
<?php if($_element->getNoSpan() !== true): ?>
<span class="field-row">
<?php endif; ?>
<?php echo $_element->getLabelHtml() ?>
<?php echo $_element->getElementHtml() ?>
<?php if($_element->getNoSpan() !== true): ?>
</span>
<?php endif; ?>

Displaying form validation errors in a template (Symfony)

let's say I have a blog with a module "post".
now I display a post like this: post/index?id=1
in the index-action i generate a new CommentForm and pass it as $this->form to the template and it is being displayed at the bottom of a post (it's just a textfield, nothing special). form action is set to "post/addcomment". How can I display the validation errors in this form? using setTemplate('index') doesn't work because I would have to pass the id=1 to it...
thanks
UPDATE:
here's a sample code:
public function executeIndex(sfWebRequest $request)
{
$post = Doctrine::getTable('Posts')->find($request->getParameter('id'));
$this->post = $post->getContent();
$comments = $post->getComment();
if ($comments->count() > 0)
$this->comments = $comments;
$this->form = new CommentForm();
$this->form->setDefault('pid', $post->getPrimaryKey());
}
public function executeAddComment(sfWebRequest $request) {
$this->form = new CommentForm();
if ($request->isMethod('post') && $request->hasParameter('comment')) {
$this->form->bind($request->getParameter('comment'));
if ($this->form->isValid()) {
$comment = new Comment();
$comment->setPostId($this->form->getValue('pid'));
$comment->setComment($this->form->getValue('comment'));
$comment->save();
$this->redirect('show/index?id='.$comment->getPostId());
}
}
}
and my Comment Form:
class CommentForm extends BaseForm {
public function configure() {
$this->setWidgets(array(
'comment' => new sfWidgetFormTextarea(),
'pid' => new sfWidgetFormInputHidden()
));
$this->widgetSchema->setNameFormat('comment[%s]');
$this->setValidators(array(
'comment' => new sfValidatorString(
array(
'required' => true,
'min_length' => 5
),
array(
'required' => 'The comment field is required.',
'min_length' => 'The message "%value%" is too short. It must be of %min_length% characters at least.'
)),
'pid' => new sfValidatorNumber(
array(
'required' => true,
'min' => 1,
'max' => 4294967295
),
array(
'required' => 'Some fields are missing.'
))
));
}
}
and finally, indexSuccess:
<?php echo $post; ?>
//show comments (skipped)
<h3>Add a comment</h3>
<form action="<?php echo url_for('show/addComment') ?>" method="POST">
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
that's it.
If you're using sf 1.4 just put executeAddComments and executeIndex together in one function (executeIndex for example) and you'll be fine. setTemplate won't work here.
Are you using the handleError method in the action ? The id=1 part of your url should not change if inside the handleError method, you do a return sfView::SUCCESS;
UPDATE:
It actually changes, what you need to do is submit the id along with the comment [Which I'm sure you're already doing because a comment that doesn't refer to a post doesn't make much sense], then in your handleError method, instantiate the post object there.
Try to change your form action to
<?php echo url_for('show/addComment?id=' . $post->getId()) ?>
Doing this, your post id parameter should be available even on your post request, and it should work with setTemplate('index') or forward at the end of executeAddComment

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources