how to get list of all route in routeProvider?

Not really sure what you are aiming for, but you have it already as the getRoutes() method works with a Symfony RouteCollection collection

class MyRouteProvider extends DefaultHtmlRouteProvider {
  public function getRoutes(EntityTypeInterface $entity_type) {
    /** @var \Symfony\Component\Routing\RouteCollection */
    $collection = parent::getRoutes($entity_type);
    /** @var \Symfony\Component\Routing\Route[] */
    $routes = $collection->all();

    return $collection;
  }
}

If sounds like, though, you want to implement a RouteSubscriber to alter the route.  There are a bunch of these in core to use as examples.  And you don't need to get all of the routes, and then search through them.  You can just use the route collection and get the route that you need.  The route subscriber defined by the Node module is probably the simplest example:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // As nodes are the primary type of content, the node listing should be
    // easily available. In order to do that, override admin/content to show
    // a node listing instead of the path's child links.
    $route = $collection->get('system.admin_content');
    if ($route) {
      $route->setDefaults([
        '_title' => 'Content',
        '_entity_list' => 'node',
      ]);
      $route->setRequirements([
        '_permission' => 'access content overview',
      ]);
    }
  }

}

Note that is just does a $collection->get() to find a particular route, and then modifies it.


Dashboard is empty for roles apart from admin

May be you have assign blocks to the region of non admin theme. If so, you have to assign the blocks to the region of admin theme(seven or enabled admin theme in your drupal system).


How to run a batch process in regular interval

You can use cron to do this, set a cron time in admin/config/system/cron for your site.

there is a hook_cron() is available in your drupal . using that hook you can configure your batch process to invoke.


Where can we store 3rd party application passwords?

Yes, if you're looking for a Drupal-centric solution, the Key module might provide what you're looking for. It supports pulling your stored secrets from a few different locations:

Config
File
Environment Variable
3rd party services

As far a best, there's really no one-size-fits-all answer. It depends on your data storage requirements and what you're protecting (e.g. an API key for a medical records REST API should have heavy restrictions whereas a Slack webhook is pretty low risk).

If you're wanting a scalable solution, you might want to consider one of the many 3rd party services that provide secret management.


Look for documentation about how precisely modules parts are loaded (Drupal 7)

After a lot of tests, I'm now pretty convinced that, despite it is not mentioned in the release notes page, a change happened in 7.34, which consists in that, now, the full-bootstrap condition is not reached yet when the MODULE.module file is loaded.

According to module_load_include() page, this function requires Drupal to be fully bootstrapped: this clearly relies to the use of drupal_get_path() (see the function code in this page), which is not available without full-bootstrap.

It is why my (global-scoped) module_load_include() calls are executed but without result (see 'file: mymodule.module' in my question above).

I had to modify my module, including a dedicated module_load_include() call inside each function which needed it, like this:

<?php

function mymodule_some_hook() {
    module_load_include('inc', 'mymodule', 'mymodule.core');
    # ...
    myfunction();
    # ...
}

This way, now all works fine anew.

I verified it is the same with Drupal 7.36: my module doesn't work in its original implementation, then it does with this modification.

Hope this helps.


Not all content showing up after uploading to live server

It could be a control character that would remain or be not there when moving from one platform to another. Line breaks in Windows, UNIX and Macintosh text files all are different. If you have moved the database from one platform to another care should be taken to insure cr lf couplets are considered.

A similar situation could result from a database conversion that did not take into account these differences.


How to change the revision uid on node save

You'll have to impersonate a user while performing your operation:

<?php
//Save current user data/session
global $user;
$original_user = $user;
$old_state = drupal_save_session(FALSE);

$field_uid = field_get_items('node', $node, 'uid');
    if($field_uid){
         // Load new $user data
         $user = user_load($node->uid);

         $node->log = $node->uid;
         $node->revision_uid = $user->uid;
    }

// Fail safe - if your code fails session won't be saved
$user = $original_user;
//Rever to old user and save session
drupal_save_session($old_state);
?>

References:

http://drupal.org/node/1082292
http://firedev.ro/blog/node-revision-when-doing-nodesave-gets-currently-logged-users-uid


try:

under Advanced Tab, create a relationship. the type will depend on your field names exactly, but if the view is for the country, you should be able to find the destination and attraction fields available.

the new related fields should show up now in your Fields list and you can add them to the view

For the count, try the following:

Entity Reference Count
or
Entity Reference Calc
or take a look at this on SO


What is the recommended method for programmatically editing or inserting values into the field_data_* tables?

If you want to create users belonging to a group (able to publish content under the group, see group content), og_group() should do the trick; I'd check your implementation and make sure it's ok before going too far astray. I'm doing the exact same thing with the following code and it's correctly inserting the group_audience values into the field_data_group_audience table.

og_group($group_id, array('entity' => $account));

However, if you're totally stuck and want to try another route, you can always manually insert the data through db_insert().


After some research I come to know that is not a good option for a big project due to performance, Field collection can be quite annoying from a performance perspective.

There are alternative ways to achieve a better result.

1 - Composed Field worked for me and improved system performance

2 - Creating a new content type to represent collection and then using Inline Entity Form to allow creation of the collection inside of the content type referencing it.

3- Using Multifield. however data extract could be a pain.


Search a content type based on certain criteria

You will need to make use of the views module  to create the functionality you are looking for.

Create a new display of type page
Then select show content of type [Your content type]
Add fields you want users to be able to search on
Create filters and expose the filters


wrapping menu items with span in Drupal 6

The answer that you found is for Drupal 7 not for Drupal 6.

In Drupal 6 you can't override theme_links() for a specific target.

You need to override theme_links() function itself to add span tag as the following code:

function sub_website_links($links, $attributes = array('class' => 'links')) {
  global $language;
  $output = '';

  if (count($links) > 0) {
    $output = '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = $key;

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class .= ' first';
      }
      if ($i == $num_links) {
        $class .= ' last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
          && (empty($link['language']) || $link['language']->language == $language->language)) {
        $class .= ' active';
      }
      $output .= '
 $class)) .'>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.

        // check if menu id attribute is set to primary-links
        if(isset($attributes['id']) && $attributes['id'] == 'primary-links') {

          // add html to link options
          $link['html'] = true;

          // wrap text with span
          $output .= l('' . $link['title'] . '', $link['href'], $link);

        } else {
          $output .= l($link['title'], $link['href'], $link);
        }

      }
      else if (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= ''. $link['title'] .'';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Then edit page.tpl.php and add id attribute for $primary_links menu

print theme('links', $primary_links, array('id' => 'primary-links', 'class' => 'links clearfix'));


How to stop webform from sending an email

If you go the end of the function webform_submission_send_mail() inside the file webform.submissions.inc (inside weform module's include directory), you'll notice that the webform module using the function drupal_mail() to send the mail.

So a better place to change the behavior of the mail from being sent (alter in Drupal terms) is hook_mail_alter(), which is used to alter an email message created by using drupal_mail() function.

Implementation of the hook to stop the e-mails:

function MODULE_mail_alter(&$message) {
  //You can do your conditional check here and depending on that
  //you can set the value of $message['send'] to false to stop the mail from being sent.
  //place the line below inside conditional loop, or else it'll stop every mail from being sent ;-)
  $message['send'] = FALSE;
}

Note: This hook will only work if the mail is generated by drupal_mail(). If you're sending mail by some other menthod, it'll not be invoked. But, by default Webform module uses drupal_mail() as mentioned earlier, so there's nothing to worry :-)
You'll also need to clear the caches to make the change effective.


I have found this to work

Use Drupal\image\Entity\ImageStyle;
$file_uri = $user->get('user_picture')->entity->getFileUri();
$styled_image_url = ImageStyle::load("large")->buildUrl($file_uri);


How to send an email to multiple recepient with contact form?

Here is a possible implementation to achieve what you're asking about:

define a new eMail ID, say x@sample.com.
configure this x@sample.com to automatically forward all incoming eMail to your "multiple eMail addresses".
in your form, use x@sample.comas the email ID where these forms should be eMailed to (which will then be forwarded after you completed the prior step).


dpm() in hook_init shows twice on the page

hook_init runs once per-page request, for non-cached pages.

See _drupal_bootstrap_full

module_invoke_all('init');

I guess what's perhaps happening in your case is an additional ajax request is bootstrapping Drupal and triggering an additional hook_init call.


Add translation only for a particular content type

It's by design...

Drupal Content translation using modules like i18n and locale works for complete site... For example if you are using Arabic language and if you add a arabic translation for a particular node, if you are viewing arabic version of node complete site changes from right to left..

As a work around..If you just want to add translations i would suggest use modules like Entity reference and node clone to connect english version with other versions and use select box to choose language.. You need to add links to redirect user to other versions based on above reference logic.. Keep in mind by implementing above you will loose Drupal powerful Multilingual feature..


Drupal 8 - Pathauto taxonomy terms in content paths

If you have a taxonomy vocabulary named company

And you have a taxonomy entity reference on your basic page machine-named field_company

Then the pattern you want in pathauto is:

[node:field_company:entity:field_short_name]/[node:title]

This says, "find the value of field_company on the current node, get it's referenced entity, find the value of field_short_name / the node title"


Without a leading '/' (or '/foo/' if the site is in a subfolder) the browser will always to try to find the image relative to the current path, not to the root of the site. That's why your current code works on the home page, but not on other pages.

To fix it you just need to add the base path as well:

  <img src="<?php print $base_path . drupal_get_path("theme", "my_custom_theme"); ?>/img/logo-mobile.png">


Views: Access CCK image delta for each image link

Depending on the views version you use, you have different options to render a multiple values field and the fields themselves.

The easiest thing in this case would be to create a special field formatter for the images. Field formatters are almost exactly same for both Drupal 6 and 7 and is what you could call a theme function for fields. In that theme function you would be able to handle the different deltas, as you will have that variable accessible.

This  post explains a bit about field formatters.
This post explains how to create a field formatter (D6).


Try the Masked-Input module. It does exactly what you are looking for.


The line item entity doesn't have revisions, so you would need to add this for all line items. Which means, you need to alter some of the very core of Drupal Commerce. It's possible, but maybe it would be better to store bookings in a custom table and save a reference on the line item instead.


This is in the settings of the content type:

  /admin/structure/types/manage/article

Here you'll find in the tab Display settings the checkbox:

  [x] Display author and date information


cron for rebuild xmlsitemap mannually without drush in cpanel

You can probably request the the Drupal 7 cronjob by using wget or curl. On my server I can use: /usr/bin/wget -O -q /dev/null http://www.example.com/cron.php?cron_key=XXXXX.

The cron key is different per website and can be found on your status report page.

This basically opens a webpage just as if you would be running cron manually, but you can set an interval for it. If you set xmlsitemap to generate a new sitemap during cron (I believe that is default behavior), you should be good. You can set the rebuild time on the settings tab:
.

There is no direct need for Drush (though you can do this with Drush as well), and it is not possible to run Drush with curl.

If you or someone else wants to use Drush;
After installing Drush on the system you can use it like any other program: drush xmlsitemap-rebuild or drush @site_alias xmlsitemap-rebuild if you configured a site alias.


Breadcrumbs for nodes have no cache tags. The reason is that the node entity has no specific breadcrumb builder. The generic path based breadcrumb builder gets the title from the title resolver and is not aware where the title is from and what tag it should set.

You can add tags for nodes in hook_system_breadcrumb alter():

function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  if ($route_match && $node = $route_match->getParameter('node')) {
    $breadcrumb->addCacheableDependency($node);
  }
}

To test this you need to have extended the breadcrumb behavior to display the title. In my test site this was the Bootstrap theme. Another option would be the module Current Page Crumb.


I want to add css class to a field inside hook_field_widget_form_alter, but it doesn't work!

Old issue but it might help future viewers.
Try this:
$element['value']['#attributes']['class'] = 'myclass';

See field_multiple_value_form() which creates the render array.
Then main theme function for rendering fields in forms is theme_field_multiple_value_form() and the parent theme function is theme_form_element()


Accord with the Documentation you can use:

none (default)
fade
slide


Try using user568458's solution, but instead of displaying fields in the view, display a "fully rendered node" and set the view mode to a custom view mode.

To customize a view mode, and then configure the layout of a custom view mode, use Display Suite module.

See this about view modes.

If you activate Display Suite's sub module Panel View modes, you can then use the Panels module interface, instead of Display Suite for layouts.

EDIT
I just went to do this myself and discovered that this feature has disappeared in the latest version of Display Suite!

Bummer :(

However, you can still utilize Display Suite to a lesser degree... Sorry


I think you need to add the pager context to item #cache


Add a signature and date line to node print template?

Add a code field to Display Suite that is visible on nodes, and add your HTML to the code field.

Place the field last for the specific view mode, and make sure to assign a class (or assign the class directly in the html of the code field) on outer html element.

Test that the html is displayed on node view (normal page view).

In you theme's style css (css that targets web page view) set the display of this class to none. Now it should only show for print. If it does not go into your theme's print.css file and set the display to block or whatever you prefer. If there is no print.css (highly unlikely) then just add a @media print rule to your css.


Permanent Deleting of files still doesn't work for me (make_unused_managed_files_temporary = true)

I just made a solution that works for me even the Drupal or config doesn't works properly. In my plugin I hooked up the hook_cron() for logging these unused files to proceed them next.

SQL SELECT; query to fetch all file_managed fid's. You can select only status=1, as permanent files, but I got all,
PHP loop all id's and making a Drupal\file\FileInterface entity reference $file = File::load($item->fid) to check all the file references $references = file_get_file_references($file). When the $references is empty() this file is unused. Save all that fid id's into array $fids,
SQL UPDATE; build update query to null these rows: UPDATE file_managed SET status=0 WHERE fid IN($fids) and UPDATE file_usage SET count=0 WHERE fid IN ($fids).

Finaly after next cron run the default function file_cron() {... will properly delete these files.


Retriving nodes by content type using Drupal::entityQuery

This is how we do this:

$ids = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->execute();

$products = \Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($ids);


How to specify a permission as an access argument?

This is based on Drupal 6 but I doubt it has changed.

access arguments returns true if the user has the permission specified in the array, however, it does not make sure to create that permission if it doesn't exist. If you want to use a module specific permission you need to define it using hook_permission (hook_perm for D6). If there already exists a permission that will suit you needs you can simply call that instead, though.


In drupal 7, How to override theme_pager?

Implement all/selected of the following theme functions in your template.php:

theme_pager() - main theming function, using:

theme_pager_first()
theme_pager_previous()
theme_pager_next()
theme_pager_last()

changing 'theme' in each of these function names to short name of your theme.


How to make slideshows work on mobile devices browsers?

Download the FlexSlider library from https://github.com/woothemes/FlexSlider

Put the folder in a libraries directory sites/all/libraries and also

Try installing the FlexSlider Views Slideshow module which integration with Views Slideshow and FlexSlider

  This is the FlexSlider Views Slideshow module which used to be
  included in FlexSlider by default.

This tutorial shows you how to create a responsive slideshow using the Views Slideshow module and jQuery FlexSlider.


file_create_url() equivalent in a javascript file?

CDN has already done its magic by the time the JavaScript file has been prepared for output, and there are no AJAX callbacks allowing it to do its magic from the JS file itself.

If you do know ahead the name of the scripts you might load (or you can iterate from your theme or module) then the trick is to inject those paths as variables directly in your theme using inline JavaScript. For example, from your module or your theme's hook_html_head_alter method in template.php, to add one file (the method would be the same for a list of files, but an array would best be used):

drupal_add_js('var my_js_file_1 = "' . file_create_url(drupal_get_path('theme', 'my_theme') . '/js/file_1.js') . '";' , 'inline');

then you can call

$.getScript(my_js_file_1);

in your code.

The magic is done through the file_create_url, which is what the CDN module processes.


Disable coupons field from checkout page when order total amout is less than $500

Hope it works.

function module_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {

  if ($form_state['order']->commerce_order_total['und'][0]['amount'] < 500) {
    unset($form['commerce_coupon']); // enter coupon form name
  }
}


Use the below code for fetching values. It will give you field_naam_value field data.

$naam = db_select('profile', 'pf');
$naam->join('field_data_field_naam', 'fd', 'pf.pid = fd.entity_id');
$all_names = $naam->fields('fd', ['field_naam_value'])
  ->condition('pf.uid', 4, '=')
  ->execute()
  ->fetchAll();
foreach ($all_names as $record) {
  die;
}


I have finally managed to find a workaround which involves creating a view that displays the media field images based on contextual information from the node.  The field formatter can be changed to a view using views_field_formatter module

Here is in a little more detail

lets assume the content type that we want to have media gallery is named "gallery" and it contains a media field "field_media" and assume colorbox and views_field_formatter modules are installed and enabled

prepare a view that displays nodes of content type "gallery" (a block view is enough)
add relationship that exposes the field_media and call it "media"
add contextual filter "Content ID" based on "media" relationship
add appropriate image field to display (based on the "media"
relationship) and use colorbox formatter (since this field is an
image colorbox will be available)
go to the gallery content type display settings and configure the media field  to use the view prepared above passing as first parameter the node id


On click of checkbox send email to selected recipients using module

"to" parameter in drupal_mail is a string. You can have as many receipent as you like in the the emails "to" string, provided they are separated by commas (",").
You can do like this

$to  = 'one@email.com, two@email.com, three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'test'), $from = NULL, $send = TRUE);

You may check the documentation of drupal_mail.


In the template.php you will write this small piece of code:

function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

Replace foo with values related to your need.


In page.tpl.php leave where ever you wants: <?php print render($page['content']); ?> and then use node--YOUR_NODE_TYPE.tpl.php and put content where ever you want. You habe $node object print it and see what variables it has.
Make sure that you also have node.tpl.php - initial template file in your theme folder.


OPTION 1:

If it's a small amount of CSS, maybe considering making your CSS selectors based on the node and including the css in your theme's CSS? Drupal 7 provides the body.page-node-NODEID selector.

OPTION 2:

You could have a look at the Code per Node module. It is also featured in this blog post.

  Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

OPTION 3:

For adding css file to specific content type, you may use this snippet;

function MYTHEME_preprocess_node(&$variables) {
  if(!empty($variables['node'])) {
    if($variables['node']->type == 'my_custom_content_type')
      {
       drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
      }
  }

}

OPTION 4:

If you want to add css to specific node then you may use this;

MYTHEME_preprocess_node(&$variables) {
  if ($variables['node']->nid == 3) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
   }
}


get all nodes created in a specific month

Here you go with the code.. I have used entity field query to retrieve results.. Code should be self explanatory..  Let me know if you have any difficulty in understanding below code..

<?php

$year_month = "2014-04";
$date = date_parse_from_format ("Y-m" ,  $year_month);
$num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
$first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
$last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);
$entity_type = 'node';
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', $entity_type);
$efq->propertyCondition('created', array($first_minute, $last_minute), 'BETWEEN');
$result = $efq->execute();
dpm($result);

?>


Drush Error: no database record could be found after failed attempt of sql-sync

I wonder if it's a file system permission on your live site. Are you sure /var/www/mysite/sites/default/settings.php on the live site is readable by your web server?

(Also, unrelated to this but Drush 4.5 is getting pretty old so if possible you might want to update it.)


Drupal Commerce: How to prevent (or suspend) checkout where no shipping rate is defined?

Look at https://www.drupal.org/project/commerce_rules_extra (Commerce Rules Extra) which allows you to alter (including disabling) checkout panes based on conditions.


Getting fields' Attributes in node template

The field values in node are the raw data from the database. You should not use them for output. They are great for coding of conditions in twig.

For output use:

{{ content.field_1 }}
{{ content.field_2 }}

These statements will output the fields using the field formatter as configured in the ui.

Edit: Adding attributes

If you need additional attributes add them in the field twig. The methods described in the link you provided in the question are only possible in the same twig your element comes from. If you want to modify the attributes of the node it is the best to do it in the node template. If you want to add attributes to the field use the field template.


It seems to be normal. Looking at the hook_schema documentation, you see that it is invoked in drupal_get_complete_schema() in includes/bootstrap.inc and in drupal_get_schema_unprocessed() in includes/common.inc. The main difference is that the latter does not invoke hook_schema_alter() after the hook_schema is invoked. The first of those functions seems to be called on practically every page load. The second function is called from drupal_install_schema() during the module install process.

Concluding, looking at the code it seems to me that:

It is normal
It happens because during installation, Drupal needs the un-altered schema definitions


Is the current faceted search effective for SEO?

There is a module for it: Facet API Pretty Paths. But I didn't try it yet.

Here is a quote about it (from the module's project page):

  Enables pretty paths for searches with Facet API. You will likely use this module in combination with either Search API or Apache Solr Search Integration.


Add interval to current date and dispay result in views

Have you tried the Views Calc module?

The other option would be to use the Computer Field module but that could be risky as you enter PHP code into the field.


Should all files/folders in an installation be owned by the web server user?

Securing file permissions and ownership is the canonical reference for this topic, and is still relevant for Drupal 8.

If we are going under the assumption where we are talking about who owns these files, then we can also assume you have root on the machine and configure the entire environment the way you need.

Having "www-data" (or equivalent) own the entire DOCROOT of any website is an unnecessary security attack surface.  If there is a security breach (either through code or the webserver), then an attacker can change code on the site.

If you have root, then you don't need to explicitly use the UI for uploading or updating modules.  This is the only real reason to have www-data own the site.

The linked article has all of the details, but I always recommend

A normal user owns everything in DOCROOT, except for sites/default/files (or wherever your files are for your sites), the private, and tmp directories (and if possible private and tmp outside of DOCROOT).
Apache runs with a proper umask so that group write is on for files
The data directories have 2775 permission on them, so group ownership is retained
Your normal users is also in the www-data group, so drush / drupal console work as expected

The script in the linked article handles most of this; I usually create custom ones for my sites that do the same thing.


Adding a join in a Views field handler class constructor?

Yes, but you need to have already defined that relationship in the view. Per the docs for views_handler_field::add_additional_fields($fields):

  @param $fields
  An array of fields. The key is an identifier
  used to later find the field alias used. The value is either a
  string in which case it's assumed to be a field on this handler's
  table; or it's an array in the form of
  @code array('table'
  => $tablename, 'field' => $fieldname) @endcode

Thus, say you had a field handler for a field on the node table with a defined author relationship to the users table. You could do this:

  function construct() {
    parent::construct();
    $this->additional_fields['mail'] = array(
      'table' => 'users',
      'field' => 'mail',
    );
  }

Which would allow you to do this:

function render($values) {
  //Get the mail column from the users table.
  $this->get_value($values, 'mail');
}

For your case, you'll need to define the entity relationship to your base table before you can do this.


Devel 'Display Query Log' not showing any queries

You need to check 'Collect query info' in the devel settings: /admin/settings/devel

Otherwise no logs can be shown.


I believe you can use the Google Maps Directions API, although I don't know any Drupal module that handles this API out of the box.


Page slide animation with horizontal anchor navigation

They used here element using html like map
example

    Speisekarte

Here the point to start the page

Desc

If you don't find a module you can make it custom


Performance and optimisation when using panels with views and content pane

The primary thing you should do, is cache as much rendered output as you can. If you cache the generated markup itself, whether you're Views configuration is optimal mostly becomes a non-issue.

Views itself, can be cached with Views content cache, or if you complicated invalidation criteria, with a long timed cache and Cache actions.

More experimental, is a module I've written myself, called Panels cache, which moves the caching one layer higher up, for even better performance, but it requires that the content being cached all comes from the same entity. (I use the module in production, but would still love testing and feedback on the module)

On the actual Views configuration, you should avoid having a single with multiple panes, if you have a lot of overrides. If your displays are significantly different, you waste processing time as builds must build and then alter the display. This however, will be a very small optimization, compared to the caching solutions suggested above.

You can read about more different performance improvements in my answer on How do you improve Drupal performance?


How can I return actual JSON using Drupal?

For Drupal 6, you can use drupal_json

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json($result);
    exit;
}

For Drupal 7, change it to use drupal_json_output

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json_output($result);
    drupal_exit();
}

It would also probably be safer to parse out the query to sanitize, error check, etc, instead of just trying to return the result.


You have two options.

You can create one product for each combonation of X and Y and have those as values on the product. If you reference all the products on the node, commerce can turn the value of X and Y into a dropdown which will trigger an ajax update, changing the other data for the product like this price.
The other options if you don't want to create a product for each combonation (my preferred solution), would be to create a pricing rule, custom code is probably needed here, to calculate and set the unit price on the line item based on X/Y data.


Why my website is showing junk characters?

When we remove � manually, we see:

Comments

Posted On: 12-13-2010

Probably it comes from comment.tpl.php in your theme. At first glance looks like UTF-8 - UTF-16 issue, but only you can really debug that.

The exact part of code you pasted seems to appear in following threads:

https://www.drupal.org/node/76407
https://www.drupal.org/node/28016

See, maybe original developer was using them? Hope it helps you with debugging, we here cen't really help more.


Create a field with options are a combination of taxonomy terms, and content types linked to those taxonomy terms, for which the content type is used

There are some caveats in your question.

Caveat—no info to pick from

One caveat is marking "featured" items, narrowing down your pick from an already narrowed down list. This means that you have to save a new Coupon twice to get to the Featured option, the first time you save you pick the terms or products, and then you edit again to pick the "featured" one from the list you narrowed down previously. You could probably come up with some Ajax voodoo to do it all in one Save, but that is out of scope here and not very straightforward.

I'll assume the double-save is acceptable, that it fits with your project processes.

Caveat—Views don't mingle entities

To solve this without the custom code you need Views, but Views only ever list one type of entity (unless they're related, which in your care they aren't).

I'll assume it's ok to use two Fields then to mark your "featured", one to list terms, and the other for Products, and you'll have to rely on your admins to only select one of those, treat them like a single field even when it's not. (You ccould combine them with custom code, of course.)

Use Entity reference Views Display

Create a Taxonomy term Views type with Entity reference Display and limit to your Category vocabulary. You'll have to use Parent term Relationship and Contextual filters to show both levels.

Then use the usual Views magic to Contextually filter out only those terms that are shared with the node currently being edited (this is your Coupon node that has already been saved with chosen Categories and Products).

Create a new Entity Reference Field on Coupon CT and make it use the Views you created previously as a Widget.

Then repeat the procedure for Products. Create a Views Display listing Products, but limit Contextually to the Entity reference you're using on your Coupon, so that when editing a Coupon only Products that have already been chosen show up to be selected as "featured". When you have it working create a new ER field on Coupon using that ER Display as a widget.

This question is too complex to answer step by step, try looking at similar answers for each part, maybe here: How do I create a list of Nodes within a list of taxonomy terms, within a node? and Entity Reference widget selctor in view referring same reference

Links

I assume the links you mention are the links to the related Featured term or Product, showing on the Coupon list.

You can get this easily in Views by adding a Relationship (on the Coupon Views) to the ER "Featured" term, and then "Taxonomy Name" Field that uses that Relationship to show the related Category link.

Repeat similarly to show related "Featured" Product: add the ER "Featured" Product Relationship, and then "Title" Field that uses that Relationship. It will show the "featured" Product (the optin to make it a link instead of plain text are inside the Field settings).

Only custom code will give polished experience

This is perhaps a bit crude but you can always polish with custom code, in various steps along the way, or even the entire set of features, depending on your needs and resources.


How can I import non-unicode text file by Feeds module?

I can only provide high-level guidance here, but you need to use the Feeds Tamper module, which allows you to alter data between when it is read from the source, and then passed to Feeds.

However, I don't think there is an existing tamper plugin that can handle your situation; you will have to create your own.

There are two patches in the issue queue that may provide guidance:

https://www.drupal.org/node/1817516
https://www.drupal.org/node/2263119 (disclosure, I wrote this one)

You can take one of those two patches, and update them to use your character set instead of the ones in the patch.

For example, in this patch, you would need to update

+function feeds_tamper_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
+  $field = drupal_convert_to_utf8($field, 'ISO-8859-1');
+}

to use your encoding name instead of 'ISO-8859-1'.


Change date format for the example dates given below date field

You can change the format in field settings. Follow below steps to change.

Go to admin/structure/types
Click on manage fields next to your content type
Click on edit link next to the field


You can use permissions to assign profile(s) to roles.

about:

  When/if they change roles, their profile type would change and any
  fields that were the same are brought forward.

Remember each profile form is independent, so what you want could be done with code.  Or you can use only one profile form and use the field permissions module to assign role(s) per field (even if this is the case, maybe you don't need profile2).

Using only profile 2 (and turning off profile2 page),  you would see your core profile fields and the profile2 fields together.


Custom template files for multiple blocks provided by a custom module?

If you want to use a different template file for your blocks, by default Drupal uses the following template files.

block--epic-module.tpl.php for all the blocks implemented by the module you are showing
block--epic-module--awesome-block.tpl.php and block--epic-module--epic-block.tpl.php for the blocks implemented by that code

Keep in mind that each underscore in the module name or in the block name (i.e. what the documentation calls delta) is replaced with a hyphen.

Reference

template_preprocess_block()


Contextual filter to show only nodes of the same type

I don't think you can do it with a contextual filter (without using coding).
Just build a view (with block output) for each of the types and then use a filter criteria "content type = news", etc.

It's pretty easy since you can clone the view, then just override the type and change the block name.


How can I add meta tags for pages created with views in Drupal 8?

I think that this is still in development, one option is to configure the View as a block, then insert that block on a Page.  This won't work for all scenarios, but is a (poor) alternative.


Setup a Tabular View to Include Total Count of Nodes

Create two block display of a view. The view should contain All content types. displays are block_1 and block_2. set content type:Content Type A as filter criteria for block_1 and content type:Content Type B as filter criteria for block_2. so block_1 and block_2 shows all of the nodes of A and B. This link shows how to count number of results. Now the following code

<?php print views_embed_view('YourView','block_1');?>
<?php print views_embed_view('YourView','block_2');?>

outputs the number of results and you can format them in any way you want.


There are basically two main directions you can go if you want to 'expand' user profiles:

You can either add fields, field groups and eventually group them in tabs or thelike.
Or you try the module Profile 2 wgich is basically the successor of the core profile module.

Both approaches can be fruitful – both will let you spread user profiles over different 'pages' (or tabs). But I'm not sure how fine-grain you can actually go with these two approaches – and if you can actually 'diconnect' the change password ui from the rest. I usually try to keep the core info on one page – and 'the rest' (contact and bio etc.) on sub-pages (tabs).


One solution I found is to add PHP fields for the data you want to present into the view. The variable $data that holds what was retrieved from the database, per row, is printed this way:

print $data->[alias];

Where [alias] is the field alias from the database, without the brackets (ex. in $sql->addField('n', 'title', 'node_title') the alias is node_title).

This solution is not as clean as I would like so I will wait for more, "cleaner" answers before accepting this one.


pass custom variable for image field from preprocess node to twig

I found that I have to use the mytheme_preprocess_field hook.

function mytheme_preprocess_field(&$variables) {
  if ($variables['field_name'] == "field_picture") {
    foreach ($variables['items'] as $key => $item) {
      $grid_class = "grid-item--width1 grid-item--height1";
      $variables['items'][ $key ]['grid_class'] = $grid_class;
    }
  }
}


Sorting a view basing on the value of a boolean field

Add a new Sort Criteria sorter that sorts based on that field. Make sure it's at the top of your list of sort criteria.

If you don't want there to be a column for it in the table, click "exclude from display" in the field settings.


Anyway, I found the problem. It was the permission setting. I should set it to "no restriction" rather than restrict to every tick-able role (because guest is not there to tick)


How to render a paragraph field in Twig in correct language?

The problem is that FieldItemInterface::view() has no language parameter. Furthermore paragraph fields are not translatable (only the subfields of the paragraph entity are translatable). So when rendering a paragraph field directly, without going through the host entity render stack, the language information is lost.

My solution was to force the translation in a preprocess function:

function MYTHEME_preprocess_field(array &$variables, $hook) {

  // field_banner_slide is a paragraph field which needs
  // translation AND is rendered directly, e.g. by using Twig Tweak's
  // {{ drupal_field('field_banner_slide', 'node', node.id) }} in page.html.twig
  //
  // don't to this for "normal" rendering, e.g. when using
  // {{ content.field_banner_slide }} in node.html.twig

  if ($variables['field_name'] == 'field_banner_slide') {
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if(count($variables['items'])) {
      foreach($variables['items'] as $key => $item) {
        if ($item['content']['#paragraph']->hasTranslation($lang)) {
          $variables['items'][$key]['content']['#paragraph'] = $item['content']['#paragraph']->getTranslation($lang);
        }
      }
    }
  }
}

For a better technical explanation see issue #2753201 on d.o


How to create a membership using rules, using membership entity module

I did a good comparison of the Commerce membership entity module and the Commerce Licenses module, and the commerce licences can do te same, and has a lot more extra features, is more flexible. So switching to that module was my solution.


Moving a contrib module from /modules into the sites/all/modules folder

It’s OK (in most cases). Drupal 7 will find new destination of module after registry rebuilding. So, just move folders in proper destination and clear all cache.

It works for moving modules, but not for disabling and uninstalling. Don't remove module folder before complete uninstalling.

Update: I can move module folder even without disabling that module, because I use Drush for immediate cache clearing. In other situations it will be useful to disable module before moving.


How to integrate the drush help --filter option with your custom module?

I found the answer searching in the code of the drush project:

If the module have less than 4 commands you can't use the drush --filter=MODULE_NAME because your commands are classified as other:

See the function drush_commands_categorize(), and at line 1125 you can see this comment:

  // Post-process the categories that have no title.
  // Any that have fewer than 4 commands go into a section called "other".

I create 3 more commands and now the drush --filter=onlyone command works.


How do I install the Spark distribution using only Drush?

From comments:

Clive: drush make build-spark.make ~/Sites/spark - Building Spark from Drush Make yourself


You should return your form using drupal_get_form in the content definition of your block. Drupal will do the rest.

For example like this:

function YOURMODULE_block_info()
{
    $blocks = array();

    $blocks['custom_block'] = array(
        'info' => t('Custom block example'),
        'title' => t('Custom block example'),
        'region' => 'content',
        'status' => 1,
    );

    return $blocks;
}

function YOURMODULE_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'custom_block' :
            $block['content'] = YOURMODULE_block_content();
            break;
    }

    return $block;
}

function YOURMODULE_block_content()
{
    return drupal_get_form('my_custom_form');
}

function my_custom_form($form, &$form_state)
{
    // Build your form

    return $form
}


Customize Search Result Snippet to use Teaser

You can take control on which content the snippet is based by modifying the view mode "search_result". If you want to hide information from a field, then simply remove it there. But you can't change the behavior, how the snippet is composed out of this content. This is hard coded. And it will be text only with all tags removed.

If you want to provide additional elements for the search result, beside the snippet, you can do this by implementing template_preprocess_search_result in your module/theme file:

function [MODULE_NAME]_preprocess_search_result(&$variables) {
  $node = $variables['result']['node'];
  if (isset($node)) {
    $variables['teaser'] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node,'teaser');
  }
};

And use it in twig:

{{ teaser }}


$form_state['redirect'] does not take full URL. It takes the same set of parameters url() does. In your case it should probably look like this:

$form_state['redirect'] = array(
  // $path
  'prodotti',
  // $options
  array('language' => $language),
  // $http_response_code
  302,
);


How to creat different user type in drupal?

Unless you wish to write a custom module with direct access to the second database, with its own login system, the only way this is going to work is with direct manipulation of the drupal database, renaming tables, and using 'Create View ...' to give you access to the information. The amount of work, maintenance problems, and security implications would be horrendous.

If the number of 'internal' users is fairly static, my suggestion would be to use the User Import module, and give them all a role of 'Internal', using the user permissions to control their abilities on the site. Any new Internal users could be added manually.


How to save custom value in DB from custom .module

Once you get your nid of the node you can use the code below to change the field value

  $node = node_load($nid);

   unset($node->field_example['und'][0]['value']);
    //similarly for other fields you can change the value
    node_save($node);


Impossible to update some modules via Composer

Major version changes contain breaking/incompatible changes in SemVer / Semantic versioning. If you would update them, it would break modules that depend on the old version. Therefore most projects lock composer entries to one specific major version number. Also doing a default composer require vendor/project - without denoting an explicit version number - will create an entry locked to the current major version number.

The common way for a major version change is to explicitly composer require a new major version, but this usually means manually doing extra upgrade/migration steps outside of composer.


How to see the error messages when I get the white screen of death?

Put this at the bottom of settings.php:

error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);


Add external JavaScript files containing a parameter in the URL

Use the hook_library_info_build hook to add dynamic library definitions.

The key(s) could be stored as configuration. e.g. use Simple Configuration API

You would then in the hook, check if the configuration has a value and if so add the library and if not, well depending on how you want to deal with it.


How to add a theme suggestion to the textfield input based on the name of the view?

If the View is displayed as a page, you can get the View ID from the current route parameters:

$view_id = \Drupal::routeMatch()->getParameter('view_id');
if ($view_id) {
  $suggestions[] = 'input_'. $element['#type']. '__'. $view_id . '__'. $element['#name'];
}

If it's a block, I can't think of a nice way to do it generically. One non-nice way would be to alter the form, and add a property to each element which can then be picked up in the suggestions hook.

Something like this:

function MODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // You could check that the current display is a block here too if you need to
  $view_id = $form_state->getStorage()['view']->id();
  _MODULE_add_view_id_to_input_elements($form, $view_id);
}

function _MODULE_add_view_id_to_input_elements(array &$root_element, $view_id) {
  $input_types = ['textfield', 'submit', '...'];

  if (in_array($root_element['#type'], $input_types)) {
    $root_element['#MODULE_view_id'] = $view_id;
  }

  foreach (\Drupal\Core\Render\Element::children($root_element) as $key) {
    _MODULE_add_view_id_to_input_elements($root_element[$key], $view_id);
  }
}

And then in the suggestions hook:

if (isset($element['#MODULE_view_id'])) {
  $suggestions[] = 'input_'. $element['#type'] . '__' . $element['#MODULE_view_id'] . '__'. $element['#name'];
}

This isn't particularly pleasant, but the exposed form elements themselves don't carry any context so you have to wedge it in there somehow I guess. Hopefully there's a cleaner method out there somewhere.


How to control content access based on value of a List (text) field in user profile?

Check taxonomy_permissions (I think will do in combination with role assignment and has a stable release too), term_access module, Access by Term


How to render a block in php for a special node id

Add this to your theme's template.php file:

function THEME_block_view_alter(&$data, $block) {
  if ($block->module == 'opening_hours' && $block->delta == 'week') {
    $node_fixed = node_load(77); // swap out 77 for your node's id
    if ($node_fixed) {
      $data['content']['#node'] = $node_fixed;
    }
  }
}


how to test if a node is flagged in twig

Write a function with hook preprocess_node in your custom module and set a custom variable isflagged ture or false
then check this variable in your twig file node is flagged or not
like

/**
 * Implements hook_preprocess_node().
 */
function yourModuleName_preprocess_node(&$variables) {
  $node = $variables['node']; // Just in case you need it

  if($variables['node']->getType() == "yourNodeType") {
    // your code
    if ($flag->is_flagged ($node->id())){
      $variables['isFlagged'] = true;
    }else{
      $variables['isFlagged'] = false;
    }

  }
}

now in your twig

{% if  isFlagged %}
  //do some thing
{% endif %}

hope this helps you


How can i find out which form mode is used from hook_form_FORM_ID_alter?

You can try EntityFormInterface::getOperation:

function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state) {
  // only continue if this is for form mode "apply"
  if ($form_state->getFormObject()->getOperation() !== 'apply') {
    return;
  }

  // do stuff

}


Add extra information across cart/checkout/invoice in Ubercart

there's no other module i know of that exposes this data. i too had to do hook alters to recalculate the total and discounts to have it show in the checkout forms.


Views exposed filter in block redirects to homepage instead of current page

There is a jquery fix for this issue.  See https://drupal.org/node/1109980, #23.


How do I allow access to my custom module to "anonymous user"

I would suggest you gain more control over the access, by switching to "access callback" => "my_custom_function".

Then in my_custom_function() you can write just "return true" which will make it always accessible.

You could also add a log before "return true" so you can  tell whether the function is being called. If it isn't, then you know access is being blocked further up, before you get to that stage.


How to use Form API and and node_submit to insert taxonomy data

Try this, if I completely understood you, this should help.

    $i = 0;
    foreach($form_state['values']['catagories'] as $tid) {
      $node->field_catagories[$node->language][$i]['tid'] = $tid;
      $i++;
    }


How do I change icons in the "Mobile sliding menu" module?

Here is what I ended up with, after using hook_mmenu_icon() and configuring the Icon API to use the icomoon bundle.

How I did it?

First of all, I opted for using the Icomoon module, which allows me to import my own defined icons collections, assembled using the icomoon app.

This is an example of a custom collection I created (and the renaming/mapping of icons to the menu points I had in mind).

After, I had to go to the administration interface of Icon API providers and import the icons (/admin/config/media/icon/import). I named the imported bundle 'icomoon', which will be important for the code I wrote. This is what that admin interface looked like.

The code

The code you need will use hook_mmenu_icon(), since you want to define your own path to icon class associations.

This is what my code looks like.

/**
* Implements hook_mmenu_icon().
*
* Here we map URLs to icon classes.
*/
function YOUR_CUSTOM_MODULE_mmenu_icon() {
  $icons = array(
    'path' => array(
      'home' => 'icon-home',
      'node/1' => 'icon-node1',
    ),
  );
  _inject_inline_css($icons);
  return $icons;
}

Notice the use of Drupal's internal paths as the key to the $icons array. This is needed by the module (inside mmenu_get_icon_class()) in order to assign our custom CSS class to the menu item that points to it.

The rest of the code is quite custom and just a random idea of how you could go about doing the assignments you need. Probably there are better approaches.

/**
 * Function for injecting Icon API icons as CSS background images.
 */
function _inject_inline_css($icons) {
  // Load a bundle provider from the Icon API.
  $bundle = icon_bundles('icomoon');

  // Sanitization, normalization.
  if (empty($bundle)) {
    return;
  }
  if (!isset($bundle['settings']['extension'])) {
    $bundle['settings']['extension'] = 'png';
  }

  $css_data = array();

  // Configure an existing icon class, 'home'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/home' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['home']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Add a custom icon class, 'node/1'.
  $icon_path = $bundle['path'] . '/' . strtoupper($bundle['settings']['extension']) . '/node1' . '.' . $bundle['settings']['extension'];
  $icon_info = image_get_info($icon_path);
  $icon_url = file_create_url($icon_path);
  $css_data[$icons['path']['node/1']] = array(
    'background-image' => 'url("' . $icon_url . '")',
    'background-size' => 'contain',
    // Or, as an alternative.
    // 'background-size' => '$icon_info['width'] . 'px ' . $icon_info['height'] . 'px'',
    'background-repeat' => 'no-repeat',
    'background-position' => 'center',
  );

  // Generate and add inline CSS, mapping the mmenu icon classes to the icomoon icons.
  $css_string = '';
  foreach ($css_data as $class => $css_properties) {
    $css_string .= '.' . $class . ' {';
    foreach ($css_properties as $css_property => $css_value) {
      $css_string .= "$css_property: $css_value;";
    }
    $css_string .= '}';
  }
  drupal_add_css($css_string, array('type' => 'inline'));
}


I might be talking out my you know what, but just try:

$form_state['redirect'] = 'node/add/media/' . $form_state['nid'];


Unity launcher / OSX Spotlight like functionality for administration?

While coffee is probably the module you are looking for, i think switching on search in admin_menu is way more productive - no roundtrip for the searches and you stay focused on the admin stuff. I bet you are using the admin_menu anyway ? Just visit admin/config/administration/admin_menu and hit save - the search field should appear on the right hand side of the admin menu :)


Views - show only items not in a given nodequeue

Alright the answer is this:

You have to create a relationship with the nodequeue(s) in question that you wish to filter against. You have to make it so that the checkbox, "relationship required" is unchecked - otherwise it will primarily filter all items that are not in the nodequeue.

At this point, this will provide a filter to you termed, "in queue" - set this queue to false.

At this point, all items that are NOT in the nodequeue will be listed.


Drupal has a function called filter_xss_bad_protocol that strips unknown protocols from links created with the l() function - This is a very smart idea but makes it difficult when you want to include emerging link protocols like skype:// for example. Dave Reid has created a fantastic module that works around this and allows developers to add their own protocols to the list.

http://drupal.org/project/filter_protocols

With that module installed, and your specific protocol added to its configuration screen, it would then be possible to do something like this in your code:

<?php print l("Displayed Text", "itms-services://?action=download-manifest"?>

Additionally, use the attributes and query parameters of the l() function to pass your url parameter to the link. See this for an example... http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7 - You'll find the particular comment regarding passing parameters on that page here: http://api.drupal.org/comment/38198#comment-38198

Hope that helps! Good luck.

P.S. To clarify, simply adding the above module and configuring it will also allow the Link module to respect the protocol since it passes everything through l() - So no code required. :) Merely for completeness.


How to remove title field from content edit page?

You want to either:

Remove the title field completely using the Fields UI. See this documentation page on the Fields UI. If you really don't want a title then just remove the field from the content type.
Use the Automatic Nodetitle module to create a title from a Token and hide the title in Edit Forms.
If not a Node, use the Automatic Entity Label module to create a title and then hide it from users in the Edit forms.

In general most content types need a title. Titles are the Names we give content to find them using Search forms and pages.


Website encountered unexpected error - how to avoid?

Does MySQL crash after that error? Either way your watchdog table is being corrupted. Are you running out of disk space? Make sure you are using InnoDB tables; MyISAM is prone to corruption.

You can check your table type by running this from a MySQL command prompt and looking for the Engine= parameter.

mysql> show create table watchdog;

You can also disable dblog and enable syslog instead. Syslog writes to your system logs and is much more scalable for higher traffic sites. See if that solves your problem.


How to display forum on a custom URL on my site?

You can use pathauto, url alias to  your forums to achieve the same.  if it is a custom menu you can use hook_menu_alter(). or an .htaccess re-direct if it is a permanent change


How can I allow the current user to only see their own page?

_permission only allows to give access to the route to the users who have that permission; it doesn't allow to give access basing on more complex conditions, as in the case of this question. As described in Custom route access checking, the route definition should be similar to the following one.
task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: '\Drupal\task_notify\Controller\TaskNotifyUserController::tasks'
    _title: 'Tasks list'
  requirements:
    _custom_access:  '\Drupal\task_notify\Controller\TaskNotifyUserController::taskAccess'
    user: \d+

The TaskNotifyUserController class would need to contain at least the following code (and other methods you need from that controller, including tasks()).
class TaskNotifyUserController extends ControllerBase {

  /**
   * Checks access for the users task page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
  public function taskAccess(UserInterface $user) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user()->id() == $account->id())
      ->cachePerUser();
  }

}

If then the access to the route should be allowed also to users with a specific permission (for example, the permission to administer users), the taskAccess() code would be similar to the following one.
  /**
   * Checks access for the users task page.
   *
  /**
   * Checks access for the tasks tab.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

Don't forget to import the class used from the controller, adding the following lines at the top of the controller file.
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

If the controller class uses other classes from different namespaces, similar lines must be added for each class.
I took the code used from Drupal core for the Tracker module as example. The Tracker module shows its tracker page on /activity/{user} using a controller to render it. See TrackerController.php.
  /**
   * Checks access for the users recent content tracker page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being viewed.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account viewing the page.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   The access result.
   */
  public function checkAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user
      ->id() == $account->id())->cachePerUser();
  }

The custom access callback is defined in tracker.routing.yml.
tracker.users_recent_content:
  path: '/activity/{user}'
  defaults:
    _controller: '\Drupal\tracker\Controller\TrackerController::buildContent'
    _title: 'My recent content'
  requirements:
    _permission: 'access content'
    _custom_access: '\Drupal\tracker\Controller\TrackerController::checkAccess'
    user: \d+


How do I programatically create a context?

After checking the code used in the context test units for Drupal 6:

ctools_include('export');
$context = ctools_export_new_object('context');
$context->name = 'testcontext';
$context->conditions = array('path' => array('values' => array('admin')));
$context->reactions = array('debug' => array('debug' => TRUE));
$saved = context_save($context);

You can easily code your reactions or conditions then save the context.

BTW to get all context you can use context_context_list().


Hide 'previous' on first and 'next' on last image in views slideshow

Easiest way out is to use css. Hide the control when you don't need it.The particular element can be found by a simple inspection. Hope it helps.

display:none;

Another alternative is to use the slideshow API to customise the behaviour. You can start here.


Trigger an action at a specific time using Trigger and Rules

Why are you interested in the $_SESSION variable? What is the bigger action you are trying to accomplish?

The easiest way to fire any event when a user visits a page in Drupal is too use hook_menu and create a custom callback.

If you are trying to fire an action at a specific time you can setup a cron job to go off at the time you desire.  Drupal 7 core has a built in cron mechanism you can tell to go off at certain time increments /admin/config/system/cron . If you don't have access to your server to setup a cron job and want it to go off at a specific time once a day (ala an alarm clock)  you can use one of these modules Advanced Cron Modules

In order to respond to a cron job you can use hook_cron or using a cron trigger at "/admin/structure/trigger/system"


How can I create the views pager on top and bottom of the view?

I think you are on the right track by editing the views template files. Do you know you can have a different template for each view, or each views display? When you are editing your view there is a link called "theme information" that will help you figure out how to name the templates.

Now, If you mean you need to have the pager in different places on page 1 of this display vs page 2 of the same display, you will have to dig inside the view object to figure out which page you're on in order to figure that out.

I also found this tutorial while Googling the answer:
http://www.adesignforlife.net/articles/drupal-tutorials/solution-how-print-pager-drupal-views-block


how to use more then one content type filter in same views in drupal 7?

You need to add both the content-type inside Filter Criteria.

Click on the "Add/Or, Rearrange"
Create new filter group


I'm an idiot, and I had configured up the DrupalFakeCache earlier in development to prevent caching. Clearly this results in no caching.


Adding my comment as an answer:

$groups = \Drupal\group\Entity\Group::loadMultiple($ids); is all that is needed to load the groups based on IDs. Group::loadMultiple() does the storage bits already, so no need to duplicate the work.

So the full snippet would be something like:

<?php

$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
if ($groups) {
  $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
}


Is there anything like get_variable storage that doesn't get loaded every page?

Variables are loaded on every page anyway, regardless of whether your custom code requests a specific variable be loaded or not.

So, the only extra memory overhead you will incur is whatever PHP packs your 20kB of data into.

If your app is sensitive enough for that to matter, then either create a custom table to store the data, or just write it to a static file and read it back from there. If not (more likely), then just use the standard variables method, it's easier.


When should I use DependencySerializationTrait?

@kiamlaluno described the technical details. This is the background why the DependencySerializationTrait was introduced:

This was the situation before:

     Any class that receives injected dependencies (whether by
  constructor injection or setter injection) typically keeps a reference
  to its dependencies in class members. That's how dependency injection
  works.   Drupal being Drupal, it serializes stuff in several
  places:

        Anything that is in a $form / $form_state : the FormInterface object, but also any object whose methods are used by
  FAPI #callbacks ('#pre_render' = array($some_object,
  'someSubmit')).
        Anything that gets cached, stored in state(), or more generally in the k/v stores...
            When an object is serialized, all the objects it references get serialized as well, and recursively, all the
  dependencies of those objects...   This leads to a
  serialization chain of hell: [#1909418] hit a case where serializing
  the form controller meant serializing the EntityManager -> the
  Container -> (among many other things) the DrupalKernel. This got
  fixed by making sure the kernel was serializable - which is just
  insane :-).

And this was the proposed solution:

  The answer for "DIC-friendly serialization" seems to be:    On
  serialize, do not serialize dependencies.   On unserialize,
  re-pull them from the container. Granted, this breaks mocking, but
  serialization/unserialization is not something you typically do in
  unit tests, so I don't see this as a real problem.

  How to do this might not be too simple though. Two approaches come to
  mind:

     Classes that want to be "DIC-friendly serialized" need to
  implement an unserialize() method that hardcodes the services ids of
  its dependencies. That means doing something similar to the create()
  factory method that is currently used at instantiation time in a
  couple places in core (controllers, some plugins). Hardcoding service
  ids in more and more classes is not a joyful perspective, though.
  Crazy idea:

        Modify the DIC so that each time a service gets instantiated, the service id by which it got instantiated gets placed
  in a public __serviceId (or something) property on the object.
        Classes that want to be "DIC-friendly serialized" do:

            On serialize() : foreach member, if (!empty($this->member->__serviceId)) {just serialize the __serviceId
  string instead of the whole object});
            On unserialize() : $this->member = \Drupal::service($service_id)

Quoted from Injected dependencies and serialization hell


Views filter criteria groups OR not working?

This answer on a related (perhaps duplicate?) issue provided settings that got the display working for me.

First, on each filter criteria, check "Reduce Duplicates".

EDIT Actually, the answer I linked says to uncheck the "DISTINCT" in the Advanced settings for the query. However, when I did that, I got duplicates. I unchecked it, and I got the right number of results. So that second step may not be necessary for you.


What are the issues with overriding nodes with views?

You could, however, do something like this in node.tpl.php:

<?php if ($node->type=='FANCYTYPE'): ?>
  <?php print views_embed_view('name_of_fancy_view', 'default', $node->nid); ?>
<?php else: ?>
  // the rest of the normal node.tpl.php stuff here
<?php endif; ?>

or create a node-TYPE.tpl.php (D6) or node--TYPE.tpl.php (D7) with just the Views logic inside.


Why isn't the page cal back needed in Ajax jQuery?

That is explained in the examples shown for hook_menu().

 function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

Using the code above, and accessing the page as http://example.com/abc/def, the page callback would get 0 and '' as arguments; accessing the page as http://example.com/abc/def/123/foo, $ghi will be equal to 123, while $jkl will be equal to 'foo'.

That is the default behavior of Drupal.

You could also use wildcards arguments, but in that case those arguments should be passed in the URL.


That happens because you are using a #tableselect form element, which is clearly described as follows:

  A table created with a far left column of radios or checkboxes. Build the table headings and columns with the #headers property, and the rows with the #options property. See Adding checkboxes to a table for a full explanation.

What you are looking for is a table, which is a theme function. See for example the following code, used by Drupal core.

function aggregator_view() {
  $result = db_query('SELECT f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block ORDER BY f.title');

  $output = '
' . t('Feed overview') . '
';

  $header = array(
    t('Title'),
    t('Items'),
    t('Last update'),
    t('Next update'),
    array(
      'data' => t('Operations'),
      'colspan' => '3',
    ),
  );
  $rows = array();
  foreach ($result as $feed) {
    $rows[] = array(
      l($feed->title, "aggregator/sources/$feed->fid"),
      format_plural($feed->items, '1 item', '@count items'),
      ($feed->checked ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $feed->checked))) : t('never')),
      ($feed->checked && $feed->refresh ? t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - REQUEST_TIME))) : t('never')),
      l(t('edit'), "admin/config/services/aggregator/edit/feed/$feed->fid"),
      l(t('remove items'), "admin/config/services/aggregator/remove/$feed->fid"),
      l(t('update items'), "admin/config/services/aggregator/update/$feed->fid", array('query' => array('token' => drupal_get_token("aggregator/update/$feed->fid")))),
    );
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No feeds available. Add feed.', array('@link' => url('admin/config/services/aggregator/add/feed')))));

  $result = db_query('SELECT c.cid, c.title, COUNT(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');

  $output .= '
' . t('Category overview') . '
';

  $header = array(t('Title'), t('Items'), t('Operations'));
  $rows = array();
  foreach ($result as $category) {
    $rows[] = array(l($category->title, "aggregator/categories/$category->cid"), format_plural($category->items, '1 item', '@count items'), l(t('edit'), "admin/config/services/aggregator/edit/category/$category->cid"));
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No categories available. Add category.', array('@link' => url('admin/config/services/aggregator/add/category')))));

  return $output;
}

In your case, your code should simply be similar to the following one. (See also the comments in the code.)

function popups_list_form($form, &$form_state) {
  // This variable is never used; remove it.
  // global $base_url;

  $header = array("Title", "Popup");
  $result = db_query("SELECT * FROM popups");

  // The following bracket is wrong placed. Remove it from your code.
  // }

  $rows = array();

  foreach ($result as $row) {
    $rows[] = array($row->title, $row->popup_org_name);
  }

  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No Popups Available'),
  );

  return $form;
}


Caching mysql results in cache table to be retrieved later

You can't store the query result resource directly in the cache table as it can't be serialised. Instead you should loop through that resource when you first run the expensive query, and cache an array of results, like so:

$q = db_query('expensive sql here');
$data = array();
while ($row = db_fetch_object($q)) {
  $data[] = $row;
}

cache_set('expensive_sql', $data, MY_CACHE_TABLE);

Then when you pick it up at the other end you can just loop through that array:

$cached_res_obj = cache_get("expensive_sql", MY_CACHE_TABLE);
$res            = $cached_res_obj->data;

foreach ($res as $row) {
  print_r($row);
}


Print image backgrounds and colors from views and blocks

Sorry if I haven't understood correctly, but it sounds like you're asking why backgrounds aren't printed when 'Print Backgrounds' is off?

That's a browser setting and is down to the user. If that option is disabled, background images and colours should not be printed as far as I'm aware. So what you're seeing is the correct/expected behaviour.

For webkit browsers you can try -webkit-print-color-adjust with the exact setting, i.e.

-webkit-print-color-adjust: exact;

That should force the background to be printed for the element regardless of the user's setting

  Background colors and images of the element to which this rule is applied are always printed, user's print settings are overridden.


How to theme help text of field groups in node form

Help text is run through content_filter_xss():

/**
 * Like filter_xss_admin(), but with a shorter list of allowed tags.
 *
 * Used for items entered by administrators, like field descriptions,
 * allowed values, where some (mainly inline) mark-up may be desired
 * (so check_plain() is not acceptable).
 */
function content_filter_xss($string) {
  return filter_xss($string, _content_filter_xss_allowed_tags());
}

/**
 * List of tags allowed by content_filter_xss().
 */
function _content_filter_xss_allowed_tags() {
  return array('a', 'b', 'big',  'code', 'del', 'em', 'i', 'ins',  'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'tt', 'ol', 'ul', 'li', 'p', 'br', 'img');
}


How do we programmatically place a section and then a block in that region on module install?

Put this code in an .install file:
// Create a Home web page with alias 'home'.
  $node = Node::create([
    'type' => '<node_type>',
    'langcode' => 'en',
    'uid' => 1,
    'title' => 'Home',
    'status' => 1,
    'path' => [
      'alias' => '/home',
      'pathauto' => PathautoState::SKIP,
    ],
  ]);

  // Variable to hold the sections for this node.
  // Defaulting to have a blank section first.
  $sections[] = new Section('layout_onecol');

  // Create a new section.
  $section = new Section('layout_onecol');

  // Config for the multi-type list block.
  $pluginConfiguration = [
    'id' => '<block_id>',
    'provider' => 'entity_block',
    'label_display' => FALSE,
    'view_mode' => 'default',
  ];

  // Create a new section component using the node and plugin config.
  $component = new SectionComponent($node->uuid(), 'content', $pluginConfiguration);

  // Add the component to the section.
  $section->appendComponent($component);

  // Add the section to the sections array.
  $sections[] = $section;

  // Set the sections.
  $node->layout_builder__layout->setValue($sections);

  // Save the node.
  $node->save();


In case other people have the same question for D7, you can always use hook_page_alter(). It will be invoked on all pages. Here's an example:

function YOUR_MODULE_page_alter(&$page) {
  // Check if the user is on /admin/people/create.
  if (current_path() == 'admin/people/create') {
    // Do whatever you want.
  }
}

However, do bear in mind that:

This code needs to be in a custom module in order to be invoked everywhere.
If you add this to your front end theme, it will not be executed unless you are using the front end theme for managing the site as well.
This way you can recognize if the user on that page, but you will not be able to alter the form. To alter the form, check out @Weboide's answer - you'll have to use hook_form_alter().


Trigger the 'add more' button with javascript, to add a set amount of field values

I had the very similar problem, but with a group of fields that all needed to be added in sync. Using setTimeout to trigger is problematic because of the guess work involved.

One of the ways to do this is to use the ajaxSuccess event to chain a list of requests. After searching for a solution to my problem, I ended up creating a small plugin called group-add-more. This can work with both Drupal 6 as well as 7.


How can I programmatically create a media object and a new file and associate the file with the media object?

Ah, I always figure it out after I say I can't do it.  Once I specified the document type, it worked:

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => \Drupal::currentUser()->id(),
  'created' => date('U'),
  'changed' => date('U'),
  'moderation_state' => 'published',
  'field_file_document_type' => 1409, //1409 is the id for pdf
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
];

Edit: I should mention that 1409 is the id we use for pdfs, yours will be different.  The field_file_document_type just needed to have a value in it to work.


according to t() documentation you can get translate the string it in any langcode,it is mean you can have reverse translation

my suggestion is

t($string,  array(), array('langcode'=>'en'));

and as example
stack dont let me use persian character(I write in Fenglish but you read it persian :) )

t('Chetori mehrdad',  array(), array('langcode'=>'en'));

return equal of string ('Chetori mehrdad') in english  if you translate it before form English to persian (How are you mehrdad), this mean 'Chetori mehrdad`(persian) => 'How are you Mehrdad'(english) :)

I hope this is useful at this time ,sometimes the answers is after you need :(


How to limit number of nodes a user can create per day?

For Drupal 6 I have used Node Limit Number with great success.

  Limit the amount of nodes or comments your users create over a given
  time period. This module has been rewritten to integrate with Rules.
  Instead of going to a page to assign limits you now just need to
  create rules. A default rule has been provided as an example.

The 2.x branch also integrates with the Rules module to make it really flexible.


How to get the selected value of a dropdown inside panel?

Apply little trick and my issue solved. Used default taxonomy search and hide it.

(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.


Import XML with nested elements into field with settings "Number of values" = "Unlimited"

Also when you import from html pages you have to set to html xpath parser.


How to link to a taxonomy term of a view?

Try this one

 term_id}) }}">{{ 'Name'|t }}

Where term_id is your taxonomy term id.


There's a few solutions you can try but take note truncating strings with html is generally a bad idea due to having potential unclosed or malformed tags.

1. Use |raw to output the html as html, may produce malformed tags:

{% set text = content.field_body|render %}
{{ text|length > 200 ? text|slice(0, 200)|raw ~ '...' : text|raw }}

2. Strip html first, cleaner:

{% set text = content.field_body|render|striptags %}
{{ text|length > 200 ? text|slice(0, 200) ~ '...' : text }}

3. Register a twig extension (untested):

https://gist.github.com/leon/2857883

Another helpful extension you can check out is the Text extension, which helps you prevent chopping up words:

http://twig.sensiolabs.org/doc/extensions/text.html


prevent user from putting 0000 in date field

You can use Field Validation to check against the date, it has a sub module or feature that has date validation.

You could also do this with a hook, probably hook node validate would be your best option for this.


Problem using tokens when mailing to site owner after an order

I encountered similar issues in the Rules email body. Standard input filters were being applied to the field. You may need to install the Token Filter module and configure input formats accordingly.


What configures Drupal to send emails on the create or update of an unpublished content?

The culprit turned to be the Antispam module, which is the client for the Akismet anti-spam system.

Its default setting causes an email to be sent to some administrators whenever a module is updated.

What baffled me was why that setting applied only when an unpublished item was created or updated.


What you are asking is rather basic module development. Setting up a page that takes an argument.

Check out the Example module, and more specifically the page_example module and page_example_arguments(). That contains the base of what you need.


How to add a contextual action link to a View?

Figured it out not long after posting. The format is view.(view_id).(display_id):

entity.room.add_form:
  route_name: entity.room.add_form
  title: 'Add Room'
  appears_on:
    - entity.room.collection
    - view.rooms.rooms_admin


How do I add a date picker that is rendered from most the browsers?

I had a similar issue just recently within a client's intranet application, after Firefox added HTML5 date field support. (FF is their corporate browser of choice.)

You can still use any JavaScript based datepicker that suits your needs. (E.g. jQuery UI's datepicker.)

In your JavaScript bind this datepicker to all input fields of type date and then change the type of the input fields to text. This prevents the browsers from using their own datepickers.

PS.: It's not exactly a Drupal specific question, but tomorrow when back in my office I might add a code example that works for Drupal 8.


Either drush cc or manually truncate cache tables in the db (Backup first!). Unsure if you are running Varnish, but if so you may want to manually flush this as well.


How can I programmatically populate a drop-down list field's options?

Ok, here's what I figured out:

Use hook_field_widget_form_alter()

My case:

function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

  // Check if element is paragraph type, belongs to a specific paragraphs
  // bundle and contains a specific field.
  if (empty($element['#entity']) || $element['#entity_type'] !== 'paragraphs_item' ||
    $element['#bundle'] !== 'content_block' || $element['#field_name'] !== 'field_dropdown_text_single') {
    return;
  }

  // Get entity metadata
  $form_field_wrapper = entity_metadata_wrapper('paragraphs_item', $element['#entity']);

  // Set default value. If there is already a set value use that,
  // else set to '_none'
  $default_value = $form_field_wrapper->field_dropdown_text_single->value();
  $element['#default_value'] = !empty($default_value) ? $default_value : '_none';

  // Code to get your custom select options goes here

  // Inject custom options into paragraph's dropdown selector.
  $element['#options'] = $my_options;
}


where is the submit handler for the Drupal Commerce Review page?

All checkout page forms are built using the checkout pane info David Thomas indicated through the function commerce_checkout_form() in commerce_checkout.pages.inc. The validate handler does double duty for the checkout form, validating and actually submitting data on a pane by pane basis to capture valid data as soon as possible. This function is aptly named commerce_checkout_form_validate(). Your best bet will be to log debug messages using watchdog instead of displaying them on the screen via drupal_set_message(), because we do some status message processing in there to put messages inline with the panes that generated them - that can make it hard to force a debug message to show when you expect it.


How do you turn off clean URLs in the database?

In drupal 8 this setting has been removed:

'clean_url' configuration setting removed; clean URLs are autodetected each request

I checked the database, there is really no setting with this name.


Move views global text field into code (attached fields and fields via relationships)

So I figured out how to accomplish a small part of what I need done.

To add an attached field (a simple text field called 'test') I did this:

class views_handler_my_custom_field extends views_handler_field {
  function construct() {
    parent::construct();

    $this->additional_fields['test'] = array(
      'table' => 'field_data_field_test',
      'field' => 'field_test_value',
    );
  }

  /**
   * {@inheritdoc}
   *
   * Perform any database or cache data retrieval here. In this example there is
   * none.
   */
  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  /**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $test = $this->get_value($values, 'test');
    return $test;
  }
}


Assuming you are trying to add a personalized text that links to the anthem of the country.

To achieve this, you can add a global text field and rewrite the output.

Step by step:

1) Add the field "Link to content" and fill out your personalized       text in the box that says "text that will show". Check the box       "exclude from display."

2) Select your title field and check the box "exclude from    display."

3) Add the field "custom text" (category global)

4) In the text field, add the token as seen in replacement patterns below called "{{ view_node }}" for the link to the content.

5) Save it all and you now have a link to the content of the current    country page, assuming you have set up the right    contextual filter.

If you are trying to achieve something else, please clarify and let me know.


How to place one region below the other while reducing the width in drupal 7?

You can either use float:left on both elements with fixed widths that will automatically stack when the page width is reduced enough.

Or use a CSS media query to make the regions adapt once a certain screen width is reached.

HTML:

CONTENT1

CONTENT2

CSS:

.container {width:100%}
.region1 {width:50%}
.region2 {width:50%}

@media only screen and (max-width: 767px) {

.region1 {width:100%}
.region2 {width:100%}

}


How to create a textfield with autocomplete function for the view?

I think no need to create block of view programmatically, You can do it with Views Autocomplete Filters module and views Module:
Try the following steps how to create view with language filter, using autocomplete:

Install Views Autocomplete Filters Module.
Create View with Fields Display add the language field The language of the content or translation.
 and your additional fields:

Add Combine fields filter

configure it like the following:

the result will be like:


Is there a module that allow to access a page using a specific URL?

I remember doing something similar with the Rules module a while ago.

Take a look at the integrations for extended functionality - I think you can use the Tokens module with it.


Yes, the FAQ module provides the ability to have separate categories of FAQ via the taxonomy module as per the project page:

  "In addition, if the 'Taxonomy' module is enabled, it is possible to
  put the questions into different categories when editing. Users will
  need the 'view faq page' permission to view the built-in 'faq' page
  and will need the 'administer faq' permission to configure the layout,
  etc."

To use the individual faq categories, use the urls: faq-page/[tid] - where the [tid] is the term ID of the category you want.

You can also use views to make additional faq pages for specific categories if you like.


I assume you are using Drupal's Form API.

  I want to limit specific entries on the client side IE: only allowing 6 characters being entered etc.

In your element definition, you need to add the HTML attribute maxlength. For example:

$form['your_field_name']['#attributes'] = array('maxlength' => array('6'));

Regarding:

  On submit I want to run through validation rules to make sure what was entered is correct. IE: only positive #s etc.

You can create your own validation function for the form or the element. For example, in your form definition, in the element you want to validate, you need to enter:

$form['your_field_name']['#element_validate'] = array('your_field_name_validate');

In this case, your_field_name_validate is the name of the function that will be invoked when the form is submitted. The function needs to be in the same module as the form definition, or in an include file. See an example here. Pasting:

function my_field_name_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}


Node titles are not unique, so they cannot be used directly. You need to create page with nice, machine-readable, numerical ID, and then assign it it's own URL Alias. Works similar in Drupal from 5 to 8 as far as I know, menu names might be a bit different, that's all.

Pathauto is nice automation for aliases, but only on nodes. There was already similar, but not identical question with some answers.


SQL error when adding an other database table

You're including the primary key as a field, which won't work. It needs to be on the same level as fields:

'fields' => [
  'id' => [
    'description' => 'The ID of the database entry of bar.',
    'type' => 'serial',
  ],
],
'primary key' => ['id'],


Try adding the following lines to your template file. Works for me.

$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
print drupal_render($main_menu_tree);


How to load a field from a user that is being viewed

Try creating a user-profile.tpl.php file in your theme and messing around with that.

Default contents are:

<div class="profile">
  <?php print $user_profile; ?>
</div>

And I suggest using a variable name other than $user as $user is a global variable referring to the logged in user.


Creating a "Related pages" view which also excludes the current node

If you use Views content panes and Panelizer, then:

Set up the view as a content pane with argument input for the Node ID (Nid). Then, set up a contextual filter for Content: Nid and check the "Exclude" box.
In Panelizer, add the view pane and pass the current node ID to the content pane as a the Nid argument.


'Any' result set for Exposed Filter w/ limited list is not limited

For the second non-exposed filter change the operator to is none ofand assign the terms accordingly (inverse to what you have now). If not otherwhise specified filters in views are AND filters.


How to keep underlying file when deleting a Filefield value

This has already been answered:
https://stackoverflow.com/questions/2101754/drupal-filefield-remove-file-from-node-but-leave-on-server


How to alter incorrect Join type generated by Views?

Complete operator error.  For the benefit of anyone else who encounters this error check your fieldname.  In my case I had misspelt the fieldname ['field_data_field_listing_type'] so it was generating a new incompleted entry in the table_queue array.


Aggregated SUM from "Referencing entity" relationship, how to include nodes without relationship

I was debugging like crazy to figure this out and then after checking some values in views_handler_field_field I realized what was wrong, and for sure it weren't Views! I forgot, or rather though of it as irrelevant, that there was third content type - a comment, that had a field "field_contact". The problem occurred because Views when summing up, was also using existing "comment" nodes, but because they didn't have "field_payment_amount" at all - Views got confused. So the real answer is that we need to filter out any additional types that are using "field_contact" field in our relationship.

I guess Views could act a bit better on this, and not get confused but use only available fields from proper nodes to create a sum, but it isn't much problem as long as we can filter out useless (for SUM) types that are using our reference field.

This explains why I got random/wrong results without type filtering on relationship, but when I added filter for "payment" - I didn't get "0" results, because then view assumed that relationship is required. The proper solution is then EXCLUDING wrong types that are in our relationship.


@font-your-face don't work when 'Aggregate and compress CSS files' is enabled

After your compress the CSS using Aggregate option in Drupal, viewing the source code you'll find that there is an syntax error for @font-face.

Check for your syntax, there would be a break-age in that while aggregation.