Exclude selected values with Lookup_Selecting (v2024)

Autofill dont work when lookup_selecting filter is enable, here is my code:

function Lookup_Selecting($fld, &$filter) {
    if ($fld->FieldVar == "x_SELECT") { // Target the correct field
        // Get selected values from the current rows
        $selectedValues = [];
        if (isset($_SESSION['selected_values'])) {
            $selectedValues = $_SESSION['selected_values'];
        }

        // Check if there are selected values
        if (!empty($selectedValues)) {
            // Sanitize selected values by casting to strings
            $selectedValues = array_map('strval', $selectedValues);

            // Exclude selected values from the lookup query
            $fld->Lookup->UserFilter = "ID_UNIQUE NOT IN ('" . implode("', '", $selectedValues) . "')";
          
        }
    }
}

Lookup_Selecting is server event side to add a filter, it has nothing to do with AutoFill (which is JavaScript). However, if your Lookup_Selecting server event filter out the options so there is no option available, there is nothing to fill. If your Lookup_Selecting server event caused server side error so there is no valid response from server, there is nothing to fill either. You may check HTTP response and see if there is any server/client side errors.

here my startup script on list page :slight_smile:

var selectedValues = [];  // Declare outside of the event listener to avoid re-initialization

$(document).on("change", "select[data-field='x_SELECT']", function () {
    selectedValues = [];  // Reset array on each change

// Collect all selected values from the grid
    $("select[data-field='x_SELECT']").each(function () {
        var value = $(this).val();
        if (value) {
            selectedValues.push(value);  // Store the selected values
        }
    });

    console.log("Selected values:", selectedValues);  // Log to check the values
    // Send the selected values to the server via Ajax
    $.ajax({
        url: "your_lookup_endpoint.php", // Replace with your PHP file endpoint
        method: "POST",
        data: { selected_values: selectedValues },  // Send selected values as POST data
        success: function (response) {
            console.log("Session updated successfully.");
        },
        error: function () {
            console.error("Failed to update session.");
        }
    });
});
``

And…? Did you see your session variables get read and used in the Lookup_Selecting server event? If you have enabled Debug and check HTTP response as suggested, you should see the built SQL for lookup in the HTTP response.