CakePHP link on Paginator ellipsis - php

I want to put a link on an ellipsis in the Paginator. When the pagination has 2 ellipsis's the ellipsis must have different link.
My code is:
echo $this->paginator->numbers(array(
'tag' => 'li',
'separator' => '',
'currentTag' => 'a',
'currentClass' => 'active',
'modulus' => 2,
'first' => 1,
'last' => 1,
'ellipsis' => "<li><a href='#' class='hellip'>...</a></li>"
));
So the result I want to create is:
1 ...(link) 6 7 8 ...(link) 12

In short, the Paginator doesn't support what you want it to do and so your only option is to modify the CakePHP source code. Specifically PaginatorHelper.php
First thing you'll need to do is modify the $defaults variable on line 720, and add leftEllipsis and rightEllipsis fields. This means that we can maintain consistent behavior when we don't set these fields in the $options variable.
$defaults = array('tag' => 'span', 'before' => null, 'after' => null,
'model' => $this->defaultModel(), 'class' => null,'modulus' => '8',
'separator' => ' | ', 'first' => null, 'last' => null, 'ellipsis' => '...',
'currentClass' => 'current', 'currentTag' => null, 'leftEllipsis' => null,
'rightEllipsis' => null);
Probably should unset our two new fields too (lines 735 - 738):
unset($options['tag'], $options['before'], $options['after'], $options['model'],
$options['modulus'], $options['separator'], $options['first'], $options['last'],
$options['ellipsis'], $options['class'], $options['currentClass'], $options['currentTag'],
$options['leftEllipsis'], $options['rightEllipsis']
);
The next bit is a tad tricky because it would be nice to be able to specify one of the ellipsis without the other, and in the absence of either, fallback onto whatever the original ellipsis field was set to. But the developers have used the magical extract and compact functions coupled with the first(...) and last(...) functions depending on certain fields being set in the $options parameter.
After line 756 insert the following code to default the $leftEllipsis to whatever $ellipsis is set to:
if(isempty($leftEllipsis)) {
$leftEllipsis = $ellipsis;
}
Next we need to modify what gets passed as the $options parameter to the first(...) function on lines 758 - 761.
if ($offset < $start - 1) {
$out .= $this->first($offset, compact('tag', 'separator', 'class') + array('ellipsis' => $leftEllipsis));
} else {
$out .= $this->first($offset, compact('tag', 'separator', 'class') + array('after' => $separator, 'ellipsis' => $leftEllipsis));
}
You can use this pattern to attack the right ellipsis too.
The proper way to do this is to fork the project on GitHub, make the changes to your version of the code base and create a pull request so you give the developers a chance to integrate your feature into the mainline. This way everyone can benefit from your work!
Good luck!

Related

is the clarity of using a 2d array worth the extra computational time required to search?

I'm pulling data from a csv and uploading it to a db, for some columns, only certain values should be inputted (or it'll break going through the rest of the system)
however users don't to write out the full input so will use "y" instead of "yes"
I wrote a function that takes an array of the possible inputs and what the correct output should be.
however, currently the array and function looks like this:
$this->acceptedInputMap = array (
'yes' => 'yes',
'y' => 'yes',
'true' => 'yes',
'no' => 'no',
'n' => 'no',
'false' => 'no',
'unknown' => 'unknown',
'unk' => 'unknown',
'' => 'unknown'
);
//these are in the parents class------------------------------------
protected function useAcceptedinput()
{
foreach ($this->columnData as $key => $element) {
if ($this->isExpectedInput($element)) {
$this->useMappedInput($key, $element);
} else {
$this->useColumnDefault($key);
}
}
}
protected function isExpectedInput($element)
{
return array_key_exists(strtolower($element), $this->acceptedInputMap);
}
protected function useColumnDefault($key)
{
$this->columnData[$key] = $this->defaultValue;
}
protected function useMappedInput($key, $element)
{
$this->columnData[$key] = $this->acceptedInputMap[strtolower($element)];
}
I wanted to change this to use a different structure:
$this->acceptedInputMap = array (
'yes' => array(
'yes',
'y',
'true'
),
'no' => array(
'no',
'n',
'false'
),
'unknown' => array(
'unknown',
'unk',
''
),
);
This is a lot clearer for future developers and would make it a lot easier to add more accepted inputs.
This also allows me to have the parent store some common acceted inputs, such as "yes", that can be pulled down for each column that requires it.
However, this is a 2d array, and attempting to find the value in the second dimension to map to the correct input is more computationally intensive.
Is the change worth it?
Also, in general, where do you draw the line on making it easier for the next dev, vs making it faster?
You could organize the original array to make it more readable without sacrificing performance by adding comments or blank lines:
$this->acceptedInputMap = array (
// yes --------
'yes' => 'yes',
'y' => 'yes',
'true' => 'yes',
// no ----------
'no' => 'no',
'n' => 'no',
'false' => 'no',
// unknown -----
'unknown' => 'unknown',
'unk' => 'unknown',
'' => 'unknown'
);

How to setup a conditional key=>value pair within php?

This is what I have:
'options' => array(
'active' => (count($panels)>=2) ? false : NULL,
'collapsible' => true,
'icons' => null,
'header' => "dt"
),
I assumed that the null on the value will be enough. However, the effect we wish will only occur, if and only if, all key=>value pair don't appear on the array.
How can I make this key=>value pair to appear:
'active' => false;
If count($panels)>=2 and to not appear at all, if that's not the case?
Is there an clear, easy and understandable way to achieve this, or should I play with array merges and stuff like that?
Please advice
I'd write it as follows:
$options = array(
'collapsible' => true,
'icons' => null,
'header' => "dt"
);
if (count($panels) >= 2) {
$options['active'] = false;
}
You'll obviously need to adapt this because your options array is contained within another.
well... something like this!
$array = array(
'options' => array(
'collapsible' => true,
'icons' => null,
'header' => "dt"
)
);
if (count($panels) >=2)
$array['options']['active'] = false;
and i know you will read this and go 'yes i couldve figured that out' but there is no other way that i know of.
Setting a value to null still creates a key. If you don't want the key, then only set the value in the cases you want:
$array['options'] = array(
...
);
if (count($panels) >= 2) {
$array['options']['active'] = false;
}
Reference:
'options' => array(
//... other key/val pairs
) + (count($panels)>=2 ? array('active' => false) : array()),

Dynamically apply a key/value pair to an array in one go (within first definition)

Imagine this situation:
$component = array(
'type' => 'chimney',
'material' => 'stone'
);
What i would like to do is to add a key/value pair to this array, if a certain condition is met.
$hasMetrics = true;
$component = array(
'type' => 'chimney',
'material' => 'stone',
'metrics' => ($hasMetrics ? array('width' => 60, 'height' => 2000) : false)
);
While this could be used, it will always cause a key called 'metrics' in my array.
Of course, if i don't want that, i could use array_merge() to merge a second array with the first (the second being either an empty array or the desired key/value pair, depending on the condition).
But what i am longing to find out is if there is any way to define this array like above, while taking care of $hasMetrics, without the use of any other means (such as array_merge()) but purely in the actual (first and only) definition of this array.
Like this: (non-applicable, demonstrative example)
$component = array(
'type' => 'chimney',
'material' => 'stone',
($hasMetrics ? array('metrics' => array(
'width' => 60,
'height' => 2000
)) : false)
);
(This, as i understand it, would generate two keys (type and material and then create one keyless value that is, itself, an array containing a key (metrics) and another array as value.)
Can anyone show me some proper approach? Perhaps there is some kind of PHP function available, with special properties (such as list() which is capable of cross-assignment).
EDIT
Perhaps some more clarification is needed, as many answers point out ways to go such as:
Using a followup assignment to a certain key
Filtering the generated array after defining it
While these are perfectly valid ways to extend the array, but i am explicitly looking for a way to do this in one go within the one array definition.
Not with the array defenition itself. I would add it to the array if necessary:
if($hasMetrics) {
$component['metrics'] = array('width' => 60, 'height' => 2000);
}
$hasMetrics = true;
$component = array(
'type' => 'chimney',
'material' => 'stone',
);
if($hasMetrics){
$component['metrics'] = array('width' => 60, 'height' => 2000);
}
Try
$component = array(
'type' => 'chimney',
'material' => 'stone',
'metrics' => $hasMetrics ? array('width' => 60, 'height' => 2000) : ''
);
And after that
$component = array_filter( $component ); // remove if it has '' value
OR
$component = array(
'type' => 'chimney',
'material' => 'stone',
);
if($hasMetrics) {
$component['metrics'] = array('width' => 60, 'height' => 2000);
}

search php assoc array (hash map) as mysql

example
public $inputs=array(
array( 'sysname'=>'pt_name','dbname' => 'users.name','label' => 'user (name/ID)','value' => '',
'type' => 'text','rules' => 'required','attr'=>'class="autocomplete"'),
array( 'sysname'=>'pt_dob','dbname' => 'users.dob','label' => 'Patient Dob','value' => '',
'type' => 'text','rules' => 'required','attr'=>'class="dob ac" Disabled'),
array( 'sysname'=>'pt_gender','dbname' => 'users.gender','label' => 'gender','value' => 'male,female',
'type' => 'dropdown','rules' => 'required','attr'=>'class="ac" Disabled'),
array( 'sysname'=>'visit_date','dbname' => 'visits.date','label' => 'Date','value' => '',
'type' => 'text','rules' => 'required','attr'=>'class="datepicker"'),
array( 'sysname'=>'visit_time','dbname' => 'visits.time_booked','label' => 'Time','value' => '',
'type' => 'text','rules' => 'required','attr'=>'class="timepicker"'),
array( 'sysname'=>'visit_type','dbname' => 'visits.type','label' => 'Visit type','value' => 'visit,schedule',
'type' => 'dropdown','rules' => 'required','attr'=>'')
);
how can i search this array for only arrays that have pt_ in its sysname for example ?
the idea is i have many types of rows all in same table, so instead of running a mysql query to fetch each type separatly example:
$pt=db->query("select * from table where sysname like 'pt_%'")->result();
$visit=db->query("select * from table where sysname like 'visit_%'")->result();
i want to fetch all at one and split them in php to decrease db load.
so how can i do this ? and is it worth it or better of keep my querys separate.
array_filter and a PHP-style closure* would be a pretty simple solution to this:
function buildFilter($key, $needle) {
return function($array) use($key, $needle) {
return (strpos($array[$key], $needle) !== FALSE);
};
}
$matches = array_filter($inputs, buildFilter('sysname', 'pt_'));
var_dump($matches);
NB: What PHP calls a "closure" is quite a bit different from what most other languages use for the same term, so please make sure to read the PHP documentation.
Doing a couple of queries is fine, your DB can handle that easily. If you're doing dozens of queries for dozens of types (each with only a few rows), it might be worth investigation moving that logic to PHP.
What I would recommend is to put the systype in a separate column with an index on it. That will speed of your query a lot and take load of your DB. Even better is you can make that column an ENUM.
public $inputs=array(
array( 'systype'=>'pt', 'sysname'=>'pt_name','dbname' => 'users.name','label' => 'user (name/ID)','value' => '',
'type' => 'text','rules' => 'required','attr'=>'class="autocomplete"'),
...
$pt=db->query("select * from table where systype = 'pt'")->result();
$visit=db->query("select * from table where systype = 'visit'")->result();

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