How to pass a function as a parameter in admin class [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
Good morning, I have a little problem using sonata admin bundle, let's suppose that I have a function which returns a String, I want to pass the result of this function into as a parameter in the datagrid : something like :
protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => function()), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id'
);
Any one knows a way to do this ? Thank you

You can override getFilterParameters() method to change your $datagridValues:
public function getFilterParameters()
{
$this->datagridValues = array_merge(array(
'email' => array ('type1' => 2, 'value' => function()),
), $this->datagridValues);
return parent::getFilterParameters();
}

The problem is the function() in
'email' => array ('type1' => 2, 'value' => function())
Pass a correct var and it will work.
'email' => array ('type1' => 2, 'value' => 'myValue')
EDIT
To pass a function in arguments (named a callback function), you have to pass the callback name in argument, and use the call_user_func to run it then:
function mycallback(){
// do things
}
protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => 'mycallback')
'_page' => 1,
'_sort_by' => 'id'
);
Then you can do in your script :
call_user_func($datagridValues['email']['value']);

within array you cant call a function..
you can do this way.
$var = function_name();
protected $datagridValues = array (
'email' => array ('type1' => 2, 'value' => $var), // type 2 : >
'_page' => 1, // Display the first page (default = 1)
'_sort_by' => 'id'
);

Related

tableselect make specific checkbox checked

foreach ($courses as $user) {
$options[$user['uid']] = [
'coursecode' => $user['coursecode'],
'coursename' => $user['coursename'],
'credithours' => $user['credithours'],
'coursetype' => $user['coursetype'],
'building' => $user['building'],
'place' => $user['place'],
'day' => $user['day'],
'time' => $user['time'],
];
}
$form['table'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
'#empty' => t('No Courses found'),
'#js_select' => false,
'#attributes' => ['checked' => 'checked'],
];
this code generates all courses I can register is there any way to check specific values as default, I had a problem with making a specific checkbox checked
so anyhelp ?
I'm using drupal 8
//Inside your foreach loop
foreach($courses as $user) {
$default_value[$user['uid']] = 1; // use 1 or 0 as appropriate
}
// now with your table select
$form['table']['#default_value'] = $default_value;
// default_value is not provided with each options, rather an array of default values is provided in the tableselect main array.
Hope this solves your problem.

php - Alternative to 'if' statement inside array

I've been reading around and cannot find a solution that works for the requirement I have. I need to dynamically add values to the 'add' part of this array depending on conditions. I know that you cannot put any if statements inside the array itself.
The correct syntax (from the documentation) is:
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
[
'inheritedFromId' => 'addon1',
'amount' => '10'
],
[
'inheritedFromId' => 'addon2',
'amount' => '10'
]
]
]
]);
From what I had read on a similar question on SO, I tried the following (where $addon1 and $addon2 would be the conditions set earlier in the code)
$addon1 = true;
$addon2 = true;
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
($addon1 ? array(
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
]) : false),
($addon2 ? array(
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
]) : false)
]
]
]);
But I get back a Warning: XMLWriter::startElement(): Invalid Element Name so I suspect that it does not like the structure and the code fails with a fatal error (interestingly, if I only set the first $addon to true it still comes up with the warning, but does actually work. With two it fails).
Is there another way to do this or did I get the syntax wrong?
I cannot hardcode all the possibilities due to the amount of possible product combinations.
Would appreciate and help. Thank you.
Don't try to do everything at once.
$add = [];
if( $addon1)
$add[] = ['inheritedFromId'=>.......];
if( $addon2)
.....
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => $add
]
]);
you can put if statements in array declarations, it's called ternary operations:
$myArray['key'] = ($foo == 'bar' ? 1 : 2);
this is the basis of how to use.
You're using the array() syntax together with the short array syntax ([]). See the manual. This means that e.g. your first element in add would be an array within an array. Perhaps that's why the XML error is occurring? Better would be:
'add' => [
($addon1 ?
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
] : null),
($addon2 ?
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
] : null)
]
]
Your syntax is fine. you are creating array with this structure
array (size=3)
'paymentMethodToken' => string 'the_token'
(length=9)
'planId' => string 'thePlanId'
(length=9)
'addOns' =>
array (size=1)
'add' =>
array (size=2)
0 =>
array (size=1)
...
1 =>
array (size=1)
...
My quess is that $gateway->subscription()->create() is does not like this structure of your array. Maybe the 'false' as value or the numeric keys. Check what does it expect and try again with new structure of the array.

CakePHP 2.x - Hash::filter - How to set a callback function? // PHP Filter

I want to filter an array over Hash::filter and use a callback function
static Hash::filter(array $data, $callback = array('Hash', 'filter'))
...You can also supply a custom $callback to filter the array elements...
(CakePHP Docs)
My question here is just... How?
Maybe there's a failure in my head with the translations, but i have the JavaScript filter function in mind, where you can filter over an array and give the filterfunction the actual element its iterating over atm. Then if it returns false it gets kicked out of the array.
maybe im just bad with php but.. could anybody help me with it, please? :)
my attempt atm is something like this
$bis_datum = '2017-01-01';
$res = Hash::filter($multidim_assoc_array, function($part_of_multidim_assoc_array){
return !strtotime($assoc_array['von_datum']) > strtotime($bis_datum);
});
i know there's something very wrong here, because it sais
array('Hash', 'filter')
in the docs and theres just an anonymous function here, but i dont get what the "Hash" and "filter" part means :S
$example = array(
'User' => array(
0 => array(
'name' => 'Bob',
'age' => 25
),
1 => array(
'name' => 'John',
'age' => 22
),
2 => array(
'name' => 'Jen',
'age' => 32
)
)
'School' => array(
'name' => 'Brainslaves High',
'adress' => 'Somestreet 42'
)
);
as an easy example.. how can i filter this array to kick out everyone whos age is below 25 ?
Thanks-a-lot!
Hash::filter won't help you for your example, you better work with array_filterdirectly
$res = array('User' => array_filter($example['User'], function($user) {
return $user['age'] > 25;
})) + array('School' => $example['School']);

Transpose an array of arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
Hah, I had no idea how else to phrase that. I'm trying to reformat a set of three arrays generated by form field inputs, into something that better matches my models, so I can save the values to the db.
Not sure if the solution should be some array manipulation or that I should change the "name" attribute in my form fields.
currently I have an array of my input data:
array(
'image_id' =>
array
0 => '454' (length=3),
1 => '455' (length=3),
2 => '456' (length=3)
'title' =>
array
0 => 'title1' (length=6),
1 => 'title2' (length=0),
2 => '' (length=6)
'caption' =>
array
0 => 'caption1' (length=8),
1 => '' (length=8),
2 => 'caption3' (length=8)
);
and would like to change it to something like, so I can iterate over and save each array of values to the corresponding resource in my db.
array(
0 =>
array
'image_id' => '454',
'title' => 'title1',
'caption' => 'caption1'
1 =>
array
'image_id' => '455',
'title' => 'title2',
'caption' => ''
2 =>
array
'image_id' => '456',
'title' => '',
'caption' => 'caption3'
);
This would iterate through the array with 2 foreach loops. They would use each other's key to construct the new array, so it would work in any case:
$data = array(
'image_id' => array(454, 455, 456),
'title' => array('title1', 'title2', ''),
'caption' => array('caption1', '', 'caption3')
);
$result = array();
foreach($data as $key => $value) {
foreach ($value as $k => $v) {
$result[$k][$key] = $v;
}
}
This'll do it:
$array = call_user_func_array('array_map', array_merge(
[function () use ($array) { return array_combine(array_keys($array), func_get_args()); }],
$array
));
Assuming though that this data is originally coming from an HTML form, you can fix the data right there already:
<input name="data[0][image_id]">
<input name="data[0][title]">
<input name="data[0][caption]">
<input name="data[1][image_id]">
<input name="data[1][title]">
<input name="data[1][caption]">
Then it will get to your server in the correct format already.

How to reorder this array?

I have a database table as follows:
This returns all column titles in the pic, but the one's that are most important are slug, and parent (not sure about id_button).
The array gets ordered automatically by id_button ASC, which really irks me. But, anyways, this is not important, as I need to order it completely different, or re-order it after the array is populated.
The array returns this, by order of id_button:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com',
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 4,
'parent' => 'testing'
'position' => 'child_of',
'slug' => 'google.com',
)
);
I need to order it so that if a slug is found within any parent, than the slug that is in the parent needs to be loaded before the one that has it defined within the parent.
Its not important if it is directly before it. For example, you see testing is the first slug that gets returned, and yet the parent for this is the last slug (google.com). So as long as the slug row where the parent is defined gets ordered so that it is BEFORE the row that has the slug value in the parent column, everything is fine.
So in this situation, it can be reordered as any of these 3 ordered arrays below:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR even this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
)
);
All 3 of these ordered arrays will work because the array with the slug that matches the parent is before the array with the matching parent, and since the slug value, sub_test_1 doesn't match any of the parent values this array order is unimportant, so that array can be located anywhere within the array.
How can I do this? I'm thinking of just looping through the array somehow and trying to determine if the slug is in any of the parents, and just do a reordering somehow...
In short, the slug needs to be ordered before the parent ONLY if there is a parent that matches a slug within the array. Otherwise, if no match is found, the order isn't important.
As Niko suggested, databases support powerful sorting functionality, so you normally can best solve this by telling the database in which order to return the data. If the data is queried with SQL, that's the ORDER BY clause. This is specified in the documentation of your database, assuming you're using MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
If you can not influence the order on the database level, you're in the need to sort the array in PHP. You actually have an array of arrays, in which the outer array is just a list having the id (primary key) of each row and the other fields as a fieldname -> value array as a value (inner array).
Your sort is *user-defined` - you specify the sort order. A common way is to have a sort function that compares two entries which each other. That sort function needs to decide which of those two is of a higher sort-order than the other (or both have the same weight). In you case one item is higher than the other if one is the child of the other.
That's the general principle. You define the sort function that decides (the so called callback function), and PHP takes care to feed it with the array data to sort with the usortDocs function.
A sub-problem you need to solve then is to decide whether or not a child exists in the whole array (an item with a slug having the same value as parent). As this all looks like it can be a bit more complex, it's wise to encapsulate this all into a class of it's own.
Example / Demo:
class menuButtons
{
/**
* #var array
*/
private $buttons;
public function __construct(array $buttons)
{
$this->buttons = $buttons;
}
public function sortChildsFirst()
{
$buttons = $this->buttons;
usort($buttons, array($this, 'sortCallback'));
return $buttons;
}
private function sortCallback($a, $b)
{
// an element is more than any other if it's parent
// value is any other slugs value
if ($this->slugExists($a['parent']))
return 1;
return -1;
}
private function slugExists($slug)
{
foreach($this->buttons as $button)
{
if ($button['slug'] === $slug)
return true;
}
return false;
}
}
$buttons = new menuButtons($new_menu_buttons);
$order = $buttons->sortChildsFirst();
Note: This code is exploiting the fact that your sort order is only roughly specified. You only wrote that you need to have children before parents, so if you take all children first, this will always be the case. It's not that each parent will directly follow the child.
Nevertheless, this skeleton class can work as a base to further improve the search functionality as it's fully encapsulated. You can even change the whole sort method, e.g. to completely write one of your own even w/o usort, like outlined below. The main code does not need to change as it's only making use of the sortChildsFirst method.
You can sort an array once populated using the usort() function.
http://php.net/manual/en/function.usort.php
Since your structure is tree-alike, the first thing that comes to mind is to build a tree out of it. It goes like this:
$tree = array();
foreach($array as $e) {
$p = $e['parent'];
$s = $e['slug'];
if(!isset($tree[$p]))
$tree[$p] = new stdclass;
if(!isset($tree[$s]))
$tree[$s] = new stdclass;
$tree[$s]->data = $e;
$tree[$p]->sub[] = $tree[$s];
}
This creates a set of objects, with the members data and sub = list of child objects.
Now we iterate the tree and for each "root" node, add it and its children to the sorted array:
$out = array();
foreach($tree as $node)
if(!isset($tree[$node->data['parent']]))
add($out, $node);
where add() is
function add(&$out, $node) {
if(isset($node->data))
$out[] = $node->data;
if(isset($node->sub))
foreach($node->sub as $n)
add($out, $n);
}
hope this helps.
Ok, first let me thank you all for your detailed explanations. They are very intuitive. However, I found another way, can you guys let me know if you spot anything wrong with this method here please?
Click here to see a Demo of this working!
$temp_buttons = array();
foreach($new_menu_buttons as $buttons)
$temp_buttons[$buttons['parent']] = $buttons['slug'];
dp_sortArray($new_menu_buttons, $temp_buttons, 'slug');
// The $new_menu_buttons array is now sorted correctly! Let's check it...
var_dump($new_menu_buttons);
function dp_sortArray(&$new_menu_buttons, $sortArray, $sort)
{
$new_array = array();
$temp = array();
foreach ($new_menu_buttons as $key => $menuitem)
{
if (isset($sortArray[$menuitem[$sort]]))
{
$new_array[] = $menuitem;
$temp[$menuitem['parent']] = $menuitem['slug'];
unset($new_menu_buttons[$key]);
}
}
$ordered = array();
if (!empty($new_array))
{
foreach ($new_array as $key => $menuitem)
{
if (isset($temp[$menuitem[$sort]]))
{
$ordered[] = $menuitem;
unset($new_array[$key]);
}
}
}
else
{
$new_menu_buttons = $new_menu_buttons;
return;
}
$new_menu_buttons = array_merge($ordered, $new_array, $new_menu_buttons);
}
Seems to work in all instances that I tested, but ofcourse, their could be a flaw in it somewhere. What do you all think of this?

Categories