Is it possible to customise drupal node reference

2019-04-14 05:06发布

问题:

I'm trying to create a bespoke form in drupal, with a node reference field.

I'd like to add a little extra functionality to the node reference auto complete. I've created a view, that contains an argument. I'd like to be able to pass that argument from a drop down as well as the typed text into the autocomplete script.

Does anyone know how I'd start this off.

/* FIELD 1 - the drop down  */
    $sql = "SELECT nid, title  FROM node where type='resourcetype' AND status =1 order by title
    ";
       $result = db_query($sql);
     $counter = 0 ;
     $options = array();
      while ($data = db_fetch_array($result)) {
       // krumo ($data);
      $options[$data[nid] ] =     $data[title]   ;
      if ($counter ==0 ) {$df = $data[nid]; }
      $counter ++;


      }


/* FIELD 2 - the node reference field  */    
         $form['sor']['type'] = array(
        '#type' => 'select',
        '#title' => t('Resource type'),
      '#required' =>TRUE,
      '#options' => $options,
      )     ;


      $form['sor']['field_asor_sors'] = array(
        '#type' => 'textfield',
        '#title' => t('Add a SOR item to this job'),
      '#autocomplete_path' => 'nodereference/autocomplete/field_asor_sors',
           '#element_validate' => array('myelement_validate_is_valid_noderef'),
      '#required' =>TRUE,

      );

Many Thanks

Matt

回答1:

AFAIK there is no easy way to do this.

I wanted to do something similar a while ago (using different arguments based on node context), but refrained from doing it, since it would've needed some significant changes of the autocomplete callback logic. You'd need to change several nodereference functions to add support for passing an argument to the initial callback nodereference_autocomplete(), passing it on from there to _nodereference_potential_references(), and finally to _nodereference_potential_references_views(), while ensuring that the changes don't break anything else.

If you want to try nonetheless, you should take a look at the patches in this thread, as they also want to do something like that and might contain some useful hints/examples.

A potentially easier alternative might be to exchange the #autocomplete_path callback of the nodereference field with your own custom version that would generate the result, while adding js logic to your dropdown to add an additional argument to that path when the selection changes.



回答2:

If you go into the nodereference field configuration form, and scroll all the way to the bottom, there's a fieldset (which may be collapsed) that is titled 'Advanced - Nodes that can be referenced (View)'. You can use this to select a view and have that view be the source of the nodereference choices without writing any new code.