How do I access webform components labels on the congratulations page Am using the following code in the Congratulations page. There is more but this is the driving force to retrieve user submissions. Its working fine but I need to retreive as well the actual component labels. How do I include the actual questions (labels) on the form. Like if I have a component:

How old are you

10
25

How do I modify the code below to show "How old are you" on the congratulations page?

<?php
include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1);
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);
    for ($i = 1; $i <= 2; $i++) {
        echo $submission->data[$i]['value'][0];
    }
?>

The loaded submission doesn't hold the label names so you'll have to get them from elsewhere. One option would be to load the webform node where they can be found. Here's an example about how this would look like in the code:

<?php
include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1);
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
foreach ($node->webform['components'] as $key => $component) {
  if (isset($submission->data[$key]['value'][0])) {
    if ($component['type'] == 'select') {
      $options = array();
      $items = explode("\n", $component['extra']['items']);
      foreach ($items as $item) {
        $item_parts = explode('|', $item);
        if (isset($item_parts[0]) && isset($item_parts[1])) $options[$item_parts[0]] = $item_parts[1];
      }
      $no = count($submission->data[$key]['value']);
      if ($no > 1) {
        $cont = '
'. $component['name'] .': ';
        foreach ($submission->data[$key]['value'] as $k => $v) {
          if ($k + 1 == $no) $cont .= $options[$v];
          else $cont .= $options[$v] .', ';
        }
        $cont .= '
';
        echo $cont;
      }
      elseif (isset($options[$submission->data[$key]['value'][0]])) {
        echo '
'. $component['name'] .': '. $options[$submission->data[$key]['value'][0]] .'
';
      }
    }
    else {
      echo '
'. $component['name'] .': '. $submission->data[$key]['value'][0] .'
';
    }
  }
}
?>


Choose Checkbox Insted of radio as a widget in drupal custom content type While adding field in content type I had chosen Check boxes/radio buttons as widget.
By default it takes radio button as a widget.I want check boxes as a widget instead of Radio Button. What should I do?

You need to edit in Field Settings to set Number of Values to Unlimited or more than 1. Then Checkboxes will be used.

Radio buttons are used when user can only select one value.


How to use token as a filter value in views I'm looking for a solution that would allow me to use tokens in views filter values. For example, if I have text field 'my_custom_text' I would like to have a filter that would allow me to use 'Is equal to' operator and a token value instead of hardcoded string.

Note that I can't use contextual filters because I have few filters that needs to be ORed.

Is there a module for that, or do I have to code that myself from ground up?

Use Contextual Filters instead of Filter Criteria.

In Drupal 8, at the time of writing this, you also have to install the views_argument_token module.

When adding a contextual filter, at the pop up window, select "Provide default value" option. From there on the remaining settings should be intuitive.


Drupal 7 admin can't upload images, but all other users can I'm experiencing a very strange error and I can't figure out what's causing it. I have a drupal 7 website and all users and roles can upload images without any issues, except user 1, the administrator. When I try to upload an image as user 1 to ANY content type or delete an already existing image it freezes or returns this:

"An unrecoverable error occurred. The uploaded file likely exceeded the", the strange part is admin has all the permissions and I disabled the admin menu and other modules that are unique to being user 1. Any ideas? It's driving me crazy.

i guess you reached the upload limit for user 1, are you using IMCE ?


How can I override the sort variable? For my view in Drupal 8 I have added a sorting criteria based on the custom field. Now, when I sort the content in the url one can see a sorting value as a name of that field.

Like ?sort_by=field_custom_value

How can I override the value of the sort criteria, so that the path doesn't look so ugly.

Expected: ?sort_by=something_different

This module might help Query Parameters To URL.

There's a D8 sandbox: Drupal 8 port

The module seems very useful, maybe it would get more attention if more people used it.


Path to translated content of a node I need to find the url path to the translated node of a page , the Multilink Module seems to do just this, is there something similar for Drupal 8? How do I find the path to the translation of a node in Drupal 8?

thanx for your help

I believe you can use:

$japanese_node = $node->getTranslation('ja');
$japanese_link = $japanese_node->toUrl()->toString();

Adjust accordingly.


How to include the same menu twice in a .tpl file I am working on a responsive design for a site I am building and I currently am having trouble including the menu twice in the header template file. I need the menu displayed inside the content wrapper for large devices and outside the template wrapper on small devices so I intende to use bootstrap classes to show/hide the correct menus. However when I include the menu twice in my template file only the second instance is ever displayed. How can I get the menu to render twice in the same template.

    <?php print render($main_menu); ?>

    <?php print render($content); ?>
    <?php print render($main_menu); ?>

You can probably use the show() function to un-hide the previously rendered element:

    <?php print render($main_menu); ?>

    <?php print render($content); ?>
    <?php show($main_menu); ?>
    <?php print render($main_menu); ?>


How to pass a form and other variables to theme functions? I wonder how can I pass a form and other variables (an array) to hook_theme(), I know that if you want to render a form in hook theme you have to use 'render element' so now I can't use 'variables' to pass my variable array. here is what I did to render the form:

function example_theme() {
  return array(
    'deductible_form' => array(
      'arguments'      => array('form' => NULL),
      'template'       => 'example',
      'render element' => 'form',
     ),
  );
}

What can I do to solve this?

As you rightly say you can't pass variables to a theme function that uses a render element, but then you don't need to.

One of the points of the render element is that the element already contains all of the properties/variables that it needs to perform the render, without having to get them from anywhere else.

A themed form is actually a good example for this: if you need to add extra variables in order to render that form, then they should be arguments to the form function itself. e.g.:

function deductible_form($form, &$form_state, $var1, $var2) {
  $form['#theme'] = 'deductible_form';
  $form['#var1'] = $var1;
  $form['#var2'] = $var2;

  // etc...

  return $form;
}

Then in your form's theme function you can easily access those vars:

function theme_deductible_form($vars) {
  $form = $vars['form'];

  $var1 = $form['#var1'];
  $var2 = $form['#var2'];

  // Render the form
}

All you need to do to get that form to render properly now is to call drupal_get_form() with your extra variables:

$form = drupal_get_form('deductible_form', $var1, $var2);


Error viewing articles/pages after assigning As an experiment I've merged core from 8.3.x branch to try out workflow. After successfully assigning 'editorial workflow' to articles and pages, I cannot access the pages or articles anymore neither to read them as a guest or to edit them as an admin.

Visiting /admin/reports/status, I see this error:

  Mismatched entity and/or field definitions
  The following changes were detected in the entity type and field definitions.

  Comment

  The Publishing status field needs to be updated.

My expectation is that the existing entities needs their workflow states to be set, but I expected the workflow module to automatically assign 'published' state to published articles. How can I fix that?

I was wrong about that this was only happening with existing articles. Another article after been created as well started behaving the same.
This was the error from log:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'content_moderation_state_field_data.workflow' in 'where clause': SELECT base_table.revision_id AS revision_id, base_table.id AS id
      FROM
      {content_moderation_state} base_table
      INNER JOIN {content_moderation_state_field_data} content_moderation_state_field_data ON content_moderation_state_field_data.id = base_table.id
      WHERE (content_moderation_state_field_data.content_entity_type_id IN (:db_condition_placeholder_0)) AND (content_moderation_state_field_data.content_entity_id IN (:db_condition_placeholder_1)) AND (content_moderation_state_field_data.workflow IN (:db_condition_placeholder_2)) AND (content_moderation_state_field_data.default_langcode IN (:db_condition_placeholder_3)); Array
      (
          [:db_condition_placeholder_0] => node
          [:db_condition_placeholder_1] => 8
          [:db_condition_placeholder_2] => editorial
          [:db_condition_placeholder_3] => 1
      )
       in Drupal\Core\Entity\EntityStorageBase->loadByProperties() (line 503 of \core\lib\Drupal\Core\Entity\EntityStorageBase.php)."
  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE…

Missing column of the contrib module indicates the corruption of the database. In your case workflow field is missing in content_moderation_state_field_data.

If this error start happening after upgrade, try running Database Update (either by going to /update.php or running drush updb command).

There is a Unofficial content_moderation 8.2.x to 8.3.0 upgrade path which can also help. It has relevant patches for content_moderation module with update hooks, which will migrate the tables accordingly.

Otherwise you'll have to reinstall the module, so its tables are re-created from scratch.


Commerce kickstart 2 creating custom front page I subthemed the original kickstart 2 commerce site and everything works fine. I also understand the CSS structure and how to regulate that.

What I'm trying to understand is how the frontpage works and how to change the structure. It looks like the frontpage is created of blocks so I can change what shows or doesn't show on frontpage via Site settings -> Blocks.

However, how could I add lets say a custom div with h1 heading and few paragraphs to it?

This can be easily created with adding a new basic page, where you can use full html in body and style the page to your liking. How does this work with a front page?

If I create a basic page with the paragraph "Welcome to the website" that I want to use on the front page, and then display it in a main content block, what bothers me is that it renders Read more button. Which I don't want.

Where can I do that for frontapge then?

I suppose you could create a custom block at admin/structure/block/add.
It comes with body field and after creating the block you can assign it to "content" region and set it to show up only on .

You have the possibility to create new regions in theme.info file and render them only in page--front.tpl.php.

I think these are the clean ways to do it, and don't require much coding.


Views Field View issue I am new to drupal, so this issue may be something extremely basic that I am missing.

Basically, I have 2 views. A parent and a child. There are 3 content types. Industries, Applications and Minerals.

I need the parent view to show all industries, then the child view should show the applications within each industry, which are linked using an Entity Reference field.

Can someone please point me in the right direction on how to pass a contextual filter from the parent view to the child view. Basically i need to filter the child view on the title field of the parent view.

FIXED

Used NID instead of Title!

Create two views or one view with two displays
Configure Parent view or display
Configure Child view or display and add context. filter by parent node title (this can be provided by Relationships). You can test it by passing one of Parent node title to Preview textfield.
Open parent view or display, add Global:View field, choose your child view and display in settings.. Important part: you need to provide parent node's title as an argument to Contextual Filters input of Global:View settings, for that expand Replacement Patterns, find Title pattern, it should be somthing like [!title], copy it and past it into Contextual Filters input of settings form.

I didn't test it but you can correct it by your needs.


Retrieve the list of posts for a particular forum From this question, I know how to retrieve a list of forum posts (forum topics?) from drupal.

curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum'

Now, I'd like to limit the list of forum posts to those belonging to a particular forum.  How do I filter the result by forum? I know the forum tid. I just don't know how to format the query.

This doesn't cut it:

curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum&tid=4'

The above returns all forum posts. This also does not work:

curl -i -X GET  \
 -H Cookie:SESSe6a353351df0bcafe98787beef=B0YAHD3-reWwwW-kzhqw6A-SgeShSYUAAQQjh \
 'http://myserver/rest/node?parameters\[type\]=forum&parameters\[tid\]=4'

It gives me:

  "Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tid' in 'where clause'"

I get the same error if I try to reference parameters\[taxonomy_forums\]

Any help?

To get all posts (forum topics) for a particular forum with id=4:

curl -i -X POST \
  -H Cookie:SESSe6a3baadbeef=ovQpO6aYeehaw_3W4onya22i9bonusQW \
  -H X-CSRF-Token:v6j7r9RactujA872hSHSKW-mYYWAA \
  -H Accept:application/json \
  -H Content-Type:application/json \
  http://myserver/rest/taxonomy_term/selectNodes \
  -d '{"tid":4}'

To find the mapping between forums and tids, refer to this answer.

I don't know how to do a parameterized query (GET) to retrieve forum topics. As far as I can tell you need to use POST, as described here.


Using Drupal 7 with APC, Varnish and Memcache, what bins to put in which cache? I'm optimizing a Drupal 7 website and I have varnish, memcache and APC all installed and working with their individual Drupal 7 modules. In my settings.php I have the $conf options below.

My question is to get better performance and have all these caches work together well, do I need to add more configuration options?

The module readme's usually assume a single cache system. Are there any tweks needed to get better performance out of running 3 separate caching backends?

// Add Varnish as the page cache handler.
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap.
// This needs to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';
//$conf['apc_show_debug'] = TRUE;  // Remove the slashes to use debug mode.

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Looks ok to me.

What you can try is play around with Memcache options. There is for example a compression flag but it usally depends on the site if it makes sense to enable it because you then have a higher cpu usage to do the compression/decompression.

I also think that page_cache_invoke_hooks flag is not necessary anymore, see http://drupal.org/node/804864. If you don't need those hooks to run then you can set it, but it's not necessary anymore for Varnish to work.

Using APC cache with multiple webservers means that you run into inconsistencies when clearing caches on one server, so if you do have multiple ones, you probably want to use Memcache for cache and cache_bootstrap as well. I've also had stability issues when using APC cache but I did use it for all caches, which might have been the issue.


How add javascrip file to a node? (module) I have create a module who add a new node named SquareOffs. I make that in my squareoffs.info file.
I would like to add to that node a javascript file, squareoffs.js, but I don't know to do that.

I have seen the drupal_add_js() documentation but I don't know understand how it works, how can I add the js file to this node??

Thank you very much for  your answers or your sugestions!!

You can add your js through drupal_add_js() function. You can control on which pages this js should be added by implementing different hook and calling drupal_add_js() function in those hooks:

1) Use drupal_add_js() in hook_init() if you want to add this js on all drupal pages.

function mymoduel_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js');
}

2) Use drupal_add_js() in hook_node_view() with content type condition check if you want to add this js on only specific content types.

function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'my_content_type') {
    $node->content['#attached']['js'][] = array (
      'type' => 'file',
      'data' => drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    );
  }
}

3) Use drupal_add_js() in module's preprocess function if you want to add this js only on specific node

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 'your node nid') {
    // Add js
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.awesome.js');
  }
}

You can implement this preprocess_page at theme level like mytheme_preprocess_page($variable) in theme's template.php file.


Drupal 7 View - How to show content based on conditions I've a travel portal and I've create a content type Destinations which I use to create content for main Destination page Continent, Countries, states and cities. This content type has uses Location module as a field.

Then I create a page e.g. Thailand which is of type Destinations.

I've create a block view to show the links to cities/countries/continents on country/continent/main destination pages.

So on my main Destination page I want to list all continents and countries, then on countries pages I want to list all states and cities, on state pages I want to show all cities.

Would it be possible to utilize the Location module to achieve this?

I'm using location to identify many type of content, e.g. Hotels, Places, Museums etc.

Or shall I use Taxonomy/Terms.

Or any other alternative ways to achieve this?

I think it would be easier to use hierarchical taxonomy tree, this would definitely make your life much easier when creating views listing child taxonomy terms or content tagged with child terms...


How to create vocabulary page? I want want to create page for vocabulary. I mean not vocabulary term, but vocabulary name.

mysite.com/myvocab

rather than

mysite.com/myvocab/term

That page should also have possibility to display text (how can I add text field to vocabulary and not vocab term?)

Thanks!

There is two simple way to do it I think :

Use Vocabulary module which gives you the taxonomy/vid page.
Or Use views to create your page. Create a taxonomy type view and add Taxonomy vocabulary: Vocabulary ID or Taxonomy vocabulary: Machine Name as argument.
If you want to display the nodes related to vocabulary then I think you need to use Views Field View with 2nd option.


Create a pager with "Yesterday", "Monday", "Sunday" etc I have a view which through contextual filters show content created on the current day, and I would like to add a pager to allow users to go back in time one day at a time.

Say we visit the site on a Tuesday. So when viewing today's posts there is one link to the left which says "Yesterday" and no link to the right (since there are no future posts), and when this link is clicked we are show yesterdays content (Monday). The links are now "Sunday" to the left and "Today" to the right. Again we click the left link and are shown the content created on Sunday, and the links now show "Saturday" to the left and "Yesterday" to the right.

I've tried using exposed filters but they only output drop downs and only let me sort by asc/desc.

Is this possible?

Contextual range filter module ( https://drupal.org/project/contextual_range_filter ) seems to be the most suitable option as per the above requirement, or you can try the views day of week module ( https://drupal.org/project/views_dow ).

I have created a view for day archive by using the contextual filter of view (without using the above modules) as below below:

but as your requirement seems to be creating a archive on the basis of week day therefore the best would be to use the above(Contextual range filter module, or the view day of week module), and than you can found the filter in the contextual filter of your view.


How to import nodes that reference each other using Feeds? I have a content type that references nodes of the same content type (using References module).

So example nodes might look like this:

Title   Body       See also (Node reference)
AAA     Testing    CCC
BBB     Testing
CCC     Testing    AAA, BBB

I'm pulling all of this information from an XML feed using Feeds Node processor. The problem is that when creating node AAA, node CCC hasn't been created yet so the reference field doesn't populate.

Do I need to create a second importer - but can two importers update the same nodes? I also had a look at Feeds Self Node Processor but don't think that's the answer.

Two importers can work on the same nodes without any problem, but that's not what you need.  Instead, You need to set the importer to update/overwrite existing nodes when they have the same GUID.  Then you run the importer twice on the same xml file.  The first time they won't be populated properly, but because they'll already exist the second time, the second run should fix it.


Changing an inner join to a left join in views 3.3? Using views 3.3, I have a view in Drupal 7 where I am showing two content types. I have a filter criteria based on the value of a field that is attached only to one of the content types. So long as I have that field criteria, views is doing an INNER JOIN, which causes it not to return views of the first content type which doesn't have that field attached.

I copied the query from the view, changed the INNER to a LEFT join, pasted it into the mysql shell, and I got all the rows that I expected to get. But I don't know how to make those changes in the view editor.

I was playing around in the 'relationship' block on the view editor, but I didn't see where I could change the join type.

Am I able to change how views 3.3 does joins?

I found clicking on the reduce duplicates checkbox converted my INNER JOINs to LEFT JOINs:

Before I was getting something akin to the following injected into my query:

INNER JOIN {field_data_field_random_field field_data_field_random_field}
        ON node.nid = field_data_field_random_field.entity_id
       AND (field_data_field_random_field.entity_type = 'node'
       AND field_data_field_random_field.deleted = '0')

These inner joins were being caused by simple taxonomy filters, so sadly I didn't have any relationships to unrequire. Checking this box however doesn't seem to have altered my query in any other way, save for removing the inner joins, which is perfect for me; and may help someone else out there in this vast monkey adventure called life.


How to export feed agregator list and setting as feature? I want to export feed aggregator list and settings as feature. If both aggregator list and settings cannot be exported, then how to export? Thanks a lot.

I have achieved this using aggregator_save_feed() function in hook_install() or hook_update_N() of my custom module. It's not a feature but there is not much difference.

Example:

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  $feed = array(
    'title' => 'Business',
    'url' => 'http://feeds.bbci.co.uk/news/business/rss.xml',
    'refresh' => 3600, // Update interval in seconds
    'block' => 5, // News items in block
  );
  aggregator_save_feed($feed);
}


Can I create two views with the same paths? I have a path pattern that looks the same for two content types. For example, pattern http://my-site.com/x/y/z, for content type 'Article' and content type 'Property'. They follow the same pattern because they only differ in the actual content. The paths are composed of taxonomy items which are the same for the two content types.

So where x/y are the taxonomies called 'categories' and 'types' while z is the title of the content. And both content types follow the same taxonomy group. So only differs in the actual content. One uses generic 'Article' fields while other one uses many custom fields.

My view mostly is defined by the system path node/% but I need to separate them for 'Article' only types and 'Property' only contents. This works for 'Property'. 'Article' based contents are no longer shown by Drupal now.

I have looked into this and this but they somehow use panels and other one is based on blocks and permissions, which is not what I needed.

I can't seem to use panels because I cannot, for some reason, see my view in the contents that can be added. (Most probably because my Views path is node/%). I can only pull those views that does not follow this format.

Is there any other simple way to pull the two types of contents without having to resort to Panels and separating contents by different blocks? Because it is more readable using Views  and much lighter and easier to just configure the parameters I think. U reduce a lot of overheads.

Any thoughts?

If I understand correctly, yes you can simply achieve that using views.

Go to your views and add an "Attachment" to the 'page' view. Set Filter Criteria accordingly. You can also achieve that using Views Block.


Add javascript to views exposed form after ajax submit I've read millions of similar posts on this but I just can't get my head around it. So far I understand that I need to use Drupal.attachBehaviors, and I've tried so many different approaches that I've seen but nothing works.

Basically I have a jQuery plugin that is styling any select boxes on the site, which works great, apart from on my views exposed form with ajax enabled. The jQuery is literally as simple as $('select').styledSelect(); after including the plugin itself.

EDIT: this is almost there:

      Drupal.behaviors.styledSelect = {
        attach: function() {
          $("select").styledSelect();
        }
      };

But now the ajax call seems to be looping.

EDIT again:

Well it seems to be something to do with the actual plugin, as other Javascript seems to work fine. I'm so close! Here is the plugin:

jQuery.fn.styledSelect = function(options) {
var isFF2 = jQuery.browser.mozilla && jQuery.browser.version.indexOf('1.8.')==0;
var prefs = {
    coverClass : 'select-replace-cover',
    innerClass : 'select-replace',
    adjustPosition : { top:0, left:0 },
    selectOpacity : 0
    }
if (options) jQuery.extend(prefs,options);
return this.each( function() {
    if (isFF2) return false;
    var selElm = jQuery(this);
    selElm.wrap('<'+'/span>');
    selElm.after('<'+'/span>');
    var selReplace = selElm.next();
    var selCover = selElm.parent();
    selElm.css({
        'opacity':prefs.selectOpacity,
        'visibility':'visible',
        'position':'absolute',
        'top':0,
        'left':0,
        'display':'inline',
        'z-index':1
        });
    selCover.addClass(prefs.coverClass).css({
        'display':'inline-block',
        'position':'relative',
        'top':prefs.adjustPosition.top,
        'left':prefs.adjustPosition.left,
        'z-index':0,
        'vertical-align':'middle',
        'text-align':'left'
        });
    selReplace.addClass(prefs.innerClass).css({
        'display':'block',
        'white-space':'nowrap'
        });

    selElm.bind('change',function() {
        jQuery(this).next().text(this.options[this.selectedIndex].text);
        }).bind('resize',function() {
        jQuery(this).parent().width( jQuery(this).width()+'px' );
        });
    selElm.trigger('change').trigger('resize');
    });
}

EDIT again:

it was the trigger 'change' that was causing the problems - I've changed it to click, and it all seems good woohoo!

As ever, thanks for everyone's wonderful advice.

You'll need to wrap the JS in a Drupal behaviour, so that it is attached after the ajax refresh.

You should also ensure it only runs once

 Drupal.behaviors.styledSelect = {
   attach: function() {
     $('select').once('ss', function() {
       $(this).styledSelect();
     }
   }
 };

That way it won't get 'styled' on every ajax change.


How can $build['#attached']['drupalSettings'] change from hook_node_view to javascript? I'm afraid the title isn't clear: I am passing a value from hook_node_view to my javascript in $build['#attached']['drupalSettings'][]. But the value that is set there is not the value that the js is using. I've checked in several places to make sure that this value is indeed the one set in the variable; nevertheless, the js script is getting a different value. I'm sure I'm missing something easy, at least something I should be aware of. The stack trace in the js debugger isn't helpful, so it seems there is some processing happening after the hook is called and the js getting the value in drupal settings.

I had strongly suspected a caching issue while ignoring something more obvious, that the hook was being called several times and passing the value of the last time it's called to the javascript. Just added a check to make sure it's passing the correct value and it solved the issue.


Solution for the URL Alias and question marks issue with Webform I am developing a site in Drupal 7. I am using webform for creating a "contact us" form. After submitting the from successfully, the page is redirected to a confirmation page where the url is http://www.somesite.com/node/11/done?sid=3. I want this particular url as http://www.somesite.com/thankyou.

I tried to set the url alias for node/11/done?sid=% as thankyou. But unfortunately it doesn't work for me.

Any suggestions about a solution for this?

By default, webform will redirect you to an internal URL with the submission parameter sid. The only way to prevent this parameter to being displayed is to redirect the user to an external URL.

What you can do is set up a bit.ly short URL that targets your thankyou page, therefore webform will think it's an external URL, won't add the submission parameter and the user will land on your http://www.somesite.com/thankyou page.


How to overcome "Add new date link" issues in the 7.x-3.4 Calendar? Solved See my solution in the answer below.

I am having an issue with the 7.x-3.4 Calendar, and would like to know if anyone has a solution, or suggested solution, to this issue.

Background: I have created a new content type of "Booking", and have created a new Calendar View that displays only dates of this content type. The Calendar works fine, and if I add new content through my Administrator option of "Add content", I can define my date, taxonomy terms and specific information (such as the Point of Contact (POC) name and email address) without an issue. These display perfectly on my newly created calendar, with a coloured stripe dependant on the taxonomy term selected (just for interest, the taxonomy term defines which room they would like to book). From here however, I have this issue:

In the page to edit the view for the calendar, I select Format > Show > Settings, and get the "Month: Row style options" page. When I select a content type in the "Add new date link"   dropdown box, I do not get an "Add" link on my Calendar. (I have tried all the different types of content, including a content type that all authenticated users are able to, and actively do, create new content within. I have edited the permissions to allow all authenticated users to create content of content type "Booking". As a point of interest, I also use OG, however have not defined an OG "Group" to this content type, and do not plan to align this content type or calendar with any form of OG functionality in the future. I thought it pertinent to mention this in case here is where my problem lies)

I would greatly appreciate any feedback or thoughts anyone has, please do not hesitate to ask for any more information that you feel you may need!

OK, so I have fixed this with a custom work around. There are many modules that I am using that may be interfering with the permissions to add a new date, and be limiting what can be displayed in the view. No matter, here is how I solved it:

First of all, set up the modules and permissions as following:

Go to admin > modules, and find the PHP Filter module, ensure it is enabled:

Next, go into the permissions and find the following:

Ensure that the last option, "Administrator", is selected.

Next, go to the view where you would like to add the "Create Booking" (or whatever content type it is you are after.) From here, create a new header of type "Global: Text area"

What I chose to do next was create a link to a new view, and on this view I expose the form to add the new date/event. If you want to embed the create form here, then skip the next step, however I find doing it this way leaves the current calendar in it's original state, and by clicking the about to be created "+ Add Event" link, you will be taken to a new view that contains the calendar and the exposed form.

Now, select "Full HTML" as the Text format, and place the following code in the text box. This will create a link to a new view, which we will make next. The two lines below are simply coloured text that I will use as a legend for the calendar.

+ Create Booking

When we next create the view containing the form to add the new date/event, if you chose to use a different path, come back here and change "/calendar/create_booking" to your preferred path.

Now, apply changes and save the view. Go back to your Admin > Structure > Views page, and locate the view of your current calendar. Now, on the "Operations" dropdown, select "Clone View"

Rename the newly created view (I called mine "Create {Your Old View Name Here}"). Now, open up the "Edit" option for this view and create a new Header of type "Global Text Area" as before. This time, we want the Text Format to be "PHP Code" and to place the following code in your text area:

<?php
  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('node_type');
  print drupal_render($node_form);
?>

Remember to change 'node_type' to your desired content type. Save the Header, and return to the last screen. Now simply change your path to what you wish:

And now finally, go back to your original Calendar view, edit the header to contain the correct path in the link we made, and you're finished! The form is now exposed for users to create a new event/date. Ensure that you set the appropriate permissions for users to be able to create this content type, and remember that their view of the create form will be much simpler than yours.

Hope this helped you if you had the same issue as me!


Display status message after submitting modal popup form Ok so i have a custom entity and want to display a custom delete form. Have created the Route and everything works except for Drupal messenger displaying status message after submission, even after a manual refresh.
The weird thing is, if i add a ksm() output to hook_entity_delete() which is called after the entity is deleted, the status message does display.
I have added a '?destination=' parameter to the end of the link the initiates the popup, and after submit, the redirect is successful.
Here is my class, which i can get to popup in a dialog window, with the form and successful deletion and window close.
Just to clarify, trying to get the status message to display on the form from where the modal popup was initiated from, not to get the message in an additional popup.
Any ideas?
class TrEntryDeleteForm extends ConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $na_entry = NULL) {

    $entry_id = $na_entry->id();

    $form['title'] = [
      '#markup' => t("
Title
"),
    ];

    $form['description'] = [
      '#markup' => t("
This action can't be undone
"),
    ];

    $form['entry_id'] = [
      '#type' => 'hidden',
      '#default_value' => $entry_id,
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#attributes' => [
        'class' => [
          'use-ajax',
          'cancel',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'closeModalForm'],
        'event' => 'click',
      ],
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Delete'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $entry_entity = \Drupal::entityTypeManager()->getStorage('entry')->load($entry_id);
    $entry_entity->delete();

    \Drupal::messenger()->addStatus(
      t('@msg', ['@msg' => 'Entity deleted.'])
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {

  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    // TODO: Implement getCancelUrl() method.
  }

}

After redirection the \Drupal::messenger() may not work. So try with the Drupal OpenModalDialogCommand
use Drupal\Core\Ajax\OpenModalDialogCommand;

/**
* {@inheritdoc}
*/
  public function submitForm(array &$form, FormStateInterface $form_state){

    $entry_entity = \Drupal::entityTypeManager()->getStorage('entry')->load($entry_id);
    $entry_entity->delete();

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand("Success", 'Entity deleted.', ['width' => 800]));
    return $response;
  }


Migrating site from localhost to production some images does not show I am in process of creating a new website from old Joomla based site. I manage to import with feeds module all the old content.
On the localhost server there is no problem but on production server all of the imported images and their derivatives are not showing.
The problem links looks something like this

news_thumb/public/field/image/274f1bf2bd18e7f0d33d6244e658426e.jpg?itok=AUwo0SYX

My first suggestion was that this images have problem with the image style 'itok' token

Any suggestion would be deeply appreciated. Thanks.

What I tried so far:
First all images were imported with single space after the extension so the link looks like this:

news_thumb/public/field/image/274f1bf2bd18e7f0d33d6244e658426e.jpg%20?itok=AUwo0SYX

I didn't catch it before uploading finished site on production where all the images disappeared so I thought that this is the problem and after trying some weird things with no avail import again all joomla based content without the space.
Second I presume that I have some problem with itok token and flushed all images and regenerated them again.

Now I uploaded the whole site on different hosting where all worked correctly so after conversing directly with the gays from original hosting company it turns out that they are updating their server on the fly during working hours and all my jumbo mumbo with database and files were restored few times on the row.

So I finished with apologies from them and one day spend searching for something that was not there.

First, make sure your images are actually uploaded to the server and accessible (go to http://SITEURL/sites/PATH/TO/IMAGE/DIR/image/274f1bf2bd18e7f0d33d6244e658426e.jpg to check), then make sure the file and directory permissions are correct. Check the admin/config/media/file-system page, and click "save" – if it's not setup correctly it should display an error message and you'll most likely have to change directory permissions.

Don't worry about the tokens or anything after .jpg (ie: ?itok=AUwo0SYX) –– those are merely for cache-clearing, and can be safely ignored, it has no impact on accessing the images on the server.


How to set type="email" attribute on a Drupal form textfield I'm doing some mobile forms with Drupal and have an email address textfield that currently has type="text" in the resulting HTML. I'd like this to be type="email" instead so that iOS shows a more useful keyboard when entering the email address.

I tried adding:

"#attributes" => array("type" => "email")

to my field but it seems to just get ignored by Drupal. Is there a correct and/or supported way to achieve this?

Elements which are input[type=email] are a builtin as of Drupal 8. They can be added (along with other HTML5 elements and markup) to Drupal 6 or 7 via the Elements module.

As of writing this answer, I found the Element-module docs quite scant; they don't explain that the method for getting an e-mail input-element is slightly different than how it's done in D8. For Drupal 7:

/**
 * Implements hook_form().
 * "For long-lasting relief you can count on!"
 *
 * hook_form() functions are passed a form-node,
 * plus extra state-info if present.
 *
 * At the end of the function, the form-node should
 * be returned to the caller.
 *
 */
function mymodule_form($node,&$form_state) {

    $node['primary_email'] = array(
        '#type' => 'emailfield',
        '#title' => t('Submitter'),
    ); // in Drupal 8, it's '#type' => 'email'

    return $node;
}

Be sure to have the Elements module enabled before you expect the above to work. Also, if you haven't already, you'll also want to make the form accessible by doing something like:

/**
 * Implements hook_menu().
 * "Money back guarantee!"
 */
function mymodule_menu() {

    // create primary menu-entry for module:
    $items['mymodule'] = array(
        'title' => 'My Very Own Module',
        'page callback' => 'mymodule_description',
        'access callback' => TRUE,
        'expanded' => TRUE,
    );

    // create menu-entry for form:
    $items['mymodule/myform'] = array(
        'title' => 'My Very Own Form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('Behold, the form.'),
        'file' => 'mymodule.module',
    );

    // ...[maybe add more stuff here]...

    return $items;

The other elements made available by Element are listed at cgit.drupalcode.org/elements/tree/elements.module#n7.


How to override a service I am trying to override a service by using a ServiceProvider Class

class MyModuleServiceProvider extends ServiceProviderBase
{
    public function alter(ContainerBuilder $container)
    {
        // Overrides MessageNotifier class to add loggin facilities to each message.
        $definition = $container->getDefinition('message_notify.sender');
        $definition->setClass('Drupal\my_module\MyModuleMessageNotifier')->addArgument([
            new Reference('logger.channel.message_notify')
        ]);
    }
}

This is out of topic, but FYI, the overrode service "message_notify.sender" is created by the message_notify module pertaining to the message stack modules

As you can see, I am adding an argument (a logger) to my new service

Here is the __construct() method of the parent (overrode) class:

  public function __construct(Manager $notifier_manager) {
    $this->notifierManager = $notifier_manager;
  }

Here is the __construct() method of my new class:

    public function __construct(Manager $notifier_manager, LoggerChannelInterface $logger)
    {
        parent::__construct($notifier_manager);
        $this->logger = $logger;
    }

But for an unknown reason the $logger variable is not an object but an array with one item... and this item is the LoggerChannel object.

Thus this code is not working but the following does:

    public function __construct(Manager $notifier_manager, array $logger)
    {
        parent::__construct($notifier_manager);
        $this->logger = $logger[0];
    }

What am I doing wrong?

The problem is that you are adding your argument as an array, so your __construct() method receives an array. So this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')->addArgument([
  new Reference('logger.channel.message_notify')
]);

Should be this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')
  ->addArgument(new Reference('logger.channel.message_notify'));

(notice that the Reference is not wrapped in an array.


Advice concerning lay-out homepage I'm having a bit of an issue here and I'm hoping for some professional advice.
Here is my situation:

That's my homepage. In the upper part, there is an image slideshow (no issues there), but underneath are 3 textblocks. The text inside those blocks is quite static but the end-user has te be able to change the content. The tricky part is it can't be blocks or panels. So the one thing I can think of is make a content type for those blocks and use a view filter to show those 3 blocks. But even then, I'm not quite sure on how to do this...

Is there anyone here who can advice me about this issue? Or alternatives on how to tackle this?

I would still use blocks for this, because I always prefer to use the most appropriate and lightweight solution for the data storage, and then tweak the admin interface to enhance usability.

You could solve this with a special content type, combined with views or display suite. However, experience has taught me that if you're creating a content type for a small, fixed number of nodes, it usually means that there are better solutions out there.

You are right that the blocks page is too complex for many users. To solve that problem, I would:

Create the 3 blocks;
Enable the Contextual Links module (part of Drupal 7 core) to provide edit links on the blocks, right there in the front end;
Install and configure Block Access to make only those 3 blocks editable by the site maintainer;
Implement hook_form_alter to hide specific form fields from the site maintainer on the block edit form.


Custom Views Filter - won't display as checkboxes Trying to do a custom filter so that the user can select multiple states to filter the data by.  This works (or will when I do some customizing to the query after) but it shows a select box.  Any ideas?  Tearing hair out :)

<?php
class custom_filters_handler_filter_state extends views_handler_filter_string{
  function value_form(&$form, &$form_state){
    $options = array(
     'DC' => 'DC',
     'MD' => 'MD',
     'VA' => 'VA',
    );
   $form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   );
return $form;
  }
}

I've the same issue, debugging the code I've seen that the exposed_translate() method changes any checkboxes form types to select if $form['#no_convert'] and #multiple are not set.

So you need to change it to:

$form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   '#no_convert' => TRUE,
);

Here is the code:

/**
   * Make some translations to a form item to make it more suitable to
   * exposing.
   */
  function exposed_translate(&$form, $type) {
    if (!isset($form['#type'])) {
      return;
    }

    if ($form['#type'] == 'radios') {
      $form['#type'] = 'select';
    }
    // Checkboxes don't work so well in exposed forms due to GET conversions.
    if ($form['#type'] == 'checkboxes') {
      if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
        $form['#type'] = 'select';
      }
      if (!empty($this->options['expose']['multiple'])) {
        $form['#multiple'] = TRUE;
      }
    }
    if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
      unset($form['#multiple']);
      $form['#size'] = NULL;
    }

    // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
    if ($form['#type'] == 'select') {
      $this->prepare_filter_select_options($form['#options']);
    }

    if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
      $any_label = variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('<Any>') : t('- Any -');
      $form['#options'] = array('All' => $any_label) + $form['#options'];
      $form['#default_value'] = 'All';
    }

    if (!empty($this->options['expose']['required'])) {
      $form['#required'] = TRUE;
    }
  }


need to show user firstname and lastname in search result page I'm very new in drupal, and I have a custom user module where I need to show the user's first name and last name in the search result page. I used some of my code which is throwing a fatal error.

What is wrong with the code I am using?

function somik_user_byline($uid) {
  $cache = &drupal_static(__FUNCTION__, array());
  if (isset($cache[$uid])) {
    return $cache[$uid];
  }

  $account = user_load($uid);
  $byline = $account->name;

  $first_name = somik_user_profile_field_value($uid, 'field_firstname');
  $last_name = somik_user_profile_field_value($uid, 'field_lastname');

  if ($first_name && $last_name) {
    $byline = $first_name . ' ' . $last_name;
  }

  $cache[$uid] = $byline;

  return $byline;
}

For your error replace:

<?php print drupal_render(somik_user_byline($user->uid)) &nbsp .$info_split['date']; ?>

with

<?php print somik_user_byline($user->uid) . '&nbsp;' . $info_split['date']; ?>

For preprocessing you would use:

/**
 * Process variables for the search result template.
 */
function THEMENAME_preprocess_search_result(&$variables) {
  // Change variables here.
}

There is some more info here http://drupal.org/node/223430
It also links to some other useful related pages.

You need to clear the drupal cache when you add or remove a preprocess function.

Edit:

For your "Fatal error: Can't use function return value in write context"

It is because of this part:

if (!empty(somik_user_byline($user->uid))) {
  $info['user'] = somik_user_byline($user->uid);
}

Because you can't pass a function call into the empty() function like that. You need to give it a variable.

Because your somik_user_byline() function is always returning a string you can do this:

if ($name = somik_user_byline($user->uid)) {
  $info['user'] = name;
}

You can go even further than that still.
Because your function always returns a non-empty string, you can just do this:

$info['user'] = somik_user_byline($user->uid);

Also, for it to be available in the template you have to add it to the $variables array.

For example, you are setting $info but to have it in the template you have to do

$variables['info'] = $info;

at the end and then $info will be available in your template file.

Also, in this case, $info is already full of other information to remember that this will overwrite whatever was alredy in $info from other modules.

If you want to keep the $info that is already there, but override the $info['user'] and $info['date'] parts, do this:

/**
 * Process the variables for search-result.tpl.php
 */
function somik_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Override the user part of the info array.
  $variables['info_split']['user'] = somik_user_byline($result['node']->uid);
  // Override the date part of the info array.
  if (!empty($result['date'])) {
    $variables['info_split']['date'] = format_date($result['node']->created, 'short');
  }
  // Re-create the info string with the overridden data.
  $variables['info'] = implode(' - ', $info_split);
}


How to include "Page Updated" in the footer of my drupal 7 site? I would like to display a "Page Updated" snippet in the footer of my site. Is there a module which I can use, and then include as a block?

There is no module specifically to do that. Its very easy todo as you just put the message variable in the bottom of your footer. Just find the message variable in your page.tpl.php file. search for message and copy that $variable to the bottom of the page.


Insert a node field programmatically I have a
 containing a node (a Basic Page), which has a title, body and a header image. I do not want to display the header image inside that div, so I removed it from the block layout. I would like the header image to be in the html before the
, that is, outside of the div into which the given content type is outputted (so I cannot solve this via block layout, since the image field is to be outputted outside of the content block).

Can I somehow programmatically instruct my theme to display the header image of my Basic Page? Or is there a better way how to do it?

Example:
I need to change this:

Title

body

to this:

Title

body

You can put php code in a block template and write something like:

$node = node_load($node_id);

and then access the specific field you want to show like:

print $node->title;
print $node->field_yourfield["und"][0]["value"]

Edit:

Also, you can modify the node template for the teaser, copying the node.tpl.php file in your subtheme (you can look how to make a subtheme here) and putting the html structure you want inside:

if($teaser)
{
...
}

There are other displays available for nodes other than page and teaser.


field_get_items('user', $user, 'field_name') empty? I have a added data to the user using:

taxonomy_term_reference

when creating the

field_create_instance($instance)

and everything is working fine, I can add and store values and these are added to the specified vocabulary.

The problem is, I cannot extract the value added as a term to the $user object using field_get_items and field_view_value since field_get_items('user', $user, 'field_name') is empty.

Is field_get_items and field_view_value not applicable to $user?

I was experiencing the same issue. field_get_items was always empty when trying to get a field attached to a user. The problem was that the $user object you get when you do a

global $user

isn't the full entity. So when you pass it into the field_get_items function, it doesn't match anything.

Do a full user_load on the $user->uid and THEN pass the resulting object to field_get_items, and everything should work.


How to wrap body text around image for drupal 8 How to wrap body text around image for drupal 8. I found tutorial for drupal 7 here https://www.drupal.org/forum/support/post-installation/2008-06-30/how-to-wrap-body-text-around-image, but I still confused to implement this for drupal 8.

I found some css files inside css folder and which one that I have to edit?

Don't edit css files in a contrib theme, because the changes will be overwritten when updating the theme. Create a subtheme and add a library with your own css file, see https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme


How to use a custom block template when the block is embedded in a panel pane? I have a block that I have templated and want to use in and out of a panel layout in various parts of my site.

So to template the block I opted to install the block_machine_name module which gives a good anchor point for the template so the block id is not relied upon (as this changes between my dev and prod sites).

Then I theme the block and it works just great using a template name like block--sweet-name.tpl.php

Then I also use the block in a panels layout and things start to go wrong.
The block template is now ignored.

So I am trying to find a way to get panels embedded block to respect block templates.

Is this possible?

If you need to use the block template in panels, make sure you choose the style from the panels option to be "Systems block".

This lets you use block--sweet-name.tpl.php.


Delete all nodes of a user using flags and rules I want to delete all nodes for a user whoes any one node has been flagged as spam.

For example:

If user has created 3 nodes of same/different content types, then If admin flag any one content as spam, then all the 3 nodes should get deleted and the user should get blocked.

I am able to block the user and delete the flagged node but not the other 2 nodes. I want to delete all nodes associated to that user.

Please help.

I did in this way without writing a single line of code.

1) Add action: Fetch entity by property: Choose Entity type as 'Node', Property as 'Author' and Data selector as 'flagged-node:author'. Choose variable label ('spam nodes' in my case) and variable name ('spam_nodes' in my case) as you wish.

2) Add Loop: Select Data selector as 'spam-nodes' (this will show as per your  variable label in step 1). Set variable label('spam node' in my case) and variable name('spam_item' in my case) as you wish.

3) Now click on 'Add action' link under 'Operations' column against the loop you have added in step 2. Select 'Delete Entity' and set the Data selector as 'spam-item' (this will show as per your variable label in step 2).


Rule for allowing purchases based on country I'm running a commerce shop where we're gonna sell stuff we don't have worldwide rights to.

By using the countries module I've ticked of which countries we can sell each product in by having a countries field on products. (see screenshot below).

I'm thinking it must be possible to make a rule banning to sell a product in a territory that hasn't been ticket of. It should be the billing country of the customer that needs to be validated against what countries the product is sellable in.

Any ideas on how to configure a rule (or another solution) that does this check?

Cheers

You can use Smart IP to determine the location of the user and with the help of drupal views, you can filter the products not available for sale on that country.

That means only the products which are OK for sale in that country will be displayed to the user..


Add element to form during (element) validation checks I'm trying to make a module that offers an #element_validate function which will check the element for dodgy looking data and if this is detected, tell the user this looks invalid and add a 2nd element to the form which can then be used to validate the dodgy-looking data.

The problem I'm having is that:

To add an element you need the form to rebuild. (see code referenced in the comment below)
To trigger a rebuild the form must have passed validation

This means that:

the #element_validate function cannot use form_error - else it would not be able to add the 2nd field. So I've had it instead set $form_state['rebuild'] = TRUE and issue a warning with drupal_set_message().
adding the 2nd element will only happen when there are not any other validation errors on the form (since these would also prevent the form rebuilding) leading to a confusing situation for the user: they will see the warning asking them to complete the 2nd element that doesn't exist. They'll correct the other errors on the form re-submit and then get that back again, this time with the 2nd element, which they'll have to complete before their submission is accepted.

Is there a way around this? e.g. a way to force a rebuild of the form from validation?

Here's how I've got around this issue.

When defining the element, add in:

#pre_render
#form_id
#element_validate

Here's the algorithm:

User completes normal form, entering something suspect.
The validation function picks up the suspect value and stores a note that this form (uses #form_id) and element has a suspect value on a global variable. It also uses form_error() to inform the user of the problem.
The #pre_render function is called for the element. This function does not get the form object at all, which is why we specifically added #form_id to the element. Using this we can check the global variable for this form and see whether suspect data was found. It was, so add another form element in asking for confirmation. This element is not part of the Form API, so as well as the usual ('#type' => 'textfield' etc. we need to explicitly set '#name').
User confirms the data on the new form element and re-submits form.
The validation function notices the confirm data in $form_state['input'] (it won't be in values because this element is not part of the Form API's form) and compares it to the submitted value. It matches, so it does not call form_error().
Assuming no more errors, form submission continues.

I've also implemented a thing for storing the confirmed suspect value in a hidden field in case other fields fail verification, meaning the user only has to confirm the data once.

Use case

My specific use case is an email validator module. Beyond the drupal sytax check it can lookup DNS records and then conduct an SMTP conversation with a server to see if mail is accepted. Some of the SMTP errors can be temporary and so we use this chance to tell the user "hmmm. we got this error (user-friendly version of error goes here) - might be a temporary thing but can you double check your email?" allowing them to complete the form while still helping them avoid typos.

My email_validator module on github


How do I display my custom menu in administrative menu? In my D7 website, I want to display my own custom menu in administrative menu (as in Dashboard, Content, etc.,).

I want those custom menu's available only for particular roles. How can I achieve this functionality without lot of code?

Thats Easy. You need to goto structure >> menus >> Management. From there you can click on add link and add the menu link in that , it will automatically get added to the administrative menu toolbar.

Making that to be visible for specific roles , you need to give permission for overlay in that you need to enable this permission for that role Access the administrative overlay.

That will make your menu appear as administrative menu for what ever role you specified in permission tab of admin.


My site language is undetected? My D7 site uses Hebrew as it's default language, and though, an application such as SEOquake told me that the language is undetected. now, that's not an SEO question and it has really nothing to do with SEOquake, i just use it as an example for the given situation of an external device not detecting the language.

I have been told to add the following input, but i have no clue how to do it on Drupal, not even at the TPL files (if it's even a starting point), the input:

<html dir="rtl" lang="he-IL">

How could i apply this to all pages of the site?

Thank you very much.

I have this in my html.tpl.php file:

<html
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="<?php print $language->language; ?>"
    version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"
>

where $language is a global object, it prints, in my case:

<html
    xmlns="http://www.w3.org/1999/xhtml"
    xml:lang="en"
    version="XHTML+RDFa 1.0" dir="ltr"
>

Check out the variables available to you in html.tpl.php.

Make sure to clear your cache after you change the template.

EDIT: Full contents of html.tpl.php:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"
    <?php print $rdf_namespaces; ?>>
    <head profile="<?php print $grddl_profile; ?>">
        <?php print $head; ?>
        <title><?php print $head_title; ?></title>
        <?php print $styles; ?>
        <?php print $scripts; ?>
    </head>
    <body class="<?php print $classes; ?>" <?php print $attributes;?>>
        <?php print $page_top; ?>
        <?php print $page; ?>
        <?php print $page_bottom; ?>
    </body>
</html>


Export configuration translation Using Drupal 8, I need to create several content types. They'll be used in a multilingual site, so I installed the Configuration Translation module from the core to translate the field labels. I can succesfully do that, but I need to create a feature (using Features module from the core) to export the content types and import them easily in the production site.

The problem is that the Features module doesn't export the configuration translation, even including the languages in the feature.

Is there any way to export the content types with their configuration translation and import them seamlessly into another site?

Exporting the entire site with the Configuration Synchronization seems to do the trick, but is more difficult to import because requires a clone site, and I only want the content types.

Anyway. You can back up the database with the back up and migrate module and import to your live site. The other tool can be drush cex for exporting configuration and drush cim for importing it.


How to upload a static copy of a pages HTML to S3 I have a need to upload a copy of a rendered output of a URL to Amazon S3 when it is edited and published.

By this I mean if I was to edit /brand-a/page-1 on a site, I would like the full rendered output of that page as seen by an unauthenticated user to be uploaded to /brand-a/page-1 in a S3 bucket. Essentually using Drupal as a content publishing platform offloading all delivery to the end user to Amazon S3.

I am comfortable using the Amazon S3 + AWSSDK + Libraries plugin for handling of media, I have not been able to find a plugin that covers off my requirements highlighted in red in the above diagram.

If you want to speed up the transfer process you could use HTTPRL to send the data to S3 in a non blocking request. You can also use it to do threading.


Calculate values from multiple content items I have a Drupal 7 website that will be used to track automobiles in a fleet, as well as their engines and a few other items. Regarding the engines, I will be tracking the number of hours the engine is used, and the number of miles put on the engine in each use. To do so, I have an "Engine Usage" content type set up with fields for "hours used this trip" and "Mileage this trip". Each time the Engine is used, a new Engine Usage content item will be created manually, and the hours/miles will be entered into those fields. The Engine Usage content type is linked to the Engine content type/item by way of the Node Reference module.

I now need to create a View that will pull in the information for the Engine content item (its specifications, etc), as well as the total usage for that Engine by way of its related/linked Engine Usage content items. Instead of displaying each of the usage items separately, I need to apply a calculation to them, in the form of "Engine Usage for content item Engine123 'Hours driven'" multiplied by "Engine Usage for content item Engine123 'Mileage this trip'". I have looked into Views Calc, bu I cannot figure out how to first combine all of the Hours for the Engine Usage content item for any given engine, and then combine all of the Mileage for the Engine Usage content item for any given engine. If I can get to that point, I think I can then figure out the rest of the calculation on my own.

The end result will be a View block with a contextual filter that will pull the info in based on the ID of the content item being viewed. So when viewing the content item Engine123, the block with the calculated hours * mileage for Engine123's usage content items would be displayed.

Any ideas? Please let me know if any of this is too vague.

did you try to use the Aggregate option (use SUM field aggregation option) and Views Calc at the same time ? That might do the trick.

If not, you can use a PhP block (you have to send it the engine node id, I hope you use Panels or node.tpl.php).

Then, the code would be (I guess) ;

$engine_usages_nids = db_select('yourentityreferencefield', 'n')
  ->condition('entity_id', $the_engine_nid, '=')
  ->field('n', 'field_yourentityreferencefield_nid')
  ->execute()
  ->fetchCol;

$myfields_values = $db_select('field_data_hoursuagefield', 'h')
    ->condition('entity_id', $engine_usages_nids, 'IN')
    ->join('field_data_mileagefield', 'm', 'h.entity_id = m.entity_id)
    ->fields('h', array('hoursuagefield'))
    ->fields('m', array('mileagefield'))
    ->groupBy('h.entity_id')
    ->execute()
    ->fetchAssoc;

$total = 0;
while($record = $myfields_values) {
  $total = $total + intval($record['hoursuagefield'])*intval($record['mileagefield']);
}

echo($total);

This is all made by heart, I advise you to double-check :)

Have fun !


Database API and Security I'm working on a controller that queries a table based on the value in a route parameter

Example route path:

path: '/path/{parameter}'

Controller:

  public function myFunction($parameter) {
    $connection = \Drupal::database();
    $query = $connection->select('my_custom_table', 'mct');
    $query->condition('mct.col', $parameter, '=');
    ...
    $result = $query->execute();
    $records = $result->fetchAll();

Is there any sanitization that should occur in this circumstance or does the database API take care of this?

For input, saving to the DB, Database API takes care of it, automatically prevents SQL injection when using dynamic query. Since your code is using dynamic query, you're all good.

If you were to use static query you have to make sure you use placeholders as the docs mention.

For output, to prevent XSS, you'll want to use a template file, and print your value via Twig. Which auto escapes everything by default. If you don't use Twig, then you need to use the appropriate API function.


How do I set the theme logo? How can I set the logo in my custom theme in Drupal 8?

I can see that Drupal looks for the logo.svg file. I have a PNG logo.png file that I used in Drupal 7 and I would like to re-use it. I cannot set the logo as a theme setting as in Drupal 7.

Is there a way through UI or custom code in the theme to set the logo?

After Drupal 8.6.x

In your THEME.info.yml add a line like logo: logo.png. You need to clear cache for Drupal to detect this change.

Before Drupal 8.6.x

Default logo file has now become logo.svg in Drupal 8. However, to use logo.png or something else, you need to add custom settings definition in your theme. To do this, add the following lines to config/install/THEME.settings.yml file in your theme folder (replace THEME with your theme's machine name).

logo:
  path: 'themes/THEME/logo.png'
  use_default: false

After doing this, you must reinstall your theme if already installed. The file asks Drupal to install the given settings when the theme is installed. Hence, when you install the theme, the logo path parameter gets saved to the database and the default logo is disabled by the use_default parameter.


Help me with my page, when open this page shows me this: PDOException: SQLSTATE[HY000]: General error: 145 Table './mapibrasil/watchdog' is marked as crashed and should be repaired: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => The file permissions could not be set on %uri. [:db_insert_placeholder_3] => a:1:{s:4:"%uri";s:18:"public://languages";} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://brasil.machupicchu.biz/ [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 190.237.102.164 [:db_insert_placeholder_9] => 1403795901 ) em dblog_watchdog() (linha 160 de /srv/www/machupicchu.biz/public_html/modules/dblog/dblog.module).

Not a drupal question, but you need to repair your table in the MYSQL database, if you can access the db server via command line:

REPAIR TABLE <table name>;

Otherwise, tools like phpmyadmin have repair tools, check this tutorial: http://www.siteground.com/tutorials/phpmyadmin/phpmyadmin_optimize_database.htm


How to count webform radio button submissions What would be the best way to count all submissions (True & False) of a radio button type in a web form?

There are about 100 radio buttons in each survey form so need to get a total number of True values

If you want do the number count after submit is done

Login as Admin
open your webfrom
Click Result
From webfrom menu click Analysis

It will give you the most complete Analysis of your form.


$GLOBALS['user']->uid returns same uid for different logged in users? I'm implementing hook_menu in my custom module. Implementation works fine except, it turns out that $GLOBALS['user']->uid returns always same value no matter which user is currently logged in. Sounds absurd! What could be the problem?

Below is a full hook_menu:

function my_tab_menu(){

    $current_user_id = $GLOBALS['user']->uid;  // $current_user_id=202 for each

    $query = new EntityFieldQuery();
        $result = $query
                ->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'profile')
                ->propertyCondition('status', 1)
                ->propertyCondition('uid', $current_user_id)
                ->propertyOrderBy('created', 'DESC')
                ->range(0,1)
                ->execute();

    if (isset($result['node'])) {
        return array(
        'user/%/alumni-spotlight' => array(
                'title' => 'Alumni spotlight',
                'page callback' => 'user_tab_page',
                'page arguments' => array(1,$result['node'],$current_user_id),
                'access callback' => 'user_tab_access',
                'access arguments' => array(1),
                'type' => MENU_LOCAL_TASK,
            ),
           );
    }
}

Hook menu is not for non-menu functionality.

Using %user in the menu item will call user_load() with whatever is in that part of the url (in this case the uid) and then when that part of the url is used in callback or access arguments it will pass in the loaded user object instead of the user id.

See wildcard loader arguments for more info on that.

To control who sees the tab, do your database check in the access control callback and deny access if there is no result. This way the tab will only show if there is a node.

Callbacks like the access control call back and the title callback run every time, not just when the cache is refreshed, so it is ok to use them in this way.

Try

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();

  $items['user/%user/alumni-spotlight'] = array(
    'title' => t('Alumni spotlight'),
    'page callback' => 'MYMODULE_user_tab_page',
    'page arguments' => array(1),
    'access callback' => 'MYMODULE_user_tab_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Access callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_access($user) {
  // Do something here to check access & return TRUE or FALSE to grant access or not.
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'profile')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $user->id)
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1)
    ->execute();

  // If there is a node, allow the user to access the page.
  if (isset($result['node'])) {
    return TRUE;
  }

  // If there is no node, deny access.
  return FALSE;
}

/**
 * Page callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_page($user) {
  // Return the content of the page.
}


How can I add a field to a content type which will accept a price value in the format of a currency? I need to have price field which will display a price field. This field is a number with the dollar sign (i.e. $200). In my view, this price field will be used for sorting also.

I have installed and enabled the currency module and the currency API.

Via structure > content type > manage fields > I tried to add a new field. But the list of field types do not have the 'currency option'. So I am not sure how I should add the currency field with a dollar sign.

My question: How can I add a field to a content type which will accept a price value in the format of a currency?

UPDATED ANSWER:

using Views field rewrite:

on the field in the view setup, in the "rewrite results" section of the editing modal select the checkbox "Rewrite the output of this field" then scroll down and open the fieldset "REPLACEMENT PATTERNS" and use the pattern there to rewrite your field in the above textarea. as an example to put a "$" in front of the users uid I used $[uid]

CCK field prefix:

You may just want to use a field that is for currency but doesn't actually include the currency symbol, so it can be saved as a number, which allows for better sorting. Then using views you can set a prefix to a displayed field of the desired currency symbol. This may only work with CCK fields.


Alter paragraph fields in closed mode I was wondering if there is a way to alter paragraph fields when the paragraph is set to "closed" in the Edit mode setting of form display. Because in that case the hook_field_widget_WIDGET_TYPE_form_alter does not return any of the inline paragraph fields inside the $element['subform']

To give a little more details, there's a paragraph field that holds some more native fields within itself. When I am trying to add/edit the node with which it is attached, i want to alter some fields within the paragraph. Since the paragraph is closed the fields within will be rendered via ajax call on the fly. I was looking for a way to alter them during this ajax call, that is just before they get rendered in the form so that I can alter their attributes.

Any idea?

I think there are two approaches you could take here. In the past I've successfully extended the InlineParagraphsWidget field widget in order to alter the form display for Paragraphs. I think that hook_ajax_render_alter() might also be a good solution.

I have not used hook_ajax_render_alter(), but I have successfully extended InlineParagraphsWidget for the purpose of altering the AJAX response. Specifically, look into overriding the ::addMoreAjax() and ::formElement() methods.

Below is a simplified version of the ::addMoreAjax() callback that I used. Use $insert_element = parent::addMoreAjax($form, $form_state); to get a reference to the triggering element.

public static function addMoreAjax(array $form, FormStateInterface $form_state)
    {
        $insert_element = parent::addMoreAjax($form, $form_state);

        // TODO: This is NOT the cleanest way to find the wrapper ID.
        // Find a cleaner way to get these values.
        $wrapper_id = explode('"', $insert_element['#prefix'])[1];
        $pos = strrpos($wrapper_id, '--');
        $wrapper_id = '#' . substr($wrapper_id, 0, $pos);

        // If you needed the field name.
        $field_name = end($insert_element['#parents']);

        $response = new AjaxResponse();
        $response->addCommand(new InsertCommand($wrapper_id, $insert_element));
        return $response;
    }

You will probably also want to provide validation by overriding ::elementValidate().

You will also likely need to implement hook_field_widget_info_alter() in order to make your new widget active.

function my_module_field_widget_info_alter(array &$info)
{

    $info['entity_reference_paragraphs']['class'] = MyCustomInlineParagraphsWidget::class;
    $info['entity_reference_paragraphs']['provider'] = 'my_module';
}

Happy coding!


Links in view - wrong language selection Ok, I'm not sure where should I go with this problem, so forgive me if this is not the exactly best place for it.

I've created multilanguage site, of course, got many problems, but solved them all - so far. Now, when I launched german version of a site, I realized there's a problem. I have a content type of X, made a view to display a page containing table with all the X content types. Just usual listing. The link to it is in the menu, displaying only for german language. So far all in that version worked fine, but now I see there's a problem.

Content X - link for adding it is on german version only and while adding it, it works fine. But when I'm on my view page, when I click on any title of content X type (which is a link of course) I'm getting redirected to default site language. And it should stay on german version. I can't think of any ideas, so: what is wrong? How can I fix it?

I found the solution here after one day struggling with same issue:

goto: Home » Administration » Configuration » Regional and language » Languages.
select the 'DETECTION AND SELECTION' tab.
Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'


Taxonomy Terms List and Features I noticed that, while I am able to build taxonomy into my feature, it doesn't seem to include the list of terms within the taxonomy. When I go to create a feature, the uuid_term section does list a few, but not many, actual terms for me to select. What am I missing? It's worth mentioning that I am starting with a Demo build and customizing from there. The only terms that are actually listed are not showing up in Structure > Taxonomy.

I tried upgrading UUID to no avail.

Drupal 7.54
UUID 7.x-1.0
Features 7.x-2.10

You must have Features, UUID and UUID Features modules enabled. In the uuid_features configuration, admin/structure/features/uuid_features, select " Auto detect uuid terms. When exporting a vocabulary, include its terms."


How to expand menu items by default? We are having an issue where the "Show as expanded" checkbox is false whenever a new link is generated regardless of menu link weight.

Using the Superfish module we are displaying the menu block and tried to the following below to see if we can have the menu links expanded by default. However, during testing this is failing. We are using the latest Bootstrap theme as our base theme.

Test case:

1) Create a menu link for custom-menu
2) Navigate to admin page to view all the menu links
3) Click on edit on the menu link item
4) The Show as Expanded is disabled

Code (only hook in my .module file):

function mymodule_menu_link_alter(&$item, $menu) {
  if($item['menu'] == 'custom-menu')
  {
    $item['expanded'] = 1;
  }
}

I tried your custom hook call, just to be sure it was called as you imagine, and to see how the $item array was build.

First, according to the hook_menu_link_alter() documentation, their is only one argument to this method in Drupal 7 (&$item).

And when I print the $item element, I can see that the name of the menu of the current element is not 'menu' but 'menu_name'.

Then your code must be something like :

function mymodule_menu_link_alter(&$item) {
  if($item['menu_name'] == 'custom-menu')
  {
    $item['expanded'] = 1;
  }
}

It is an interesting hook, because it is also called when a user add a menu directly from a node form options.


How to get drupal module path in javascript? I'm trying to use this: var path = Drupal.settings.mymodule.basePath;but I'm getting this error: Uncaught TypeError: Cannot read property 'basePath' of undefined.

First of all you need to call drupal_add_js() with a 'settings' parameter. This will inform your Drupal.settings javascript namespace about the settings/variables you need in this file via drupal. Try the following :

Lets suppose you want to call a specific *.js file on a nodes' view page, call it as :

drupal_add_js(array('myModule' => array('basepath' => '<your-drupal-base-path>')), 'setting');

This basepath is global and you can get it in any *.js file called at this point. Next, you can use this basepath in your *.js file as :

var path = Drupal.settings.myModule.basepath;


programmatically change link URL in view I have a view that shows all of a particular user's content (content the user has created on the site). This works fine, but I need to link the results (title field) to the pages where the content is displayed - not to the original node of the created content.

Since the content types may be different, I guess I need to set the URL's programmatically.

For example one content type is "projects" projects are displayed at site.com/projects/!arg

Another content type is "photos" photos are displayed at site.com/photos/!arg.

How do I write a conditional that will set the URL's correctly?

I don't recommend to use views php module,

Menu item with callback:

The idea here is to override all the links of the titles in your view with one link which pass an argument to custom menu callback, then in the callback, you write your PHP code which does the routing.

to implement this solution you need to do the following:

1- Override the link in the view

2- Create callback using hook_menu():

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['my-routing/%node'] = array(
    'title' => 'Custom callback',
    'page callback' => 'my_custom_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

3- Create your custom callback to do the routing:

function my_custom_callback($node) {
  switch ($node->type) {
    case 'product' :
      drupal_goto('project/' . $node->nid);
      break;
    case 'post' :
      drupal_goto('blog/' . $node->nid);
      break;
  }
}


Problem with login page On my drupal website every page with "/nl" in the url, give an error.
Only the home page works, because there is no "/nl" in the url.

Example:
Home page: http://wnl.be/
All other menus, links, ... on the website give errors, such as http://www.wnl.be/nl/wagenpark

The big problem is that the login page also "/nl" contained in the url. You can test it: www.wnl.be?q=user/login

How can I fix this?

Seems you have infinite redirection which causes the page not to load. (stops after x redirects)

It happens on every page (the once that load and the once that don't load) see my screenshot of the network tab to see it in action:


Programmatically create taxonomy term How would you programmatically create taxonomy term? I wish to bulk create some in a custom module.

You'll want to use taxonomy_save_term. The array you pass in to taxonomy_save_term should look like this.

$term = array(
 'name' => 'Taxonomy Term 1',
 'vid' => 1, // The VID of the vocabulary this term should be saved under
 'description' => 'A description of this term', // Not required
 'weight' => 5, // Not required
);
taxonomy_save_term($term);


Problem w/ Migrate Source CSV importing Body content w/ HTML I am using migrate_source_csv to import node body fields. The header for my CSV file is: "nid, title, body". The body fields contain HTML. My problem is that, on import, the HTML is being encoded into literals. See the screen grab below. Here is my migration YML file:

id: news_article_nodes
label: News article data we want.
migration_group: gdg_group
source:
  plugin: csv
  path: 'modules/custom/gdg_migration/import/news_article/news_articles.csv'
  ids: [nid]
  header_row_count: 1
process:
  nid: nid
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: full_html
destination:
   plugin: entity:node
   overwrite_properties:
     - body
   default_bundle: news_article

I must be missing something. Is there a plugin that imports the data as plain text?

You could try to use PHP's html_entity_decode() on the source field:

process:
  nid: nid
  title: title
  body/value:
    plugin: callback
    callable: html_entity_decode
    source: body
  body/format:
    plugin: default_value
    default_value: full_html

PS: You've written that your source CSV doesn't contain encoded entities... have you checked the display settings for your field? (Manage > Structure > Content types > NODE_TYPE > Manage display). It could be that the import is correct, but the render settings are incorrectly set to something like plain text or a |raw filter in a Twig template file.


An URL that is all parameters I'm building a website related to videogames. There's a view that shows all videogames catalogued in the website, using taxonomy terms as arguments, that is:

mysite.com/games/genre/platform

The problem is that the "games" part in the URL is unnecesary: everything is games. For SEO reasons we want to remove this part, so, for example, this...

mysite.com/games/strategy/android

becomes this...

mysite.com/strategy/android

That is, a view with no fixed part in the path, just the parameters. How can I get this working?

You can go directly in your View's settings, in "Page settings" bloc, configure the path manually. Just remove the game part of the path.

For your information:

I suggest you to take a look at Pathauto module that allows you to define URL patterns very precisely for all the default pages of your site (but not views apparently): https://www.drupal.org/project/pathauto

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

Maybe it will be helpful for other cases.


Disable a Module after Fatal Error without Server/DB access? I'm working on a Drupal 7 site and recently triggered a fatal error via installation of incompatible modules. Is it possible to disable a module when site is giving fatal error on each page? Specifically without direct access to files or database?

Without access to the server, files or database?

No, there's nothing you can do.

It's the database you need to update, and if you can't get to that externally or locally to run some SQL, you're out of luck.

You could theoretically alter some code somewhere in core to bypass the issue of the broken module, but of course that would require access to the files, at which point you could've just run the SQL via PHP.


Limiting access by role So I basically have a custom module created and I just want to know how I can limit the users who can access the 2 forms I have by predefined roles -- the IT and Facilities roles that I have defined in Drupal (7) already so that only IT and Facilities people can access them..

I've been looking at access callback/access arguments but I'm not exactly sure what to use in my form definition/hook_menu in order to limit access to just those two roles.

Here's my hook_menu function:

//hook_menu
function ibbr_inv_menu(){
    //'Inventory Items' page
    $items['inventory_scan'] = array(
    'title' => 'Inventory Items',
    'page callback' => 'ibbr_inv_menu_page_callback',
    'access callback' => TRUE,
    'page arguments' => array(1, 2),
    'type'=> MENU_CALLBACK,
);
    //'Add new item' page
    $items['inventory_scan/add_item'] = array(
    'title' => 'Add new item',
    'page callback' => 'ibbr_inv_add_new_item_callback',
    'access callback' => TRUE,
    'page arguments' => array(1, 2),
    'type'=> MENU_CALLBACK,
);
return $items;
}//end hook

Thank you!

Since you are setting 'access callback' to TRUE, you are actually giving access to those routes to every user, including the anonymous users.
You could easily set the access callback to a function in your module 'access callback' => 'ibbr_inv_access_callback' and check the roles the global $user variable has, but that would be a bad idea, since every time you need to give access to those routes to a new role, you would need to change the code of your access callback. Plus, since you are hard-coding the roles in your code, the module could not easily be adapted to different needs, such as sites using totally different roles.

The Drupal way is to assign permissions to the roles that should be able to access the routes you define, and use user_permission() as access callback for your routes. In this way, the code would check for the same permission, which could be given to new roles, or to totally different roles; any change in the roles having that permission would not reflect on your code, which would still work in any case.

As permission, you could use one that Drupal already use, or (if that is not restrictive enough) define a new permission.

function ibbr_inv_menu() {
  $items['inventory_scan'] = array(
    'title' => 'Inventory items',
    'page callback' => 'ibbr_inv_menu_page_callback',
    'access arguments' => array('administer inventory items'),
    'type'=> MENU_CALLBACK,
  );
  $items['inventory_scan/add_item'] = array(
    'title' => 'Add new item',
    'page callback' => 'ibbr_inv_add_new_item_callback',
    'access arguments' => array('administer inventory items'),
    'type'=> MENU_CALLBACK,
  );
  return $items;
}

function ibbr_inv_permission() {
  $permissions['administer inventory items'] = array(
    'title' => t('Administer inventory items'),
    'description' => t('Creates/deletes inventory items.'),
  );
  return $permissions;
}

To use a access callback that checks the roles the currently logged-in user has, I would use the following code. It's not the code I would use, but if you need to use such code for any reason, this is what I would suggest.

function ibbr_inv_menu() {
  $items['inventory_scan'] = array(
    'title' => 'Inventory Items',
    'page callback' => 'ibbr_inv_menu_page_callback',
    'access callback' => 'ibbr_inv_access_callback',
    'access arguments' => array('the role the user needs to have'),
    'type'=> MENU_CALLBACK,
  );
  $items['inventory_scan/add_item'] = array(
    'title' => 'Add new item',
    'page callback' => 'ibbr_inv_add_new_item_callback',
    'access callback' => 'ibbr_inv_access_callback',
    'access arguments' => array('the role the user needs to have'),
    'type'=> MENU_CALLBACK,
  );
  return $items;
}

function ibbr_inv_access_callback($role_name) {
  if ($role = user_role_load_by_name($role_name)) {
    return user_has_role($role->rid);
  }

  // The role doesn't exists; return FALSE as safe value.
  return FALSE;
}

The code works on Drupal 7.36 and higher, since it is using a function that previous versions didn't implement (user_has_role()).

As side note, since for inventory_scan/add_item you are using array(1, 2) as page arguments, the page callback would receive 'add_item' as argument, which doesn't make much sense; it would make sense if you were using the same page callback for different routes, and you would use 'add_item' to make the page callback know which action to perform.
In the same way, it doesn't make much sense to use array(1, 2) as page arguments for a route like inventory_scan; if you are not visiting inventory_scan/first_value/second_value, the page callback will not receive any arguments at all.


Can I use hook_block_info() in a theme? In Drupal 7, can I use hook_block_info() in a theme?

I would like my theme to create a block (which would contain dynamic content). This will allow the user to move it around where he wants to, or simply hide it.

Is this the way to go?

/**
 * Implements hook_block_info()
 */
function mytemplate_block_info()
{
  $blocks['mytemplate-block'] = array(
    'info' => t('TemplateBlock'),
    'weight' => -100,
    'status' => 1,
    'region' => 'content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>',
  );

  return $blocks;
}

/**
 * Implements hook_block_view()
 */
function mytemplate_block_view($delta = '')
{
  $block = array();

  switch ($delta) {
    case 'mytemplate-block':
      $block['content'] = 'some custom html';
    break;

  }

  return $block;
}

I'm afraid you can't, no, it has to be in a module.

The array of blocks is built up in _block_render_blocks() using the module_invoke() function which, as its name suggests, only invoke hooks for modules and not themes.

If you haven't written a custom module before don't be afraid to get stuck in its pretty easy. I'd highly recommend the Module Developer's Guide which will tell you everything you need to know.


adding class to drupal8 taxonomy i want to add custom class for each term

function sometheme_preprocess_field(&$variables) {
  if ($variables ['links']['#title'] == "Consulting"){
    // I'm lost here // how can i assign class here or even add a custom picture // Please help
  }
}

You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}