Zend Framework2 表单错误数组到 JSON

问题描述 投票:0回答:3

我从 zend 表单接收这个数组

Array
(
    [user] => Array
        (
            [firstName] => Array
                (
                    [isEmpty] => Please enter First Name
                )

            [lastName] => Array
                (
                    [isEmpty] => Please enter Last Name
                )

            [password] => Array
                (
                    [isEmpty] => Please enter Password
                )

            [confirmPassword] => Array
                (
                    [isEmpty] => Please enter Confirm Password
                )

            [email] => Array
                (
                    [isEmpty] => Please enter Email Address
                )

            [gender] => Array
                (
                    [notInArray] => Gender must be Male OR Female
                    [isEmpty] => Please select your gender
                )

            [phone] => Array
                (
                    [isEmpty] => Value is required and can't be empty
                )

            [birthDate] => Array
                (
                    [isEmpty] => Please enter Birth Date
                )

            [country] => Array
                (
                    [id] => Array
                        (
                            [isEmpty] => Please select Country
                        )

                )

            [userGroup] => Array
                (
                    [id] => Array
                        (
                            [isEmpty] => Please select User Group
                        )

                )

        )

)

我希望这个数组转换为以下数组:

Array
(
    [user[firstName]] => [{"Please enter First Name"}]
    [user[lastName]] => [{"Please enter Last Name"}]

    ...........

    [user[gender]] => [{"Gender must be Male OR Female","Please select your gender"}]

    ..............
    [user[country][id]] => [{"Please select Country"}]
)

我尝试了以下代码,但它不起作用

$errors = $form->getMessages();
$newErrors = array();
foreach ($errors as $key => $value) {
    $elementName = $key;
    if(is_array($value)) {
        foreach ($value as $k => $v) {
            $elementName .= $k;
            if(!is_array($v)) {
                $message = $v;
                $newErrors[$elementName] = json_encode($v);
            } else {
                foreach ($v as $ke => $va) {
                    $elementName .= $ke;
                    if(!is_array($va)) {
                        $newErrors[$elementName] = json_encode($va);
                    }
                }
            }
        }
    }
}

但是没有成功。

php arrays multidimensional-array zend-framework2
3个回答
0
投票

直接回答你的问题。

虽然我相信它应该有效,但尚未经过测试。

public function formatElementErrors(FieldsetInterface $collection, array $data, $parent = null)
{
    $results = [];

    foreach($data as $name => $errors) {

        if (! $collection->has($name) || ! is_array($errors)) {
            continue;
        }

        $element = $collection->get($name);

        $name = isset($parent) ? sprintf('%s[%s]', $parent, $name) : $name;

        if ($element instanceof FieldsetInterface) {

            $results = array_merge(
                $results,
                $this->formatElementErrors($element, $errors, $name)
            );

        } else {
            if (! isset($results[$name])) $results[$name] = [];

            foreach($errors as $message) {
                $results[$name][] = $message;
            }
        }
    }
    return $results;
}

$errors = $this->formatElementErrors($form, $errors);

0
投票

虽然这是可能的,但我选择返回预渲染的整个表单 HTML(包括错误样式等),而不是检索包含表单错误的 JSON 数组。

我可以看到您尝试重新设置结果数组的键是因为表单元素在嵌套时被赋予了新名称;这意味着您需要一些混乱的 JS 代码来在 DOM 中搜索这些元素并添加相关样式。

在我的解决方案中,我们使用标准视图渲染(即普通的 ZF2 视图助手)来应用错误。

例如

// We are creating something
public function createAction()
{
    $serviceManager = $this->getServiceLocator();
    $formElementManager = $serviceManager->get('FormElementManager');

    $form = $this->formElementManager->get('MyModule\Form\SomeCreateForm');

    $request = $this->getRequest();

    $view = new ViewModel(compact('form'));

    if ($request->isPost()) {

        $form->setData($request->getPost());

        if ($form->isValid()) {

            // handle form success

        } else if ($request->isXmlHttpRequest()) {

            // The form data was posted via ajax and is invalid

            // Set the view template to a view that just renders the form
            //
            // For example, the script would include:
            //
            // <?php echo $this->form($form);
            //
            $view->setTempalte('my/view-template/form');

            // Now render the view, using the view renderer
            $content = $serviceManager->get('ViewRenderer')->renderer($view);

            return new JsonModel([
                'success' => false, // flag for us to know we have an error in JS
                'content' => $content // The HTML content of the form, including the errors
            ]);
        }
    }

    $view->setTempalte('my/view-template/create');

    return $view;
}

要对此进行扩展,您还可以创建一个控制器插件“JsonModel”来封装它。如果您传入

Zend\View\Model\ViewModel
作为“内容”键,插件将处理它的渲染

控制器代码将变得更干净

return $this->jsonModel([
    'content' => $view
]);

0
投票

以下代码将数组转换为所需的格式。但首先你想要的输出是 json 和 php 数组的混合,这是不应该做的。相反,转换为 php 数组,然后进行 json 编码。

$data = array(); 
foreach($arr['user'] as $key => $item)
{
    foreach($item as $key1 => $item1)
    {
        if(is_array($item1))
        {
            list($key2, $item2) = each($item1);
            $data['user'][$key][$key1] = $item2;
        }
        else
        {
            $data['user'][$key] = $item1;
        }                   
    }               
}
print_r($data);
echo json_encode($data);

数组输出为

Array
(
    [user] => Array
        (
            [firstName] => Please enter First Name
            [lastName] => Please enter Last Name
            [password] => Please enter Password
            [confirmPassword] => Please enter Confirm Password
            [email] => Please enter Email Address
            [gender] => Please select your gender
            [phone] => Value is required and can't be empty
            [birthDate] => Please enter Birth Date
            [country] => Array
                (
                    [id] => Please select Country
                )

            [userGroup] => Array
                (
                    [id] => Please select User Group
                )

        )

)

应用 json_encodereturn 后的 json 字符串。

{
  "user": {
    "firstName": "Please enter First Name",
    "lastName": "Please enter Last Name",
    "password": "Please enter Password",
    "confirmPassword": "Please enter Confirm Password",
    "email": "Please enter Email Address",
    "gender": "Please select your gender",
    "phone": "Value is required and can't be empty",
    "birthDate": "Please enter Birth Date",
    "country": {
      "id": "Please select Country"
    },
    "userGroup": {
      "id": "Please select User Group"
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.