0

I have created a view to render all taxonomy terms and displayed it through a service. I have also created an endpoint in the service module to hit the url through firefox add-on RESTer to test the JSON response. Now I want to alter the JSON response to add more key and value programatically. I am sharing all my resources which I have used but nothing changed

This is my view

This is my JSON response so far:

[
        {
            "Name": "<a href=\"/forum/1\">General discussion</a>",
            "tid": "1",
            "description": ""
        },
        {
            "Name": "<a href=\"/forum/2\">Miscellaneous - Hangout forums</a>",
            "tid": "2",
            "description": ""
        },
        {
            "Name": "<a href=\"/forum/3\">Debt Management and Debt Consolidation</a>",
            "tid": "3",
            "description": ""
        },
        {
            "Name": "<a href=\"/forum/6\">Archive</a>",
            "tid": "6",
            "description": ""
        }

But I want my JSON like this:

[
        {
            "Name": "<a href=\"/forum/1\">General discussion</a>",
            "tid": "1",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "<a href=\"/forum/2\">Miscellaneous - Hangout forums</a>",
            "tid": "2",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "<a href=\"/forum/3\">Debt Management and Debt Consolidation</a>",
            "tid": "3",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        },
        {
            "Name": "<a href=\"/forum/6\">Archive</a>",
            "tid": "6",
            "description": "",
            "MY_CUSTOM_KEY": "MY CUSTOM VALUE"
        }
]

I had used hook_views_pre_render to alter the JSON but couldn't get it:

function MY_MODULE_views_pre_render(&$view) {
    if($view->name == 'MY_VIEW_NAME') {
        $results = &$view->result;
        foreach($results as $key=>$value) {
            $value->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
        }
    }
}

2 Answers 2

0

Try

foreach($results as $key => &$value) {
    $value->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
}
1
  • not worked this solution
    – Souvik Das
    Sep 11, 2020 at 11:59
0

This hook solved my question: hook_views_post_render

function MY_MODULE_views_post_render(&$view, &$output, &$cache) {
    if($view->name == 'MY_VIEW_NAME') {
        $results = &$output;
        foreach($results as $result) {
            $result->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.