What's the opposite of inList in my cakePHP model? - php

inList states that your array should contain a certain string value.
I'm looking for a rule that will exclude certain values for names in my model.
The following code states that the name should be Bob, Bobbie or Bobzilla:
'name' => array(
'rule' => array('inList', array('Bob', 'Bobbie', 'Bobzilla')),
'message' => 'Stop it Bob!'
),
I need the user to be unable to enter any of these names. To me it seems as if inList should be notInList.
I've tried many ways but none of them lead me to Rome.
If you could help me that would be very much appreciated!

Take a look at PHP in_array function
something like
if (!in_array(ENTERED_NAME,YOUR ARRAY)) {
}

This is the best solution I was able to come up with:
public function itsBob($check) {
$bobArr = ['Bob', 'Bobbie', 'Bobzilla'];
if (!in_array($check['name'], bobArr) {
return false;
}
return true;
}
With the following lines in the $validation:
'name' => array(
'rule' => array('itsBob'),
'message' => 'Stop it bob!'
),
itsBob literally does the opposite of inList.

Related

Why multiple scenario are not working in Yii?

I am using multiple scenarios in my application but facing a problem that every time the last scenario overrides the first one.
Model:
public function rules()
{
return array(
[...]
array('cost_spares', 'cost_spare_func', 'match',
'pattern' => '/^[a-zA-Z]+$/',
'message' => 'Do not enter zero or/and characters for Spare parts!',
'on' => 'cost_spare_func'),
array('cost_labour', 'cost_labour_func', 'match',
'pattern' => '/^[a-zA-Z]+$/',
'message' => 'Do not enter zero or/and characters for Labour Charges!',
'on' => 'cost_labour_func'),
);
}
Controller :
public function actionUpdate ($id)
{
if (isset($_POST['TblEnquiry']))
{
[...]
$model->setScenario('cost_spare_func');
$model->setScenario('cost_labour_func');
}
}
Regarding to the documents:
Firstly it is important to note that any rules not assigned a scenario will be applied to all scenarios.
So I think you maybe do not need a scenario and just use common rules/validation.
OR
You have ONE scenario for your rules like this:
public function rules()
{
return array(
[...]
array('cost_spares','numerical',
'integerOnly' => true,
'min' => 1,
'max' => 250,
'tooSmall' => 'You must order at least 1 piece',
'tooBig' => 'You cannot order more than 250 pieces at once',
'message' => 'Do not enter zero or/and characters for Spare parts!',
'on' => 'myScenario'),
array('cost_labour','numerical',
'integerOnly' => true,
'min' => 1,
'max' => 250,
'tooSmall' => 'You must order at least 1 piece',
'tooBig' => 'You cannot order more than 250 pieces at once',
'message' => 'Do not enter zero or/and characters for Labour Charges!',
'on' => 'myScenario'),
);
}
And in your controller you just write:
public function actionUpdate ($id)
{
if (isset($_POST['TblEnquiry']))
{
[...]
$model->setScenario('myScenario');
}
}
Edit: Regarding to this document, I just see that you only want numerical input. So this might fit better to your needs. And since both got same check, you could just do one check and pass the message later into it. But for now, this should work.
Extra:
There is another bug in your rules like you wrote.
array('cost_spares', 'cost_spare_func', 'match',
'pattern' => '/^[a-zA-Z]+$/',
'message' => 'Do not enter zero or/and characters for Spare parts!',
'on' => 'cost_spare_func'),
That is not possible. You can not mix a rule validate function and a default validation like match.
That means you can only define a validation function like this:
array('cost_spares', 'cost_spare_func',
'message' => 'Do not enter zero or/and characters for Spare parts!',
'on' => 'cost_spare_func'),
OR use a default validation like this:
array('cost_spares', 'match',
'pattern' => '/^[a-zA-Z]+$/',
'message' => 'Do not enter zero or/and characters for Spare parts!',
'on' => 'cost_spare_func'),

Yii ConditionalValidator Not Working

I am trying to set a field as reuired only when another field selected value not equal to 11.
I have tried this example
array('role', 'ext.YiiConditionalValidator',
'if' => array(
array('role', 'compare', 'compareValue'=>"11"),
),
'then' => array(
array('company_id', 'required'),
),
),
),
I tried downloading new ConditionalValidator.
And even tried custom condition:
public function checkEndDate($attributes,$params)
{
$this->addError('company_id','Error Message');
}
public function rules() {
return array(
array('company_id', 'checkEndDate')
);
}
But it all shows error. Any simple way to solve this?.
Why not using scenarios? If you're creating/editing model with 'customer_type=active' you can before hand create it with special scenario:
$model = new MyModel(MyModel::SCENARIO_ACTIVE);
and then define your rules including scenario:
array('birthdate, city', 'required', 'on' => MyModel::SCENARIO_ACTIVE),
array('city', 'in', 'range' => array("sao_paulo", "sumare", "jacarezinho"), 'on' => MyModel::SCENARIO_ACTIVE)
If you don't like this way, you can always very simply create your own validator.
In rules:
array('customer_type', 'myCustomValidator'),
In the model class:
function myCustomValidator(){
if($this->customer_type == 'active'){
...
if($error){
$this->addError(...);
}
}
}

Validating URL-Parameter by using Model-Rules CakePHP

i just write my first article so please tell me if i've done something wrong!
My Problem: I want to validate data given by url.
../Logs/requests?from=2011-10-18T16:15:00&to=2011-10-18T16:30:00&fmt=csv
I have just find out that there is an option to validate with the rules added to the Model.
public $validate = array(
'request_id' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
)
);
Using "ModelName->set($params)" in the Controller and after that the "ModelName->validates()"-function should deliver the answer if its valid or not. The only differenz between my solution and the solution at http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
is that my controller using a couple of Models to collect the data for the response.
The problem is that the "validates()"-function just return "valid" even if i put in special-characters or other stuff what should be "not valid"-signed by the model-rules.
Help!
This is not an answer, but added to assist the OP;
I've created a test controller/model to test your situation. I deliberately did not extend the 'AppController' / 'AppModel' to remove any code in those from causing problems.
My test model (app/Model/Some.php)
class Some extends Model
{
public $name = 'Some';
public $useTable = 'false';
public $validate = array(
'request_id' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
)
);
}
My test controller (app/Controller/SomeController.php)
class SomeController extends Controller
{
public $uses = array('Some');
public function index()
{
$this->autoRender = false;
$params = array('Some' => array('request_id'=>'4*G/&2'));
$this->Some->set($params);
$result = $this->Some->validates();
debug($result);
$params = array('Some' => array('request_id'=>'AAAA'));
$this->Some->set($params);
$result = $this->Some->validates();
debug($result);
}
}
Outputs:
\app\Controller\SomeController.php (line 32)
false
\app\Controller\SomeController.php (line 37)
true
This test setup seems to work as planned, so you may try to test these in your application as well to narrow down the cause of your problem. Maybe some behavior is attached to your AppModel that contains a 'beforeValidate()' callback and disables the validation of the request_id field?

CakePHP empty field versus not empty field validations

I have the follow validation rule for a file:
modelFile.php
public $validate = array(
'image' => array(
'maxWidth' => array(
'rule' => array('maxWidth', 2000),
),
'maxHeight' => array(
'rule' => array('maxHeight', 2000),
),
'extension' => array(
'rule' => array('extension', array('gif', 'jpg', 'png', 'jpeg')),
),
'filesize' => array(
'rule' => array('filesize', 5120000),
)
)
);
Have a way to skip validations, if image are empty?
You may have to adjust how you check if the image is empty/not uploaded - I'm not sure if what I have is correct. But the idea is to check and unset the validation rule.
public function beforeValidate($options = array()) {
if (empty($this->data[$this->alias]['image']['name'])) {
unset($this->validate['image']);
}
return true;
}
See below URL
cakePHP optional validation for file upload
Or try it
"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"
So by the time you save your data array, it looks something like this I assume:
array(
'image' => 'foobar',
'imageupload' => array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
)
Which means, the imageupload validation rule is trying to work on this data:
array(
'name' => 'foobar',
'size' => 1234567,
'error' => 0,
...
)
I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".
Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it
Ok, as far as I know there is no such code to set this in your $validate variable. So what you are going to have to do is:
In the beforeValidate of the corresponding model add the following piece of code:
<?php
# Check if the image is set. If not, unbind the validation rule
# Please note the answer of Abid Hussain below. He says the ['image'] will probably
# never be empty. So perhaps you should make use of a different way to check the variable
if (empty($this->data[$this->alias]['image'])){
unset($this->validate['image']);
}
I used http://bakery.cakephp.org/articles/kiger/2008/12/29/simple-way-to-unbind-validation-set-remaining-rules-to-required as my main article. But this function doesn't seem to be a default cake variable. The code above should work.

CakePHP validation alpha problem w/ validation is checked - what am I doing wrong?

Excuse my ignorance on this question, but what seems to be an obvious fix is not coming together for me..
My validation is working perfectly fine with the exception of when I enter any alpha characters in my form field, I get a sql error:
SQL Error: 1054: Unknown column 'abcde' in 'where clause'...
As you can see I entered 'abcd' as a test..
But if I enter a numeric character and per my validation its all fine.. It appears the alpha value is being read as a column name??
Here is my validation rule:
...'Age' => array(
array(
'rule' => array('maxLength', 3),
array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Age must be numeric.'
),
),
Here is my controller validation code:
if ($this->RequestHandler->isAjax()) {
if ($this->Plan->validates()) {
$this->Plan->set($this->data);
$errors = $this->Plan->invalidFields();
$this->set('errors', $errors);
} else {
$this->Plan->set($this->data);
}
}
As you can see I am returning my errors to my view, and the correct error "Age must be numeric." does in fact display as expected, but just with the SQL error stuff.
Thanks for any insight as to why this is happening.
Do you even read the manual? It's clearly stated in the CookBook that you need to give your rules names if you want to use multiple rules.
Also, your array is nested completely wrong. I don't know how this could be working, but anyway, this is how your validate should look like:
var $validate = array(
'Age' => array(
'length' => array(
'rule' => array('maxLength', 3)
),
'numbers' => array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Age must be numeric.'
)
)
);

Categories