0

have a page that features a few views based on content types. Each content type includes a keyword field. This page is reached from a short quiz. I'm trying to limit the content in the views based on responses in the quiz by pulling the $_POST data and comparing it to the keyword field. The code is executing, and I'm fairly sure I have the join right, but instead of limiting the content to matching keywords, the entire display block just disappears.

Here is my module code:

<?php

if (!empty($_POST["q1"])) {

    $q1 = $_POST['q1'];
    $q3 = $_POST['q3'];

    /**
     * Implements hook_views_query_alter to add a where clause to the views queries
     */
    function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        global $q1, $q3;

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q3, '=' );
        }

    }

}

Can anyone see where I've gone wrong here?

Interesting update: If I replace $q1 with 'somekeyword' in the add_where call, it actually works.

1
  • I have confirmed that 'global' is not working. I can echo the vars outside the function, but inside they are empty. I've also tried $GLOBALS['q1'] but that doesn't work either and generates errors. – Anonymous Man Jan 27 '15 at 22:24
0

It was a problem with accessing the global variables. In the end, I got it working with the following function:

function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        $q1 = $GLOBALS["_POST"]["q1"];
        $q3 = $GLOBALS["_POST"]["q3"];

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q3, '=' );
        }

    }
0

You can access the content of a where condition modifying its value:

$query->where[0]['field_condition'][0]['value'] = 'something...';

Pretty similar what you did with orderby. Also you can add custom where conditions add_where_expression

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.