zend validation messages - zend-form

consider the following part of a form
$name = new Zend_Form_Element_Text('name');
$name->setLabel('name: ')
->setRequired(true)
->addValidator($empty)
->addValidator($alpha)
->setDecorators($newdecorators);
$this->addElement($name);
I defined $empty and $alpha as:
$empty = new Zend_Validate_NotEmpty();
$empty->setMessage('some text', Zend_Validate_NotEmpty::IS_EMPTY);
$alpha = new Zend_Validate_Alpha();
$alpha->setMessage('some text',Zend_Validate_Alpha::NOT_ALPHA);
Now my question:
with this code I get a double validation message when the input is empty. First the custom message and then: '' is an empty string
When i drop the setRequired, the empty validator does not run. Why is this? I don't want to use the setRequired, because if i add an errorMessage for setRequired, the $alpha error message is overwritten.
thx,
J

This happens because the default behaviour is to check against all validators that are assigned to an element, even if one of the prior validations fails.
Luckily it is quite easy to prevent this: In the addValidator method you can pass a second parameter $breakChainOnFailure that stops further validation upon failure if set to true.
So in the example you gave, all you need to do is to set the second parameter to true:
$name = new Zend_Form_Element_Text('name');
$name->setLabel('name: ')
->setRequired(true)
->addValidator($empty, true)
->addValidator($alpha, true)
->setDecorators($newdecorators);
$this->addElement($name);
And only one error message is displayed in case you enter an empty string.
For further information refer to the Zend Framework Documentation on Validator Chains.

Related

How to I get the detail (custom error message) returned with a bad request status code? So that I can do an ASSERT on it

Hi so I am setting up some Integration tests (using Xunit) and I would like to run an Assert to check whether the correct custom error message is returned.
This is the data I need to get is in the following response see image...
detail: "Username must be unique" Don't worry this message will be modified to be more useful later on I am just wanting to get it working first
Required Info
This is the current code...
//Act
response = await _httpClient.PostAsync("CompleteUserSetup", formContent);
//Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode) ; //Bad request should be returned
//TODO: check custom error message is correct
So hoping for...
ASSERT.Equal("Username must be unique", some code to get detail from response)
Okay so I figured out how to get the data I needed. I just needed to convert the result into an object and then I was able to pull the detail data that I needed.
var resultModel = await System.Text.Json.JsonSerializer.DeserializeAsync<Result>(response.Content.ReadAsStream(), JsonSerializerHelper.DefaultDeserialisationOptions);
var errorMessage = resultModel.detail;

patching a collection to add a field

I'm wanting to patch a RavenDB to add a field to a collection but am just getting errors using the suggested syntax. (I'm probably not understanding what I'm supposed to use)
I've tried the following in the patch window but get error: ' "Message": "Deserializing Json object with empty string as property name is not supported."
'
store
.DatabaseCommands
.Patch(
new ScriptedPatchRequest
{
Script = "_.extend(this, { 'GroupPlayString': 'Group Play'});"
});
Use:
Script = "this.GroupPlayString = 'Group Play'"

Behat - Check list element contains content

I have a drop down menu containing list elements that are sometimes static and sometimes changed. My main goal is to check that the menu contains some content [followed by outputting that content and exporting it in a report].
The function I created in my FeatureContext.php looks like this:
/**
* #Then /^I check content exists for element "([^"]*)"$/
*/
public function iCheckElementContent($locator)
{
//check element exists on page
$element=$this->assertSession()->elementExists('css', $locator);
//check element content is not empty (returns exception if true)
if ( empty($this->getPage()->find('css', $locator)->getText()) ) {
throw new Exception;
}
}
As you can notice, it is based on the reply to the other question regarding this feature. My problem however is that it doesn't seem to like the getPage() parameter. The error I get is:
PHP Fatal error: Uncaught Error: Call to undefined method FeatureContext::getPage()
I also tried changing it to getValue(), without any success. Any ideas? (bonus awesome points for also helping me with the second step of my requirements)
I think I found a solution, but I'm not sure if it passes because it works or because it's searching for nothing and finding it.
$session = $this->getSession();
$element = $session->getPage()->find('css', $locator);
//check element content is not empty (returns exception if true)
if (empty ($element->getText()) ) {
throw new Exception;
}
Can someone please code-review this?

Getting "Editor" field value throws the value range exception under a non-System account

Below's the piece of legacy code of migration from 2007 to 2010. It gets the values of the author and the editor fields. The values are the same user, actually. When I login under the SPAdmin rights, both fields work okay. However, under a test account, the attempt to get the value of the Editor field fails with the following exception: "Value does not fall within the expected range", while the Author field still works fine. Let's see the code:
SPQuery sPQuery = new SPQuery();
sPQuery.Query = queryString;
sPQuery.ExpandRecurrence = true;
sPQuery.CalendarDate = startDateTime;
sPQuery.DatesInUtc = false;
SPListItemCollection items = list.GetItems(sPQuery);
SPListItem item = items[0];
object author = item["Author"]; //works always, under any account
object editor = item["Editor"]; // **doesn't work under non-system account**
Well, here is the line of code that always works for the Editor too:
object editor = item.ParentList.GetItemById(item.ID)["Editor"];
So I wonder what wrong with that and what should I check.
Thanks.
Well, the problem was in the the lookup threshold limitation.

Linqpad - Outputting into anchor to use title

I have a db that stores exception messages.
I would like to create a query that gets these exceptions but instead of dumping huge amounts of text i would prefer it to be "on demand".
I figured putting the exception into an anchor tag like so and then reading the message when needed by mousing over it would work... apparently not.
var logsForErrors = (from error in Logs
select new {
error = LINQPad.Util.RawHtml("<a title='"+ error.Exception+"'></a>"),
errorDate = error.Date,
errorMessage = error.Message
}).Take(10);
logsForErrors.Dump();
This is throwing an exception (lol) - "Cannot parse custom HTML: "
Encoding the exception message
...RawHtml("<a title='"+ Uri.EscapeDataString(error.Exception)+"'></a>")
Message Could not translate expression 'RawHtml((("h__TransparentIdentifier0.error.Exception)) +
"'>"))' into SQL and could not treat it as a local expression.
will generate a new error
Any ideas? - I am open to alternative solutions to this also.
I just want a container for the message instead of it just dumping right into the output as it it so huge!.
Thanks,
Kohan
Have you tried using the "Results to DataGrids" mode in the recent betas? It might do just what you need without having to write anything else.
Edit: your error was probably due to emitting HTML without escaping the text. The easiest solution is to call Util.RawHtml with an XElement instead of a string. You could write an extension method that does what you want like this:
public static class Extensions
{
public static object Tooltipize (this string data)
{
if (string.IsNullOrEmpty (data) || data.Length < 20) return data;
return Util.RawHtml (new XElement ("span", new XAttribute ("title", data), data.Substring (0, 20)));
}
}
Put this into My Extensions and you can use it from any query.