Laravel-Validation of unknown array keys - laravel-9

I have created a controller to validate and save a form.
I don't know how the individual form fields are named because this is assigned by the system in the form designer.
For this reason I first make a query ($valArrays) to find out which fields are required and then find out what the array key is.
The field order_title is always required.
$valArrays = FormDetail::where('form_details.form_id', $request->form_id)
->where('required', 'yes')
->get();
$array = array();
$array['order_title'] = 'required';
foreach ($valArrays as $valArray) :
$array[$valArray->detail_id] = 'required';
endforeach;
$request->validate($array);
when I query via dd($array) I get the following evaluation:
^ array:6 [▼
"order_title" => "required"
"QS0brKe5LP" => "required"
"TjFusWAKLh" => "required"
"uNqAPbNwkg" => "required"
"OvclFtOlvF" => "required"
"52e515mfRf" => "required"
]
so everything is ok! but the programme jumps back to the form without saving.
If I take out the code part everything works but without validation :0(
Do you have any idea why this could be?

Related

Validate date of one column greater than with another column in yii

I have a form which has date_of_purchasing and expiry_date. I need to check date_of_purchasing should not be greater than expiry_date. How can i write this validation rule in model.
Im using YII framework. And im new for this framework.
Yii2
This should work if the compared column comes from the same table.
public function rules()
{
return [
[
['date_end'],
'compare',
'compareAttribute' => 'date_start',
'operator' => '>=',
'type' => yii\validators\DateValidator::TYPE_DATE,
'message' => 'Date end has to be greater than date start',
'enableClientValidation' => false
],
// other rules...
];
}
Don't forget to set enableClientValidation to false because Yii2 can't check the other date without a server side request.
Other configuration options here.
PS. I decided to update this thread 3+ years after because it remains
one of the first StackOverflow results on Google Search for this argoument.
Try to use CompareValidator at this link: Compare .

send an array variable to formtype in symfony from the controller

I have an sql request in my controller:
$results = $conn->query( " select field 1....fieldn from tableA " );
$row = $results->fetch();
I want to show the returned result $row in twig as dropdown menu list
in other word, how I can send the $row variable to the formtype to use it after that as choice field.
Try it from the other site. Create a "Form Type" and in your "Form Type" you can use an entity field and select data from your database through doctrine for example:
->add('User', 'entity', array(
'required' => true,
'class' => 'Test\TestBundle\Entity\User',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')->where('u.id > 150 and u.id < 160');
}
))
Then you should get an dropdown by default.
The class is here your entity class witch is automatically given to the query builder under that class field and you can use it.

Problems returning result of CDbCriteria based query

I have a query as follows
$criteria1 = new CDbCriteria();
$criteria1->condition = 'id = 1';
$modelA=Table1::model()->find($criteria1);
I can pass it to a view and return the title and entry
$this->widget('bootstrap.widgets.TbBox', array(
title' => $modelA['title'],
'content' => $modelA['entry'] ));
Now I'd like to return a range of entries
$criteria2 = new CDbCriteria();
$criteria2->condition = 'id > 7';
$modelB=Table1::model()->findAll($criteria2);
(btw : I'm following a form as laid out here). I was expecting to be able to read the resulting array of values out as below, but ['title'] is now being seen as a undefined index (obviously I'm expecting to read this out in a loop but you get the point)
$this->widget('bootstrap.widgets.TbBox', array(
'title' => $modelB['title'][0],
'content' => $modelB['entry'][0]));
Where am I going wrong?
Thanks
No, the indexes should be specified in the different order: the number of a specific element first, then the name of the property. Additionally, it's better (=cleaner) to name the result of findAll so it'll show you (and any other reader) that it's a collection, not a single model:
$models = Table1::model()->findAll($criteria2);
// ...
$this->widget('bootstrap.widgets.TbBox', array(
'title' => $models[0]['title']
//...
));
But even that's not necessary if you use foreach (and you probably will):
foreach ($models as $model):
// ...
$this->widget('some.name', array(
'title' => $model['title']
);
endforeach;

Restricting a category for a certain country in Prestashop 1.5

I need to restrict a category to a set of countries in Prestashop 1.5.
This restriction would prevent the shipping of a product belonging to such a category; as such, the users would still be able to see the products but they would not be able to buy them.
Ideally, I wanted to develop a module that would insert a list of countries (checkbox style, as in the Modules -> Payment page (AdminPayment)) inside a category's edit page, but I haven't been able to do so.
Why can't i simply paste the following code inside the renderForm() function?
Only the description is visible if i do so...
array(
'items' =>Country::getCountries(Context::getContext()->language->id),
'title' => $this->l('Country restrictions'),
'desc' => $this->l('Please mark the checkbox(es) for the country or countries for which you want to block the shipping.'),
'name_id' => 'country',
'identifier' => 'id_country',
'icon' => 'world',
),
EDIT:
I managed to get the list of countries working:
array(
'type' => 'checkbox',
'label' => $this->l('Restricted Countries').':',
'class' => 'sel_country',
'name' => 'restricted_countries',
'values' => array(
'query' => Country::getCountries(Context::getContext()->language->id),
'id' => 'id_country',
'name' => 'name'
),
'desc' => $this->l('Mark all the countries you want to block the selling to. The restrictions will always be applied to every subcategory as well')
),
Now, I can save these values by checking if the value "submitAddcategory" is being submitted in the postProcess function and by running an insert query there. Similarly, I can also load the IDs of the blocked countries from the database, but how can I tick the respective select boxes in the list of countries?
My initial "quick and dirty" idea was to use jQuery selectors inside a document.ready(), but the code gets inserted before everything else and, as such, it won't work because jQuery isn't even loaded yet.
How can this be done?
Cheers
I solved it by using the following code right before the end of the renderForm() function.
The Pièce de résistance was $this->fields_value, as sadly I didn't known of its existence.
public function getRestrictedCountries($obj)
{
// Loading blacklisted countries
$country = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT DISTINCT id_country
FROM `'._DB_PREFIX_.'category_country_restriction`
WHERE id_category = ' . (int)Tools::getValue('id_category') . ';');
$blacklisted_countries = array();
if (is_array($country))
foreach ($country as $cnt)
$blacklisted_countries[] = $cnt['id_country'];
// Global country list
$c_todos = Country::getCountries(Context::getContext()->language->id);
// Crossmatching everything
foreach ($c_todos as $c)
$this->fields_value['restricted_countries_'.$c['id_country']] = Tools::getValue('restricted_countries_'.$c['id_country'], (in_array($c['id_country'], $blacklisted_countries)));
}
PS: The table I am reading from is basically an associative table between 'category' and 'country'

multiple checkbox valiadation for any one in YII frame work for this example

Hi can you please tell how can i validate the multiple checkbox any one is checked in yii framework
array('accept', 'required', 'requiredValue' => 1, 'message' => 'You should select alteast one')
As these value are usually sent as arrays, I wrote an array validator for these cases once: https://github.com/schmunk42/p3extensions/blob/master/validators/P3ArrayValidator.php
Usage example:
array('accept',
'ext.validators.P3ArrayValidator',
'min'=>1,
'allowEmpty'=>false,
'message' => 'You should select at least one'
),
sorry for the late reply.
But, I found a solution without installing any extension.
Take a hidden field with the same name [Checkboxes list field].
<?php echo $form->hiddenField($model,'categories');?>
Display a list of categories with name different from our field name (multiple checkboxes).
But, remember the 'class', and play with the class to save the values.
<?php
echo CHtml::checkBoxList(
'group',
//you can pass the array here which you want to be pre checked
explode(',', trim($model->attributes['categories'], ',')),
CHtml::listData(Category::model()->findAll(),'id','name'),
array('separator'=>'', 'template'=>'<tr><td style="width:5%;">{input}</td><td>{label}</td></tr>', 'class' => 'group')
);
?>
This way validation should work also, you get category ids as comma separated e.g. [,1,2,6,]
<script>
$(function(){
$(".group").click(function(){
var str = $('.group:checked').map(function() {
return this.value;
}).get().join();
var groupCats = (str.length > 0) ? ','+str+',' : '';
$('#ModelNAME_field').val(groupCats);
// Get the 'ModelNAME_field' by viewing source of HTML of hidden field.
});
});
</script>