0
votes

I am trying to create a custom datatype in cakephp 3 for multi select dropdown. I have a multiple => true control in my form:

- PHP
- HTML
- CSS

When I submit this form, I get the value for that control as an array (0 => PHP, 1 => HTML), that is fine, Now I want to save these value in string format like this PHP,HTML and retrieve back as an array again.

Saving of this input is going well but data is retrieved in the form of string only. For this I have followed this answer and created a custom datatype:

class MultiSelectType extends Type
{
    public function toPHP($value, Driver $driver)
    {
        if (!$value) {
            return null;
        }
        return explode(',', $value);
    }

    public function marshal($value)
    {
        return explode(',', $value);
    }

    public function toDatabase($value, Driver $driver)
    {
        return implode(',', $value);
    }

    public function toStatement($value, Driver $driver)
    {
        if ($value === null) {
            return PDO::PARAM_NULL;
        }
        return PDO::PARAM_STR;
    }
}

How do I modify this code

  1. to get array back so that my form will automatically select values from mutiple select box.

  2. to get string back whenever I want to show that value as a string.

1
First of all... why? Why not use use proper 1:n, or probably better n:m related associations?ndm
@ndm That data doesn't have much significance than just showing it as a string in the view mode, that is why I didn't normalize itSagar Guhe
But for the sake of cleaner code I was trying to do this...Sagar Guhe
@ndm Why did you delete last comment, that actually solved my first problem...Sagar Guhe
Because I think I misunderstood your question a little bit, I thought the type wasn't working at all, but now I think that the problem is that you expect the type object to do something that it cannot do (interacting with the view layer).ndm

1 Answers

1
votes

As mentioned in the comments, you'd better normalize your schema properly and use a belongsToMany association. The fact that the data is (currently) only "decoration" is not a good reason for ditching normalization.

That being said, the type looks OK-ish. If there is a problem only with retrieving the data, then I can only guess that the type is actually not being applied, which probably is a problem with the table object that retrieves the data.

However you cannot use type objects to make decisions at the view layer, the type objects have already done their work by that time. If you need the data in your views to be sometimes an array, and sometimes a string, then you better always retrieve it in array format, and use a helper to convert it to a string list, or maybe even use a virtual property on the respective entity class (but remember that entities shouldn't really be responsible for presentation).

See also