Sort by closest to today? I've got an show/performance relationship, where a show can have multiple performances, and each performances has a single date (when the performance takes place).

I'm showing these in a Drupal view, but it's becoming a bit problematic.

I need to sort this list so that the shows with the closest performances to now appear at the top, the problem is that shows with only past performances also need to show.

The last part appears particularly problematic, I think I could just sort this by greater than or equal to now, but I don't think that will be sufficient in this case.

Is this possible? Or do I need to try and argue for a different way of displaying this content

I would make two view lists, one to show forthcoming performances and one to show past performances.

This way you can title each list so it's clear to users which is which. It would be feasible through careful CSS to make it look like they are one list. And each list will only show as required.

Filter on the date, either '>= now' or '<= now', to make each list work as you wish.


How to reduce BARCODE FONT in barcode module? I am using Barcode module to generate barcode i have downloaded that module from drupal.org modules,i am able to reduce the rectangle lines of barcode but under the rectangles lines i have serial number like "123456" i cant able to reduce the size of it,I need to reduce the size of serial number.any suggestions.Thanks in advance

Add this to your theme css file, in /sites/all/themes/yourtheme/css

.barcode { font-size: 10px; }


I can't remove an manage_file field image I have the next managed_file field:

$form['portada_field']['imagen_portada'] = array(
            '#title' => t('Imagen'),
            '#type' => 'managed_file',
            '#description' => t('Extensiones permitidas: gif png jpg jpeg'),
            '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
            '#upload_location' => 'public://articulos/portada',
            '#progress_indicator' => 'throbber',
            '#status' => FILE_STATUS_PERMANENT,
            '#progress_message' => 'One moment while we save your file...',
                '#states' => array(
                    'visible' => array(
                      ':input[name="checkbox_imagen"]' => array('checked' => TRUE),
                    ),
                ),
         );

After upload an image, If I want to remove the image I can't do it, it appears again

How I can remove it?

Thank you very much.

You can use db query to remove the entry

  $mydir =  variable_get('file_public_path', conf_path() . '/files');
  $filename = $mydir .$file_directory. $filename;
  unlink($filename);
  db_delete('file_managed')
      ->condition('filename', $filename)
      ->execute();
  $FileStatus = "The file has been removed - ".$filename;

Get the public directory path and delete the file from file_managed table

This will make your work easy.


Remove child elements from Taxonomy List Exposed Filters I have a view with (Taxonomy Reference Field) as Exposed Filter, The vocabulary contain parent terms and some child terms, I want to see the first level terms only and remove any children if any.

Currently It look like this

I want to remove the Keyboard Type 1, Type 2 and so on.

I was thinking of using a hook_form_alter, but not sure about the exact usage to remove any child term.

Here is my solution which I think is quite a bit simpler. Simply remove the entries from the form if they start with a '-'. Note that you must have the 'Show hierarchy in dropdown' option selected for the children to begin with a '-' hyphen.

/**
* Implements hook_form_alter().
*/
function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  if($form['#id'] == 'views-exposed-form-[your-view-here]') {

    foreach ($form['tid']['#options'] as $term_key => $term) {

      // Check if this isn't the 'ANY' option
      if($term_key !== 'All') {
        // Check if this is a child by looking for '-' as first char in string
        $term_value = reset($term->option);
        if($term_value[0] == '-') {
          unset($form['tid']['#options'][$term_key]);
        }
      }

    }

  }

}


Why won't my module table populate I have a page that is supposed to output a table of values from my database. I am logged in as an admin and another page I created works just fine, outputting a form for data to be entered into the database. I have the following lines of code pertaining to the new page..

function achievementList_menu() {
$items = array();
$items['achievementList/list'] = array(
    'title' => 'Achievement List',
    'description' => 'A list of all of my achievements',
    'page callback' => 'achievementList_generate_table',
    'access arguments' => array('access content'),
);
return $items;
}

and

EDIT:

function achievementList_generate_table() {
$header = array('ID', 'Name', 'Description', 'Points');
$rows = array();
$results = db_query("SELECT * FROM {achievements}");

foreach ($results as $row){
    $rows[] = $row;
}

return theme('table', array('header' => $header), array('rows' => $rows) );
}

The headers render fine but the $rows array does not. Any idea why?

I can see a few problems at first glance:

'access callback' => TRUE, will mean everyone gets access no matter what and make 'access arguments' redundant.

The default access callback is user_access, which would accept your access arguments of array('access content'). So to use that just omit the access callback line.

$items['achievementList/list'] = array( is a strange path.
Generally best to keep it all lower case but that's not a requirement.

'page arguments' => array(1), will be passing in the string "list" to your achievementList_generate_table() function, but there is no point passing in a parameter that never changes and you arent actually using it, so just array() is fine for those arguments.

For more information I recommend reading all of the documentation for hook_menu().

The real problem though would be that your callback function is not returning anything for some reason.

(as per Clive's comment) I'm going to assume you are using Drupal 7.
In which case your call to the theme() function is incorrect.

In drupal 7 all variables going into the theme function should be in an array, so your line should look like this:

return theme('table', array('header' => $header, 'rows' => $rows));


How to prevent "drush up" from destroying my git repo I just updated Drupal to 7.39 using Drush, in particular the command drush up and all related steps as explained here: https://www.drupal.org/node/2550801.
During the update I have noticed this extremely worrying line, saying that Drush is messing with my .git directory:

and indeed after the update:

So I got back the .git folder from the backup created by the Drush updater, committed and pushed.

The problem is that Drush, without any warning, not only corrupted the .git directory but also messed with my .gitignore file, deleting several lines.

As a result I pushed a very large number of cache and temporary files to my company's git repo and had to later fix it and apologise to my colleagues.

My question is: is there a way to update Drupal programmatically (no admin or manually moving files) without Drush trying to destroy my git repo?

The deletion of the .git directory and other non-Drupal files when running drush up drupal has been a somewhat randomly occurring problem for many Drush users as documented on this GitHub issue. As far as I know, no definitive reason for this behavior has been found, and there is even debate about whether this behavior is, or should be, by design.

In my experience and that of others participating in the GitHub discussion, this deletion of the .git directory did not happen when using Drush 6, but happens in some circumstances when using Drush 7 or 8. Therefore, there's no surefire way of avoiding the deletion of the .git directory and other non-Drupal files when running drush up drupal besides moving those files out of the Drupal root directory before running the update.

However, the overwriting of .gitignore when running drush up drupal occurs by design. .gitignore is a core Drupal file, and as Drush warns, updating core will discard any customizations:

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal
core files, most noteworthy among these are .htaccess and robots.txt.  If
you have made any modifications to these files, please back them up
before updating so that you can re-create your modifications in the
updated version of the file.

.gitignore isn't mentioned explicitly in that warning, but it is treated similarly since it, too, is a Drupal core file.


How can i add .pdf extention on the default upload files When i create an article i saw that i'm allowed to upload image files only

  Allowed file types: .png .gif .jpg .jpeg

How can i add .pdf file extension and attached with the article?

I'm using zen theme

Go to Structure > Content types, click manage fields for the article content type, then edit on the Image field. There you can edit the allowed file types.

However, note that this is an image field. It does not make sense to upload PDF files to an image type field. Instead, you might want to add a new field with type file and configure that to allow pdf files.

Also note that you can't leave the allowed values empty, that would not allow any file types.


Can't retrieve POST parameters in Webform This post is the continuation of this question : Form isn't sending POST parameters?

I now have difficulties to retrieve my parameters in a Webform. In Chrome, I can see that my parameter is sent but the POST header have a "302 Moved Temporarily" status

In my webform I try to get my parameter with %post[email] but it don't works

Here is my code using the Form API in a custom module (see my old post for more informations)

function gn_ot_block_contact_newsletter_form()
{
  $form = array();

  $link_newsletter = drupal_get_path_alias('node/'.variable_get('gn_ot_webform_newsletter_default_nid', ''), $language->language);
  if(strstr($path_newsletter, 'node/') !== FALSE){
    $link_newsletter = drupal_get_path_alias('node/'.variable_get('gn_ot_webform_newsletter_default_nid', ''), 'fr');
  }

  $form['#action'] = base_path() . $link_newsletter;
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('INSCRIVEZ-VOUS A LA NEWSLETTER !')
  );
  $form['email'] = array(
    '#type' => 'textfield',
    '#default_value' => t('Votre adresse e-mail')
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('OK'),
  );

  return ($form);
}

I'm using Drupal 6.25. Thank you if you have any advice !

You need to use hook_form_alter to change value of full form email field. Just take value from table or session where you save one-field email result per user.


How do I pass variables into Twig template? In my preprocess function I have variables with the route name and route parameters:

function my_theme_preprocess_node(&$variables){
  $variables['route_name'] = $route_name;
  $variables['route_parameters'] = $route_parameters;
}

How do I pass them to the following link function in my page.html.twig file:

{ Link to the object with $route_name and $route_parameters }

Is it at all possible?

The '$' isn't used in twig to designate a variable. This code should work:

<a href="{{ path(route_name, {'node': route_parameters}) }}">
   Link to the object with {{ route_name }} and {{ route_parameters }}
</a>


Allow all users with a certain role to set Groups Audience to any Organic Group I am using Drupal 7.
What I am trying to achieve is the following:
I have several users with a particular role say "A". And I have several content types set as "Group content"
When a user with role "A" creates content I would like the user to be able to set the Groups Audience field to any of the existing Organic Groups.

Is it possible to achieve without adding those users as Administrators to all existing Organic Groups?

I was able to achieve the above requirement using OG Role Override module.
From Global Permissions for role "A" we would set:
"Act as role 'member' in OG Node Group Main Page groups"

Hope this helps!


Google Analytics setup not working I am trying to setup a Google Analytics property. I have done this before and have had no problems. However this time I am setting it up though the drupal module rather than manually inserting the code.
I have my tracking ID and everything filled out, and I inspect the page and I can see the tracking code is installed.
However my tracking code isnt being picked up by Google Analytics. This is what it says:

Status: Tracking Not Installed

I have enabled debugging for the module, and all seems to be sending correctly. Here is the log:

Initializing Google Analytics. analytics_debug.js:10
Running command: ga("create", "UA-49353541-2", "auto") analytics_debug.js:10
Creating new tracker: t0 analytics_debug.js:10
Auto cookieDomain found: "carbonfunding.co.uk" analytics_debug.js:10
Running command: ga("send", "pageview") analytics_debug.js:10

Sent beacon:
v=1&_v=j30d&a=1343148915&t=pageview&_s=1&dl=http%3A%2F%2Fwww.carbonfunding.co.uk%2F&ul=en-us&de=UTF-8&dt=Carbon%20Funding%20%7C%20Th…_u=MCCAAEQAI~&jid=&cid=2073925826.1413195127&tid=UA-49353541-2&z=327379316

 analytics_debug.js:10
_j1              (&jid)  analytics_debug.js:10
adSenseId        (&a)   1343148915 analytics_debug.js:10
apiVersion       (&v)   1 analytics_debug.js:10
clientId         (&cid) 2073925826.1413195127 analytics_debug.js:10
encoding         (&de)  UTF-8 analytics_debug.js:10
flashVersion     (&fl)  15.0 r0 analytics_debug.js:10
hitType          (&t)   pageview analytics_debug.js:10
javaEnabled      (&je)  1 analytics_debug.js:10
language         (&ul)  en-us analytics_debug.js:10
location         (&dl)  http://www.carbonfunding.co.uk/ analytics_debug.js:10
screenColors     (&sd)  24-bit analytics_debug.js:10
screenResolution (&sr)  1920x1080 analytics_debug.js:10
title            (&dt)  Carbon Funding | The ECO people analytics_debug.js:10
trackingId       (&tid) UA-49353541-2 analytics_debug.js:10
viewportSize     (&vp)  1903x955

I read that it can take up to 72 hours before Google will pick up the tracking code, but I also read that at least the real-time view should be picking myself up on the site. I have also disabled do-not-tack everywhere and no prevail.

Why is this the case?

Thanks,
Darryl

Adding Google Analytics using the module is not difficult. Please check this YouTube Video "Adding Google Analytics" it will walk you on the process of how to set-up your Google Analytics on your Drupal site. In addition it will to provide you the steps on how to set-up this video will give useful information about the different setting.

If you want to make sure that your website contain the Google Analytics you can check the output of your website (as an anonymous) and you should have something similar to this...

Usually takes few minutes to Google Analytics to recognize your website.

<script>
  (function(i, s, o, g, r, a, m) {
    i["GoogleAnalyticsObject"] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
  })(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
  ga("create", "UA-xxxxx-1", "auto");
  ga("send", "pageview");
</script>


Continuous migration I would like to know what is the best way to achieve a continuous migration from external DB (via Migrate).

Basically, there are several migration classes that need to be to repeatedly migrated in an ordered way (the external DB is also updated).
This said, exception management is welcomed/required during the run.

I was trying to find a solution for this but found nothing concrete.
From gathered information some approaches are to use Jenkins/Drush combination, but I wonder if adding Jenkins would be an overkill in my case.

Is there a good way to achieve this via Drush only?

Thanks

Set up a script to call drush at regular intervals. There are several drush commands to manage migrations, such as drush migrate-status.


Render a link from a FieldPluginBase I created a custom view field with the hook _views_data and a custom Class who extends FieldPluginBase.

With the render method, I can return a sample string :

class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
      return $node->id(); // My view field shows the nid of the current node
    }
...

Now, I want shows a link with my field. I tried :

class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
      return "custom link"
    }
...

But my field in my view shows :

custom link

and not

custom link

How can I show the link as an html element, not a sample text ?

Thank you =)

UP

This code work :

return array('#markup' => \Drupal::l("test",\Drupal\Core\Url::fromUri("http://www.example.com")));

ut the l() function is deprecated. If I use Link::fromTextAndUrl instead :

return array('#markup' => \Drupal\Core\Link::fromTextAndUrl("test",\Drupal\Core\Url::fromUri("http://www.example.com")));

I get the error :

  [Sun Sep 18 22:17:59.444188 2016] [:error] [pid 2143] [client
  192.168.1.48:53322] Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string in
  /var/www/xxxxx/core/lib/Drupal/Component/Utility/Xss.php
  on line 67, referer:
  https://192.168.1.45/admin/structure/views/view/customview

  [Sun Sep 18 22:17:59.446098 2016] [:error] [pid 2143] [client
  192.168.1.48:53322] PHP Fatal error:  Uncaught Error: Call to a member function get() on null in
  /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php:76\nStack
  trace:\n#0
  /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Handler/WriteCheckSessionHandler.php(89):
  Drupal\Core\Session\SessionHandler->write('BTaHaVF0t-bMk2Z...',
  '_sf2_attributes...')\n#1
  /var/www/xxxxx/core/lib/Drupal/Core/Session/WriteSafeSessionHandler.php(75):
  Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHandler->write('BTaHaVF0t-bMk2Z...',
  '_sf2_attributes...')\n#2
  /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php(77):
  Drupal\Core\Session\WriteSafeSessionHandler->write('BTaHaVF0t-bMk2Z...',
  '_sf2_attributes...')\n#3 [internal function]:
  Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy->write('BTaHaVF0t-bMk2Z...',
  '_sf2_attributes...')\n#4 [internal function]:
  session_write_close()\n#5 {main}\n  thrown in
  /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php
  on line 76, referer:
  https://1xxxxx/admin/structure/views/view/customview

How can I replace the l deprecated function ?

You need to convert array to string to show it as link. May this works for you.

class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
$title = 'Custom Link';
$url = \Drupal\Core\Url::fromUri('http://www.test.com');
$link = \Drupal\Core\Link::fromTextAndUrl($title, $url)->toString();

      return $link;
    }


Does Drupal distinguish types of error messages? In D7, under Configuration > Development > Logging and errors you can set "Error messages to display" to "none".

However, I would think users should still be able to see form error messages, for example when they don't fill out a required field.

Are there different 'types' of 'error messages'?

This setting is for server errors, the drupal form errors will still be shown.

Here is some more information on this topic:
https://www.drupal.org/node/1036982


How do I use custom marker icons with Gmap? I want to show markers like on this map here http://demo.symphonythemes.com/drupal7/bizreview/ which are obviously custom.

How do I go about this? I'm either searching for the wrong thing or something.

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here).


Adding class to module block When I use the this code; <?php $block = module_invoke('locale', 'block_view', 'language'); print $block['content']; ?>, I get the following output. But I'd like to add another class to ul.

EN

RU

Have you tried rendering the content instead?

<?php print render($block['content']); ?>

That, combined with the Block Class module should at least allow you to add a class to the wrapper, which is the next best thing to overriding the theming of the actual UL.


Organizing search in Drupal Commerce. I have site (e-shop) that uses Search API. Just Search API, Search Autocomplete, Display Suite Search and Database Search are enabled. It was not configured by me.

However, we have big problem. Search returns strange results, we cannot use search by brand cause when we choose brand on Exposed Filter with AJAX and catalog reloads, add to cart product's forms wont work cause forms were rebuild and there's no workaround for this issue.

Can you tell best (and modules) way to organize search in Commerce shop?

Do I need to use Facets and Apache Solr - technologies, which are not used now?

You can use the Search_api_db to avoid Apache Solr. Facets come in many flavors, there's no standard tutorial but some googling will get you started...


Why does the upload progress bar reset at 40% when uploading large files? I'm uploading a 5 GB file and the upload progress bar resets at 40%.
When it gets to 40% it starts counting again from 0%.
Eventually the file does upload completely but this is not good UX.
I was wondering if any knows how I can make the progress bar reach 100% like it should.
EDIT:
Here are some configuration settings requested in the comments:
post_max_size = 6G
upload_max_filesize = 6G
default_socket_timeout = 60
max_execution_time = 7200
max_input_time = 7200

This doesn't happen for smaller sized files.
When uploading the 5G file, the file upload does end. It doesn't get to 40% again after it resets to 0. It seems to get stuck at 19%.
All this time the file is being correctly uploaded to the temporary directory like it should. Like when the bar reaches 40% the file will continue to upload the temp file until it reaches the full 5G.

I was able to fix the Upload Progress so that it didn't stop at 40% (2 GB).
This is a temporary fix:
I uncommented the ondrej repo in the sources list (/etc/apt). This gave me access to uploadprogress 1.1.3-3 which has a couple of patches that the PECL repo doesn't have.
Then I got the source code:
apt source php7.3-uploadprogress

cd php-uploadprogress-1.1.3

And changed:
int read_bytes;

to:
unsigned long int read_bytes;

and recompiled from the source:
phpize; ./configure; make; make test; sudo make install; sudo service apache2 reload

It seems like the references to int were all changed except the reference to read_bytes. The maximum value of an int is 2GB.


How to show fields in the Inline Entity Form display widget? I've just started with Inline Entity Form and seem to have it working with a custom entity type that has fields. My problem is, none of these fields show in the Inline Entity Form widget, it just shows an empty ID column and Edit / Delete buttons:

I've looked through what little documentation there is, and browsed related issues and questions, but they all seem to be doing things more complex than what I'm trying to do.

Is there any simple way to just choose a field or two to display in the Inline Entity Form widget?

It seems to "just work" for nodes - how can I have it pick up the entity fields in a similar way?

Use hook_inline_entity_form_table_fields_alter() this is what I am using on a current site:

function MY_MODULE_inline_entity_form_table_fields_alter(&$fields, $context) {
  //Determine the bundle and entity type from $context

  unset($fields['id']); //<get rid of the id field

  //add any fields you need to the $fields array
  $fields['FIELD_NAME'] = array(
    'type' => 'field',
    'label' => t('FIELD'),
    'weight' => 2
  );

}


Differences between Firefox and Chrome in the Omega theme I'm building a site in Omega, and I'm having trouble understanding why Firefox is so much different than Chrome/IE. For example, in the menu bar, the font is fine and the text has plenty of room on the right side; in IE and Chrome, the font is much larger and the text wraps to another line. The display width doesn't seem to be that much different. Zooming in and out don't seem to matter.

Why does it seem to fit like it should in Firefox, but not IE/Chrome? How can I control that?

As I previously mentioned in comment, its not related to Omega nor Drupal, but you can still try to use normalize.css.

A modern, HTML5-ready alternative to CSS resets (as used by Twitter
Bootstrap, HTML5 Boilerplate, TweetDeck, Soundcloud, and many others)

Alrternatively as you didn't provide any link or capture, I suggest to check your styles and libraries list in your omega subtheme settings, go to Appearance > THEMENAME > Settings , under Toggle styles and Toggle Libraries


How do I show content in an overlay? I want to display some content, returned from an AJAX call in an overlay or popup.

Do you have any idea on how I can do it?

If your are using Drupal 7 you could make a use of the administrative overlay with a custom module.

You will need 3 hooks in your CUSTOM_MODULE_NAME_HERE.module file :

/**
 * Implements hook_menu().
 */
function CUSTOM_MODULE_NAME_HERE_menu() {
  $items = array();
  $items['your/path/to/your/page'] = array(
     'page callback'    => 'CUSTOM_MODULE_NAME_HERE_page',
     'access arguments' => array('access content'),
     'type'             => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implements hook_admin_paths_alter().
 */
function CUSTOM_MODULE_NAME_HERE_admin_paths_alter(&$paths) {
    $paths['your/path/to/your/page'] = TRUE;
}

/**
 * page callback
 */
 function CUSTOM_MODULE_NAME_HERE_page(){
    $output = 'your page content';
    return $output;
}


Field-Group Tabs not displaying on product page I'm trying to display a handful of fields as tabs on my product detail pages, but it seems that the field-group tabs are being completely ignored by the Commerce product display. Anyone else have this problem? Did I miss something in the tab setup/display?

The fields display as any other field for the Product, just output as regularly expected. As mentioned, just seems to ignore the 'tabs' display.

Kind of late to the party, but I ran into this same problem earlier today and it appears to be caused by the fact that the Field Group module hardcodes the entity types that it latches onto.

The 1.x-dev version now includes a HOOK_field_group_content_element_keys_alter() that you can use to expose any entity type to the Field Group module.

To expose products and product variations you need to create a custom module and hook into the above alter function like this

MYMODULE_field_group_content_element_keys_alter(&$keys) {

  if (!isset($keys['commerce_product_variation'])) {
    $keys['commerce_product_variation'] = 'product_variation';
  }

  if (!isset($keys['commerce_product'])) {
    $keys['commerce_product'] = 'product';
  }

}

Hopefully this will be integrated into Drupal Commerce in the near future, but for now this is the only way.

Edit You can read up on the actual issue here https://www.drupal.org/node/2842280


rest POST via Postman always ends in 403 access denied I try to create a node via a rest POST over Chrome's Postman using Drupal 8.2.3., but i always get a 403 access denied.

Can anyone point out a step-by-step how-to on the settings? Mainly regarding the permissions that need to be set accordingly.

I did obtains the token at /rest/session/token and added into the request header.

The Request was: MYURL.de/rest/node?_format=json. For your information: I created the service-endpoint /rest, and I also tried with: MYURL.de/node?_format=json, but the same result.

Can anyone drop me a hint?

Your request need ?_format=json on the end of request.
Clear cache.
Delete all sessions, delete from sessions.
Call login service, /user/login?_format=json,
method POST
choose raw in Body and there put username and password in JSON format:

{
   "username": "value",
   "password": "value",
}

and choose JSON (application/json).

This service will return X-CSFR-TOKEN, use it for your request.


drupal_http_post redirect I am currently experimenting with drupal_http_request to send my users information to a payment service - there is more configuration to be done so it is not working yet.

When I do get it successfully POSTing users details, it is important that the user is redirected to the payment service.

Can anyone tell me if drupal_http_request does redirect as it POSTs data?

If it doesn't I would appreciate suggestions on how I can achieve simultaneous POSTing and redirection.

Here is an example of how to use drupal_http_request().

$options = array(
  'method' => 'POST',
  'data' => 'name=Test&email=example...',
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com', $options);

In $result, you will get an object with the data of the request.
Check the $result object and make sure the payment is gone through (or whatever the condition that should pass before redirecting the user).

Then, use drupal_goto() to redirect the user to the new location.

Note that this is just a normal redirect (GET) and data is already submitted to the Payment server by your site.

If you want to use Paypal IPN-like requests that the user POSTs data to the server, you need to create a form instead.

function _test_payment_form() {
  $form = array();

  $form['user'] = array(
    '#type' => 'hidden',
    '#name-info' => 'user', // this is the field name that will become name attribute of the input tag. No need to use this if your $form['KEY'] is same as this one.
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Proceed to @server for the payment', array('@server' => 'Paypal')),
  );

  $form['#action'] = 'http://example-payment-server.com/example/2/3/4'; // Information will now be submitted to this URL other than Drupal.
  $form['#method'] = 'POST', // Just for clarification. This is the default value.

   return $form;
}

You can print the form using the following code.

print drupal_render(drupal_get_form('_test_payment_form'));

You can also use the following code, where render arrays are accepted.

drupal_get_form('_test_payment_form');


How can I display a taxonomy term's parent ID in Views? I am using a JSON plugin to Views to output taxonomy terms as a JSON object for Javascript manipulation. I was to be able to include the parent ID in this output.

In view I see "Taxonomy term: Parent term" under relationships and I have added that to the view. But under "Fields" -> "Add" there is still no "Parent term" listed in the available fields. I'm pretty sure the "pid" should be available. Is there some other way of accessing that field via the Views UI?

Thanks Clive! Yes - I just found the solution. I took the following steps:

Under "Relationships" add "Parent term" and untick "Require relationship"
Under "Fields" add "Taxonomy term: Term ID" and under that select from the "Relationship" pulldown "Parent"

Since the relationship is not required, it will correctly show both top-level terms and all children term. Top-level terms has parent ID of 0.


Drupal form does not save the user input value in the $form_state array This question extends a prior question. I the previous one, I found several errors relating to coding, and thought I had solved the basic question, only t discover that it still is not working correctly.

I have a form to get a file name for opening (http://pastebin.com/8NfGGNSn). When I set the form field type as a textfield, the form widget saves my text entry (in the $form_state ['values']['upload_file] field). When I change the form widget type to 'file' the entry text from the form is not saved. My browser is Firefox and it makes available a browse button and a file selection window in the form. When I select the file from the window dialog, the form widget is completed with the full file path, however, it appears that the path text in the widget is not being placed in $form_state[values][update_file]. It remains empty. IN both textfield and file cases I am checking the value of the $form_state array during validation, so there should not be any clear or reset activity at that point. Any ideas why the content is deleted from the widget? OR does a file name get saved at another location?

File input fields work differently than other input fields. This is a restriction of HTML. The file path is not transmitted to the server, because it is considered sensitive information. Only the file data and the name of the file is transmitted to the server.

Use file_save_upload() to save the file. To find out what to pass as the $source argument, print out both $form_state[values] as well as the $_FILES array.


drupal_add_js in html template file I am using a zen subtheme and I am trying to add some javascript using the drupal_add_js
 on a certain node.
When I use the drupal_add_js from within the html--node--XX.tpl.php file, it does not work.

But when I use it in the page--node--XX.tpl.php it does. I don't understand what causes the difference in the behavior. I thought that this would be the same.
These are the lines I am adding in both cases:

drupal_add_css("sites/all/libraries/shadowbox/shadowbox.css", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("sites/all/libraries/shadowbox/shadowbox.js", array('type' => 'file', 'scope' => 'header', 'weight' => 5));
drupal_add_js("Shadowbox.init({skipSetup: true});", array('type' => 'inline', 'scope' => 'header', 'weight' => 6));

Can anyone illuminate me here?

You can try to insert the JS files by the preprocess function in your theme's template.php file:

Here goes an example:

function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

You can use an if() to validate the current path in the $variables in order to prevent the script to be loaded on every page.

To debug the $variables values you can install the devel module an use the dpm() function.

For example:

function MYTHEME_preprocess_page(&$variables) {
  dpm($variables);
}


How to make mymodule_preprocess_node run only once? We have a custom mymodule that calls mymodule_preprocess_node(&$variables) hook. When we add ksm($variables); to the hook, we are finding the message is printed multiple times (average has been 5x).

How to make mymodule_preprocess_node run only one time?

I am needing to run this hook because I want to check to see if a field is populated with some value then perform some other logic.

Example:

function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link'))) {
    // perform some logic.

   ksm('in here'); // printed multiple times.
  }
}

I found the issue. As @Kevin mentioned, it was being called for every node being rendered. I added a condition to check the view more as well and it is being called just one time now.

function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link')) && $variables['elements']['#view_mode'] == 'my_view_mode') {
    // perform some logic.

   ksm('in here'); // printed once as expected
  }
}


How to pass an argument to be used in the view called by rules Context: drupal 7, views, Rules, Views_rules

Goal: to send an email to all users that have the same taxonomy-term as the newly posted node

Possible solutions known to me:

(1) A Rule calls the view with mailadresses and terms of each user. I would need to evaluate a condition within the view loop, which is possible, using a component of type rule or ruleset that will be executed for each item in the loop. This will be inefficient (give a lot of “skip this”).

(2) Or I could make a view for each term, as proposed in the comments of
How to send out email based on matching taxonomy terms in user profiles?
However, I would prefer to give my users more flexibility then just a few options.

Question: How could I pass the taxonomy-term to be used in the filter-criteria in the view? The view would then only return the records where actually something has to be done (i.e. send a mail to).
Is there a way to  send an argument when calling the view loop?

I found 2 working prototypes.
Each require a taxonomy-list "field of interest" in both user and node.

Users can select multiple items, according to their fields of interest.
When registering a new post, the posting user can indicate in which field of interest (one) this post is matching.

ONE

using 5 views (one for each term) to select the email adresses of users interested in this "field of interest".
In the action I use "switch case" (from conditional_rules) to select the view corresponding to taxonomy-term of the new node

TWO

fetch entity (user) by taxonomy term(field of interest)

loop thru the list of users

THREE

Finally I chose to make 5 views and 5 reaction rules, each rule having as condition a particular value of the taxonomie term in the new node en using the relevant view to select the users. No switch case needed.


Translating fields in node.tpl.php file with drupal 7 I have a drupal English/French website. I have a custom content type called 'ad' with all sort of fields. I have created the file 'node--ad.tpl.php' in my theme directory to customize the display of the 'ad' content. I use pixture reloaded theme and DRUPAL 7.
In node--ad.tpl.php fields are displayed with this code:
  print render($content['field_my_field_name']);

I am trying to translate fields (both labels and values) by using 'field translation' module.

Field translation works when I CREATE or MODIFY a content via admin.

However, when I DISPLAY a content of type 'ad', fields are not translated. This is because drupal calls to 'node--ad.tpl.php' and the translation module is probably not invoked. When deleting 'node--ad.tpl.php', drupal calls the default node.tpl.php with a similar results.

Any help would be appreciated, Thanks in advanced,

Notes :

I correctly activated every dependencies for the module.
User interface translation correctly works.

OK, I found out myself how to do this:

Translate field labels and values in "Configuration > Regional and language > Translate > Import". You should import the values as 'User Interface', not as 'Fields'. Do not specify a URL, only msgstr and msgid.
Now, you need to add your t() function in node.tpl.php for the translation to be effective, like so:

In the node.tpl.php file, to translate field label write something like this:
$content['field_my_field']['#title'] = t($content['field_my_field']['#title']);
To translate field's value, use: $content['field_my_field']["#items"][0]['value'] = t($content['field_my_field']["#items"][0]['value']);

You can now render your field:

print render($content['field_my_field']);


How do I render the main navigation menu? In Drupal 7, we were able to render the main navigation menu onto a page outside the main Drupal folders by including bootstrap.inc and displaying it with this code.

 $menuData = menu_tree_output(menu_tree_all_data('main-menu'));
 print drupal_render($menuData);

Can something similar be done in Drupal 8?

Here is how to get the render Array :

  $menuService = \Drupal::service('menu.link_tree');
  $parameters = $menuService->getCurrentRouteMenuTreeParameters('main');
  $mainMenutree = $menuService->load('main', $parameters);
  $renderArray = $menuService->build($mainMenutree);

If needed, here is how to generate the HTML

$html = \Drupal::service('renderer')->render($renderArray);

Note : replace 'main' by menu name for another one.


check current path in using comtext php I use Context PHP module to write a simple condition:

$curr_uri = check_plain(request_uri());

if($curr_uri == '/mypath?123'){
   return TRUE;
}
else{
   return FALSE;
}

While this works perfectly for logged in users, it doe's not work for anonymous users. How this might be possible? Permissions are set ok.

First off, there could be manly causes to this, most likely permissions but if you're saying these are correct I'd look at the caching.

From how you wrote the question it suggested you're using the php filter (I'd advise against the use of this really and opt for module development). If you are doing this within a module I would check that the hook you are using is the correct one and is being fired.

As for your code, check_plain isn't needed here because you're not outputting the uri to the browser only checking against it.

I would use the inbuilt drupal functions to do this though either way.

current_path() - https://api.drupal.org/api/drupal/includes!path.inc/function/current_path/7
drupal_get_query_parameters() - https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_get_query_parameters/7

Take note, the current_path() function returns the internal path for the url, not the friendly one, 'node/1' instead of 'this-url'.

$query = drupal_get_query_parameters();
return current_path() === 'mypath' && $query['key_of_query'] === '123';


Best practice for template theming - #markup vs safe_value When doing complex display logic and breaking apart a renderable array in a field collection template, what's the best string output to use from the array: #markup, or safe_value? Presumably #markup is already run through the right filters... right?

You actually want to use the render() function like so:

<?php print render($content[FIELD_NAME]); ?>

See http://api.drupal.org/api/drupal/includes%21common.inc/function/render/7 for reference. Also, be sure to use hide($content[FIELD_NAME]) right before you render $content or you will render the field a second time (unless you've hidden it in the view mode on the Manage Display tab of the content type).


How do I allow facets on my full content display page? I have installed Kickstart Commerce 2. I have been able to allow facet searches on my collection pages, by simply adding collection/* under the "Show block on specific pages" section of the blocks that I want to have the facet search block appear on. It works great, except they are not appearing on the full content display pages. The URL path for my product's content type shows as "examplesite.com/lightfixtures/", but adding "lightfixtures/*" under the "Show block on specific pages" didn't make the block appear on my "lightfixtures" pages.

Currently, a user will see several products displayed in a teaser view. The user clicks on the product they want more information on and are brought to a full content display page of that one product. As this page contains no search facets, the user has to click their browser's back button in order to search for something else.

How do I allow facets on my full content display page?

Thank you to anyone they can offer some direction in this please.

So I've decided this does not need to be done. When a user gets to the product page (however they land there), they simply click the next level of the breadcrumb link to get to that parent group.

Here are some examples of how this is shown is various e-commerce sites:

Macy's product page (no facets showing): http://www1.macys.com/shop/product/louis-raphael-pants-hidden-extention-pleated-pants?ID=796776&CategoryID=89#fn=sp%3D1%26spc%3D546%26ruleId%3D60%26slotId%3Drec%281%29
Then you click on "Pants" on the breadcrumb link and you see the facets: http://www1.macys.com/shop/mens-clothing/mens-pants?id=89

I hope that helps others who may have this question.

Best,

Tom


Drupal 7 access arguments Is this right? I want to only give access to the people who have 'Download Original' checked in permissions.

function userDownload_menu() {
  $items['user/download'] = array(
   'title' => 'User Download',
   'page callback' => 'user_download_init',
   'access arguments' => array('Download Original'),
   'type' => MENU_SUGGESTED_ITEM,
 );

return $items;
}

If this is correct it's not working for me. Otherwise how can I pass a user role to this?

You need to use Hook permission to define the permission within your module


including jquery.ui 1.6 directly from theme.info It is possible? because i've tried to include jquery ui library through drupal.org/project/jquery_ui module (followed instructions in readme.txt) but that library won't show up in source code. What's the problem?

Should i go for jquery_ui module or i can include that script through .info file?

Jquery ui version = "6.x-1.5"
Downloaded jquery ui library 1.6

The correct way to include jQuery UI, from README.txt:

In your module, call the following function:

jquery_ui_add($files);

For example:

jquery_ui_add(array('ui.draggable', 'ui.droppable', 'ui.sortable'));
jquery_ui_add('ui.sortable');  // For a single file


A line feed gets added in the "Let's Encrypt Challenge" I am using the Let's Encrypt module for Drupal 7, trying to follow the instructions outlined here by Redfin Solutions, to install free SSL on Acquia's servers, but I've run into a curious problem:

Each time I generate the challenge using the certbot manual mode (using sudo certbot certonly --manual -d example.com), It tells me the key authorization file from the server does not match the challenge.

  Failed authorization procedure. example.com (http-01): urn:acme:error:unauthorized :: The client lacks sufficient authorization :: The key authorization file from the server did not match this challenge
  [TBgi6LPQfn7SJOTMcA67Crjrb_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI] != [
  TBgi6LPQfn7SJOTMcA67Crjrb_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI]

  IMPORTANT NOTES:

  The following errors were reported by the server:
  Domain: example.com
  Type: unauthorized
  Detail: The key authorization file from the server did not match    this challenge [TBgi6LPQfn7SJOTMcA67Crjrb_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI] != [TBgi6LPQfn7SJOTMcA67Crjrb_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI]

  To fix these errors, please make sure that your domain name was entered correctly and the DNS A record(s) for that domain contain(s) the right IP address.

As you can see, the second one (which is the one in the server), shows with a linefeed at the start. I am baffled by this, I went into the module and it just displays the value saved in a system variable, which I verified in the database. Other than that they seem to be identical, I have not been able to go further. Has anybody experienced anything similar? Any suggestions on how to fix this?

Turns out the module works like a charm, the problem was theme related, sending out a blank line at the top of the page: this was enough to confuse Let's Encrypt when running the validation of the site.


How can I disable jquery_update when my admin theme is in use? I have installed jQuery Update but it breaks some core functionality that makes the admin UI a struggle to deal with. Is there a way to keep jQuery Update enabled but disable it when the admin theme is visible?

It should be noted the underline issue is really a core problem which is now fixed over at http://drupal.org/node/1480568

Anyways if people still need a fix for this this is what I have in place.

/**
 * Implements hook_module_implements_alter().
 */
function hook_module_implements_alter(&$implementations, $hook) {
  // Make sure to check if the module is enabled or this will cause fatal errors
  if ($hook == 'library_alter' && module_exists('jquery_update')) {
    // Move jquery update to the end. This will make sure our hook_library_alter
    // is always called before the jquery_update.
    $jquery_update = $implementations['jquery_update'];
    unset($implementations['jquery_update']);
    $implementations['jquery_update'] = $jquery_update;
  }
}

/**
 * Implements hook_library_alter().
 */
function hook_library_alter(&$libraries, $module) {
  // If it is an admin path all we want to do is change the global $conf
  // variable so when jquery_update runs right after us it will use 1.5.
  if (path_is_admin(current_path())) {
    // Modifying global $conf variable, can be dangerous. Be carefull.
    global $conf;
    $conf['jquery_update_jquery_version'] = '1.5';
  }
}

This changes the variable right before jquery_udpate uses it when is an admin path. Also this doesn't hard-code to checking the url 'admin' because and admin path can also be /node/1/edit etc..


Different image for markers and cluster markers Openlayers I want to display different markers for different event types eg. skiing (little guy on skis), sailing (little boat). I am using views so this shouldn't be hard.

The fun starts when clustering. I want to use a marker with a the number of "sub" markers clustered. Also easy. But how to do this and then swap to the icon markers when zoomed past the clustering?

I'm not entirely sure what effect you're after, but I have a map that uses clustering and custom markers. I've added the code at the end of the answer. The code changes the marker dynamically: if there are visible markers of more than one type (taxonomy term) then it shows a general purpose marker; if all the visible markers belong to one type then it shows that type's marker. It works by creating a copy of the Style object with a custom context object that allows you to specify JS functions named after the placeholder that take the cluster as an argument and return a value to replace the placeholder. I've used the delete render intent to signify a marker's hidden and I get the feeling that might not be standard (but it works for me:). I'm not an OpenLayers guru, so no promises this is the best way!

var style_properties = settings.styles.service_providers;
var default_marker_path = style_properties.externalGraphic;
// Convert the path to an internal one. This can't be done via the
// OpenLayers interface.
// @see http://drupal.org/node/1166076#comment-5633868
default_marker_path = default_marker_path.replace(new RegExp('http(s)?://.*?' + Drupal.settings.basePath), '');

var options = {
  context: {
    /**
     * Dynamic attribute replacement function. Returns the path to the
     * appropriate marker for this cluster. It will return a specific
     * service type's marker if there's only one kind of visible marker
     * within the cluster; the default marker otherwise.
     *
     * @param OpenLayers.Feature cluster
     *   The cluster containing the pseudo features.
     *
     * @todo Create a TID-based index into the features array for
     *   performance benefits.
     */
    field_service_type_marker_path: function (cluster) {

      var marker_path = default_marker_path;

      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        if (feature.renderIntent !== 'delete') {
          // Feature is visible.
          if (marker_path === default_marker_path) {
            marker_path = feature.attributes.field_service_type_marker_path;
          }
          else if (marker_path !== feature.attributes.field_service_type_marker_path) {
            // There's more than one type of visible marker - early out
            // and use the default marker.
            marker_path = default_marker_path;
            break;
          }
        }
      }
      return marker_path;
    },
    /**
     * Checks through the features in the cluster and returns whether
     * this cluster should be visible (ie whether or not it has any
     * visible features).
     */
    cluster_display: function (cluster) {
      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        // I could use .getVisibility(), but there's no need at the
        // moment, because the only way that a feature might not be
        // visible is if I changed its renderIntent.
        if (feature.renderIntent !== 'delete') {
          // Any return value that's not 'none' will cause the cluster
          // to be rendered.
          return '';
        }
      }
      return 'none';
    }
  }
};

// Set up the variable externalGraphic to allow different marker images
// based on the TID.s
style_properties.externalGraphic = Drupal.settings.basePath + '${field_service_type_marker_path}';
// Set up variable display, so that the clusters can be hidden if every
// feature inside them is.
style_properties.display = '${cluster_display}';

// Set up new styles for both 'default' and 'selected' renderIntents.
layer.styleMap.styles['default'].destroy();
layer.styleMap.styles['default'] = new OpenLayers.Style(style_properties, options);
layer.redraw();


I want to make node views "Edit link" field as a menu Is it possible to make "Edit link" field as a menu.
On my site one user can create only node and I have a page view which displays the node the user logged on has created.
This views has a "Edit link" field so that the user can jump to node edit page from this view page.

However I want to have a menu or tab that can directly link to the node edit page of the node the logged in user has created.
It should a menu or a tab that says "edit my node" and the user can directly jump to the node edit page without visiting the page views.

I'm a bit confused, because your question sounds like a basic Drupal feature that has been around for years: tabs with "local tasks" as they are called. Here is a screenshot from a Drupal 7 site, without any extra modules:

If I understand correctly, the 'Edit' tab is what you are looking for... Or isn't that what you need?


How can I programatically change the (D8 core) workflow state of an entity with Content Moderation? I'm using Drupal 8.4-rc2.  When you enable the Workflow and Content Moderation modules, you automatically get the Editorial Workflow as a demonstration.

The states are as follows:

Archived
Draft
Published

And the transitions are as follows:

Create new draft (from draft/published to draft)
Publish (from draft/published to published)

How can I programatically call a transition?  Or, how can I programatically change the state without calling a transition (although this seems to violate the spirit of having transitions defined in the first place)?

Specifically, I have a node subject to content moderation (states: archived, draft, published).  By default, on the edit node page, the node is saved in the original state (so a draft node is saved as a draft).  I want to add a second button "save as published" with a submit handler, but I don't understand how I can programatically change the state.

What I do understand so far is that workflows are entities and so are states, so it's different than Drupal 7 in which most workflow-type modules used fields to track what was going on.

I checked the Examples module but there's nothing on configuration management/workflows yet.

A great example could be found in Content Moderation module's code.

$entity->set('moderation_state', $new_state);
if ($entity instanceof RevisionLogInterface) {
  $entity->setRevisionLogMessage($form_state->getValue('revision_log'));
  $entity->setRevisionUserId($this->currentUser()->id());
}
$entity->save();


Views global text area replacement patterns for multiple values I have a views block that is listing the similar nodes (based on taxonomy terms).

I want to show some custom text and the taxonomy term field's value(s) on the footer of the block.

I added Global: Text area to footer of the views and selected the Use replacement tokens from the first row option.

What I want to show is that My Term's other nodes and I'm using that for what I wanted:

  [field_my_taxonomy_term]'s other nodes.

It works correctly if the field_my_taxonomy_term field has only one value but if it has multiple values (multiple terms) it only shows the first taxonomy term value.

How can I show multiple values on Global: Text area?

This is the replacement patterns part of the Global: Text area:

[title] == Content: Title
[field_my_taxonomy_term] == Content: My Term
%1 == Content: Nid title
!1 == Content: Nid input
%2 == Content: Has taxonomy term ID title
!2 == Content: Has taxonomy term ID input

You need to either display as a table, or change the settings to force fields to be included in the View.

When you add a field to Views, you can alter how it is represented, including Rewrite, Style and if it contains multiples, how to display those values.

Adjust the field settings for the field you want and then that should be represented in the replacement pattern further down the chain


Looking for an employee scheduling module Using D7, I need to be able to schedule call center staff. Is there any "employee scheduling" module out there?

If not, are there a combination of modules I can use to create such a feature?

I created a shift scheduler module about a year ago.

Documentation and Releases: http://code.google.com/p/drupal-shift-scheduler/

Video tutorial: http://www.youtube.com/watch?v=9pPHtoE2ivg

Development: http://drupal.org/sandbox/mcstrother/1075572

I'm no longer actively developing it, but I believe both the 6 and 7 versions are actively in use on at least one production site each with no new bugs reported.


Panels page variant that targets a single node I am a little new to Panels, but I am using it to manage layouts for different content types and it is working out really well. However I want to be able to create a page variant that will only target a single node. Is there any way to do this based on the node's id?

Assuming you already have the node override Panel enabled:

Edit the panel page for the node override (node_view for node/%node)
Make a new variant, enable selection rules
For the selection rule, choose String: Url Path
In the criteria, keep Allow access on the following pages selected
In the textarea, add the internal node paths for this nid(s) you want.  To target nid 1234, use

node/1234
Configure the test of the panel as needed.

Just make sure this comes before any less-specific rules, like matches on content type.


How do I debug/kint Simple XML Sitemap link array? I am trying to find how I can debug/kint a variable/array from the Simple XML Sitemap?
I worked through the documentation here: https://www.drupal.org/docs/8/modules/simple-xml-sitemap/api-and-extending-the-module#s-api-hooks to find the hook I need.
My goal is to unset any links that have node/ to remove published, but un-aliased nodes of included content types.
The array key ['path'] looks to be the unaliased URL and the below code removes all links except the home page. I am unsure how I can kint($link) in this function so I can see what other array keys are available to see what else I may use for comparison.
function HOOK_simple_sitemap_links_alter(array &$links, $sitemap_variant) {

  foreach ($links as $key => $link) {
    if (strpos($link['meta']['path'], 'node/') !== FALSE) {
      unset($links[$key]);
    }
  }
}

Is there a way to kint() these sitemap arrays? Or maybe some documentation that shows the structure of these arrays?

As Clive said, you will need to make sure that both the devel and kint modules are enabled.  (NOTE: D8's Devel 4.0 now includes the kint module but requires 'composer require kint-php/kint' to be done to make it work) Then you can add your hook and just do a ksm($links); statement.
Make sure to clear cache so the hook will be found.  Then doing a regenerate of the sitemap(s) in the gui will product the kint output that you can examine for the structure.
Also, not totally sure, but I think this hook has to be in a module and will not work in the .theme file.
FYI - Here's a code snippet from a working hook that does what you want, including removing untranslated nodes.
/**
 * Implements hook_simple_sitemap_links_alter().
 */
function my_module_simple_sitemap_links_alter(&$links, $variant) {
  foreach($links as $key => $link) {
    // Filter out any node/### URLs
    if ( preg_match("!(/[a-z-]*)?/node/\d?!", $link['url']) ) {
      unset( $links[$key] );
      continue;
    }
}


Javascript Not Functioning At All on Drupal 7 I haven't worked on building out my site for about 5 or 6 days only to come back to find that Javascript is completely non-functional on my site. As far as I can remember (about 90% positive), everything worked fine last time I worked on it.

Using Firebug, I've found the following error 4 times:

jQuery is not defined
})(jQuery);

And this error 7 times:

Drupal is not defined
jQuery.extend(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"capstoneskele","theme_token":"4I-qysgFuZXzCXVlRhgBo6i118JK5s1LLy2-a_ti1lE","js":{"misc\/jquery.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js"......(cont'd)

I've been mostly playing around with a custom theme, so perhaps it's something with one of my tpl.php files - I'm new to Drupal so I really don't know. Any ideas/help would be greatly appreciated as my graduating college is dependent on this project...thanks!

please let me know what further details I can provide also...

Check that in html jquery.js and drupal.js correctly open - just click on links in firefox html source view, it's should open js files.
Check your jquery.js and drupal.js in misc folder, if files exists, compare with drupal archive.
Check how many jquery-VERSIONS.js files attached in html, possibly conflicts can be there.
Check your html source for embedded js scripts (viruses like it).


How do I redirect after saving the user account with $user->save()? How can I redirect users in a custom module after saving a user account with $user->save()? It always goes to the user profile after saving and I want to redirect to a custom page.

function user_update_redirect(&$form, $form_state) {
  $value1 = $form_state->getValue('panel');
  $value2 = $form_state->getValue('type_of_user');
  $storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
  $user = \Drupal::currentUser();
  $user = user_load($user->id());
  $user->set('field_panel', $value1);
  $user->set('field_type_of_user', $value2);
  kint($user);
  $user->save();
}

I suppose you want to remain on your site when redirecting.
I don't recommend hardcoded URL's anywhere else but in route.yml files.
Call the right service and don't forget to use dependency injection in your services and don't use a trait or directly call it from the container.

  private function redirect(string $route) {
    $path = $this->container->get('url_generator')->getPathFromRoute($route);
    return new RedirectResponse($path);
  }


Auto-submit exposed form I'm currently working on a views exposed form block. I want the form to auto-submit using AJAX, whenever an exposed filter is changed.

I have searched for this, but I couldn't find any tutorial or guide.
I cannot see any setting in the view, so I guess I have to implement  hook_form_alter. Is that correct, or am I missing something?

I actually found the answer myself. Using the Better Exposed Filters module did the trick.

From the module's description:

  Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed.


How to change URLs of Mini-Calendar Block View? I'm using the calendar module in drupal 7. I put the block-view mini-calendar but I want to make a change to the URL of each day's link of the month that showing me.

By default, the URL sent me to the full schedule of activities in that month (use event_calendar content type). However, I want to change that view and I just want to make a simple listing of activities for the month.

How I can change the URL to do access the new view I want to create?

Sorry for my english. Thanks in advance.

In mini-calendar view go to advanced -> other -> Link display and change it


Browse only mode for Drupal 6 While we do some server maintenance, how might be prohibit our users from editing or adding content but not put the site in offline mode. That is, we'd like to have content browseable but temporarily prohibit content from changing.

I have never used this module, but seems to do what you want: Read only mode.


Drupal 8 Commerce Module Hook_Theme() I'm working on a custom module that I want to hook into a custom commerce template.

Heres is the code inside of my custom module the returns the variable.

 /**
     * Implements hook_theme().
     * @param $existing
     * @param $type
     * @param $theme
     * @param $path
     * @return array
     */
    function my_theme($existing, $type, $theme, $path) {
        return [
              'commerce-product--full' => [
                'variables'=> array (
                    'key'=> "I'm a key.",
                ),
              ],
        ]
}

Inside of commerce-product--full, using kint(key), I get null as a response.

Am I missing something?

Try implementing hook_theme_registry_alter() and see how that goes.

function mymodule_theme_registry_alter(&$theme_registry) {
    $theme_registry['commerce_product__full']['path'] = drupal_get_path('module', 'mymodule') . '/templates';
}

Your module presumably will have a folder named templates. And inside the folder you have a file called commerce-product--full.html.twig


My battle with drupal's form In the ancient times when things were easy, you just had to code a form in html and then your php would typically have a if($_REQUEST['some_value']) to handle the request. But now with Drupal, nothing is easy... Here is once more my latest battle to understand how Drupal thinks.

Context: I have a list of news (content type "news") shown on a page with paging system. Each news title links to the news details page. This works fine. There is a new requirement that each news must have one or more "tags". The goal is to show a list of checkboxes on top of the news list to allow the user to filter in/out news with the selected tags.

EDIT: After being defeated by Drupal's form I decided to completely bypass the Form API and generate my own fully flexible form.

There is only one thing remaining, Drupal is forcing some div wrappers around each of my input fields. I want to get rid of them (and stop Drupal to think at my place).

In my_news_list.tpl.php I coded:

<form action="" method="post">
<?php
foreach($tags as $tag){
    ?><input type="checkbox" name="tags[]"
        value="<?php echo $tag['id'] ?>"
        onchange="form.submit();"
        <?php if(isset($tag['checked'])){?>checked="checked"<?php }?>
      /><?php echo $tag['value'] ?><?php
}
?>
</form>

Result(!):

<form action="" method="post">

        <input type="checkbox" name="tags[]" value="15" onchange="form.submit();">

    Acquisitions

        <input type="checkbox" name="tags[]" value="14" onchange="form.submit();">

    Corporate

        <input type="checkbox" name="tags[]" value="18" onchange="form.submit();">

    Investor News

        <input type="checkbox" name="tags[]" value="16" onchange="form.submit();">

    Products and Services
</form>

Drupal's Form API is complex but gives you lot of things: is secure, is extensible, is themeable. Indeed is more difficult than coding a simple HTML form, but with a simpel HTML form you have a simple functionality: just that simple HTML form.

Form API generates the form HTML element and handles the POST requests, and validate and submithandlers, you don't and you shouldn't code your own HTML form.

I recommend you to read the Drupal 6 Form API Quickstart Guide. Drupal 7 form handling is pretty the same, but check the Drupal 7 Form API Reference and Form API Internal Workflow Illustration.

In the other hand you may prefer to use a module that address what you need without coding, that's a faceted search: Facet API. From its documentation page:

  Faceted search allows our search results to be filtered by defined
  criteria like category, date, author, location, or anything else that
  can come out of a field. We call these criteria facets. With facets,
  you can narrow down your search more and more until you get to the
  desired results.


How to find all views that have "broken or missing handler"? Is there an easy way to get a list of all views that have a "broken or missing handler" ? To make sure it is ok to disable a module that defines views plugins.

I think in D8 we have proper dependency management for this stuff. But in D7?

Yes, there is a debug option within Views's advanced settings that will print out debug statements via the Devel when a handler is broken.

Combined with Devel's Execute PHP block/form, you can use the execute the following snippet to enable debugging, evoke execution on all Views, and review the output messages for any broken handler warnings between each execution prompt.

// Capture/set debug settings.
$views_debug = variable_get('views_devel_output', FALSE);
$views_region = variable_get('views_devel_region', 'watchdog');
variable_set('views_devel_output', TRUE);
variable_set('views_devel_region', 'message');

// Execute all views/displays
foreach( views_get_all_views() as $view) {
  $displays = array_keys($view->display);
  foreach($displays as $display) {
     dpm("Executing $view->name ($display):");
     $view->execute($display);
     $view = $view->clone_view();
  }
}

// Reset debug settings.
variable_set('views_devel_output', $views_debug);
variable_set('views_devel_region', $views_region);


Don't show Header view after clicking next on pager I'm -very- close to finishing my first drupal site, I've got just one or two more hurdles to overcome and I'm hoping you can help me.

On my /news page (showing Articles), at the top I want to show the 4 most recent Articles as teasers. Below that, I want to show a grid of next 12 most recent Articles. Below that I want to include a pager to allow them to see older Articles.

Using Views and Page Manager I've created a page that gets me very close.

I have a View for "Most Recent Articles" which shows the 4 most recent teasers.

I have a View for "More Articles" which shows a grid of fields of 12 Articles with an offset of 4 so that it doesn't include the 4 most recent.

In Page Manager I created a page that includes the Most Recent Articles View and then includes the More Articles View. This works very well and gives me exactly what I want.

My Problem: When I click the "next" link in the pager at the bottom of the More Articles view, I don't want to show the Most Recent Articles anymore. I'd either like to hide that View on subsequent pages or I'd like to selective only include it on the 1st page (two different approaches to the same idea).

Help?

I have an idea:

Create a third view that's a page showing articles with an offset of 16 (so it skips the 4 and the 12).  Call it 'older articles'.

Then instead of a pager, have a 'more' link under your view of 12.  It's important, in the 'Advanced' section of the view, to set the more link to go to that new views page (older articles).  The older articles page can then have its own pager!!!  But the initial articles page -- the landing page -- can just have a 'view more' link so it can hop over to the older views altogether.

Would that be sufficient?


Translating paths in routing.yml How do you translate the path portion of a module route?

For instance you have:

module_name.my_route_name:
  path: '/path/to/content'
  defaults:
    _controller: \Drupal\module_name\Controller\MyController

How do I get /es/ruta-de-acceso/a/contenido to point to the same route name?

As far as I know (anyone, correct me if I'm wrong!) this is not possible in the routing system. You can however add a path alias, and make "/ruta-de-acceso/a/contenido" an alias in the Spanish language for '/path/to/content'.

Now the problem with path aliases, compared to routes, it that they are considered content, not core or configuration. As a result there is (again: AFAIK) currently no way to export them and deploy them to a server. For a recent project, I solved that with some custom code in the .install file of a custom module. You can see the code in this Github gist: Drupal 8: Custom path aliases exported to code.


Grey out other checkboxes My scenario looks as follow: I have a form element of checkboxes, e.g. 3. If the rightmost checkbox is marked, the other 2 are greyed out and so on. I don't know how to do this, because if I use the #disabled property all of them are greyed out.

I thought about to make several single checkboxes of type #checkbox and use an ajax call and look at the $form_state and rerender all of them as single ones (disable them then etc.). But there is a problem that I use a form in a drupal block, and I haven't got the &$form_state as a parameter of the function.

What is the best method to do this?

This question is not exactly related to drupal.

Still you can use jQuery to make it work.

Just get the wrapper class of parent element

jQuery('#edit-field-hobby-und .form-checkbox').click(function(){
  jQuery("#edit-field-hobby-und .form-checkbox").each(function(){
  jQuery(this).attr('disabled',true);

  });
  jQuery(this).removeAttr('disabled','disabled')
})

Here form-checkbox is the class of the checkboxes and edit-field-hobby-und is the id of its wrapper.

Hope it will help!


Disable locale module breaks site We want to disable the locale module in Drupal site. Because some content was saved as language 'en' previously, disabling locale does not reset content and field database tables language field to 'und' or LANGUAGE_NONE. After disabling the module any nodes or fields that have been saved as 'en' are not displayed.

to fix this I created a module to update the entire database.

    $schema = drupal_get_schema();

    foreach($schema as $table =>$structure){

     if(isset($structure['fields']) && isset($structure['fields']['language'])){

           set_time_limit(0);

          db_update($table)
            ->fields(array('language' => 'und'))
            ->condition('language','en')
            ->execute();
   }
}

This code does not update the language field and i'm not sure why. Is it because the language field is an index?

also this should be incorporated into the locale module uninstall function to avoid other sites breaking in future.

Any help is appreciated

Origional post -- https://drupal.org/node/2106247

Here is what I did to solve this problem:

Learn how to run scripts with Drush http://www.oliverdavies.uk/blog/dont-bootstrap-drupal-use-drush/
Write this script:

<?php

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')->addMetaData('account', user_load(1));
$result = $query->execute();
$nids = array_keys($result['node']);
$n = count($nids);

foreach($nids as $i => $nid) { // go through ALL nodes
  $node = node_load($nid); // load the node
  $type = $node->type; // get the content type
  $field_langs = field_language('node', $node); // get the language of each field
  foreach($field_langs as $field => $lang) { // go through ALL field of this node
    if ($lang != LANGUAGE_NONE) { // if the field is in the wrong language
      $items = field_get_items('node',$node,$field,$lang); // get all field values
      if (!empty($items)) {
        $node->{$field}[LANGUAGE_NONE] = $items; // put it under language neutral
        unset($node->{$field}[$lang]); // remove the old language
      }
    }
  }
  $node->language = LANGUAGE_NONE; // set the node language to neutral
  node_save($node); // commit changes
  echo ("$i/$n\tnid=$nid\t$type\n"); // progress report
}

Run it to translate every node on the site back to language neutral

I cannot guarantee that this works for nodes with fields that have values in more than one language at a time. Feel free to use and improve this code. I have tested this on my development site, and all seems fine after disabling & uninstalling locale. Let me know in the comments if this works for you, too!


Using OR in conditional fields I have several select fields in content type, which is more like Q/A & most of the answers are YES/NO. It's like tree flow, all question are dependent upon answer of previous question.

I am using condition fields & field conditional state module for this purpose. OR can be implemented by help of FIELD CONDITIONAL STATE as module description says --

Module supports AND/OR functionality for control fields which means:

    AND - all choices must be selected to control the filed
      (example: field A will be visible when in field B option 1 and option 2 is selected)
    OR - any choice will control field
      (example: field A will be visible when in field B option 1 or option 2 is selected).

But I have some fields(e.g. Field C) which should be appear on selection of YES of Field A or NO of Field B.

Is it possible to achieve it by this module or some other way by any contributed module. I am not looking for making my own form by FORM API as I have around 60 question in content type & it will become so messy to manage in code.

Edited --

I have searched & got option such as using OR in conditional field in this manner-

field_atleast_50_capital is visible when field_property_deriving has value "No".
OR
field_atleast_50_capital is visible when field_arrangements_90_subsidiary has value "Yes".

But it doesn't work..

just an observation from looking at the module documentation:

there is a note under interaction with other dependencies on the Edit dependency page which says this:

When this dependent has more than one dependee, how should this condition be evaluated against the others?
Note that sets will be grouped this way: ANDs AND ORs AND XORs

with a selection for AND, OR and XOR

This would indicate that you

define your dependency of field C on A,
define your dependency of field C on B
and select OR as your interaction with other dependencies


How can I use PHP to print a view in the content area of a page? The Private Message module displays conversations between users as "threads" that resemble e-mail or forum friends.  I am attempting to customize the default display by printing a view that shows the recipient/sender profile information.

Through trial and error I arrived at the following code, which prints out the view content pane that I want.

  foreach($thread['participants'] as $participants => $participant ) {
    global $user;
    if ($user->uid !== $participant->uid) {
      print views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);
    }
  }

This code resides in privatemsg.pages.inc in function privatemsg_view($thread), which returns the content of the page for rendering.

The problem with this is that print views_embed_view() prints the content pane out at the top of the page, above the header, with no extra markup.  How can I print the content pane in the content region of the page?

As a starting point I would have the function return the view rather than attempting to print it. Try:

 $content['view'][] = views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);

and then render it in the page at the proper place. (views_get_view might be better in this context.)


How do I alter images being added via IMCE CKEditor plugin? I just wanted to share my solution since I did not find any clue or different way of fixing the following problem:

Formerly, you could add a default class/ alter attributes of newly inserted images (or elements) in CKEditor. In Drupal 8, the ckeditor.config.js apparently was removed. Also, images added via IMCE CKEditor plugin are added via insertHTML and there seems not to be any way of manipulate the html string (despite listening to the insertHtml event) with the htmlParser.

How to alter the attributes of images added via imce in ckeditor?

So, here is what I did, even if maybe its dirty.

Add a new module which attaches a custom library to forms:

function mymodule_form_alter(&$form, $form_state) {
  $form['#attached']['library'][] = 'mymodule/form';
}

In the mymodule.libraries.yml:

form:
  version: 1.x
  js:
    js/mymodule.js: {}
  dependencies:
    - core/ckeditor
    - ckeditor/drupal.ckeditor
    - imce/drupal.imce
    - imce/drupal.imce.ckeditor

And in the mymodule.js I pretty much just re-write the imce sendto function:

if (undefined !== CKEDITOR && CKEDITOR.imce.sendto) {
  CKEDITOR.imce.sendto = function (File, win) {
    var imce = win.imce;
    var editor = CKEDITOR.instances[imce.getQuery('ck_id')];
    if (editor) {
      var i;
      var text;
      var lines = [];
      var selection = imce.getSelection();
      var is_img = imce.getQuery('type') === 'image';
      for (i in selection) {
        if (!imce.owns(selection, i)) {
          continue;
        }
        File = selection[i];
        // Image
        if (is_img && File.width) {
          lines.push('');
        }
        // Link
        else {
          // Use the selected text/image for the first link
          text = !lines.length && CKEDITOR.imce.getSelectedHtml(editor) || File.formatName();
          lines.push('' + text + '');
        }
      }
      editor.insertHtml(lines.join('
'));
    }
    win.close();
  };
}

Hope this is helpful to somebody. And maybe there is another, better way of doing this - glad for any input!


db_query() to retrieve the image path using the fid In Drupal 7, I'm trying to retrieve the image path for a given fid.

If I am running a query such as the following, that is fine and dandy and returns a bunch of numbers that relate to the images on each row.

$query = db_query("Select s.field_swatch_image_fid as fid from {field_data_field_swatch_image} s");

foreach ($query as $row) {
  $swatch_fid => $row->fid .'<br />';
}

However, the table contains no information as to how to retrieve the actual image. Does anyone know the secret to pull the actual image URL into the foreach loop, or is there some sort of render function that needs to be run on the fid values? I'm guessing it is easy, but I can't seem to find any documentation on this.

Also, if I wanted to apply a style to the images, would that be a necessary step if the style was already set on the field image itself, and if so, what would be that process?

EDIT:
here is the full query. I was doing it manually because I have to retrieve the value and send a json object back to jquery and then render it in jquery. But this is kindof the start to a different and larger question.

Declare database variables to be used in the database call
 - so far this was easier than looking at all the giant field names Drupal creates in the database
 - hoping to rewrite the query in the new improved drupal 7 style soon

*/

  $swatchcolor = "field_data_field_swatch_color";  // sc - swatch color data table
  $color = "field_swatch_color_value";
  $states = "field_data_field_state"; // s the table that holds the swatch's reference to the state
  $state = "field_state_value";
  $swatchref = "field_data_field_swatch_ref"; // sr - swatch reference target table
  $target = "field_swatch_ref_target_id";
  $imagetable = "field_data_field_swatch_image"; // swatch image ref
  $parent_ref = "field_product_ref_target_id";
  // If a swatch has not been selected, run this query and select all colors as options

  if($swc == '') {

    $query = db_query ("Select n.nid AS nid, n.title AS title, s.$state AS state
        FROM {node} n
        INNER JOIN {$swatchref} sr ON sr.$target = n.nid
        INNER JOIN {$states} s ON s.entity_id = sr.entity_id
        WHERE (s.$state IN $theregion)
        GROUP BY title");

  } else {

      $query = db_query ("Select n.nid AS nid, n.title AS title, sc.$color AS color, s.$state AS state
        FROM {node} n
        INNER JOIN {$swatchcolor} sc ON sc.entity_id = n.nid
        INNER JOIN {$swatchref} sr ON sr.$target = n.nid
        INNER JOIN {$states} s ON s.entity_id = sr.entity_id
        WHERE (sc.$color = '$swc') AND (s.$state IN $theregion)
        GROUP BY title");

  }

EDIT!!
Here is how the image path was integrated into the json output:

 $json = array();
        foreach ($query as $row) {

        // get the image fid

          $fid = $row->thefid;
          $file = file_load($fid);
          // $file = str_replace('public:\/\/', '', $file1);

        // create the output as an array
          $jsonelement=array(

             'title' => $row->title,
             'path' => $file->uri,
             'style_name' => 'swatch'

            );
              array_push($json,$jsonelement);
        }

            // encode to json
            $jsonstring = drupal_json_encode($json);

            //output the json string
            drupal_json_output($jsonstring);

There is no need for manual queries.

You can load a file using file_load($fid), and then the path is in $file->uri. It might look a bit stringe ('public://something.jpg'), but that's a so called stream wrapper, and it works just fine with plain PHP file functions.

It's not exactly clear to me what you are trying to achieve; if you want to render an image field from a node/user/..., there are better ways to embed title and things like that, but this would work if you really just have a field. (That you are trying to query the field data table suggests otherwise, though.)

<?php
  $file = file_load($fid);
  $variables = array(
    'path' => $file->uri,
    'style_name' => 'your_style_name',
  );
  print theme('image_style', $variables);
?>


Better Exposed filter when shown in pane configuration, then they are all coming as checked Create a view of type Content Type, add a filter expose it, select it as drop down (Will be better if term reference field). After that select Exposed Form Style as Better Exposed Filters, and under BEF settings, show the filter as checkbox. After that under Pane Settings >> Allow Settings >> Check the checkbox "Use exposed widgets form as pane configuration", and save the view. After that create a mini panel through pane, and under settings you will see filters as checked.

Please give me some idea for the same.

Issue was of BEF version, prev. version was 7.x-3.0beta3, after upgrading to 7.x-3.2, problem gets resolved.


Move footer structure to html.tpl.php I've attempted to move the footer structure of a theme from page.tpl to html.tpl so the footer elements can occur outside of internal width specific layout.

In doing so I receive an error:

  Fatal error: Only variables can be passed by reference in....

One of the many lines in question is:

<?php print render($page['footer_first']); ?>

Can someone explain what exactly the issue is here and how I can best solve it ? Muchly appreciated!

I am not too sure what this error would be caused by but I would recommend instead of putting the footer into the html.tpl.php put a wrapper div around the other elements within the page.tpl.php excluding the footer and styling that wrapper with a specific width.

eg.

      //all content in here

      //footer here


How to point a menu link at a View with multiple options on the same exposed filter selected? I've got a view page that serves like a catalog, using many exposed filters.

I want a menu link that points to a certain combination of filters. Let's say the URL for this filtered view is>

  view?option[]=7&option[]=12&option[]=14

Sounds simple, but I'm finding this difficult for a number of reasons:

Menu considers this an invalid path
I can't turn it into a path alias, because that also considers it an invalid path
I can set it up as a redirect, but Menu still won't recognise the redirect as a valid path
I can set it up as a Page Manager page using cTools' page manager, and set that to act as a redirect, but every parameter except the last one gets chopped and it redirects to this. It seems like it doesn't like the ampersands:

  view?option[]=14

If I input it with the ampersands URL encoded, it gets confused because it double URL encodes the URL encoded characters, breaking them.

Got it working. I set it up as a Page Manager page with an arbitrary path (e.g. options or view/options), set to "HTTP Response Code" then "301 redirect".

The problem in the question where the ampersand-seperated characters were getting eaten seemed to be caused by Drupal treating them as duplicates of each other and rejecting all except the last. To get around that, I set the redirect URL to:

  view?option[1]=7&option[2]=12&option[3]=14

Note how each one has a unique number in the square brackets.

Views doesn't seem to care about the numbers in the square brackets, and they stop Drupal merging the parameters into one.

Note you should always input the non-encoded version, like above, else Drupal will double-encode it causing it to break. Keep this in mind if you edit it - you'll need to replace the whole string with the original, non-encoded version then edit that before saving.


Pass values to twig file from #theme options I need to create a select field in a config form and pass values to it along with custom #theme options.
Its easy to pass header & row values. But after selecting a value from select box, I need to load another dropdown, Below is my reference code:
addslider.php
 public function buildForm(array $form, FormStateInterface $form_state) {
 $vid = 'my_categories';
 $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);

 foreach ($terms as $term) {
   $custom_categories[$term->tid] = str_repeat('-', $term->depth) . $term->name;
 }
  $form['block']['sliders'] = array(
  '#type' => 'fieldset',
  '#title' => $this->t('My Sliders'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#theme'  => 'my_custom_slider_table',
);

foreach ($block['sliders'] as $key => $slider) {

$form['block']['sliders'][$key]['tid'] = array(
  '#type'          => 'select',
  '#title'         => t('Categories'),
  '#options'       => $custom_categories,
  '#required'      => TRUE,
  '#default_value' => !empty($slider['tid']) ? $slider['tid'] : NULL,
);
}

hook_theme() in module file:
function mycustom_theme() {
  return [
    'my_custom_slider_table' => [
    //'variables' => [
    //'header' => $header,
    //'rows' => $example_rows,
    //'attributes' => array('id' => $table_id),
    //],
    'variables' => [
    'slider ' => [],
    ],
  ],
];

}

my-custom-slider-table.html.twig file:

      {{ 'Taxonomy select' }}
      {{ 'Reference Node' }}
      {{ 'Options' }}

 {{ slider }}	Test Sponsors	Edit/Delete

I need to get the output of $custom_categories variable in twig file, for the first td in {{ slider }} . Can you please help, new to Drupal8.

You need to add it to your $build render object. Here's a piece of sample code, in this case from a Block plugin with a form on it, similar to yours:
...
in my BlockPlugin
..

public function build() {
    // getConfiguration returns the values from the form I have and save to a config object.
    $source = $this->getConfiguration()['source'];
    $access_token = $this->getConfiguration()['access_token'];

    $build = [
      '#theme' => 'my_fancy_search_widget',
      '#source_data' => $source,
      '#access_token' => $access_token,
    ];
    return $build;
  }

...
in my .module file:
...

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
  'my_fancy_search_widget' => [
      'template' => 'main-search',
      'variables' => [
        'source_data' => NULL,
        'access_token' => NULL,
      ],
  ];
}

in my twig template I can print these vars with {{ source_data }} and {{ access_token }}


Is it possible to subscribe to a newsletter without first having to register? I am using the Simplenews module, but from what I've been able to conclude, is not possible to subscribe to a newsletter without first having to register.  Is that correct?

Is there a different newsletter module which will enable me to do this: offer a newsletter subscription to users without having to first become a registered user?

It is supposed to be possible, but the anonymous user is still required to confirm their email address. Check this issue in the Simplenews issue queue.


Where is the index file? I've made a drupal site using acquia Dev desktop 7.16.16 and i would like to know where the index.HTML or index.php file is stored? I found an index.php file at /Sites/acquia-drupal/ directory but it seems to need a root to work.

Drupal is a dynamic application, having an index.html file wouldn't make much sense.

There is an index.php file at the root of the install (the one you've already found). All requests are sent to that script, and the Drupal bootstrap takes over and routes them to the PHP function responsible for serving the appropriate content.

If you want to change the content on the front page, the simplest way would be to create a new node (of whatever type you feel is appropriate), visit /admin/config/system/site-information, and set the "Default front page" to the page of that new node.


How to add print stylesheets How do I add a print stylesheet in Drupal 8?  Here is what my libraries file looks like in my theme...

global-styling:
  version: 8.0
  css:
    base:
      css/style.css: {}
    theme:
      css/print.css: { media: print }

Does that look correct?  If it is correct, should I also include print media queries in the print.css file?  Or do I not need those media queries because of the "media: print" annotation in my libraries file?

Since I can't inspect the print-preview source, how do I know what classes to use in my print CSS?

(And is there anything else in Drupal 8 that influences the print styles?  I am working on a site I did not build, and it has print styles, but I don't know where they are coming from.  I thought maybe they were coming from the base theme, but I removed the base theme from my theme's info file and I continue to see styled output when I print-preview the page.  The styled output is bad, and needs to be corrected, but I don't know where it's coming from.)

If it is correct, should I also include print media queries in the print.css file?

It's correct, and there's no need for media queries in the CSS file.

(Separately, I'm still trying to determine what else is supplying the print styles in my site, aside from the ones I'm adding intentionally.  But I can confirm that the above annotation example works.)


Periodically set the userpoints for every user I would like to set the user points of members of my site to an x amount at the start of each month.
What would be the best way for this?

The closest I found so far was this:
http://drupal.org/node/549640

There are a few issues with this though:
1. It adds 5 points, instead of setting it to 5 universally
2. It uses a while loop which can take long if there are a lot of users

I am thinking of a quick and dirty UPDATE SQL query that does this in one go.

you could extend the userpoints module to have some actions exposed to VBO then execute that periodically with Rules. Depends how much time you have, but it would be a nice addition to that module..


global variable for path In my project I want to provide path of some files from root directory. Path has repeated 4 to 5 time in one module so I am thinking that put one global variable and access that variable in same module?

I have try (dirname(__FILE__).'\sound\new'); realpath; drupal_realpath ; pathinfo; .

You can get the path using drupal default function drupal_get_path();

It return path to any module or theme from root of installation.

If i want to access path of any module e.g. mymodule

Then i just need to use,

$path = drupal_get_path('module','mymodule');   //path to module directory

If i want to access path of my theme e.g. mytheme

$path =  drupal_get_path('theme','mytheme');   //path to theme directory

Now you can make the path variable global..