Zend Translate Zend Form! - php

Currently, isEmpty errors throw:
Value is required and can't be empty
I'm loading my translator up like this:
[translation]
adapter = array
content.english["emailNotUnique"] = "Your user already exists"
content.english["Value is required and can't be empty"] = "You must specify your ID"
locale = en
The config above produces a valid array according to zend translate spec, so:
$this -> form -> setTranslator(new Zend_Translate($this -> getConfig() -> translation));
expected result is that isEmpty errors should now show up as
You must specify your ID
However I'm getting no love. No errors and no translation. I'm on Zend 1.11.1 and PHP5.3.5.

I think that the problem is with english key in your ini file. Specifically it should not be there, because what you are actually passing to Zend_Translate as a content is:
'content' => array(
'english' => array(
"emailNotUnique" => 'Your user already exists' ,
"Value is required and can't be empty" => 'You must specify your ID'
)
);
And it should be:
'content' => array(
"emailNotUnique" => 'Your user already exists' ,
"Value is required and can't be empty" => 'You must specify your ID'
);
Hope this will help.

Try to change
content.english["isEmpty"] = "You must specify your ID"

you can user language file(MO) its simple translate in multiple language
when initialize bootstrap at a time initialize selected language

Related

Getresponse API 2 (Adding Custom fields and contacts using PHP)

Im new to coding and web development as it is and diving into the deep end with API's is a thing i wish i never had done! However being said i have progressed further than expected. I am now having problems when trying to add custom fields to the add contact feature. Im trying to get the code to add the hidden form input fields when the user hits my thankyou page. I dont want to use Getresponses own Form builder for my main page so it was better to use the API. I have the code running perfectly when it comes to just adding the contact however when i add the set_contact_customs the code does not execute and fails with the following error: (Request have return error: Array) So i understand its to do with the set_contact_customs array however im clueless as to what it is i have done wrong.. Any advice and help is greatly appreciated as i am still learning the basics so picking up on what you experts say is a great learning curve. Thanks.
--- Below is the working version without the set_contact_customs ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
echo "<p style='color: blue; font-size:24px;'>No Errors, Contact and Custom Fields have been added...</p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
--- Here is the code that causes the problems (with set_contact_customs) ----
<?php
// Add contact to selected campaign id
try{
$result_contact = $client->add_contact(
$api_key,
array (
'campaign' => 'My-Camp-ID',
'name' => $fullname,
'email' => $emailaddress
)
);
$result_contact = $client->set_contact_customs(
$api_key,
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
);
echo "<p style='color: blue; font-size:24px;'> Contact Added </p>";
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
API 2 doesn't really exist: in GetResponse they say version "1.5.0 - this is last JSON/RPC version of our API", especially if you were speaking 10 months ago. Now they are preparing to beta-test v3. So I will assume you were speaking about 1.5 and answer about it (I'm not familiar with v3, maybe there it's different).
You must send contact id with set_contact_customs, and you didn't.
When it says, "request error: array", it doesn't relate to your array (even though the problem is in your array, because you don't send in it contact id), they are sending an array as a response with error messages.
I'd love to tell you, where to get the contact id in order to send it, but I'm looking for it myself now. :)
UPDATE:
Ok, I combined it from pieces all over the internet, and now here's the working format.
You don't need to add_contact and then update it, you can do it in one go, adding the 'customs' parameter to the add_contact call (GR say, that we shouldn't expect for the contact to be added immediately, so you might not even get whom to update, if you call that function right away).
The fields for add_contact are described here.
The 'customs' parameter should look differently. Instead of:
array(
'Survey Type' => $surveytype,
'Survey Cost' => $surveycost
)
it should be:
array(
array( 'name' => 'Survey Type', 'content' => $surveytype ),
array( 'name' => 'Survey Cost', 'content' => $surveycost )
)
By the way, from what I tested, - blessedly, you don't need to define in GR UI those custom fields first, whatever you send, will be added or updated (in their limits for the custom field names and values).
I got error, when tried to send one custom field with empty content, when calling add_contact. When I sent it with set_contact_customs, I didn't get any error; I wanted to see, if it would delete the field or field value - it didn't do a thing.
If you still wish to update the existing contact, here's how to send the contact id with the update call:
$result = $client->set_contact_customs(
$api_key, array(
'contact' => $contact_id,
'customs' => $custom_fields_array
)
);
To first find contact id, you should call get_contacts. And since it's been said (I haven't tested it), that in different campaigns contacts with the same email address have different contact id, you should pass both the campaign, and the email with it.
As you can see, campaign can be sent in 'campaigns' parameter (then campaign id, that you got for add_contact, should be used), or in 'get_campaigns' (then the campaign name or even prefix can be used).
Here's the call with campaign id, for your code:
$result = $client->get_contacts(
$api_key, array(
'campaigns' => array( 'My-Camp-ID' ),
'email' => array( 'EQUALS' => $emailaddress )
)
);
To retrieve contact id from get_contacts, do the same as recommended for retrieving campaign id:
$contact_id = array_pop( array_keys( $result ) );
if ( empty( $contact_id ) ) {
//still not ok
}
else {
//you can call set_contact_customs
}
In order for that error message to be more descriptive, instead of just 'Request have return error: Array', open your jsonRPCClient.php, which you most surely include in your file with these GR function calls, and look for the following line:
!is_null($response['error']) => 'Request have return error: ' . $response['error'],
and replace it with the following, at least:
!is_null($response['error']) => 'Request have returned error: ' . var_export($response['error'], true),
Now your code will use the beloved var_export function and if you make a mistake, you will see in your error log something like:
Request have returned error: array (
'message' => 'Invalid params',
'code' => -32602,
)
I dedicate this thorough answer to all those, who helped me endlessly here on StackOverflow, just giving their answers to someone else's questions, sometimes years ago. Thank you! Hopefully my answer will save someone time, efforts, and mood, too. :)

how to Assign name to drop down options

Using Phalcon framework, I have a Form class file where I declare select and render in .volt file:
$soc_bulding = new Select("soc_building_id", $options['soc_bulding'],
array('using' => array('soc_building_id', 'soc_building_name'),
"class" => "mandatory-field") );
$soc_bulding->setLabel("Buiding name" . REQ_FIELD);
$this->add($soc_bulding);
in the above code, 'using' => array('soc_building_id', 'soc_building_name') reflect soc_building_id as option value and soc_building_name actual text in drop down option, but I want one more property name in that same option box, already tried to pass 3 parameter to that array but it's not working.
Please use the code below and replace yours
echo $this->tag->select(array("users",
Users::find(),
"useEmpty" => true,
"emptyText" => "Please select",
"using" => array("id", "name"),
));

Messages not working on Zend_Form_Element_Text

In a form, I have the following element:
$email = new Zend_Form_Element_Text('username');
$email
->setLabel($this->getView()->l('E-mail'))
->setRequired(TRUE)
->addValidator('EmailAddress')
->addValidator('Db_NoRecordExists', true,
array(
'table' => 'pf_user',
'field' => 'email',
'messages' => array(
'recordFound' => 'This username is already registered',
)
))
->setErrorMessages(array(
'emailAddressInvalidFormat' => 'You must enter a valid e-mail',
'isEmpty' => 'You must enter an e-mail',
'recordFound' => 'This e-mail has already registered in out database'
));
$form->addElement($email)
the problem is that I always I get the same message "You must enter a valid e-mail" (the first one). Does anybody knows what is the mistake??
Actually, what you're doing is the following :
You set the errors on the element
Zend now thinks that the element did not validate correctly and that the first error is
"You must enter a valid e-mail"
When you display the form, since you set errors, Zend will find them and display the first one it finds. If you switch the order then you'll find that whichever error you put up top will be the error you get.
The more correct way is to set the custom messages in the validator. When the validators are called to validate the element, if the validation fails, the validator will call the setErrorMessages on the element to set the custom errors you specify. Use this type of code below to set your custom messages.
$element->addValidator( array( 'Db_NoRecordExists', true, array(
'messages' = array(
Zend_Validate_Db_Abstract::ERROR_NO_RECORD_FOUND => 'Myy custom no error record',
Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND => 'My custom record error'
)
) ) );
You'll find that usually there are consts in each validator class that specify one type of error. In this case, the consts are in the parent class of the DB_NoRecordExists class but usually you'll find them directly in the class near the top.
Basically by passing 'true' as second parameter to addValidator() you are saying the validator to break the chain whenever validator fails . Since "" is not an valid email address hence the first email validator fails and breaks the chain
From Zend Doc http://framework.zend.com/manual/en/zend.validate.validator_chains.html
In some cases it makes sense to have a validator break the chain if
its validation process fails. Zend_Validate supports such use cases
with the second parameter to the addValidator() method. By setting
$breakChainOnFailure to TRUE, the added validator will break the chain
execution upon failure, which avoids running any other validations
that are determined to be unnecessary or inappropriate for the
situation. If the above example were written as follows, then the
alphanumeric validation would not occur if the string length
validation fails:
$validatorChain->addValidator(
new Zend_Validate_StringLength(array('min' => 6,
'max' => 12)),
true)
->addValidator(new Zend_Validate_Alnum());

Clearing Validation Error Messages from a Zend Form Element

I have a form element for capturing email addresses. I am using Zend_Validate_EmailAddress on the element, and it generates error messages that aren't very user-friendly.
My first step was to specify new messages that were more user-friendly, but some of the checks simply don't lend themselves to a user-friendly message. I then tried to simply clear those messages after running isValid() on the form and specify my own, but none of the functions I've found will clear the messages.
What I've tried and results
setErrorMessages() - Values set here seem to be ignored altogether
clearErrorMessages() - Seems to be ignored
setErrors() - Adds my message, but leaves the others intact
This is the code that displays the errors in my custom view script:
<?php if ($this->element->hasErrors()): ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
MY SOLUTION
I'm awarding Gordon with the answer, because his solution is most complete, but I ended up using the addErrorMessage() function on the element like this:
$element->addValidator('EmailAddress', false, $this->_validate['EmailAddress'])
->addErrorMessage("'%value%' is not a valid email address");
$element->addValidator('Date', false, array('MM/dd/yyyy'))
->addErrorMessage("Date must be in MM/DD/YYYY format");
From the Reference Guide (emphasis mine):
Some developers may wish to provide custom error messages for a validator. The $options argument of the Zend_Form_Element::addValidator() method allows you to do so by providing the key 'messages' and mapping it to an array of key/value pairs for setting the message templates. You will need to know the error codes of the various validation error types for the particular validator.
So you can do:
$form = new Zend_Form;
$username = new Zend_Form_Element_Text('username');
$username->addValidator('regex', false, array(
'/^[a-z]/i',
'messages' => array(
'regexInvalid' => 'foo',
'regexNotMatch' => 'bar',
'regexErrorous' => 'baz'
)
));
$form->addElement($username);
$form->isValid(array('username' => '!foo'));
which will then render 'bar' for the error message, because the regex does not match because it doesnt start with a letter from a-Z.
This is equivalent to using:
$username->setErrorMessages(
array(
'regexNotMatch' => 'The value %value% must start with a-Z',
…
)
);
I've used a different pattern to illustrate how to use the validated value in the pattern.
You can also use setErrors, if you want to delete any default templates, e.g.
$username->setErrors(array('The value must start with a-Z'));
Whatever you do, you have to configure that before validating with isValid. Once the validation is run, the Zend_Form_Element will contain the default error message otherwise. I am not aware of any way to reset that then (though someone might want to correct me on that).
Further quoting the reference guide:
A better option is to use a Zend_Translate_Adapter with your form. Error codes are automatically passed to the adapter by the default Errors decorator; you can then specify your own error message strings by setting up translations for the various error codes of your validators.
All the validation messages can be customized from the file in
http://framework.zend.com/svn/framework/standard/trunk/resources/languages/en
The file should be in APPLICATION_PATH/resources/languages, but can really be placed anywhere as long as you tell Zend_Translate where to find it.
When you define a form element like this
$titel = new Zend_Form_Element_Text ( "titel" );
$titel->setLabel ( "Titel" )->setRequired ( true )
->addValidator ( 'regex', false, array ("/[\pL\pN_\-]+/" ) );
you can specify a error message in your view script
<?php
$form = $this->form;
$errorsMessages =$this->form->getMessages();
?>
<div>
<label>Titel</label> <?php echo $form->titel->renderViewHelper()?>
<?php
if(isset($errorsMessages['titel'])){
echo "<p class='error'>There's something wrong!</p>";
}
?>
</div>
I don't know if this conforms your way but I really like defining my forms this way ;)
One way you can attack it is to create your own custom validator by extending the validator you plan on using and overriding the messages. For instance, looking at Zend_Validate_Alnum, it looks like this:
class Zend_Validate_Alnum extends Zend_Validate_Abstract
{
const INVALID = 'alnumInvalid';
const NOT_ALNUM = 'notAlnum';
const STRING_EMPTY = 'alnumStringEmpty';
[ ... ]
protected $_messageTemplates = array(
self::INVALID => "Invalid type given. String, integer or float expected",
self::NOT_ALNUM => "'%value%' contains characters which are non alphabetic and no digits",
self::STRING_EMPTY => "'%value%' is an empty string",
);
[ ... ]
}
Override the $_messageTemplates array in your own class like this
class My_Validate_Alnum extends Zend_Validate_Alnum
{
protected $_messageTemplates = array(
self::INVALID => "My invalid message",
self::NOT_ALNUM => "foo",
self::STRING_EMPTY => "'%value%' is bar",
);
[ ... ]
}
Then instead of using Zend_Validate_Alnum, use My_Validate_Alnum as your validator. Custom validators are very simple to create.

Symfony 1.4 Form Value change after getValues()

I've got some problem with symfony form value (i guess it's the clean value, but not so clear yet). Here's the problem :
I got a sfFormDateJQueryUI widget setup like this in my form :
$this->setWidgets(array(
'needDate' => new sfWidgetFormDateJQueryUI(),
));
$this->setValidators(array(
'needDate' => new sfValidatorDate(array(
'required' => true,
'date_format' => '/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/',
'date_output' => 'd/m/Y'
)),
));
Then when i submit, say 26/06/2010, it turns out right in the HTTP Header (viewed via Firebug) and $request (i just print it). But after i get the value via
$formVal = $form->getValues();
the date value in $formVal["needDate"] become today's date (03/06/2010). I really don't understand, and after checking in the API documentation it says that the getValues will return the 'cleaned' value. Is that because of it ? I don't understand what's 'clean'.
Thanks before..
Somehow I solved the problem.
It turns out that the value can't validate, so when I changed the validator to:
'needDate' => new sfValidatorRegex(array(
'pattern' => '/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/'
))
everything works fine.

Categories