Today I was using one of CakePHP’s helper methods, $text->truncate
. It gave me these errors and I can’t say I was pleased about it. It reminded me that sometimes, functions aren’t a piece of cake.
Warning (2): array_merge() [function.array-merge]: Argument #2 is not an array [CORE/cake/libs/view/helpers/text.php, line 184]
Warning (2): extract() [function.extract]: First argument should be an array [CORE/cake/libs/view/helpers/text.php, line 185]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 187]
I also used it in the same view a little later. It gave errors down there as well.
Notice (8): Undefined variable: ending [CORE/cake/libs/view/helpers/text.php, line 238]
Notice (8): Undefined variable: exact [CORE/cake/libs/view/helpers/text.php, line 241]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 244]
Notice (8): Undefined variable: ending [CORE/cake/libs/view/helpers/text.php, line 258]
Notice (8): Undefined variable: html [CORE/cake/libs/view/helpers/text.php, line 260]
I wasn’t sure what was going on, so I went into the CakePHP source code to check it out. Traveling to cake/libs/view/helpers/text.php
, I found the truncate
method. Check out the code for it.
function truncate($text, $length = 100, $options = array()) { $default = array( 'ending' => '...', 'exact' => true, 'html' => false ); $options = array_merge($default, $options); extract($options); // continues }
This code is expecting only two real arguments. The third is a magic options array. Apparently nobody has thought about updateing the CakePHP book. Of if they have made updates, forget to tell people by putting a huge notice somewhere. The documentation explains the new arguments quite well, actually.
To fix those errors, I simply didn’t use any extra arguments, as I was satisfied by the defaults. But I could easily specify some other options.
__( $text->truncate($problem["Task"]["description"], 75) ); // other options __( $text->truncate($problem["Task"]["description"], 75, array("ending" => ". . .", "exact" => false, "considerHtml" => true)) );
My favorite feature about this is the exact
option. It doesn’t chop up words, which is great.
Thanks for this. Been wondering why truncate doesn’t work even though i copy-pasted the ones found on the tutorial.
Cheers! Problem solved for me too.
Thanks – that’s what I was looking for. I’ve submitted a (pending) change to the CakePHP Book.
Thanks! +1