1

I have a CCK nodereference field, displayed as a dropdown, and populated by a view.

I'd like to change that view depending on user permissions. Can I change the view programmatically before it gets rendered?

I can't do it in hook_form_alter() because CCK isn't available here. So I set up an #after_build, and inspect here. But this seems to late. The #options have already been rendered and there's no view property to change.

  • 1
    what are you trying to change exactly in the view? – Jimajamma Feb 18 '12 at 7:40
  • @Jimajamma The populated options of the nodereference dropdown. I suppose I could manually load a view in #after_build, parse the results, and put those into #options... – ack Feb 18 '12 at 15:05
  • 1
    I understand that, I think. What I mean is what in the view itself do you want to be able to change in order to change what it returns to eventually populate the dropdown? Eg, are you wanting to change a filter, an option, a sort, a what? in the view itself? – Jimajamma Feb 18 '12 at 17:06
  • Oh, a filter (or argument). I want to change what qualifies as a valid entry. – ack Feb 18 '12 at 20:44
1

Thanks for the sugs. I prefer to do everything in code so this was my solution. I just manually loaded the view given some argument, and parsed the results.

function module_form_nodetype_node_form_alter(&$form, &$form_state)
{
    // Manipulate form after build so we have access to CCK
    $form['#after_build'][] = '_form_afterbuild';
}

function _form_afterbuild($form, &$form_state)
{
    // Custom options list for this nodereference
    $arg = user_access('administer nodes') ? false : true; 
    $form['field_fieldname']['nid']['nid']['#options'] = _GetOptions($arg);
}

function _GetOptions($arg=false)
{
    $viewResults = views_get_view_result('view_name', '', $arg);

    $options = array();
    foreach ($viewResults as $row) {
        $optionTitle = $row->title;
        $options[$row->nid] = $optionTitle;
    }

    // Sort options by alpha
    asort($options);

    return $options;
}
| improve this answer | |
0

If you want to change the argument at run time, you can specify the argument in the view, and then in the argument "definition," you can select supply default argument if not present (which it won't be unless you specify it in your CCK definitions) and select PHP code, and there you can program the argument however you want. You can also do the same thing with argument validation.

| improve this answer | |
0

You can utilize Advanced View to filter the display depending on user roles. And use Views UI Permissions to implement that. Essentially, you will create a new view, and use that view as an advanced view option in your the field referencing.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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