Answer the question
In order to leave comments, you need to log in
Get cookie value via ajax?
Hello. I'm stupid.
The situation is as follows, there is a created view (view), which displays the nodes. This view has the ability to sort, I store the value for sorting in cookies, which I take in hook_views_query_alter and, based on this value, I use one or another sort for the view.
function hook_views_query_alter(&$view, &$query) {
if($view->name == 'product'){
# Сортировка полей
$sorting_field = 'default';
if(isset($_COOKIE['sorting_field'])){
$sorting_field = $_COOKIE['sorting_field'];
}
$sort_default = $view->query->orderby[0];
$sort_price_asc = $view->query->orderby[1];
$sort_price_desc = $view->query->orderby[2];
unset($view->query->orderby[0]);
unset($view->query->orderby[1]);
unset($view->query->orderby[2]);
# Дефолтная сортировка (по дате)
if($sorting_field == 'default'){
$view->query->orderby[0] = $sort_default;
}
# Сортировка по цене (по возрастанию)
if($sorting_field == 'price_asc'){
$view->query->orderby[1] = $sort_price_asc;
}
# Сортировка по цене (по убыванию)
if($sorting_field == 'price_desc'){
$view->query->orderby[1] = $sort_price_desc;
}
}
}
function hook_form($form, &$form_state){
$form = array();
# Ctools autosubmit
ctools_add_js('auto-submit');
$form['#attributes']['class'][] = 'ctools-auto-submit-full-form';
# Сортировка
$sorting_options = array(
'price_asc' => 'цена 1',
'price_desc' => 'цена 2',
'default' => 'без сортировки'
);
$form['sorting'] = array(
'#type' => 'select',
'#title' => 'Сортировать по:',
'#options' => $sorting_options,
'#default_value' => isset($_COOKIE['sorting_field']) ? $_COOKIE['sorting_field'] : 'default',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Сортировать',
'#ajax' => array(
'callback' => 'skate_product_sort_form_submit',
'event' => 'click',
),
'#attributes' => array('class' => array('ctools-use-ajax', 'ctools-auto-submit-click')),
);
return $form;
}
function hook_form_submit($form, &$form_state){
# Время хранения cookie
# По умолчанию на 30 дней
$time_cookie = time()+60*60*24*30;
# Домен
$domain = str_replace('http://', '', $GLOBALS['base_root']);
# Сохраняем в куки сортировку по полю
$sort_field = $form_state['values']['sorting'];
setcookie('sorting_field', $sort_field, $time_cookie, '/', $domain);
$commands = array();
# Результат представления
$result_output = views_embed_view('product', 'page');
$commands[] = ajax_command_invoke('.selector', 'html', array($result_output));
return array('#type' => 'ajax', '#commands' => $commands);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question