简体   繁体   English

Cakephp 3:自定义数据类型无法正常工作

[英]Cakephp 3: Custom Datatype not working properly

I am trying to create a custom datatype in cakephp 3 for multi select dropdown. 我试图在cakephp 3中为多选下拉列表创建一个自定义数据类型。 I have a multiple => true control in my form: 我的表单中有multiple => true控件:

- 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. 提交此表单时,我以数组的形式获取该控件的值( 0 => PHP, 1 => HTML ),现在,我想将这些值保存为类似PHP,HTML字符串格式PHP,HTML然后取回再次作为数组。

Saving of this input is going well but data is retrieved in the form of string only. 该输入的保存进行得很好,但是仅以string形式检索数据。 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. 返回array以便我的表单从多个选择框中自动选择值。

  2. to get string back whenever I want to show that value as a string. 得到string回来,每当我要表明的价值为字符串。

As mentioned in the comments, you'd better normalize your schema properly and use a belongsToMany association. 如评论中所述,您最好正确地规范自己的架构,并使用一个belongsToMany关联。 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 也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM