Zend Form: add message to the element - php

Usually I used Zend Form's messages in the following way:
Code in form:
$element = new Zend_Form_Element_Text('form_resource_type');
$validator = new Zend_Validate_NotEmpty();
$validator->setMessages(
array('isEmpty' => 'Please choose type of resource')
);
$element->addValidator($validator);
$element->setRequired(true);
$this->addElement($element);
Code in view:
<?php foreach($subForm->getElementsAndSubFormsOrdered() as $element):?>
<?php echo $element?>
<?php foreach($element->getMessages() as $errorMsg):?>
<?php echo $this->escape($errorMsg);?>
<?php endforeach;?>
<?php endforeach;?>
So, for outputting error messages I used getMessages() function. But right now under certain circumstances (in case of special combination of fields' values) I need to mark element as invalid and add custom error message. I tried to use addError($message) function, but it adds message to _errorMessages property, while getMessages output _messages Zend_Form_Element property.
I didn't find function of adding messages to the _messages property. How can I do this? Or I should not work with this property directly and change a way of outputting error messages in view?
UPD:
I use Zend Framework 1.12

Since you are accessing the error messages from the form element. Then you can try to set message in the element by using the following statement in the controller:
$form->getElement('elementName')->addErrorMessage('custom Message');
You will then be able to print the message in your way.

You can use markAsError() for marking an element as invalid Custom Error Messages
I think this will do the trick for you
if($error)
{
$element->addErrorMessage('Custom Error');
$element->markAsError();
}

Related

Passing value to PHP form_open function

I am trying to call the form_open function and pass a value to the function it's calling. I'm trying to pass the value for $data->advisee_id. Once it calls the setAdvisees function I want it to echo the value. I've tried a number of things and I'm thinking I might need to pass it into the array which is the second parameter for form open. Does anyone know how I would do this? The below code I have currently gives an error when form_open is called stating:
"An Error Was Encountered. The URI you submitted has disallowed characters."
eligibletoenroll_view.php
<?= form_open('app/staff/advisees/setAdvisees($data->advisee_id)', array(
'class' => 'user-contact',
)) ?>
advisees.php
function setAdvisees($advisee_id) {
echo $advisee_id;
Just send like this
<?= form_open('app/staff/advisees/setAdvisees/$advisee_id)'
This sill act as
<form action="app/staff/advisees/setAdvisees/$advisee_id"
If advise id coming from array then before form open
$advisee_id = "some thing"
Example
<form action="app/staff/advisees/setAdvisees/25"

Laravel MessageBag undefined property

On every page of the site I have a a newsletter signup box. If there is an error, it shows using the following:
<?php if($errors->newsletter->first('emailAddress')) : ?>
<span class="input-error-notification">{{$errors->newsletter->first('emailAddress');}}</span>
<?php endif; ?>
Which works fine, for the most part. However, as soon as I have a page that requires other errors I get the error Undefined property: Illuminate\Support\MessageBag::$newsletter.
In a customer registration controller I have the following:
$message = new Illuminate\Support\MessageBag;
$message->add('codeError', 'Invalid confirmationCode code. Please click the link in the email we sent you.');
return View::make('components.message')->withErrors($message);
This gives me the error. I know I am overwriting the default global MessageBag, which I don't want to do.
I also get the error if I do not create a new MessageBag.
Anybody have any ideas what can be done here? I can't find anything relating to this.

Codeigniter form_error() displays only one error

I'm running CI form validation and using form_error() to display errors individually for each field. The problem, though, is that the form_error() function only returns the first validation error
Example field:
<input type="text" name="value" value="short">
validation script:
$validationRules = "min_length[6]|numeric";
$this->form_validation->set_rules(
'value',
'lang:mod_the_field',
$validationRules
);
if($this->form_validation->run() === FALSE){
echo form_error('value');
}
The above outputs: <p>The Value field must be at least 5 characters in length.<\/p>
Although the field also fails validation as a numeric value.
I cannot seem to find documentation on this. Is there a simple step I am missing to get all validation errors for a single field output? Is there a better solution than running the validation multiple times, once for each rule?
EDIT:
To be clear, the output I'm looking for in this particular example is:
<p>The Value field must contain only numbers.</p>
<p>The Value field must be at least 5 characters in length.</p>
One solution is to run the validation once for each rule and aggregate the output, but I'm trying to find out if there is a way to do this out of the box in CI?
SOLUTION:
I checked the Form_validation library and found that Samutz' comment is correct. The script breaks out and returns after the first validation error.
rather than extending any classes, I changed my code to iterate over each rule and concatenate the error string like so:
$validationRules = "min_length[6]|numeric";
$validationRules = explode('|', $validationRules);
$errors = '';
foreach($validationRules as $rule){
$this->form_validation->set_rules(
'value',
'lang:mod_the_field',
$rule
);
if($this->form_validation->run() === FALSE){
$errors .= form_error('value');
}
}
$errors = ($errors) ? $errors : FALSE;
echo $errors;
The problem
When testing for errors in a CI form that errors served by validation_errors() in form helper are not exactly what I would call 'accessible'.
Sure they are neat in the way that there's an error message presented for every error (so failing to populate both user name and password when they are required, will display two error messages by default), but this should be taken a step further. I'm talking about error labels, e.g.:
<label for="password">The Password field must be at least 6 characters in length</label>
So users can click on error and get straight to field that needs fixing.
The idea
My first idea was to write a wrapper for form helper or somehow extend the form class. While this seemed as a good solution, a deeper study of validation class usage revealed a quicker fix. By default, rule for password could look like this:
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|md5');
Where set_rules() method parameters are as follows:
Password field name attribute (the same which you've defined)
Quoting the manual - A "human" name for this field, which will be inserted into the error message.
Validation rules for password field (in the above example password is required and at least 6 characters long) plus some modifiers (trimming spaces and instant conversion to md5).
A simple solution is to insert a label into second parameter, which will be literally used for displaying the error. It could look like this:
$this->form_validation->set_rules('password', '<label for="password">Password</label>', 'trim|required|min_length[6]|md5');
But why not take it a step further and use form_label() from form helper? That would result in:
$this->form_validation->set_rules('password', form_label('Password', 'password'), 'trim|required|min_length[6]|md5');
As you've probably noticed, the fix will result in a slightly different code that we were aiming at:
The <label for="password">Password</label> field must be at least 6 characters in length
Only the actual field name is wrapped in label tag. But hey - with some simple styles (below) it's not that bad at all. For more organised styles it would be nice to add a custom class to that label, or better yet - wrap the whole error message in some unique container (so you'll be able to specify styles only for that error label) using set_error_delimiters():
$this->form_validation->set_error_delimiters('<div class="form_error">','</div>');
That will result in following html:
<div class="form_error">The <label for="password">Password</label> field must be at least 6 characters in length</div>
Add some styles to that:
.form_error label {color:#F00;text-decoration:underline}
Hope you can do more with form_error() at this point:
// in stylesheet
.form_error label {color:#F00;text-decoration:underline}
// in form controller
$this->form_validation->set_error_delimiters('<div class="form_error">','</div>');
$this->form_validation->set_rules('password', form_label('Password', 'password'), 'trim|required|min_length[6]|md5');
just stumbled upon this myself and found a way around it. It's not really an orthodox solution but here it is
$errors = validation_errors('/', '/');
$errors = explode("/", $errors);
echo $errors[1];
This will only output the first error in the array.
EDIT: Make sure you check if your array has more than 1 value in it
if(count($errors) > 1) {
echo $errors[1];
}
first error
second error
box p:nth-child(2){display: none;}

Why can’t I get my Flashdata for my next server request in CodeIgniter?

I’ve been trying to figure out how to use those flashdatas.
I remember having difficulties last time, and this time again, it seems that I forget something.
So basically, I’m trying to set up a flasherror somewhere :
if(!$this->paypal_pro->APICallSuccessful($PayPalResult['ACK']))
{
$this->session->set_flashdata('flashError',
array('Errors'=>$PayPalResult['ERRORS']));
redirect('main/form');
}
And in my main/form I got :
function Form()
{
// Process validation form
if ($this->form_validation->run() == FALSE)
{
//IF the validation process hasn't been run or there are validation errors
$this->parser->parse('template/template', $data);
}
And in that view, I’m trying to get that flashError :
<?php if($this->session->flashdata('flashError')):?>
<div class='flashError'>
<?php
$flashError=$this->session->flashdata('flashError');
foreach( $flashError['Errors'] as $Error) {
echo $Error['L_SHORTMESSAGE'].' ('.$Error['L_ERRORCODE'].'):';
echo '<br/>';
echo $Error['L_LONGMESSAGE'];
}
?>
</div>
<?php endif?>
I don’t have anything in that variable, and when I try to var_dump it, It returns me false.
Can someone explain me how to use it despite the official documentation saying “will only be available for the next server request, and are then automatically cleared”
From Codeigniters documentation:
If you find that you need to preserve a flashdata variable through an
additional request, you can do so using the keep_flashdata() function.
$this->session->keep_flashdata('item');
UPDATE:
Problem seems to be here:
$this->session->set_flashdata('flashError',
array('Errors'=>$PayPalResult['ERRORS']));
Try this one:
$this->session->set_flashdata(array('Errors'=>$PayPalResult['ERRORS']));
As you are doing
if($this->session->flashdata('flashError'))
You are actually removing the flashError item, as it has been read.
What you need to do, is as you have a little further down, assign it to a variable and then do your checks.

How do we use more than one message in flashMessenger using zend framework

I am using zend. I have the following piece of code,
....
$cust = 'test#test.com';
$list.='Also Sent Mail to following members';
foreach($m_list as $value)
{
$mail_to_manu = new Zend_Mail('utf-8');
$mail_to_manu->clearFrom();
$mail_to_manu->setBodyHtml('Text')
->setFrom('noreply#test.com', 'test admin')
->addTo($value['email'])
->setSubject('Test');
$mail_to_manu->send();
$list.=$value['manufacturers_email'].'<br/>';
}
$this->_helper->flashMessenger->addMessage('Mail send to '. $cust. ' Successfully'.$list);
$this->_redirector->gotoUrl('/index');
.....
I got message with out any break.my message looks like,
Mail send to test#test.com Successfully Also Sent Mail to following members some1#example.com some2#example.com...
I need to my message will be like,
Mail send to test#test.com Successfully
Also Sent Mail to following members,
some1#example.com
some2#example.com
...
So i need some break one after another.Is it possible to do that in Flash messenger. If yes,Kindly Advice.
Are you using strip_tags or something similar in the view script? It could cause the <br /> tags to get stripped out.
It's also possible to add multiple messages by calling flashMessenger->addMessage() once for every address:
$cust = 'test#test.com';
$this->_helper->flashMessenger->addMessage('Mail send to '. $cust. ' Successfully');
if(count($m_list)>0 )
$this->_helper->flashMessenger->addMessage('Also Sent Mail to following members');
foreach($m_list as $value)
{
$mail_to_manu = new Zend_Mail('utf-8');
$mail_to_manu->clearFrom();
$mail_to_manu->setBodyHtml('Text')
->setFrom('noreply#test.com', 'test admin')
->addTo($value['email'])
->setSubject('Test');
$mail_to_manu->send();
$this->_helper->flashMessenger->addMessage($value['manufacturers_email']);
}
$this->_redirector->gotoUrl('/index');
Your question
The reason why it's all bunched up together is that you're echoing it all out in a loop without additional markup.
What about something like:
foreach ($this->messages as $message)
{
echo '<p class="message">' . $this->escape($message) . '</p>';
}
But, in fact, there is a much better way of handling the flashMessenger in views. As you know the Zend FlashMessenger is an action helper. But there is also a great view helper avaiable which helps you output your messages nicely. The best thing about it is, that you can pass an array('warning' => 'This is a warning') and the array key (warning) will be used as class for the <p> tag. You can find information about this helper on Carlton Gibson's blog and additional explanations in this SO question.
Your variable naming needs improvement
Write readable variable names like $customer instead of just $cust. Nobody ever said shortening variable names is a means of writing lean code ;). Shortening variable names is bad (code smell) because it make code less readable for others and for yourself in the future.
Use casing like this $mailToManufacturer instead of using underscores. It's a general agreement (standard) and therefore good for readability and understanding of code too.

Categories