CakePHP IBM Tutorial: Incorrect API doc for Model::validate()? - cakephp

Okay, this is driving me nuts. I’m working through the IBM CakePHP Tutorial, and in the first part, I’m at the section where the author is introducing validation rules for form input:
www.ibm.com/developerworks/opensource/tutorials/os-php-cake1/section5.html#N107E3
For the life of me, I can’t figure out what’s happening in this line of code:
$this->invalidate('username_unique');
According to the CakePHP documentation, the Model::invalidate() method takes as its first parameter a string that specifiies “The name of the field to invalidate”. How is “username_unique” the name of the field to validate? Looks to me like it should be just plain old “username”. But incredibly enough, the author’s code works, and mine doesn’t when I change “username_unique” to “username” (or even “User.username”), so I’m thinking there might be a serious flaw in the documentation (or very possibly, with me).
[FWIW, I can see that the CakePHP 1.25 provides a better means of doing validation, but I still find it troubling that what seems to be a well-documented method doesn't seem to be doing what it advertises, and I want to understand why the tutorial code works.]
Can anyone shed any light on this?

The "magic" is actually in the $form in this case.
When calling $this->invalidate('username_unique'), Cake takes a note that the field username_unique is invalid. The fact that this field does not actually exist is irrelevant.
Now, take another look at the actual $form field (slightly reformatted):
echo $form->input('username', array(
'after' => $form->error('username_unique', 'The username is taken. Please try again.')
));
It's outputting a normal form field, but "manually" places an error() output after the form field. $form->error('username_unique', $message) means "if there's an error for the field username_unique, output the message $message". So you're actually marking an imaginary field as invalid and are manually outputting an error message for this imaginary field.
And actually, that's a load of outdated cr*p you should forget right away. There's a built-in syntax for multiple validation rules per field, so you can test for character length and uniqueness at the same time and even get different error messages for each error type. There's even a built-in isUnique rule, so you won't even have to code a manual uniqueness test.

Related

ADNStoreFront Multistore AddtoCartForm function crashing page

I am trying to modify an existing XML package of Aspdotnetstorefront Multistore. It's an internal XML package to show the variants of a certain product. What I did to start with was to copy-paste the whole code as is and throw it into a new custom XML package. The problem is that it works fine in the original package but not in the copied package. When I try to run it the function "AddtoCartForm" crashes the page and show the following error while display in red the line that contains the function call:
An HtmlHelper is required for this method. Make sure to specify one when you call the RunXmlPackage method
The format of the function is:
<xsl:value-of select="aspdnsf:AddtoCartForm(ProductID, VariantID, 1, 1, $SelectedSize, $SelectedColor)" disable-output-escaping="yes"/>
I removed the line with the function just to be sure and then everything else works fine. I have no idea what's wrong here. Everything is identical unless by the structure of the url which calls the package:
For the internal package it is: \product\123456
For the custom package it is: \topic\packagename?ProductID=123456
I checked the XML produced by the SPs, the runtime and requested data and it's basically the same in both cases. The ProductID and VariantID values are there. SelectedColor and SelectedSize are not in the XML (not even in the internal package) so it may be just providing null value and probably it's not necessary anyway.
And there is more. If I supress the productid value from the url like this:
\topic\packagename
It won't crash the page (but also won't render because there will be not be any value to process).
In any way I cannot see why it wouldn't work just passing the variable in the querystring (that is basically what it does in the original package even in a different format) and the var value (productid) it getting there. However it seems that it is indeed the url format that is not pleasing the package but it doesn't make too much sense to me. I am over this for several days already and nothing I do seem to produce any positive result. :-(
I looked up online for some documentation but didn't get lucky and didn't find absolutely anything. In extreme cases I try to reach the Vortx support (and they usually answers me giving some valueable clue) but this time it seems that for this specific issue there will not be any help unless I pay an obscene hour fee and unfortunately it's out of question... LoL!
Any idea?
UPDATE: We don't use Multistore regular search tool. Due to the nature of our products (recycled car parts) we have a custom search tool that will try to find 'similar' items that MAY fit the user needs when we don't have the EXACT part. I don't know if you are ware of but several mechanical car parts are interchangeable among different models and makes (like alternators, AC compressors, battery, suspension, cooling system, etc), so when one of our customers needs a part to fix his car he won't tell us the part code; instead he will tell us the car model, year, and generic name of the part so we will try to find the part for him. It does mean that a certain Corolla part will fit perfectly in a Honda Accord and so on. Some times we have some parts in stock that MAY fit his car but we are not absolutely sure. When it happens we will show those parts for the customer and he will decide if he can take his chances. For the sake of customer comfort we want to show all these parts in the same page, but since they normally are variants of different products we cannot use the regular product page for this purpose (because the product page will only show variants of ONE product at time). For this reason I am going to write a package - a modified version of the product page - that will do that but I am struggling with the AddtoCartForm function. In fact I JUST found a workaround by adding the item to the cart accessing directly the /shoppingcart/addtocart script and now my problem is being to force it return to a specific url after to add the item to the shopping cart...
The error has to do with the topic token able to properly get html helper filled out.
I do question why testing is being done on a topic. To test a new product xmlpackage I normally change change the xmlpackage for just one product in a testing environment.
If chaning the product xmlpackage isn't possible then I suggest using the XmlPackageController/engine instead. Which is documented on page https://help.aspdotnetstorefront.com/1000/xml_packages.htm under the heading of "Invoking XML Packages by Themselves". If using the XmlPackageController make certain that the allowengine attribute is set to true in the xmlpackage otherwise that will throw an error as well.

Cakephp 2.0 ReCaptcha plugin always wrong

I've taken a reCaptcha plugin from this guy
(github link of the plugin)
I've entered the following code form in my view:
[form creation]
[table]
[inputs]
[/table]
echo $this->Recaptcha->show(array('theme' => 'white'));
echo $this->Recaptcha->error();
[/form]
I've followed the steps suggested, and the reCaptcha window appears properly, but no matter what I enter in the captcha, it never gets verified and I always receive the 'message' field of beforeValidate (I've set it to "You've entered a wrong message" etc).
I'm not even sure how to debug it to see at which point it fails. Even if I just replace all the code in checkRecaptcha function with "return true" to try and skip the validation with the keys and just see if the rule itself is correct, it still remains the same, and I'm generally not getting any of the specific incorrect-captcha-sol messages that I read around.
Am I correct to assume that the only code I need inside my controller function (assuming I've already included the component and helper in the controller) is Configure::load('Recaptcha.key'); and no further manual validation checks?
(unfortunately I can't link you my whole project due to rights)
I had a similar issue. Try removing the 2 response and challenge field lines in the component and overwrite them with these:
$controller->$modelClass->set('recaptcha_response_field',
$controller->request->data['recaptcha_response_field']);
$controller->$modelClass->set('recaptcha_challenge_field',
$controller->request->data['recaptcha_challenge_field']);

How to add a custom field into template.php using Zen sub theme

First time poster here, I'm a designer not skilled at all with php and I have a small issue I don't seem to be able to solve. I'm making a site in drupal 7 using a sub theme on zen.
Btw this is a great CMS, even though people say it's really more a developers CMS. I have no trouble to do what I need using views, rules, display suite etc. So a big thank you for all the developers out there making this such a good CMS. But for this apparently simple problem... no module will help me (I think) and I'm kinda stuck.
So here it is: I'd like to add a subtitle next to the title in all my pages.
So what I did was to add a custom field into the content type basic page (machine name: field_sub_title) which is a simple text field.
I uncommented the following line in my template.php
function mytheme_preprocess_page(&$variables, $hook) {
$variables['sub_title'] = t('field_sub_title');
}
Now my question is how do I load the content of my custom field into that variable?
I know i need to change the second part, but I don't have a clue as into what I need to change this.
Displaying the variable into the the page.tpl.php is something I know about so I only need help with the first part.
{EDIT}
Ok I found how to do this :)
I was looking for a solution in the wrong place. I don't need to change any thing in the template.php file.
Just needed to add this bit of code into my page.tpl.php:
<?php
print $node->field_sub_title['und'][0]['value'];
?>
So I'm posting this here for other Drupal newbies struggling with this....
Your solution may work for now, but there may be a more Drupal-y way to handle a problem like this. If you haven't noticed any problems yet, you may find one or more of the following issues down the road:
Someone who doesn't know php or Drupal theming may need to change the way this works.
If you're like me, you may forget where exactly in code this was implemented.
You may see superfluous markup and/or errors on nodes (content) that do not have this sub-title field (ie. event content not having a sub-title field while basic pages and news articles do).
When you add a field to a content type, it will automatically appear anytime content in that content type is displayed. You should be able to add the sub-title field for your page, event or whatever else you need and have it automatically appear in the markup.
You can 'manage display' of a content type to drag and drop the order for fields to appear. You could take it a step further by using a module like Display Suite to add formatting or layout per-content type.
If you feel like this isn't good enough and the markup for the subtitle must be at the same level as the page title (which is rare), at least add an if statement to make your code check to see if the variable is present before trying to print it. I'd also add a new variable and comments for code readability.
<?php
$subtitle = $node->field_sub_title['und'][0]['value'];
if($subtitle){
print $subtitle;
}
?>
Consider using field_get_items or field_view_value, or at least use the LANGUAGE_NONE constant instead of 'und'
See https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7 and https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7
This has the added benefit of reducing the number of potential security holes you create.

Solr/Lucene Query Validation

Does anyone have a regex that can be used to validate that a query to be sent to lucene is is well formatted?
https://github.com/praized/lucene-query-validator/blob/master/src/luceneQueryValidator.js
This is a JavaScript attempt. I have not verified it's success but from reviewing the code, everything looks legit.
If you're allowing your users to enter in free text, there is always the chance that they'll mistype a field name (i.e. naem:Bob instead of name:Bob ). This validator will not catch issues like that.
I've created a js AMD module here: https://github.com/grahamscott/lucene-validator-amd-module
It's based on the praized module above, but is easier to integrate client-side, and doesn't rely on window.alert()

cakephp and get requests

How does cakephp handle a get request? For instance, how would it handle a request like this...
http://us.mc01g.mail.yahoo.com/mc/welcome?.gx=1&.rand=9553121_pg=showFolder&fid=Inbox&order=down&tt=1732&pSize=20&.rand=425311406&.jsrand=3
Would "mc" be the controller and "welcome" be the action?
How is the rest of the information handled?
Also note that you could use named parameters as of Cake 1.2. Named parameters are in key:value order, so the url http://somesite.com/controller/action/key1:value1/key2:value2 would give a a $this->params['named'] array( 'key1' => 'value1', 'key2' => 'value2' ) from within any controller.
If you use a CNN.com style GET request (http://www.cnn.com/2009/SHOWBIZ/books/04/27/ayn.rand.atlas.shrugged/index.html), the parameters are in order of appearance (2009, SHOWBIZ, books, etc.) in the $this->params['pass'] array, indexed starting at 0.
I strongly recommend named paramters, as you can later add features by passing get params, without having to worry about the order. I believe you can also change the named parameter separation key (by default, it's ':').
So it's a slightly different paradigm than the "traditional" GET parameters (page.php?key1=value1&key2=value2). However, you could easily add some logic in the application to automatically parse traditional parameters into an array by tying into how the application parses requests.
CakePHP uses routes to determine this. By default, the routes work as you described. The remainder after the '?' is the querystring and it can be found in $this->params['url'] in the controller, parsed into an associative array.
Since I found this while searching for it, even though it's a little old.
$this->params['url']
holds GET information.
I have tested but it does work. The page in the Cakephp book for it is this link under the 'url' section. It even gives an example very similar to the one in the original question here. This also works in CakePHP 1.3 which is what I'm running.
It doesn't really use the get in the typical since.
if it was passed that long crazy string, nothing would happen. It expects data in this format: site.com/controller/action/var1/var2/var....
Can someone clarify the correct answer? It appears to me that spoulson's and SeanDowney's statements are contradicting each other?
Would someone be able to use the newest version of CakePHP and get the following url to work:
http://www.domain.com/index.php/oauth/authorize?oauth_version=1.0&oauth_nonce=c255c8fdd41bd3096e0c3bf0172b7b5a&oauth_timestamp=1249169700&oauth_consumer_key=8a001709e6552888230f88013f23d5d004a7445d0&oauth_signature_method=HMAC-SHA1&oauth_signature=0bj5O1M67vCuvpbkXsh7CqMOzD0%3D
oauth being the controller and authorize being a method AS WELL as it being able to accept the GET request at the end?

Resources