CakePHP disable some radio buttons? - php

I have a simple form with some radio buttons. I want to disable some of the radio buttons, is this possible?
$sixMonths = true;
$twelveMonths = true;
$twentyfourMonths = false;
echo $this->McForm->create('Wizard', array ('url'=>'/wizard/create'));
$options = array('24' => '24 months','12' => '12 months', '6' => '6 months');
$attributes = array('legend' =>false, 'default' => '6');
echo $this->McForm->radio('period', $options, $attributes);
echo $this->McForm->submit('Save');
echo $this->McForm->end();
So in this case I'd like to disable the first radio button and enable the other two.
I know I could probably do it with jQuery, but I'd prefer to do it without using it, is it possible?
Any ideas?
Thanks!

You can add a disabled array in $attributes that contains the values ​​of the radios:
$attributes = [
'legend' => false,
'default' => '6',
'disabled' => ['6', '24']
];

This isn't possible unless you call the radio function for each option separately and add 'disabled' => 'disabled' to the $attributes array for the ones you wish to disable. Here's a possible solution:
// Options
$options = array('24' => '24 months','12' => '12 months', '6' => '6 months');
// Disabled options
$disabled_options = array('12');
// Default attributes (these may need to be adjusted)
$attributes = array('legend' => false, 'default' => '6');
// Loop through all of the options
foreach ( $options as $key => $value )
{
// Output the radio button.
// The field name is now "period.n" which will result in "data[Model][period][n]" where "n" is the number of months.
// The options is an array contain only the current $key and $value.
// The 'disabled' => 'disabled' is added to the attributes if the key is found in the $disabled_options array.
echo $this->McForm->radio('period.' . $key, array($key => $value), ( in_array($key, $disabled_options) ? $attributes + array('disabled' => 'disabled') : $attributes ));
}

Related

Check if array contains array matching a value then store result into new array

I have an odd question which I cannot find an answer to on Google or SO.
I have an array containing all the bits of information about the pages on my website. So the array contains multiple of the arrays like the example below:
'home' =>
array (size=7)
'title' => string '' (length=0)
'url' => string 'home.php' (length=8)
'mobile' => string 'home.php' (length=8)
'keywords' => string '' (length=0)
'description' => string 'test123' (length=126)
'login_needed' => boolean false
'original_page' => string 'home' (length=4)
What I need to do is to find each array that contains a value that comes from a search bar. For example if the user searches for "bruidsmode" every array that contains "bruidsmode" should be put into another array which I can then output into elements to display on the website.
Below you will find a stripped example of what I have on my page. (I tried making a working example but was unable to do so):
<?php
$config['menu']["home"] = array (
'title' => '',
'url' => 'home.php',
'mobile' => 'home.php',
'keywords' => '',
'description' => '',
'login_needed' => FALSE
);
$config['menu']["bruidsmode"] = array (
'title' => '',
'url' => 'bruidsmode.php',
// 'mobile' => 'bruidsmode.php',
// 'mobile' => 'bruidsmode.php',
'keywords' => '',
'description' => '',
'login_needed' => TRUE,
'robot' => FALSE
);
if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
// Put search value into variable
$searchvalue = $_POST['generalsearchresult'];
// Fill variable with all page items
$array = $config['menu'];
// Set search cretaria to search in array
$key = $searchvalue;
// Search for key value inside array
$result = #$array[$key] ?: null;
if($result == null){
echo "Geen resultaten gevonden...";
}else{
var_dump($result);
}
}
?>
<form method="POST">
<input type="text" name="generalsearchresult">
<input type="submit" name="generalsearch">
</form>
The above code works but only outputs arrays which exactly match the search criteria. So for example the searchterm "bruidsmode" with the above code outputs only the page "bruidsmode" but not the page "bruidsmode-overzicht" for example.
I hope the above is understandable, if not please tell me how to improve it.
Kind regards,
Robbert
Your code isn't really what I would call a search. In order to search you should loop over the array to find potential matches, rather than return the requested property.
function searchMenu($menu, $term) {
$matches = [];
foreach($menu as $key => $value) {
if (stripos($key, $term) !== false) {
$matches[] = $value;
}
}
return $matches;
}
if(isset($_POST['generalsearch']) && isset($_POST['generalsearchresult'])){
$result = searchMenu($config['menu'], $_POST['generalsearchresult']);
if(!count($result)){
echo "Geen resultaten gevonden...";
}else{
var_dump($result);
}
}
If you want to return multiple results, you will need to store them in an array and return that.
If you are going to do that, you can extend the search to check against child fields as well, not just the top level keys:
$page_data =[
'my-cat' => [
'title' => '',
'url' => 'my-cat.php',
'mobile' => 'my-cat.php',
'keywords' => 'cat,kitten',
'description' => 'i love my cat',
'login_needed' => false,
'original_page' => 'mycat',
],
'home' => [
'title' => '',
'url' => 'home.php',
'mobile' => 'home.php',
'keywords' => 'cat,dog,other',
'description' => 'a site about cats',
'login_needed' => false,
'original_page' => 'home',
],
'about' => [
'title' => '',
'url' => 'about.php',
'mobile' => 'about.php',
'keywords' => 'about',
'description' => 'about me',
'login_needed' => false,
'original_page' => 'about',
],
];
function search(array $page_data_to_search, string $search_term, array $fields_to_search): array{
$out=[];
$search_fields = array_flip($fields_to_search); //O(1)
foreach($page_data_to_search as $key => $page_data){
//first test the key
if(isset($search_fields['key']) && strpos($key, $search_term) !==false){
$out[$key]=$page_data;
continue; //no need to check other fields
}
//then the user supplied fields
foreach($search_fields as $field => $unused){
if(isset($page_data[$field]) && strpos($page_data[$field], $search_term) !==false){
$out[$key]=$page_data;
break;
}
}
}
return $out;
}
echo '<pre>';
var_dump(search($page_data, 'cat', ['key', 'keywords', 'description']));

Add a new field to array elements in a foreach PHP - Laravel

I have this variable:
$families = array(
array(
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
And I want add to my $families items a field called 'href', like this:
$families = array(
array(
'href' => 'http://mipage/wall-art/AAER',
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'href' => 'http://mipage/personalised-mug/EEER',
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
To do this I iterate $families in a foreach loop:
foreach($cat['families'] as $cat_fam) {
$cat['families'][]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
But this not works for me.
How can I make this?
You've to repalce empty [] with the specific key. For this update foreach block to get key of the element and use that inside foreach loop.
$cat['families'][$key] which points to individual element of the families array.
Like this,
foreach($cat['families'] as $key=>$cat_fam) {
$cat['families'][$key]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
Demo: https://eval.in/636898
just iterate over the array, and add a key ahref
$newArray= array();
foreach($families as $innerArray){
$innerArray['ahref']='YOUR LINK HERE';
$newArray[] = $innerArray;
}
$families = $newArray ;//if you want to update families array
Do something like:
$href = array('href'=>'http://mipage/wall-art/AAER');
$combined_array = array_combine($families[0],$href);
Don't tested but you can try or modify as per your use
Please try this:
I think you also forgot to add index description in your str_slug call.
foreach($cat['families'] as &$cat_fam) {
$cat_fam['href'] = 'http://mysite/'.str_slug($cat_fam['description']).'/'.$cat_fam['family_id'];
}
You can use the php function array_walk
Liek this :
array_walk($cat['families'], function(&$family){
$family['href'] = 'http//mysite/'.str_slug($family).'/'.$family['family_id'];
});
note the $family variable is passed by reference.

How do I echo previously chosen dropdown value in codeigniter?

This code works well in terms of adding new entry with this dropdown category. My problem is, this sets Option1 as the default value to make sure the dropdown is not left unanswered. My question is, how do I echo the previously saved value for dropdown category? I should have it correctly displayed so I can do edit function correctly.
<tr>
<span style="font-size: 10pt" class="label label-info">Category</span><br/>
<? $options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, 'Option1');?>
</tr>
I am looking forward to any help.
Have a nice day! :)
EDIT: this works (by the way there are good classes to handle forms with codeigniter out there, where you don't have to use all this code for each field and that manage validation rules etc. in a much more flexible way - keeping the view and controller very simple and moving most of it into models).
<?php $model = array(
array('value' => '1', 'display' => 'Option1'),
array('value' => '2', 'display' => 'Option2'),
array('value' => '3', 'display' => 'Option3'));
echo '<select name="category_id">';
foreach($model as $i) echo '<option '.($this->input->post('category_id') === $i['value'] ? 'selected="selected"' : '').' value="'.$i['value'].'">'.$i['display'].'</option>';
echo '</select>';
?>
in ref from your question : Edit form echoes previously saved data correctly but does not update the form fields
<?php
foreach($model as $row)
{
if($row="" )
{
$selected_category_id = '';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
else
{
$selected_category_id = '$row->(database column name where vale is stored)';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
}

Semi-advanced PHP array

So I'm new to Arrays, but I think this should be fairly easy, I just can't wrap my head around it.
I've got an array, that can have a varying amount of keys in it, based on how much input is given by the user.
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10'
));
easy enough, right?
but I've got 1-4 more keys that could be in it, based on user input. They fill out a form on the first page, and it submits to the second page (which contains the array above).
I need to grab City, State, First, last, based on how many fields the user fills out on the previous page. I can't have blank ones so
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
'city' => '',
'state' => '',
'first' => $_GET['first']
));
won't really work. I need a way to determine which fields have been submitted (preferrably via GET) and build the array that way. so can end up with
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
'state' => $_GET['state'],
'first' => $_GET['first']
));
because state and first had a value while city and last did not.
The first thing that came to mind was something like
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
$constants => $variables
));
//where
$constants = array( //_GET stuff values );
$variables = array( //_GET stuff with values );
// magic method to make it like
// CONSTANTS[0] => VARIABLES[0];
// CONSTANTS[1] => VARIABLES[1];
// so everything is lined up
but I'm not sure how to do it :/
You will want to use a whitelist of possible keys from $_GET so your array doesn't get polluted with spurious (or possibly malicious) keys, and then you can simply append them onto your array with a loop over $_GET.
// Your array is already initialized with some values:
$array = array(
'type' => 'representatives',
'show_this_many' => '10'
);
// Allowed GET keys
$allowed = array('city','state','first');
// Loop over get and add the keys (if allowed)
foreach ($_GET as $key => $value) {
// If the key is allowed and the value isn't blank...
if (in_array($allowed, $key) && !empty($value)) {
$array[$key] = $value;
}
}
// See all the newly added keys...
var_dump($array);
Another option is to just add all the keys to the array, then call array_filter() to remove the blanks.
$array = array(
'type' => 'representatives',
'show_this_many' => '10',
'city' => '',
'state' => '',
'first' => ''
);
// Add values from $_GET, then filter it
$array = array_filter($array, function($val) {
return $val !== '' && !is_null($val);
});
Try the below code
$array = array(
'type' => 'representatives',
'show_this_many' => '10'
);
$fields = array ('city', 'state', 'first');
foreach ($fields as $field) {
if (!empty($_GET[$field])) {
$array[$field] = $_GET[$field]
}
}

Get array index

I have a array in PHP (like example) and I need to get the value tipo from the index, whitch is the first parameter, codigo_tipo. I tried a lot of times, but no one works. Thanks.
$this->conteudo['tipos'] = array(array('codigo_tipo' => '0', 'tipo' => 'Notícias'), array('codigo_tipo' => '1', 'tipo' => 'Informativos'), array('codigo_tipo' => '2', 'tipo' => 'Agenda'));
If I understood you correctly:
$search = 0; // codigo_tipo
foreach ($this->conteudo['tipos'] as $key => $value)
{
if ($value['codigo_tipo'] == $search)
{
echo $value['tipo']; // Noticias
}
}
You have a nested array there, so you need to address each step separately.
$this->conteudo['tipos'][0]['tipo']; // <-- 'Noticias'
Not sure this is what you want, but this iterates through the array:
<?php
$this->conteudo['tipos'] = array(array('codigo_tipo' => '0', 'tipo' => 'Notícias'), array('codigo_tipo' => '1', 'tipo' => 'Informativos'), array('codigo_tipo' => '2', 'tipo' => 'Agenda'));
foreach ($this->conteudo['tipos'] as $elem) {
echo "codigo_tipo: ".$elem['codigo_tipo']." - tipo: ".$elem['tipo']."\n";
}
?>

Categories