Skip to content

Instantly share code, notes, and snippets.

@St0iK
Created August 12, 2015 11:31
Show Gist options
  • Save St0iK/48aaaf2c11752c5b191a to your computer and use it in GitHub Desktop.
Save St0iK/48aaaf2c11752c5b191a to your computer and use it in GitHub Desktop.
t
<?php
/**
* Implementation of hook_views_pre_render()
*
* @param view $view
*/
function vw_product_listing_sort_views_pre_render(&$view) {
if ($view->name == "shop" && $view->current_display == 'page') {
// Get last item from url arguments
$term_name = end(arg());
$term_uuid = _get_term_uuid($term_name);
if ($term_uuid) {
// Get all products sorted for this category UUID
$results = db_select('product_listing_weights', 'p')
->fields('p', array( 'entity_id','weight'))
->condition('category_uuid', $term_uuid)
->orderBy('weight')
->execute()
->fetchAll();
// If this category has been sorted in the admin area
if($results){
// Build a new array that contains an assosiation
// between entity_ids and weight
$entity_weight = array();
foreach ($results as $key => $result) {
$entity_weight[$result->entity_id] = $result->weight;
}
// Attach that weight to the results of the view
foreach ($view->result as $key => $result) {
$entity_weight[$result->entity];
}
// Sort View results object based on weight
usort($view->result, '_creode_objectsort');
echo "<pre>";
print_r($view->result);
echo "</pre>";
}
}
}
}
/**
* Returns the Term UUID based on a term name
*
* @param string $term_name
*/
function _get_term_uuid($term_name) {
if (!empty($term_name) && arg(0) == "shop") {
$term = taxonomy_get_term_by_name($term_name);
if (!empty($term)) {
$term_array = reset($term);
return $term_array->uuid;
}
}
return FALSE;
}
/**
* Implements hook_menu().
*/
function vw_product_listing_sort_menu() {
$items['admin/commenrce/product_sorting/%'] = array(
'title' => 'Sort category products',
'description' => 'Admin ui to sort products by on each category',
'page callback' => 'drupal_get_form',
'page arguments' => array('vw_product_listing_sort_fields_form', 3),
'access arguments' => array('administer search_api'),
'type' => MENU_LOCAL_TASK,
);
return $items;
}
/**
* Form: Form Table for sorting products within the category
*/
function vw_product_listing_sort_fields_form($form, &$form_state, $term_id) {
drupal_add_css(drupal_get_path('module', 'vw_product_listing_sort') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
// Get Term info
$term_info = taxonomy_term_load($term_id);
// Get weights for products on this category
$results = db_select('product_listing_weights', 'p')
->fields('p')
->condition('category_uuid', $term_info->uuid)
->orderBy('weight')
->execute()
->fetchAll();
$node_weight_info = array();
foreach ($results as $key => $result) {
$node_weight_info[$result->entity_id]['weight'] = $result->weight;
$node_weight_info[$result->entity_id]['id'] = $result->id;
}
// Get all nodes tagged with this term
$taxonomy_select_nodes = taxonomy_select_nodes($term_id);
// Load their details
$node_info = node_load_multiple($taxonomy_select_nodes);
$taxonomy_select_nodes_to_sort = array();
foreach ($taxonomy_select_nodes as $key => $node) {
$taxonomy_select_nodes_to_sort[$key]['entity_id'] = $node;
$taxonomy_select_nodes_to_sort[$key]['weight'] = $node_weight_info[$node]['weight'];
}
// Sort array based on weight key
usort($taxonomy_select_nodes_to_sort, '_creode_arraysort');
$taxonomy_select_nodes_sorted = array();
foreach ($taxonomy_select_nodes_to_sort as $key => $value) {
$taxonomy_select_nodes_sorted[] = $value['entity_id'];
}
// create a parent element and use our custom theme
$form['fields'] = array(
'#prefix' => '<div id="vw_sort_fields">',
'#suffix' => '</div>',
'#tree' => TRUE,
'#theme' => 'vw_product_listing_sort_theme_name',
);
$form['info_text'] = array(
'#weight' => -12,
'#markup' => '<h1>Lorem ipsum dolor sit amet</h1><p>Nam id purus scelerisque, finibus ipsum nec, rhoncus diam. Vivamus eget quam rutrum, varius urna in, fermentum nisi. In neque lorem, sodales et urna non, pharetra feugiat dolor. Maecenas ac vestibulum odio, vel malesuada purus. Nunc vel purus dui. Sed vel massa hendrerit, feugiat elit vitae, malesuada arcu. Praesent non diam et metus cursus consequat quis tempor mi. Vivamus luctus eleifend neque, ut congue arcu scelerisque at. Proin molestie tellus eu urna fermentum porta. Phasellus sit amet egestas mi. Nulla aliquam neque vel volutpat tempus. Donec pellentesque pulvinar euismod. Sed lacus nibh, efficitur id lacus sit amet, tempus convallis metus. Integer hendrerit arcu ut sem consectetur lacinia. Cras tempor pharetra lacus, sit amet porta dolor volutpat quis. Aenean sit amet massa vel massa facilisis congue.</p>'
);
if(empty($results)){
$form['status_text'] = array(
'#weight' => -11,
'#markup' => '<h1>Status</h1><p style="color:red">Products for this category havent been sorted yet</p>'
);
}
// create the form elements for each item
foreach ($taxonomy_select_nodes_sorted as $key => $item) {
$form['fields'][$key]['name'] = array(
'#type' => 'item',
'#title' => $node_info[$item]->title,
);
$form['fields'][$key]['entity_id'] = array(
'#type' => 'textfield',
'#title' => $item,
);
$form['fields'][$key]['entity_id'] = array(
'#type' => 'hidden',
'#default_value' => $item,
'#title' => $item,
);
$form['fields'][$key]['category_uuid'] = array(
'#type' => 'hidden',
'#default_value' => $term_info->uuid,
'#title' => $term_info->uuid,
);
$form['fields'][$key]['id'] = array(
'#type' => 'hidden',
'#default_value' => $node_weight_info[$item]['id'],
'#title' => $node_weight_info[$item]['id'],
);
$form['fields'][$key]['weight'] = array(
'#type' => 'textfield',
'#default_value' => $node_weight_info[$item]['weight'],
'#size' => 3,
// needed for table dragging
'#attributes' => array('class' => array('rank-weight')),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* Implements hook_theme().
*/
function vw_product_listing_sort_theme($existing, $type, $theme, $path) {
return array(
'vw_product_listing_sort_theme_name' => array(
'render element' => 'element',
),
);
}
function theme_vw_product_listing_sort_theme_name($vars) {
$element = $vars['element'];
// needed for table dragging
drupal_add_tabledrag('form_id', 'order', 'sibling', 'rank-weight');
$header = array(
'name' => t('Product title'),
//'field' => t('field'),
'weight' => t('Rank'),
);
$rows = array();
foreach (element_children($element) as $key) {
$row = array();
$row['data'] = array();
foreach ($header as $fieldname => $title) {
$row['data'][] = drupal_render($element[$key][$fieldname]);
// needed for table dragging
$row['class'] = array('draggable');
}
$rows[] = $row;
}
return theme('table', array(
'header' => $header,
'rows' => $rows,
// needed for table dragging
'attributes' => array('id' => 'form_id'),
));
}
/**
* Handles form submission
*/
function vw_product_listing_sort_fields_form_submit($form, &$form_state) {
$fields = array();
foreach ($form_state['values']['fields'] as $item) {
$items[] = array(
'id' => $item['id'],
'category_uuid' => $item['category_uuid'],
'entity_id' => $item['entity_id'],
'weight' => $item['weight'],
);
}
// Sort entities by weight
if (!empty($items)) {
usort($items, '_creode_arraysort');
}
foreach ($items as $item) {
$data = array(
'category_uuid' => $item['category_uuid'],
'entity_id' => $item['entity_id'],
'weight' => $item['weight'],
);
// Check if 'id' is empty
// to determine if you are going to update or insert a record
if(empty($item['id'])){
drupal_write_record("product_listing_weights", $data);
}else{
$data['id'] = $item['id'];
drupal_write_record("product_listing_weights", $data, 'id');
}
}
drupal_set_message(t('Ordering have been saved.'));
}
/**
* Sort an Array based on weight key value
*/
function _creode_arraysort($a, $b) {
if (isset($a['weight']) && isset($b['weight'])) {
return $a['weight'] < $b['weight'] ? -1 : 1;
}
return 0;
}
/**
* Sort an Object based on weight property
*/
function _creode_objectsort($a, $b) {
if($a->weight == $b->weight){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment