Coding standards
Security in ResourceSpace
Developer reference
Database
Action functions
Admin functions
Ajax functions
Annotation functions
API functions
Collections functions
Comment functions
Config functions
CSV export functions
Dash functions
Debug functions
Encryption functions
Facial recognition functions
File functions
General functions
Language functions
Log functions
Login functions
Message functions
Migration functions
Node functions
PDF functions
Plugin functions
Render functions
Reporting functions
Request functions
Research functions
Slideshow functions
Theme permission functions
User functions
Video functions
Database functions
Metadata functions
Resource functions
Search functions
Map functions
Job functions
Tab functions
Test functions

render_search_field()

Description

Renders the HTML for the provided $field for inclusion in a search form, for example the
advanced search page. Standard field titles are translated using $lang. Custom field titles are i18n translated.

$field the field being rendered as an associative array of field data, i.e. one row from the resource_type_field table.
$fields the array of fields data, i.e. multiple rows from the resource_type_field table.
$name the input name to use in the form (post name)
$value the default value to set for this field, if any
$reset is non-blank if the caller requires the field to be reset

Parameters

ColumnTypeDefaultDescription
$field
$fields
$value ""
$autoupdate false
$class "stdwidth"
$forsearchbar false
$limit_keywords array
$searched_nodes array array Array of all the searched nodes previously
$reset ""
$simpleSearchFieldsAreHidden false

Location

include/render_functions.php lines 20 to 919

Definition

 
function render_search_field($field,$fields,$value="",$autoupdate=false,$class="stdwidth",$forsearchbar=false,$limit_keywords=array(), 
                             
$searched_nodes = array(), $reset="",$simpleSearchFieldsAreHidden=false)
    {
    
node_field_options_override($field);

    global 
$auto_order_checkbox$auto_order_checkbox_case_insensitive$lang$category_tree_open$minyear$daterange_search$searchbyday
        
$is_search$values$n$simple_search_show_dynamic_as_dropdown$clear_function$simple_search_display_condition$autocomplete_search
        
$baseurl$fields$baseurl_short$extrafooterhtml,$FIXED_LIST_FIELD_TYPES$maxyear_extends_current;

    
# Certain edit_fields/x.php functions check for bulk edit which must be defined as false prior to rendering the search field  
    
$multiple=false;
?>
<!-- RENDERING FIELD= echo $field['ref'] . " " escape($field['name']);?> -->


    
// set this to zero since this does not apply to collections
    
if (!isset($field['field_constraint'])){$field['field_constraint']=0;}

    
$name="field_" . ($forsearchbar escape($field["name"]) : $field["ref"]);
    
$id="field_" $field["ref"];

    
# An array of conditions spanning all governed fields and all governing fields
    
$scriptconditions=array();

    
# Assume the field being rendered should be displayed
    
$displaycondition=true;

    
# If the field being rendered has a display condition
    #  For advanced search, always check the display condition
    #  For simple search, only check the display condition if the field is included in the simple_search_display_condition config array 
    
if ( $field["display_condition"]!="" 
    
&& ( !$forsearchbar || ($forsearchbar && !empty($simple_search_display_condition) && in_array($field['ref'],$simple_search_display_condition)) ) )
        {
        
# Split the display condition of the field being rendered into an array of tests (if there are more than one, they are separated by a ";")
        # Each test is in the form governing field = governing field value 
        #   If the field being rendered is itself a governing field then "On Change" code must be generated for the governing field
        #   If the field being rendered is a governed field then "Checking" code must be generated for each governing field
        
$s=explode(";",$field["display_condition"]);
        
$condref=0;
        foreach (
$s as $condition# Check each individual test
            
{
            
# Assume that the current test does not need to be checked
            
$displayconditioncheck=false;
            
$s=explode("=",$condition);

            
# Process each field to see if it is being referenced in the current test
            
if (!is_array($fields))
                {
                return 
false;
                }
            for (
$cf=0;$cf<count($fields);$cf++) # Check each field to see if it is a governing field whose value needs to be checked
                
{
                
# If the field being processed is referenced in the current test, then it is a governing field 
                
if ($s[0]==$fields[$cf]["name"]) 
                    {
                    
# The script conditions array contains an entry for each governing field
                    
$scriptconditions[$condref]["field"]               = $fields[$cf]["ref"];  # governing field
                    
$scriptconditions[$condref]["governedfield"]       = $field["ref"];  # governed field

                    
$scriptconditions[$condref]["name"]                = $fields[$cf]["name"];
                    
$scriptconditions[$condref]['type']                = $fields[$cf]['type'];
                    
$scriptconditions[$condref]['display_as_dropdown'] = $fields[$cf]['display_as_dropdown'];
                    
# Get the node references of the governing field
                    
$scriptconditionnodes get_nodes($fields[$cf]['ref'], null, (FIELD_TYPE_CATEGORY_TREE == $fields[$cf]['type'] ? true false));

                    
$checkvalues=$s[1];
                    
# Prepare an array of values present in the test
                    
$validvalues=explode("|",strtoupper($checkvalues));
                    
$validvalues array_map("i18n_get_translated"$validvalues);
                    
$scriptconditions[$condref]['valid'] = array();
                    
$scriptconditions[$condref]['validtext'] = array();
                    foreach(
$validvalues as $validvalue)
                        {
                        
# The validtext array is for checking input values instead of their corresponding node references
                        
$scriptconditions[$condref]['validtext'][] = strtolower($validvalue);

                        
# Convert the value name into a node entry if it is a valid node within the governing field
                        
$found_validvalue get_node_by_name($scriptconditionnodes$validvalue);

                        
# If there is a node which corresponds to that value name then append its node reference to a list of valid nodes
                        
if(!= count($found_validvalue))
                            {
                            
$scriptconditions[$condref]['valid'][] = (string)$found_validvalue['ref'];

                            
# Is the node present in search result list of nodes
                            
if(in_array($found_validvalue['ref'],$searched_nodes))
                                {
                                
# Value being tested is present in the searched nodes array
                                
$displayconditioncheck true;
                                }
                            }
                        }

                    
# Suppress this field if none of the nodes (of the values) in the test match the searched nodes array
                    
if (!$displayconditioncheck)
                        {
                        
$displaycondition=false# Do not render field
                        
}


                
// Certain fixed list types allow for multiple nodes to be passed at the same time

                // Generate a javascript function specific to the field being rendered
                // This function will be invoked whenever any governing field changes
                
if(in_array($fields[$cf]['type'], $FIXED_LIST_FIELD_TYPES))
                    {
                        if(
FIELD_TYPE_CATEGORY_TREE == $fields[$cf]['type'])
                            {
                            
?>
                            <!-- SETUP HANDLER FOR GOVERNOR= echo $fields[$cf]['ref']; ?> GOVERNED= echo $field['ref']; ?>-->
                            <script type="text/javascript">
                            var wto;
                            jQuery(document).ready(function()
                                {
                                jQuery('#CentralSpace').on('categoryTreeChanged', function(e,node)
                                    {
                                    // Debounce multiple events fired by the category tree
                                    clearTimeout(wto);
                                    wto=setTimeout(function() {
                                        // Reflect the change of the governing field into the following governed field condition checker
                                        console.debug(" echo "DISPCOND CATTREE CHANGEGOVERNOR=".$fields[$cf]['ref']; ?>");
                                        for (i = 0; i<categoryTreeChecksArray.length; i++) {
                                            categoryTreeChecksArray[i]();
                                        }
                                    }, 200);
                                    });
                                });
                            </script>
                            
                            
}
                        elseif(
FIELD_TYPE_DYNAMIC_KEYWORDS_LIST == $fields[$cf]['type'])
                            {
                            if (
$forsearchbar) {
                                if (
$simple_search_show_dynamic_as_dropdown) {
                                    
$checkname       "nodes_searched[{$fields[$cf]['ref']}]";
                                    
$jquery_selector "select[name=\"{$checkname}\"]";
                                }
                                else {
                                    
$jquery_selector "input[name=\"field_{$fields[$cf]["name"]}\"]";
                                }
                            
?>
                            <!-- SETUP HANDLER FOR GOVERNOR= echo $fields[$cf]['ref']; ?> GOVERNED= echo $field['ref']; ?>-->
                            <script type="text/javascript">
                            jQuery(document).ready(function()
                                {
                                jQuery(' echo $jquery_selector?>').change(function ()
                                    {
                                    // Reflect the change of the governing field into the following governed field condition checker
                                    console.debug(" echo "DISPCOND DYNAMKKD CHANGEGOVERNOR=".$fields[$cf]['ref']." CHECK GOVERNED=".$field['ref']; ?>");
                                    checkSearchDisplayCondition echo $field['ref']; ?>();
                                    });
                                });
                            </script>
                            
                            
}
                            else { 
# Advanced search
                            
?>
                            <!-- SETUP HANDLER FOR GOVERNOR= echo $fields[$cf]['ref']; ?> GOVERNED= echo $field['ref']; ?>-->
                            <script type="text/javascript">
                            jQuery(document).ready(function()
                                {
                                jQuery('#CentralSpace').on('dynamicKeywordChanged', function(e,node)
                                    {
                                    // Reflect the change of the governing field into the following governed field condition checker
                                    console.debug(" echo "DISPCOND DYNAMKWD CHANGEGOVERNOR=".$fields[$cf]['ref']." CHECK GOVERNED=".$field['ref']; ?>");
                                    checkSearchDisplayCondition echo $field['ref']; ?>();
                                    });
                                });
                            </script>

                            
}
                            }
                        else
                            {
                            
# Otherwise FIELD_TYPE_CHECK_BOX_LIST or FIELD_TYPE_DROP_DOWN_LIST or FIELD_TYPE_RADIO_BUTTONS

                            # Simple search will always display these types as dropdowns
                            
if ($forsearchbar) {
                                
$checkname       "nodes_searched[{$fields[$cf]['ref']}]";
                                
$jquery_selector "select[name=\"{$checkname}\"]";
                            }
                            
# Advanced search will display these as dropdowns if marked as such, otherwise they are displayed as checkbox lists to allow OR selection
                            
else {
                                
# Prepare selector on the assumption that its an input element (ie. a checkbox list or a radio button or a dropdown displayed as checkbox list)
                                
$checkname "nodes_searched[{$fields[$cf]['ref']}][]";
                                
$jquery_selector "input[name=\"{$checkname}\"]";

                                
# If however its a drop down list then we should be processing select elements
                                
if ($fields[$cf]['display_as_dropdown'] == true)
                                    {
                                    
$checkname       "nodes_searched[{$fields[$cf]['ref']}]";
                                    
$jquery_selector "select[name=\"{$checkname}\"]";
                                    }
                            } 
                            
?>
                            <!-- SETUP HANDLER FOR GOVERNOR= echo $fields[$cf]['ref']; ?> GOVERNED= echo $field['ref']; ?>-->
                            <script type="text/javascript">
                            jQuery(document).ready(function()
                                {
                                jQuery(' echo $jquery_selector?>').change(function ()
                                    {
                                    // Reflect the change of the governing field into the following governed field condition checker
                                    console.debug(" echo "DISPCOND CHANGEGOVERNOR=".$fields[$cf]['ref']." CHECK GOVERNED=".$field['ref']; ?>");
                                    checkSearchDisplayCondition echo $field['ref']; ?>();
                                    });
                                });
                            </script>
                            
                            
}
                        } 
                    else
                        { 
# Not one of the FIXED_LIST_FIELD_TYPES
                        
?>
                        <!-- SETUP HANDLER FOR GOVERNOR= echo $fields[$cf]['ref']; ?> GOVERNED= echo $field['ref']; ?>-->
                        <script type="text/javascript">
                        jQuery(document).ready(function()
                            {
                            jQuery('#field_ echo $fields[$cf]["ref"]; ?>').change(function ()
                                {
                                // Reflect the change of the governing field into the following governed field condition checker
                                checkSearchDisplayCondition echo $field['ref']; ?>();
                                });
                            });
                        </script>

                        
}
                    }
                } 
# see if next field needs to be checked

            
$condref++;
            } 
# check next condition

        
?>
         echo "<!-- CHECK CONDITIONS FOR GOVERNED FIELD ".$field['name']." [".$field['ref']."] -->";
        
$function_has_category_tree_check=false;
        
?>
        <script type="text/javascript">

        checkSearchDisplayCondition echo $field["ref"];?> = function ()   
            {
            // Is the governed field resource type ok; if not then no checking necessary as its already hidden
            const conditionalquestion = document.getElementById("question_ echo $n ?>");
            if (Object.hasOwnProperty(conditionalquestion, 'dataset') 
                && conditionalquestion.dataset.resource_type_ok !="1") { return; }

            // Check the node passed in from the changed governing field
            var idname echo $field['ref']; ?>     = " echo $forsearchbar?"#simplesearch_".$field['ref']:"#question_".$n?>";
            var ixThisField;
            // Get current display state for governed field ("block" or "none")
            field echo $field['ref']; ?>status    = jQuery(idname echo $field['ref']; ?>).css('display');
            newfield echo $field['ref']; ?>status = 'none';

            // Assume visible by default
            field echo $field['ref']; ?>visibility = true;

            
            
foreach($scriptconditions as $scriptcondition)
                {
                echo 
"// Checking values on field ".$scriptcondition['field']."\n";
                
# Example of $scriptconditions: [{"field":"73","type":"3","display_as_dropdown":"0","valid":["267","266"]}] 
                
if ($scriptcondition['type'] == FIELD_TYPE_CATEGORY_TREE) {
                    
$function_has_category_tree_check=true;
                }
            
?>

            field echo $field['ref']; ?>valuefound = false;
            fieldokvalues echo $scriptcondition['field']; ?> =  echo json_encode($scriptcondition['valid']); ?>;

            
            
if (
                
$scriptcondition['type'] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST
                
&& $forsearchbar
                
&& !$simple_search_show_dynamic_as_dropdown
                
) {
                    
?>
                        // When a dynamic keyword list is rendered as regular input field on simple search, the valid values to check against are the text values (not nodes) 
                        fieldokvalues echo $scriptcondition['field']; ?> =  echo json_encode($scriptcondition['validtext']); ?>;
                    
                
}
            
?>

             echo "// CHECK IF GOVERNING ".$scriptcondition['name']." [".$scriptcondition['field']."] VALUE(S) ENABLE DISPLAY";?>

            

            
# Generate the javascript code necessary to condition the rendered field based on value(s) present in the governing field

            # Prepare base name for selector 
            
$checkname "nodes_searched[{$scriptcondition['field']}]";
            
$js_conditional_statement  "fieldokvalues{$scriptcondition['field']}.indexOf(element.value) != -1";

            
# Prepare fallback selector 
            
$jquery_condition_selector "input[name=\"{$checkname}\"]";

            if(
in_array($scriptcondition['type'], $FIXED_LIST_FIELD_TYPES))
                {
                
# Append additional brackets rendered on category tree and dynamic keyword list hidden inputs
                
if (in_array($scriptcondition['type'], array(FIELD_TYPE_CATEGORY_TREEFIELD_TYPE_DYNAMIC_KEYWORDS_LIST)) ) {
                    
$jquery_condition_selector "input[name=\"{$checkname}[]\"]";
                }

                
# Prepare selector for a checkbox list or a radio button or a dropdown list
                
if (in_array($scriptcondition['type'], array(FIELD_TYPE_CHECK_BOX_LISTFIELD_TYPE_RADIO_BUTTONSFIELD_TYPE_DROP_DOWN_LIST))) {

                    
# Simple search will always display these types as dropdowns, so search for selected option
                    
if ($forsearchbar) {
                        
$jquery_condition_selector "select[name=\"{$checkname}\"] option:selected";
                    }
                    
# Advanced search will display these as dropdowns if marked as such, otherwise they are displayed as checkbox lists to allow OR selection
                    
else {
                        
# Prepare selector on the assumption that its an input element (ie. a checkbox list or a radio button or a dropdown displayed as checkbox list)
                        #   so search for checked boxes
                        
$jquery_condition_selector "input[name=\"{$checkname}[]\"]:checked:enabled";

                        
# If however its a drop down list then we should be searching for selected option
                        
if ($scriptcondition['display_as_dropdown'] == true)
                            {
                            
$jquery_condition_selector "select[name=\"{$checkname}\"] option:selected";
                            }
                    }                    

                }

                
# Prepare selector for unusual dynamic keyword list configurations
                
if (
                    
$scriptcondition['type'] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST
                    
&& $forsearchbar
                    
) {
                        if(
$simple_search_show_dynamic_as_dropdown) {
                            
# Prepare selector for a dynamic keyword list configured to display as a dropdown list on simple search
                            
$jquery_condition_selector "select[name=\"{$checkname}\"] option:selected";
                        } else {
                            
# Prepare selector for a dynamic keyword list rendered as regular input field
                            
$jquery_condition_selector "input[name=\"field_{$scriptcondition['name']}\"]";
                        }
                    }

                
?>
                    jQuery(' echo $jquery_condition_selector?>').each(function(index, element)
                    {
                        if( echo $js_conditional_statement?>)
                        {
                        // The governing node is in the list of qualifying node(s) which enable this governed field
                        field echo $field['ref']; ?>valuefound = true;
                        }
                    });

                
                
}?>

                // If no governing node found then disable this governed field
                if(!field echo $field['ref']; ?>valuefound)
                {
                field echo $field['ref']; ?>visibility = false;
                }

            
                
echo "// End of checking values on field ".$scriptcondition['field']."\n\n            ";
                }
            
?>

                // If not yet defined, initialise an array of governed fields to be hidden when resetting simple search
                if(typeof fieldsToHideOnClear == "undefined")
                    {
                    fieldsToHideOnClear = new Array();
                    }

                // If the governed field is enabled then set it to display
                if(field echo $field['ref']; ?>visibility)
                    {
                    newfield echo $field['ref']; ?>status = 'block';
                    // This governed field will be shown, so remove it from array of fields to hide when resetting simple search
                    ixThisField = fieldsToHideOnClear.indexOf(' echo $field["ref"]; ?>');
                    fieldsToHideOnClear.splice(ixThisField,1);
                    }
                else
                    {
                    // This governed field will be hidden, so add it to array of fields to hide when resetting simple search
                    ixThisField = fieldsToHideOnClear.indexOf(' echo $field["ref"]; ?>');
                    if (ixThisField < 0) 
                        { 
                        fieldsToHideOnClear.push(' echo $field["ref"]; ?>'); 
                        }
                    }

                // If the governed field display state has changed then enact the change by sliding
                if ( newfield echo $field['ref']; ?>status != field echo $field['ref']; ?>status )
                    {
                    console.debug("IDNAME " + idname echo $field['ref']; ?>);
                    console.debug("   FIELD  echo $field['ref']; ?> STATUS '" + field echo $field['ref']; ?>status+"'");
                    console.debug("NEWFIELD  echo $field['ref']; ?> STATUS '" + newfield echo $field['ref']; ?>status+"'");
                    // Toggle the display state between "block" and "none", clearing any incomplete actions in the process
                    jQuery(idname echo $field['ref']; ?>).slideToggle(function()
                        {
                        console.debug("SLIDETOGGLE FIELD  echo $field['ref']; ?>");
                        jQuery(idname echo $field['ref']; ?>).clearQueue();
                        });

                    // Adjust the border accordingly
                    if(jQuery(idname echo $field['ref']; ?>).css('display') == 'block')
                        {
                        jQuery(idname echo $field['ref']; ?>).css('border-top', '');
                        }
                    else
                        {
                        jQuery(idname echo $field['ref']; ?>).css('border-top', 'none');
                        }
                    }
        }

         
        
if ($function_has_category_tree_check) {
        
?>
        categoryTreeChecksArray.push(checkSearchDisplayCondition echo $field["ref"];?>);
        
        
}
        
?>

        </script>
        
        
if($forsearchbar)
            {
            
// add the display condition check to the clear function
            
$clear_function.="checkSearchDisplayCondition".$field['ref']."();";
            }

        } 
// Endif rendered field with a display condition

    
$is_search true;

    if (!
$forsearchbar)
        {
        
?>
        <div class="Question ConditionalVisibility" data-resource_type_ok="" data-for_resource_types=" 
        
// Add class for each supported resource type to allow showing/hiding on advanced search
        
if($field["resource_types"] == "Collections")
            {
            echo 
"Collections";
            }
        elseif(
$field["global"] == 1)
            {
            echo 
"Global";
            }
        else
            {
            echo (string)
$field["resource_types"];
            }
        
?>" id="question_ echo $n ?>" data-has_display_condition=" echo !$displaycondition '1' '0'?>" data-question_field_ref=" echo (int) $field['ref']; ?>"
        
if (strlen((string) $field["tooltip_text"])>=1)
            {
            echo 
"title=\"" escape(lang_or_i18n_get_translated($field["tooltip_text"], "fieldtooltip-")) . "\"";
            }
        
?>>
        <label> echo escape(lang_or_i18n_get_translated($field["title"], "fieldtitle-")) ?></label>
        
        
}
    else
        {
        
hook("modifysearchfieldtitle");
        
?>
        <div class="SearchItem" id="simplesearch_ echo $field["ref"]; ?> if (!$displaycondition || $simpleSearchFieldsAreHidden) {?>style="display:none;" } if (strlen($field["tooltip_text"] ?? "" ) >= 1){ echo "title=\"" escape(lang_or_i18n_get_translated($field["tooltip_text"], "fieldtooltip-")) . "\"";} ?> ><label for="simplesearch_ echo $field["ref"]; ?>"> echo escape(lang_or_i18n_get_translated($field["title"], "fieldtitle-")) ?></label><br/>

        
        
#hook to modify field type in special case. Returning zero (to get a standard text box) doesn't work, so return 1 for type 0, 2 for type 1, etc.
        
if(hook("modifyfieldtype")){$fields[$n]["type"]=hook("modifyfieldtype")-1;}
        }

    
# Generate markup for field
    
switch ($field["type"]) {
        case 
FIELD_TYPE_TEXT_BOX_SINGLE_LINE:
        case 
FIELD_TYPE_TEXT_BOX_MULTI_LINE:
        case 
FIELD_TYPE_TEXT_BOX_LARGE_MULTI_LINE:
        case 
FIELD_TYPE_TEXT_BOX_FORMATTED_AND_CKEDITOR:
        case 
$forsearchbar && $field["type"]==FIELD_TYPE_DYNAMIC_KEYWORDS_LIST && !$simple_search_show_dynamic_as_dropdown:
        case 
FIELD_TYPE_WARNING_MESSAGE:
        
# Dynamic keyword list behaviour replaced with regular input field under these circumstances
        
if ((int)$field['field_constraint']==0)
            {
            
?><input class=" echo escape($class?>" type=text name=" echo escape($name?>" id=" echo escape($id?>" value=" echo escape((string)$value)?> if ($autoupdate) { ?>onChange="UpdateResultCount();" } if(!$forsearchbar){ ?> onKeyPress="if (!(updating)) {setTimeout('UpdateResultCount()',2000);updating=true;}" } if($forsearchbar){?>onKeyUp="if('' != jQuery(this).val()){FilterBasicSearchOptions(' echo escape((string)$field["name"]) ?>',[ echo escape((string)$field["resource_types"]) ?>]);}" ?>> 
            
# Add to the clear function so clicking 'clear' clears this box.
            
$clear_function.="document.getElementById('field_" . ($forsearchbar$field["ref"] : escape((string)$field["name"])) . "').value='';";
            }
        
// number view - manipulate the form value (don't send these but send a compiled numrange value instead
        
elseif ((int)$field['field_constraint']==1)
            {
             
// parse value for to/from simple search
            
$minmax=explode('|',str_replace("numrange","",$value));
            (
$minmax[0]=='')?$minvalue='':$minvalue=str_replace("neg","-",$minmax[0]);
            (isset(
$minmax[1]))?$maxvalue=str_replace("neg","-",$minmax[1]):$maxvalue='';
            echo 
escape($lang["from"]); ?><input id=" echo escape($name?>_min" onChange="jQuery('# echo escape($name?>').val('numrange'+jQuery(this).val().replace('-','neg')+'|'+jQuery('# echo escape($name?>_max').val().replace('-','neg'));" class="NumberSearchWidth" type="number" value=" echo escape($minvalue)?>"> echo escape($lang["to"]); ?><input id=" echo escape($name?>_max" onChange="jQuery('# echo escape($name?>').val('numrange'+jQuery('# echo escape($name?>_min').val().replace('-','neg')+'|'+jQuery(this).val().replace('-','neg'));" class="NumberSearchWidth" type="number" value=" echo escape($maxvalue)?>">
            <input id=" echo escape($name?>" name=" echo escape($name?>" type="hidden" value=" echo escape($value?>">
             
            
# Add to the clear function so clicking 'clear' clears this box.
             
$clear_function.="document.getElementById('".$name."_max').value='';";
             
$clear_function.="document.getElementById('".$name."_min').value='';";
             
$clear_function.="document.getElementById('".$name."').value='';";
            }



        if (
$forsearchbar && $autocomplete_search) { 
                
# Auto-complete search functionality
                
?></div>
                <script type="text/javascript">

                jQuery(document).ready(function () { 

                    jQuery("#field_ echo escape($field["ref"])?>").autocomplete( { source: " echo $baseurl?>/pages/ajax/autocomplete_search.php?field= echo escape($field["name"]) ?>&fieldref= echo escape($field["ref"]) ?>"} );
                    })

                </script>
                <div class="SearchItem">
 }

        break;

        case 
FIELD_TYPE_CHECK_BOX_LIST
        case 
FIELD_TYPE_DROP_DOWN_LIST:
        case 
$forsearchbar && $field["type"]==FIELD_TYPE_DYNAMIC_KEYWORDS_LIST && $simple_search_show_dynamic_as_dropdown:
       if(!
hook("customchkboxes""", array($field$value$autoupdate$class$forsearchbar$limit_keywords)))
            {
            global 
$checkbox_ordered_vertically;

            
# -------- Show a check list or dropdown for dropdowns and check lists?
            # By default show a checkbox list for both (for multiple selections this enabled OR functionality)

            # Translate all options
            
$adjusted_dropdownoptions=hook("adjustdropdownoptions");
            if (
$adjusted_dropdownoptions){$options=$adjusted_dropdownoptions;}

            
$node_options array_column($field["nodes"], "name");

            if((bool) 
$field['automatic_nodes_ordering'])
                {
                
$field['nodes'] = reorder_nodes($field['nodes']);
                }

            
$order_by_resetter 0;
            foreach(
$field['nodes'] as $node_index => $node)
                {
                
// Special case for vertically ordered checkboxes.
                // Order by needs to be reset as per the new order so that we can reshuffle them using the order by as a reference
                
if($checkbox_ordered_vertically)
                    {
                    
$field['nodes'][$node_index]['order_by'] = $order_by_resetter++;
                    }
                }

            if (
$field["display_as_dropdown"] || $forsearchbar)
                {
                
# Show as a dropdown box
                
$name "nodes_searched[{$field['ref']}]";
                
?>
                <select class=" echo escape($class?>" name=" echo escape($name?>" id=" echo escape($id?>"
                     if ($autoupdate) { ?>onChange="UpdateResultCount();" 
                          if(
$forsearchbar){ ?>onChange="FilterBasicSearchOptions(' echo escape($field["name"]) ?>', echo escape(($field["global"] == "[0]" "[" escape((string)$field["resource_types"]) . "]")) ?>);"  ?>>
                    <option value=""></option>
                
                
foreach($field['nodes'] as $node)
                    {
                    if(
'' != trim($node['name']))
                        {
                        
?>
                        <option value=" echo escape(trim($node['ref'])); ?> if (count($searched_nodes) && in_array($node['ref'], $searched_nodes)) { ?>selected ?>> echo escape(trim(i18n_get_translated($node['name']))); ?></option>
                        
                        
}
                    }
                
?></select>
                
if($forsearchbar)
                    {
                    
// Add to the clear function so clicking 'clear' clears this box.
                    
$clear_function .= "document.getElementById('{$id}').selectedIndex = -1;";
                    }
                }
            else
                {
                
# Show as a checkbox list (default)
                
$setnames=trim_array(explode(";",$value));
                
$wrap=0;

                
$l    average_length($node_options);
                switch(
$l)
                    {
                    case 
$l 40$cols 1; break; 
                    case 
$l 25$cols 2; break;
                    case 
$l 15$cols 3; break;
                    case 
$l 10$cols 4; break;
                    case 
$l 5:  $cols 5; break;
                    default:       
$cols 10;
                    }

                
$height ceil(count($field['nodes']) / $cols);

                global 
$checkbox_ordered_vertically$checkbox_vertical_columns;
                if(
$checkbox_ordered_vertically)
                    {
                    if(!
hook('rendersearchchkboxes'))
                        {
                        
# ---------------- Vertical Ordering (only if configured) -----------
                        
?>
                        <table cellpadding=4 cellspacing=0>
                            <tbody>
                                <tr>
                                
                                
for($i 0$i $height$i++)
                                    {
                                    for(
$j 0$j $cols$j++)
                                        {
                                        
$order_by = ($height $j) + $i;

                                        
$node_index_to_be_reshuffled array_search($order_byarray_column($field['nodes'], 'order_by''ref'));

                                        if(
false === $node_index_to_be_reshuffled)
                                            {
                                            continue;
                                            }

                                        
$node $field['nodes'][$node_index_to_be_reshuffled];
                                        
?>
                                        <td valign=middle>
                                            <input id="nodes_searched_ echo $node['ref']; ?>" class="nodes_input_checkbox" type="checkbox" name="nodes_searched[ echo $field['ref']; ?>][]" value=" echo $node['ref']; ?> if((count($searched_nodes) && in_array($node['ref'], $searched_nodes)) || in_array(i18n_get_translated($node['name']),$setnames)) { ?>checked ?>  if($autoupdate) { ?>onClick="UpdateResultCount();" ?>>
                                            <label class="customFieldLabel" for="nodes_searched_ echo $node['ref']; ?>">
                                                 echo escape(i18n_get_translated($node['name'])); ?>
                                            </label>
                                        </td>
                                        
                                        
}
                                        
?>
                                    </tr>
                                    <tr>
                                    
                                    
}
                                    
?>
                            </tbody>
                        </table>

                        
}
                    }
                else
                    {
                    
# ---------------- Horizontal Ordering (Standard) ---------------------             
                    
?>
                    <table cellpadding=4 cellspacing=0>
                        <tr>
                    
                    
foreach($field['nodes'] as $node)
                        {
                        
$wrap++;

                        if(
$wrap $cols)
                            {
                            
$wrap 1;
                            
?>
                            </tr>
                            <tr>
                            
                            
}

                        if(
'' != $node['name'])
                            {
                            
?>
                            <td valign=middle>
                                <input id="nodes_searched_ echo $node['ref']; ?>" class="nodes_input_checkbox" type="checkbox" name="nodes_searched[ echo $field['ref']; ?>][]" value=" echo $node['ref']; ?> if ((count($searched_nodes) && in_array($node['ref'], $searched_nodes)) || in_array(i18n_get_translated($node['name']),$setnames)) {?>checked ?>  if ($autoupdate) { ?>onClick="UpdateResultCount();" ?>>
                                <label class="customFieldLabel" for="nodes_searched_ echo $node['ref']; ?>">
                                     echo escape(i18n_get_translated($node['name'])); ?>
                                </label>
                            </td>
                            
                            
}
                        }
                        
?>
                        </tr>
                    </table>

                    
}

                }
            }
        break;

        case 
FIELD_TYPE_DATE_AND_OPTIONAL_TIME:
        case 
FIELD_TYPE_EXPIRY_DATE
        case 
FIELD_TYPE_DATE
        case 
FIELD_TYPE_DATE_RANGE
        
$found_year='';$found_month='';$found_day='';$found_start_year='';$found_start_month='';$found_start_day='';$found_end_year='';$found_end_month='';$found_end_day='';
        if (!
$forsearchbar && $daterange_search)
            {
            
render_date_range_field($name$valuetrue$autoupdate, array(), $reset);
            }
        else
            {
            
$s=explode("|",$value);
            if(
is_array($s))
                {
                
$found_year  $s[0];
                
$found_month = (array_key_exists(1$s)) ? $s[1] : '';
                
$found_day   = (array_key_exists(2$s)) ? $s[2] : '';
                }
            
?>      
            <select name=" echo escape($name);?>-y" id=" echo $id?>-y" class="SearchWidth if ($forsearchbar){ echo "Half";} ?>" style="width:120px;"  if ($autoupdate) { ?>onChange="UpdateResultCount();" ?>>
              <option value=""> echo escape($lang["anyyear"])?></option>
              
              $y
=date("Y");
              
$y += $maxyear_extends_current;
              for (
$d=$y;$d>=$minyear;$d--)
                {
                
?><option  if ($d==$found_year) { ?>selected ?>> echo $d?></option>
                
}
              
?>
            </select>

             if ($forsearchbar && $searchbyday) { ?><br /> ?>

            <select name=" echo escape($name);?>-m" id=" echo $id?>-m" class="SearchWidth if ($forsearchbar){ echo "Half SearchWidthRight";} ?>" style="width:120px;"  if ($autoupdate) { ?>onChange="UpdateResultCount();" ?>>
              <option value=""> echo escape($lang["anymonth"])?></option>
              
              
for ($d=1;$d<=12;$d++)
                {
                
$m=str_pad($d,2,"0",STR_PAD_LEFT);
                
?><option  if ($d==$found_month) { ?>selected ?> value=" echo $m?>"> echo escape($lang["months"][$d-1])?></option>
                
}
              
?>
            </select>

             if (!$forsearchbar || ($forsearchbar && $searchbyday)) 
                { 
                
?>
                <select name=" echo escape($name);?>-d" id=" echo $id?>-d" class="SearchWidth if ($forsearchbar){ echo "Half";} ?>" style="width:120px;"  if ($autoupdate) { ?>onChange="UpdateResultCount();" ?>>
                  <option value=""> echo escape($lang["anyday"])?></option>
                  
                  
for ($d=1;$d<=31;$d++)
                    {
                    
$m=str_pad($d,2,"0",STR_PAD_LEFT);
                    
?><option  if ($d==$found_day) { ?>selected ?> value=" echo $m?>"> echo $m?></option>
                    
}
                  
?>
                </select>
                 
                
}
            if(
$forsearchbar)
                {
                
# Add to the clear function so clicking 'clear' clears this box.
                
$clear_function.="
                    document.getElementById('field_" 
$field["ref"] . "-y').selectedIndex=0;
                    document.getElementById('field_" 
$field["ref"] . "-m').selectedIndex=0;
                    "
;
                if(
$searchbyday)
                    {
                    
$clear_function.="document.getElementById('field_" $field["ref"] . "-d').selectedIndex=0;";
                    }
                }
            }

        break;

        case 
FIELD_TYPE_CATEGORY_TREE:
        global 
$category_tree_add_parents$category_tree_search_use_and;

        
$set  preg_split('/[;\|]/'cleanse_string($valuetrue));
        
$name "nodes_searched[{$field['ref']}][]";

        
/*
        For search, category trees work slightly different than the intended behaviour shown in edit_fields/7.php:
        Intended behaviour:
        1. Selecting a sub (child) node will automatically select all parent nodes up to and including the root level,
        unless the option $category_tree_add_parents is set to false

        On search this should work like this:
        Selecting a sub (child) node will NOT select all parent nodes unless the system is configured to search using AND
        */
        
$category_tree_add_parents $category_tree_search_use_and;

        if(
$forsearchbar)
            {
            
$original_category_tree_open $category_tree_open;
            
$category_tree_open          true;
            
$treeonly                    true;
            
$status_box_elements         '';

            
?>
            <script type="text/javascript">
                jQuery(document).ready(function()
                {
                    jQuery('#SearchBox').on('categoryTreeChanged', function(e,node)
                    {
                        FilterBasicSearchOptions(' echo escape($field["name"]) ?>',[ echo escape((string)$field["resource_types"]) ?>]);
                    });
                });
            </script>
            

            
foreach($searched_nodes as $node)
                {
                
$n_details = array();

                if(
get_node($node$n_details)===false)
                    {
                    continue;
                    }

                if(
$n_details["resource_type_field"] != $field["ref"])
                    {
                    continue;
                    }

                
// Show previously searched options on the status box
                
$status_box_elements .= "
                <div id=\"tree_
{$field['ref']}_selected_{$n_details['ref']}\" class=\"tree_{$field['ref']}_options_status\">
                    <span id=\"nodes_searched_
{$field['ref']}_statusbox_option_{$n_details['ref']}\">{$n_details['name']}</span><br />
                </div>"
;
                }
            
?>
            <div id="field_ echo escape($field['name']); ?>">
                <div id="nodes_searched_ echo $field['ref']; ?>_statusbox" class="MiniCategoryBox">
                     echo $status_box_elements?>
                </div> 
                <a href="#"
                   onClick="
                        jQuery('#cattree_ echo $field['name']; ?>').slideToggle();

                        return false;"> echo escape($lang['showhidetree']); ?></a>
                        <div id="cattree_ echo $field['name']; ?>" class="RecordPanel PopupCategoryTree">
                    
                    
include __DIR__ '/../pages/edit_fields/7.php';

                    
// Reset category_tree_open because normally searchbar occurs before edit/ advanced search page
                    
$category_tree_open $original_category_tree_open;
                    
?>
                </div>

            </div>
            
            
# Add to clear function
            
$clear_function .= "
                jQuery('#search_tree_
{$field['ref']}').jstree({
                    'core' : {
                        'themes' : {
                            'name' : 'default-dark',
                            'icons': false
                        }
                    }
                }).deselect_all();

                /* remove the hidden inputs */
                var elements = document.getElementsByName('nodes_searched[
{$field['ref']}][]');
                while(elements[0])
                    {
                    elements[0].parentNode.removeChild(elements[0]);
                    }

                /* update status box */
                var node_statusbox = document.getElementById('nodes_searched_
{$field['ref']}_statusbox');
                while(node_statusbox.lastChild)
                    {
                    node_statusbox.removeChild(node_statusbox.lastChild);
                    }
                "
;
            }
        else
            {
            
# For advanced search and elsewhere, include the category tree.
            
include __DIR__ "/../pages/edit_fields/7.php";
            }
        break;

        case 
FIELD_TYPE_DYNAMIC_KEYWORDS_LIST:
            include 
__DIR__ '/../pages/edit_fields/9.php';
        break;      

        case 
FIELD_TYPE_RADIO_BUTTONS:
            
// auto save is not needed when searching
            
$edit_autosave           false;
            
$display_as_radiobuttons false;
            
$display_as_checkbox     true;
            
$name                    "nodes_searched[{$field['ref']}][]";

            if(
$forsearchbar || $field['display_as_dropdown'])
                {
                
$display_as_dropdown true;
                
$display_as_checkbox false;
                
$name                "nodes_searched[{$field['ref']}]";

                
$clear_function .= "document.getElementsByName('{$name}')[0].selectedIndex = -1;";
                }

            include 
__DIR__ '/../pages/edit_fields/12.php';
            
// need to adjust the field's name value
            
?>
            <script type="text/javascript">
                jQuery("#field_ echo $field['ref']; ?>").attr('name', 'field_ echo $field["name"]; ?>');
            </script>
            
        
break;
        } 
## END CASE
    
?>
    <div class="clearerleft"> </div>
    </div>
    <!-- ************************************************ -->

    
# End of render_search_field

This article was last updated 17th November 2024 15:05 Europe/London time based on the source file dated 13th November 2024 14:05 Europe/London time.