Validating country dropdown form - codeigniter

First of all, I have already readed this: Validating form dropdown in CodeIgniter
But it doesnt solve my problem:
As you know, <option> value can be faked for example using firebug.
My select options looks like this:
<option value="ger">Germany</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
[...]
Now, how can I validate if the choosen and posted value is correct?
These values are builded on the large array. It looks following:
$countries = array (
'ger' => 'Germany',
'uk' => 'United Kingdom',
'usa' => 'United States of America'
);
So how can I validate, of choosen value is correct? Will I have to use the array_key_exist with function callback on form validation?
What in case if my select options looks like this?
<option value="0">Choose Something</option>
<option value="1">Select-1</option>
<option value="2">Select-2</option>
[..]
How can I validate the above using the form validator, so I could check if the posted value is correct and not faked, also how to prevent from choosing the 0 value?
The best idea for this in my opinion is creating the function callback, which will look following:
public function validate_values($input)
{
$allowed = array(1, 2, 3, 4); //[..]
if ( !in_array( $input, $allowed ) )
{
//throw error, and do the rest...
}
}
Are my ideas "ok" or there are any better solutions for these cases?

The callback is exactly what you need. I think that's why they were created. In user guide:
"The validation system supports callbacks to your own validation
functions. This permits you to extend the validation class to meet
your needs."
So if your need is to check if submitted values are from defined range, use it.
Of course it should return false or true depending on result. user guide for callbacks
For me it's the best solution. Especially because you need to check those values after form is submitted.
As for preventing from choosing 0, don't put 0 to in_array or check first if $input is !empty for example and set correct error message. If you're creating your own callback you can validate that $input for whatever you want.

Related

Laravel 5.4 - exists validation but not required

I have an 'array type' dropdown field in my form, e.g:
<select name="category_id[]">
<option value="">Please Select</option>
// more options
</select>
There are 3 of these same fields (hence it being an array type) and they are all optional, but if a value is selected it checks whether it is a valid value as follows:
$rules['category_id'] = 'exists:universities,id';
The problem I'm having is that if the empty option is selected, it is still giving me a validation error, e.g "The selected category is invalid." If I select a valid value I don't get any errors (as expected).
I have tried adding both nullable and sometimes to the validation rule but they don't make any difference. Do I need to do something different with it being an array type field?
If you use "array-like" name for your select, you should use array validation like so:
$rules['category_id.*'] = ['nullable', 'exists:universities,id'];
But if it's not multi select, you can change the name to category_id to make it work
Can you try <option value="" selected disabled>Please select</option>. Also what does dumping $request->category_id give you when no selections are made?

What is the way to do it with Vuejs

I have a page with 3 combos, 6 dependents inputs text ( if a special value is selected in combo, it will show, otherwise it will hide)
Then, I will have A text fields that is a computed property. Each time an input is changed, it will reevaluate this field value.
So, For instance, My fields are:
GradeIni, GradeFin, Category, AgeCategory, AgeIni, AgeFin , Gender (selects)
isTeam ( Checkbox )
CategoryFullName
So, for example, There is 5 predefines AgeCategory,and the 6th is Custom, when Selected, it show AgeIni and AgeFin
Each time a value is change, CategoryFullName is reevaluated.
My first answered question was how to get values from server.
I knew how to do it with Ajax, but in this case, it was easier to just use Server variable sent by Laravel when pages load.
So, the answer was 2 options:
#foreach ($grades as $grade)
<option ...>{{ $grade }}</option>
#endforeach
Or
<grades :grades="{{ $grades }}"></grades>
So, I would like to use the second one, but it means I have to create a component for each Select Option in my page, which seems a little heavy.
So, I'm a little bit confused about how should I make this page. Is it better by AJAX, is it better to be able to get data from laravel, and o make a component for each list, or is there a better way to do it????
You dont need to use many components. One component and one variable to keep the selected grade are fine.
You can create a component template to display all the grades.
I have created one template with dummy data to show you how you can do it.
<template id="grades-list">
Curently selected: Title {{selected.title}} Value: {{selected.value}}
<select v-model="selected">
<option v-for="grade in grades" :value="grade">{{grade.title}}</option>
</select>
</template>
The component should be registered like this:
Vue.component('grades', {
props: ['grades', 'selected'],
template: '#grades-list'
})
The tricky part is how you will select a default value and keep it synced with the parent. To do so, you can use .sync
<!-- you can use :grades="{{ grades }}" with Blade too-->
<grades :grades="grades" :selected.sync="selectedGrade"></grades>
To set default value you can update the selectedGrade variable when the document is ready, using vm.$set.
new Vue({
el: 'body',
data: {
'selectedGrade': ''
},
ready() {
this.$set('selectedGrade', this.grades[1])
}
})
I have created an example with dummy data here.

how to validate checkbox number in Yii

My page has many checkbox, varies from 5 to 100, I need to verify the checked number. The minimal number is 2, max is 8. I went through yii documents, and not found such a validation method. How can I achieve this in an elegant way?
In addition, I want to save the checkbox value in session while user manipulating it , how to achieve this?
By using range validation you can achieve this functionality.
Rule will come something like bellow. Just modify this according to your program
public function rules()
{
return array(
array('your_attribute', 'required'),
array('your_attribute', 'in','range'=>range(2,8),'message'=>'Range should be in 400 to 690'),
);
}
I got some syntax here http://www.yiiframework.com/forum/index.php/topic/25286-yii-numbers-range-validator/

CakePHP Pagination sort() on Related Models

I have two models: Plans and PlanDetails.
Relationship is: PlanDetails hasMany Plans. Plans belongTo PlanDetails.
In the PlanDetails view.ctp, I am pulling in related Plans.
I am trying to sort the Plans by ANY field (I've tried them all), and I cannot get it working. I assume I am overlooking something very simple.
Here is my base code:
PlanDetail >> view.ctp:
...foreach ($planDetail['Plan'] as $plan_edit) :
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}...
<?php echo $this->Paginator->sort('Plan ID', 'Plan.id'); ?>...
...<?php echo $plan_edit['id']; ?>
plan_details_controller.php:
...function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid plan detail', true));
$this->redirect(array('action' => 'index'));
}
$this->PlanDetail->recursive = 2; // To run the editable form deeper.
$this->set('planDetail', $this->PlanDetail->read(null, $id));
$this->set('plan', $this->paginate('Plan'));
}...
I should add, no errors are being thrown and the sort() arrows on the ID field are showing as expected, but the sort order DOES not change when clicked either way.
Sorry, I'm not able to comment on the question itself, but I've noticed that in your action, you set planDetail to be the PlanDetail record you read (with recursive set to 2), and then you set plan to be the result of the paginate call.
Then, in your view template, you're iterating over $planDetail's contained Plan association, like this:
foreach ($planDetail['Plan'] as $plan_edit):
But in order to get the sorting and pagination done, you need to be displaying the results of the paginate call i.e. iterate over the records contained in $plan.
Do a debug($plan) in your view template to see what results you get there and to see if the records' ordering changes when you sort by different fields.
Also, perhaps you're using syntax I'm not aware of, but if you simply call $this->paginate('Plan') in your controller, I don't know that you're going to get only the related Plan records for your particular PlanDetail record. (There's nothing tying the $id passed into your view action with the Plan records.) You might need to add some conditions to the paginate call, like so:
$this->paginate['Plan'] = array('conditions' => array('Plan.plan_detail_id' => $id));
$this->set('plans', $this->paginate('Plan'));
Here is what I did to solve this. Based on some helpful direction from johnp & tokes.
plan_details/view.ctp:
...$i = 0;
foreach ($plan as $plan_edit) : // note $plan here.
}...
In my plan_details_controller.php view action:
$conditions = array("Plan.plan_detail_id" => "$id");
$this->set('plan', $this->paginate('Plan', $conditions)); // note "plan" in the first argument of set (this is required to pass the results back to the view). Also. The $condition is set to return ONLY plans that match the plan_detail_id of id (on the plan_details table).
And in my view, in order to get my results (because I changed the array name), I had to change the way I was getting the values to:
$plan_edit['Plan']['modified'] // note I placed ['Plan'] in front of these calls as the array called for this to get the data...
Well until the next problem! SOLVED.

How do I filter a collection by a YesNo type attribute?

I have a ‘featured’ attribute, which has a Yes/No select-list as the admin input. I presume that the values for Yes and No are 1 and 0, as they are for every other Yes/No list. However, if I try and filter a collection using the ‘featured’ attribute, it doesn’t work:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId(1);
But, if I make a ‘featured’ attribute with a dropdown, and write my own Yes and No, then it works as below:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId('Yes');
Anyone any ideas? I’ve also tried values as true/false, yes/no, on/off etc, but no joy.
This seems to be an old thread, but anyway I just had the same issue, I set the attribute to be visible in product listing and product view, and then apply addAttributeToFilter(feature_product_attribute, 1) for Yes/No type.
Maybe you are supposed to use '1' and '0' instead of the integer-values?
Like:
$feat_attribute = $_product->getResource()->getAttribute($featuredattribute)->getSource()->getOptionId('1');
Whenever Magento's behavior is confusing me, I start hacking on the core source (a development copy, of course) to see what it's doing and why not doing what I think it should. I haven't done much playing around with the Admin UI stuff so I don't 100% understand your question, but take a look at the getOption function
File: /app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Abstract.php
public function getOptionId($value)
{
foreach ($this->getAllOptions() as $option) {
if (strcasecmp($option['label'], $value)==0 || $option['value'] == $value) {
return $option['value'];
}
}
return null;
}
I'd add some Mage::Log and/or var_dump calls in there for the values of $option['label'] and $option['value'] and see why your comparison is failing.

Resources