Wednesday, January 12, 2022

[FIXED] Cakephp Hash combine concatenate two fields

Issue

How can I concatenate two fields inside a select box using cakephp 2.5 and Hash:combine ?

Today I have name:

$banks = Hash::combine($banks, '{n}.Bank.id', '{n}.Bank.name');

I need name and identifier, I tried this:

$banks = Hash::combine($banks, '{n}.Bank.id', '{n}.Bank.name {n}.Bank.identifier');

But it return NULL.

How can I have : name - identifier ?

Also try to concatenate the two fields at the model but could not add an hiffen between name and identifier.


Solution

You can provide array’s for both $keyPath and $valuePath. If you do this, the first value will be used as a format string, for values extracted by the other paths:

$result = Hash::combine(
    $a,
    '{n}.User.id',
    array('%s: %s', '{n}.User.Data.user', '{n}.User.Data.name'),
    '{n}.User.group_id'
);
/* $result now looks like:
    Array
    (
        [1] => Array
            (
                [2] => mariano.iglesias: Mariano Iglesias
            )
        [2] => Array
            (
                [14] => phpnut: Larry E. Masters
            )
    )
*/

$result = Hash::combine(
    $a,
    array('%s: %s', '{n}.User.Data.user', '{n}.User.Data.name'),
    '{n}.User.id'
);
/* $result now looks like:
    Array
    (
        [mariano.iglesias: Mariano Iglesias] => 2
        [phpnut: Larry E. Masters] => 14
    )
*/

See CookBook > Hash for mode details.



Answered By - Rayann Nayran

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.