How to change default language for configuration entities?

I changed the configuration directly in the MySQL table "config" (In my case table names has a prefix ("something_config") so change the example below if necessary).

The configuration values are in the column "data".

First I cast the content to a string.

Then I replace the definition of the wrong langcode. In my case I replace 's:8:"langcode";s:2:"de"' with 's:8:"langcode";s:2:"en"'.

In the end I cast the result of this replace operation back to binary and save it in "data".

These three steps can be managed in one single SQL statement:

UPDATE `config` SET data = cast(
 replace(
    cast( data AS char ) , 's:8:"langcode";s:2:"de"', 's:8:"langcode";s:2:"en"'
 )
 AS BINARY )

Then clear the cache and you are done.


Undo to Taxonomy term system path unset with _menu_alter

The question is a little unclear, to reverse that effect, you would simply delete that hook_menu_alter snippet.

To change the paths to something else, you would use hook_menu and create the relevant menu callbacks.

The last step there would be to change the taxonomy_term entity_uri so it uses your new callback.

i.e redefine taxonomy_term_uri in hook_entity_info_alter

/**
 * Implements hook_entity_info_alter
 */
function mymodule_entity_info_alter(&entity_info){
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
 * Custom taxonomy_term entity_uri callback
 */
function mymodule_taxonomy_term_uri($term){
  return array(
    'path' => 'mymodule/taxonomy/term/' . $term->tid,
  );
}

Not sure why you'd want to do that though ;)

edit: If you want to deny access, better to use hook_menu_alter to add your own access callback to the taxonomy menu paths. Alternatively, override the path with Panels or Views and set access control there.


Working with template suggestions on Drupal 8

You can implement the new hook_theme_suggestions_HOOK_alter() hook.

  Alters named suggestions for a specific theme hook.

  This hook allows any module or theme to provide altenative theme function or template name suggestions and reorder or remove suggestions provided by hook_theme_suggestions_HOOK() or by earlier invocations of this hook.

You can use it like so

function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (\Drupal::request()->query->get('foo') == 'bar') {
    $suggestions[] = 'page__myCustomTpl';
  }
}

You can implement it in either a module or theme


Why does trying to POST a node from Android result in "HTTP/1.1 415 Unsupported Media Type"?

I have faced same problem with same situation as you described above.
After spending 2-3 hours I have got data through:

$formdata = file_get_contents('php://input');

It's worked for me.


How to display a date without hour, minutes, and seconds?

Steps to achieve your requirement:

Goto /admin/config/regional/date-time/formats/add link, and add Format string as explained in the PHP manual.

Now add Date type and select the format you created.

Finally, go to content type Manage Display settings and add your newly created date format.
At URL /admin/structure/types/manage/page/auto_label, add token of the DOB field with the format you created by Browsing Available Tokens.


How can I get views_save_view($view) to return TRUE when using Drush?

You can run a script as a user with the right command line option. Basically:

drush php-script YOURSCRIPTNAME.php --user=1

or --user=UID where UID is a valid drupal user ...


Undefined variable error in node.tpl.php

Try if ($node->status == 0) instead of if ($unpublished).

This may be happening because the variable is not set correctly in a hook_preprocess_node() implementation of the theme; you may also want to check the template.php file in your theme for these hooks.


How to filter content on a view page using cookies?

A better way to tackle your problem might be the Flag module.

It also has a good views integration and is quite easy to set up.

Just add a "favorites" flag and set it as private flag, so every user can have its own favorites.

On your favorites-view set your filter criteria to match the flag and you are good to go.


How to theming attachment views? I don't get nothing when I add elements to the tpl

you can use display suit module and write some tpl file for your element you want to theme in a specific view mode you choose for your view and suggest it to drupal.


Permission restrictions deny you access to this broken link

I was able to view what the links were by modifying linkchecker.pages.inc line 158 to be the following:

if (empty($nids) && empty($cids) && empty($bids) && !user_access('bypass node access')) {

With this change, assuming that you have bypass node access, you will be able to see the links instead of the annoying message. Unfortunately, the "Edit Link Settings" option will not work for these rows still, because the link data may be out of date.

In order to fix the result list for real, I ran the following drush commands, one after the other. They are defined in linkchecker.drush.inc:

drush linkchecker-analyze

Reanalyzes content for links. Recommended after module has been upgraded. This can also be done from the settings page: /admin/config/content/linkchecker

drush linkchecker-check

Check link status. (Note that this doesn't check them all, only the batch number set in your linkchecker settings.)

If necessary, you may also try running this first:

drush linkchecker-clear

Clears all link data and analyze content for links. WARNING: Custom link check settings are deleted. This can also be done from the settings page: /admin/config/content/linkchecker


Dynamically enabling checkout panes based on cart contents?

You may want to follow this issue:
http://drupal.org/node/1122386

it develops Rules based pane visibility.


Using the Panopoly and Commerce Kickstart distributions together

I would do #2.  To my knowledge, all of the modules in Commerce Kickstart can be downloaded separately; Commerce Kickstart just offers some default configurations.  If you run into trouble setting up the Commerce modules, you can always install a copy of Commerce Kickstart on a local machine/another server and reference that while you are setting up your main site.

By contrast, the problem with #1 is that not all of Panoply is easily configurable if you are not using that distribution (for example, the responsive layouts).  So it will be much easier to use that, especially if you are going to host it on Pantheon, which is behind Panoply.

You could edit the distribution makefile but that is probably more trouble than it's worth; the Commerce modules are designed to be installed on any Drupal site, so adding them to Panoply is very straightforward.


Sending notifications to users from other users dependent on certain conditions

I put a hierarchical taxonomy term in a user profile, and then had rules send to any user with that county selected.


Changing site:mode throws Twig memory error

You're debugging an entity or other object somewhere that has recursive references and debug gets into an endless recursion until all memory is used up.

Instead of debug(node) or similar, use debug(node.toArray()), that gives you the raw value instead of huge object structures.


Display content that reference the logged in user using Views

Create a content view and add a contextual filter for the field you created. My test contextual filter was called Content: User Ref Test. Your contextual filter will have the same name as the field you created.

2 . In the contextual filter's settings, click Provide Default: User ID from logged in User. This will only show content where the user has been referenced.


How do I pre / post process aggregated css or js files?

Using dependency injection we are able to inject a modified Asset Dumper, which can contain custom code.

Add to a custom module / or create a new module:

mymodule/mymodule.services.yml

services:
  asset.css.dumper:
    class: Drupal\mymodule\Asset\Utf8CssAssetDumper
  asset.css.collection_optimizer:
      class: Drupal\Core\Asset\CssCollectionOptimizer
      arguments: [ '@asset.css.collection_grouper', '@asset.css.optimizer', '@asset.css.dumper', '@state' ]

mymodule/src/Asset/Utf8CssAssetDumper.php

<?php
namespace Drupal\mymodule\Asset;

/**
 * Dumps a CSS asset and injects a utf-8 encoding string at beginning.
 */
class Utf8CssAssetDumper extends \Drupal\Core\Asset\AssetDumper {

  /**
   * {@inheritdoc}
   *
   * Injects utf-8 encoding statement at start of data string.
   */
  public function dump($data, $file_extension) {
    if ($file_extension == 'css') {
      // Don't override existing charsets.
      if (FALSE === strpos($data,'@charset ')) {
        // Charset string not found prepend.
        $data = "@charset \"UTF-8\";\n" . $data;
      }
    }
    return parent::dump($data, $file_extension);
  }
}

A short note on this: since this kicks in for all aggregated css files you might want to add additional checks to existing encodings etc.. If you have everything encoded the same way (which is very much suggestible) then this shouldn't cause weird side effects.

This approach also works for javascript (js) files:

services:
  asset.js.dumper
  asset.js.collection_optimizer


Rules: action before a user gets deleted

I may need a bit more info on what you're trying to access and what conditions or actions you're trying to perform on the deleted user, but I'll give it a shot.

You should have access to the deleted user's data when using the "User has been deleted" trigger. If by profile you mean data connected to the user using something like the Content Profile module, then you may want to instead use the "After deleting content" trigger, since Content Profiles are actually just regular nodes.

If that doesn't help, let me know more specifics on what you're trying to do and I'll see if I can help.


Configuring/using Drupal Pathauto module

A module must be enabled and configured after installing its files.


Migrating XML source twice, according to language

Turns out I didn't look at SimpleXML enough.

Using XPath, I can very easily select one of the languages through the lang attribute, and as such have one language imported.

If i then make a second migration for the other language, my problem is solved.

For reference, the selector for the description now looks like this:

$this->addFieldMapping('body', 'desc')
  ->xpath('desc[@lang="nl"]');


I don't think this can be answered here. It seems to be a call to Drupals Batch API that fails. But why can't be answered without some debugging and is not in the scope of your question.

Basically you are doing it right. You can try the otherway round and add menu items to you desired menu and than let them point to taxonomy/term/123. This should give you the same result.


if you look into your console log you will see the following errors

this happens when you hide a required field.

I had a look at your markup and found that you have the above 4 fields display set as none; and at the same time also has attribute required.

So remove the required attribute or apply novalidate on submitting form.


Check out

http://drupal.org/node/751826

and look into forms validation.  You could check if your date is less than the current date and if not, bzzzzt.


Date range or date with operation (greater than, etc.) contextual filter

I don't understand why we don't have operator (>=, <=, etc.) in contextual filter...

Temporary solution... affect all views with argument :

File :

\core\modules\views\src\Plugin\views\argument\Formula.php

Change :

$formula = $this->getFormula() . ' = ' . $placeholder;

to

$formula = $this->getFormula() . ' >= ' . $placeholder;

Function :

public function query($group_by = FALSE) {
    $this->ensureMyTable();
    // Now that our table is secure, get our formula.
    $placeholder = $this->placeholder();
    $formula = $this->getFormula() . ' >= ' . $placeholder;
    $placeholders = [
      $placeholder => $this->argument,
    ];
    $this->query->addWhere(0, $formula, $placeholders, 'formula');
}


Most likely your version regex ist wrong. According to the source code, the version string looks like this:

crossfilter.version = "1.3.7";

The regex pattern needs to account for the whitespace around the equal-sign. I'd probably write it like this

'pattern' => '/crossfilter\.version\s*=\s*"(\d+\.\d+\.\d+)"/',


form_set_error highlight single field in multiple value field

I solved this by using the delta of the field with the error. In this example, field_acceptable_domains is a multi-value text field and I'm using valid_url to validate each value.

// This is a multi-value field, so we need to loop through the values.
foreach ($form_state['values']['field_acceptable_domains'][LANGUAGE_NONE] as $delta => $url) {
  if (!valid_url($url['value']) && !empty($url['value'])) {
    form_set_error('field_acceptable_domains][' . LANGUAGE_NONE . '][' . $delta, t('The domain %domain is not valid.', array('%domain' => $url['value'])));
  }
}


It appears that email is already in the database on another row. This can have many causes; importing users twice, creating accounts in a custom module without proper checking if the email address is available, etc.

If you do not use the account edit forms, but modify users programmatically, it can appear that the same email is added to the database twice (the form validation does not run in those cases). Then later when you try to edit one such user, it cannot save because that account should not have existed in the first place. This measure is there so users cannot sign up with the same email twice, but since the user creation and edit form are in fact the same form (and as such have the same validation), it can happen during the save of a user as well.

Double check that you have no modules that can create accounts from email addresses (eg. Drupal commerce) and check your database users table to identify the duplicate account.


How to load node object in node preview page?

If you need to use the node object in hook_preprocess_page() on the preview page, you need to use the "node_preview" parameter, instead of the "node" parameter:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  if ($route_name == 'entity.node.canonical') {
    $node = \Drupal::routeMatch()->getParameter('node');
  }
  elseif ($route_name == 'entity.node.preview') {
    $node = \Drupal::routeMatch()->getParameter('node_preview');
  }


How can I use conditional logic to not display a  in page.tpl.php based on node id?

If you're trying to hide the left sidebar when viewing node 51, this is not the right way to do it. Edit the block visibility settings for the blocks in the left sidebar so they are hidden when the path is 'node/51'. Then in your template you can do this:

<?php
  if ($left) {
    print '
' . $left . '
';
  }
?>

This will hide the entire div#left when there are no blocks in the left sidebar.


When exiting views modal I am returned json

Make sure you use the default jQuery version (1.5) when using The Views UI module.


Please try this:

/**
 * Implements hook_facetapi_searcher_info_alter().
 */
function mymodule_facetapi_searcher_info_alter(array &$searcher_info) {
  foreach ($searcher_info as &$info) {
    $info['url processor'] = 'term_facet_url';
  }
}

Create a folder inside your mymodule directory, and name it facetapi.

Next is create an .inc file and name it, url_processor_term_facet_url

So you should have this structure:

mymodule/facetapi/url_processor_term_facet_url.inc

Inside of your url_processor_term_facet_url.inc, add the following code.

<?php

/**
 * @file
 * A custom URL processor.
 */

/**
 * Extension of FacetapiUrlProcessor.
 */
class FacetapiUrlProcessorTermFacetUrl extends FacetapiUrlProcessorStandard {

  public function getQueryString(array $facet, array $values, $active) {
    $params = $this->params;
    unset($params[$this->filterKey]);
    return $params;
  }

  public function getFacetPath(array $facet, array $values, $active) {
    // Change the line below to your desired taxonomy term path, currently it
    // is set to 'taxonomy/term/[tid]'. And also make sure only taxonomy terms
    // are affected. Check other parameters to pull the data you might need.
    $path = 'taxonomy/term/' . $values[0];
    return $path;
  }

}

I hope it helps.


How to display text next to image drupal view?

The simplest solution to your problem is, on right side in views there is a format option set it to Unformatted list, in settings do not select Add views row classes and Add striping (odd/even), first/last row classes.

Below that is Show:Fields | Settings , click settings and select Provide default field wrapper elements and then select the fields mentioned below it to be displayed inline, which in your case is image Title and description.

Also the Table Format is good option but it creates a lot of problem in CSS customization.


How to get the path to the translated node?

After looking at the source of the "Content translation" module I've come up with this solution:

    global $language;
    $translations = translation_path_get_translations("node/42");
    /*
    Returns the paths of all translations of a node, based on its Drupal path:
    array(2) {
        ["de"]=>string(7) "node/42"
        ["en"]=>string(7) "node/43"
    }
    */
    print l(t('Link Title'), $translations[$language->language]); //l() will return the alias to node/42

This will output the link to the correct node alias. Works and isn't overly complicated - still wonder if there's a function that already does this.


How to theme each nodes in a taxonomy term page seperately in drupal 7

this could be done with view.

Create a taxonomy view of the type page.
Set the path as taxonomy/term/% this will override the default taxonomy path and will show the views page instead.
Add the fields that needs to be shown in all the nodes accept the first one.
Add a contextual filter of taxonomy term id.
With in the pager settings give an offset 1 so that the first node is skipped.
Set the Format to grid and give number of columns as 2 so that it displays in two columns

The above steps will display all the nodes except the first one in two columns.

Next we need to create a block to display the first node.

With in the current view add a block.
Set the pager to display only one element without the pager being shown.
Add the required fields. (Image in the size you want etc.)
Add a contextual filter of taxonomy term id.
Now go back to the page view and add a header.
Select "Global:view Area"
Choose the block we created above form the drop down and tick "Inherit contextual filters."

Now your taxonomy page would display as you wanted.


Since you posted this question, hook_library_info was replaced with *.libraries.yml files.

An example of a simple library declaration looks like this:

jquery.form:
  remote: https://github.com/malsup/form
  version: 3.39
  js:
    assets/vendor/jquery-form/jquery.form.js: {}
  dependencies:
    - core/jquery
    - core/jquery.cookie

Once declared, this library can be attached to a render array like this:

$element['#attached']['library'][] = 'core/jquery.form';

Now Drupal should take care of adding the library and all required dependencies to the page. Even though the library declaration can contain a remote url, Drupal will not automatically download the library for you.

If I'm not mistaken, you will always need a module or a theme with a .libraries.yml file to act as the provider of your library. However a module can be really simple, you only need a .info.yml file to declare a module.


Unable to install ... already exist in active configuration

With Drush, you can run drush config-delete module_name.settings to delete the configuration causing the error.


How to theme separately the node content and the comments

A- The node_menu (hook_menu implementation) has node_page_view() as a page callback for a node page.
B- node_page_view() calls node_show() which:
1- is not a themable function.
2- mixes (concatenates) the output of node_view() (the node content itself) and of comment_render().
C- comment_render() calls theme('comment_wrapper', ...)

This is where the serpent bit its tail:
As mentioned in the question, I could reimplement comment-wrapper.tpl.php to nix the output mixed with the node,
but then calling comment_render() separately to get the comments where I want returns nothing for the same reason!

The conclusion is that the solution cannot be implemented by a theme alone. One would need to implement this in a module and override the node_page_view() callback and re-implement node_show(), taking care of the fact that node_show() is also called when viewing a node revision ('node/$nid/revisions/$vid/view').


How to customize Commerce order admin view

In Drupal 7, Commerce 1 (7.x-1.x)

For the actual individual order page, you'll want to edit the view entitled "Line items (Commerce Line Item)"
Bear in mind however, the column you add may cause errors if the field only exists for some product types and not others. You might need to add an additional relationship to the view to get the field of data.

For the actual order summary page found at /admin/commerce/orders, you'll want to edit the "Orders" view.  You'll probably need to add a relationship for Commerce Order Line Items.


For getting the node ID you need to first save the node. For eg:

$node = Node::create([
      'type' => 'my_content_type',
      'title' => 'My Title',
      'uid' => \Drupal::currentUser()->id(),
      'status' => 1
]);
$node->save();
    :
    :

$id = $node->id();
$year = date("Y", $date);
// default format: 'SWAN%s%08dIMOV'
$format = $this->getSetting('format');
$node->field_custom->value = sprintf($format, $year, $id);
$node->save();


Submit form and disable submission button

For those wanting to disable the form submit button on load, try this:

$form['actions']['submit']['#attributes']['disabled']  = 'disabled';


Facing Repetition in records when I use multiple relations in Views

Have a look at the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


Fatal error: Class 'SelectQuery' not found in includes/database/database.inc on line 813

Rolling back this patch... https://www.drupal.org/node/2170453 solved the first problem, and then using htaccess to define the correct php version fixed the next error.


Once you removed the patch from composer.json and run updates, core directory will be overridden by the new release and here the "b" directory will be removed.

For best practices reasons, I invite you to manage your project patches using composer patches plugin, and to be more specific use external patch file method.


To view the database field data in the admin page custom module

There are plenty of ways to get your fields in a page.
You can try

Views OR Data

If you prefer some coding you could try theme_table or theme_item_list

I would do it by theme_table if i prefer coding.

  Returns HTML for a table.

Read HowTo: Create Simple Tables

<?php
  $header = array('Node ID', 'Title', 'Type', 'Terms', 'Created', 'Published', 'Sticky', 'Promoted');
  $rows = array();
  $no_yes = array('No', 'Yes');

  $results = db_query("SELECT * FROM {node} ORDER BY promote DESC, sticky DESC, created DESC");

  while ($node = db_fetch_object($results)) {
    $termlist = taxonomy_node_get_terms($node->nid);
    $terms = array();
    foreach ($termlist as $key => $value) { $terms[] = $value->name; }
    $rows[] = array($node->nid,
                    l($node->title, 'node/'. $node->nid .'/edit'),
                    $node->type,
                    implode(' | ', $terms),
                    format_date($node->created),
                    $no_yes[$node->status],
                    $no_yes[$node->sticky],
                    $no_yes[$node->promote],
                );
   }
  return theme('table', $header, $rows);
?>

To get Edit/Delete work you should write your own code if its not nodes.


Problem solved.

Thanks to @hansfn comment, I found a similar issue on drupal.org: Doesn't work for anonymous users

I told about it to the developer I work with and he updated the RobotsTxt module from the version 7.x-1.2 to the version 7.x-1.4, and it solved the problem.


Different styling for each teaser display

You can create different Entity View modes instead of the single teaser. While you can do that via a custom module in Drupal 7, there is a nice little module for that (https://www.drupal.org/project/entity_view_mode) too.

Create different modes like 'teaser_front', 'teaser_sidebar' and theme them differently using the standard theming convention (can also be found in the module page).


How to apply patches on Term Reference Tree

If you would take one second and google how to apply patches, you would come across this page: https://www.drupal.org/patch/apply. It explains how to apply patches.


Date popup - how to restrict typing into the textfield and return timestamp instead of formated date

You can use ['#attributes'] = array('readonly' => 'readonly');

Ex:

    $date_format = 'd/m/Y H:i';
    $form['campaign_popup'] = array(
          '#type' => 'date_popup',
          '#date_format' => $date_format,
          '#default_value' => variable_get('campaign_popup'),
          '#title' => t(' Campaign Start Date.'),
          '#date_label_position' => 'within',
          '#date_year_range' => '0:+3',
          '#datepicker_options' => array('minDate' => 0),
          '#attributes' => array('readonly' => 'readonly'),
    );


Ecommerce site with square area calculation in price

I strongly recommend you get some formal instruction, such as the book "Pro Drupal Development" or "Front End Drupal" as well as get accounts at BuildAModule.com and/or Drupalize.me to get a deeper look into Drupal. The decision is ultimately one where you need to figure out your own level of technical competence - creating an eCommerce web site is complex, with legal ramifications if you screw up. So, this is serious.

Magneto is a good platform, but they just got bought by eBay, and in my mind that places their structure (support, UI, community) in an uncertain position. Drupal's not going anywhere but up.

I suggest you create one or two non-eCommerce Drupal sites first, just to learn the environment. Do this on your local machine, so you get personal experience with where files go, their organization, how to add and remove AND update modules. How to configure a what-you-see-is-what-you-get editor, and so on. These are all essential Drupal skills that take time to develop; not a huge amount of time, but time none-the-less that you NEED to spend before you take on the larger and more serious task of creating your online store. After that, move one of your web sites to an online host; forcing you to learn how to manage and maintain a remotely hosted Drupal site. Another essential skill you do not want to be developing with live customers.

Frankly, I would never recommend creating an online store as your first exposure to any eCommenrce environment. You need to be familiar with the CMS first, to insure you are not doing basic entry-level mistakes; such mistakes in a live online store could bankrupt you, land you in jail, or even expose your customers to massive credit card fraud.


Views - sticky items per page paginated using several displays (Hooks or UI way)

First off, this can all be done in views, no custom code required (yay!). This is accomplished by creating an attachment view which will inherit the pager settings.

First you create a view with a page display that shows 7 Y nodes only.

Second, on the same view, add an attachment display. For the attachment, set it to show 3 X nodes only. In the attachment settings, make sure that Inherit arguments, Inherit exposed filters, and Inherit pager are set to yes. Set Render pager to no. Set Position to before and set Attach To to your page display.


By conditional field do you mean a simple Boolean? If so, you should be able to pull this off with some tactical field rewriting.

When creating the Boolean in your content or entity type, have 'Yes' as the only value, leaving the unchecked state assumed as no. Then in views add the flag list field first and exclude. Next the Boolean but don't exclude. Use its default formatting not its key. In its settings rewrite using the flag list field replacement pattern, and in the empty behaviour (eg the result of the empty checkbox when no value has been specified for it), choose to hide rewriting.

You may need to fine tune this or perhaps add additional fields, chasing the replacements until it works. You'll be amazed at the sophisticated conditions you can set up in this fashion.


How to delete a particular variable from a configuration created by a custom module

Deleting a config key:

Updating per Berdirs comment, deleting/clearing a key within a config object, not deleting the entire config object:

Drupal::configFactory()->getEditable('abc_settings')->clear($entity->id() . '_options')->save();

Deleting config objects:

I did this within TVI module, anytime a term or vocab is deleted:

/**
 * Implements hook_ENTITY_TYPE_delete().
 * Remove TVI settings when vocabularies are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_vocabulary_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_vocabulary.' . $entity->id())->delete();
}

/**
 * Implements hook_taxonomy_term_delete().
 * Remove TVI settings when terms are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_term_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_term.' . $entity->id())->delete();
}

Of course, you would pass your own config name to getEditable(), and the hook names need to have your module name and not tvi.

This will delete any config matching that name when a term or vocab is deleted.

I haven't taken the step yet in my own code, but you could go further and implement a method that before a vocabularly entity is deleted, get all of its children, loop and delete config, then delete the vocab and its config.

Example:

Drupal::configFactory()->getEditable($entity->id() . '_options')->delete();


How do I completely uninstall a custom entity implemented by my module?

The tables declared by the hook_schema() will be automatically remove when you uninstall your module.

If you need to remove other tables or variables use the hook_uninstall()


What is the syntax for using a token on webform confirmation page for Drupal 7 Webform 4

Use Webform tokens module

  Webform Tokens provides tokens for user form submissions for forms
  created with the module Webform 3.

But Webform4 has this feature inbuilt, you might try this patch to fix it.

OR

You can try writing webform-confirmation.tpl.php to achieve the same.


MailChimp + Drupal 8: How to install properly? (page could not be found)

You should use Composer to fetch this module, as it has an external dependency noted in its composer.json file:

http://cgit.drupalcode.org/mailchimp/tree/composer.json

It seems to include an older version with the module, I'm not sure why, but the current version of Mailchimp API by Thinkshout looks to be 1.0.8. I don't see any installation notes. The module comes with 1.0.6... ?

Other than that, clear your caches and try to access the page again.


"Output this field as a custom link" set here link to the content

Found a solution:

Add a Link to Content field, outer fields hide from display and remove links.

then setup Link to Content like this:

Link to Content haven't link path input - it always link to content.  This what I needed!


Ok I found 2 ways to do that.

1. In a custom theme

You can alter variables in your my_theme.theme file. You need to figure out the name of the function you need. ex: my_theme_preprocess_twig_file(), in my case I needed my_theme_preprocess_links__language_block() You need to take the twig file name and replace all - for _.

my_theme.theme:

function my_theme_preprocess_links__language_block(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables['links'] as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['link']['#options']['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['links']['activeLink'] = $link;
      unset($variables['links'][$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables['links']) == 2) {
    unset($variables['links']['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables['links']);
    $alternate['link']['#options']['attributes']['class'][] = 'btn';
    $alternate['link']['#options']['attributes']['class'][] = 'btn-primary';
    $variables['links'] = [$alternate];
  }
}

2. In a custom module

You can also create a module that will change those same variables. There is a big difference in the values of the variables because this preprocess happened earlier in the flow. The name of the function is also quite different, ex: my_module_api_to_modify_alter(). In my case I needed to modify the language_switch_links from the language.api.php. You can find all alter function by searching for *.api.php files in drupal 8. Those are there as a reference for exactly that.

my_module.module:

function my_module_language_switch_links_alter(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['activeLink'] = $link;
      unset($variables[$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables) == 2) {
    unset($variables['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables);
    $alternate['attributes']['class'][] = 'btn';
    $alternate['attributes']['class'][] = 'btn-primary';
    $variables = [$alternate];
  }
}

And my Twig template for both cases links--language-block.html.twig:

{% if links -%}
    {%- if links|length == 1 -%}
        {# show only alternate language button #}
        {{ (links|first).link }}
    {%- else -%}
        {# show selected language in button and other languages in drop down #}
        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ links['activeLink'].text }} </button>

            {% for key, item in links %}
                {% if key is not same as("activeLink") %}

{{ item.link }}

                {% endif %}
            {% endfor %}

    {%- endif -%}
{%- endif %}


Replace UID in view tab with name on user profile page

To replace UID in view tab with name on user profile page:

follow those steps:

Create a user relationship :

Add contextual filters with User Name

3.Configure your contextual filter ((author) User: Name) like this

Save your configuration.

Result


Like i noted above, drupal thinks it's installed in a sub-folder because of the php-docroot lies in the parent-folder of the drupal-install, so it added /domain2/ to the $base_url.

To fix it, just edit your current settings.php in sites/* folder:

$base_url = 'http://domain2.tld';  // NO trailing slash!

Make sure settings.php is writable, it's often read-only!
(this was the problem here, otherwise i would've saved a lot of time searching a alternative ways to fix the $base_url... looks like there's a overhaul needed in my svn:post_commit-ftp_upload-script ;)


Checkbox list for content type in drupal 7

You're right...the CCK module has now been incorporated natively into Drupal 7, so you would use that.

Just visit http://mysite.com/admin/structure/types/manage/CONTENT_TYPE/fields to add the fields to your content type in pretty much exactly the same way you did using CCK in Drupal 6.

EDIT

Sorry I understand your problem now, the node reference and user reference modules aren't part of the default field system in Drupal 7; you just need to download and install the References module and then you'll have the "Node Reference" option in your field type drop-down like you're used to seeing.


Pass field value of original node in webform

I'm answering this with how I solved it in case anyone else has the same question. Maybe my question could be worded better though...

I was able to get this working with the Webform Node module.

I installed webform node. Then, I added a webform field to my content type. I selected the form I wanted as the default field settings. I selected the "Use this field's Content entity as the webform submission's source entity." checkbox.

I added my form to the display of the nodes I wanted it to be on in the content type's twig:

{% if node.field_name.entity.label == "My condition label" %}
  {{ content.field_name_of_webform_field }}
{% endif %}

Now, on my course page the same form appears for each section and I get the code for the section that the person filled-out the form on in the [webform_submission:source-entity:field_code:value] token!!

A couple of the resources that helped me:
https://www.youtube.com/watch?v=B_ZyCOVKPqA
https://www.webwash.net/moving-forward-webform-drupal-8/#attaching-a-webform-to-a-node


How to setup a rule to redirect to shopping cart?

I think you're probably missing a step, if I was integrating this I would create a product called Subscription (or something similar)

Your rule actions should be something like:

Add product Subscription to cart
Go to checkout


Views listing of content types a user is allowed to create

Like @googletorp said, you can't do this with Views, you will have to create a custom module.  If you are creating your own module, this short snippet will give you an array ($types) with the links to content types the logged in user can create (D6).  If the user cannot create any content types it will show a message:

<?php
  $types = array();
  foreach (node_get_types('types', NULL, TRUE) as $type) {
    if (node_access('create', $type->type)) {
      $types[$type->type] = l($type->name, 'node/add/' . str_replace('_', '-', $type->type));
    }
  }
  if (count($types) == 0) {
    drupal_set_message('You cannot create any content types!', 'warning');
  }
?>


How to display node details and call function in *.html.twig

I think I would have implemented this feature differently. Let me just answer the specific question, and then I will tell you an alternative approach.

Custom 'functions' in Twig

The easiest thing for you could be to Implement a twig macro.

However, macros could be limiting. To have all the PHP power you can create a twig extension function

If you are in a rush and are into bad practices, then there is the twig tweak php filter, so that you can do this:

<div class="bad-practice">
     {{ 'return _get_node_details();'|php }}
</div>

Alternative implementation using Drupal views

Create a Drupal View, with a Block Display.
Place the new Block, using the Block Layout.
If you need to do a heavy alteration use a hook_views_data_alter().


Creating fielded entities in a module: how to ensure unique field names?

The only way to be sure you have a unique field name is to test on creation whether the same field already exists.

As you have realised, this is a problem when deploying your fields as a feature, as you do not know what environment your fields will be deployed in. Unfortunately Features does not provide you with a way to rename the fields when a feature is first enabled.

This is something you could implement yourself ; it should be possible to do this in a way that doesn't stop you from automatically re-creating the feature. Here is an idea about how this could be done:

(1) Name all your fields prefix_fieldname (I will assume you used 'mymodpref' for the prefix) and ensure they are no more than (say) 30 characters ;

(2) In your module's .install file, implement hook_install such that you find a safe field prefix that will make your fields unique. For instance:

function mymodule_install() {
  $prefix = 'mymodpref';
  $prefix_index = $prefix;
  $index = 1;
  $found_unique = FALSE:
  while (!$found_unique) {
    $c = db_query("
      SELECT COUNT(*)
        FROM {field_config}
       WHERE field_name LIKE :prefix",
    array(':prefix' => $prefix . '_%')
    )->fetchField();
    if ($c > 0) {
      $prefix_index = $prefix . $index;
      $index++;
    } else {
      $found_unique = TRUE;
    }
  }
  if (strlen($index) > 2) {
    // Our fields are up to 30 characters, so we can't have an index
    // of more than 2 characters. If this happens we're in trouble -
    // add some code here to tell the user we can't install the module.
  } else {
    variable_set('mymodule_field_prefix', $prefix_index);
  }
}

(3) In you feature's main module file, add an implementation of hook_field_default_fields_alter which allows you to change the default field definitions, and rename them with the right prefix :

function mymodule_field_default_fields_alter(&$fields) {
  $prefix = variable_get('mymodule_field_prefix', 'mymodpref_');
  $new_fields = array();
  foreach ($fields as $key => $field_info) {
    // Replace 'myentity' and 'mybundle' accordingly
    if (strpos($key, 'myentity-mybundle-') === 0) {
      $new_field_name = $prefix . '_' . $fied_info['field_config']['field_name'];
      $field_info['field_config']['field_name'] = $new_field_name;
      $field_info['field_instance']['field_name'] = $new_field_name;
      unset($fields[$key]);
      $new_fields['myentity-mybundle-' . $new_field_name] = $field_info;
    }
  }
  $fields = array_merge($fields, $new_fields);
}


Blank window when i press select media link

Use Firebug or Chrome Developer tools and look at the "Network traffic" and "Console" windows. I'll bet your getting a 404 or a JS related error in 1 of those windows.

You can then correct your server file permissions, fix the JS code error, or whatever.

You dont just have a blank page -- you have a blank page and an error reported somewhere.


That code doesn't work on Drupal 8 because l() has been removed from Drupal 8. The correct code for Drupal 8 is closer to the following one.

use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => Link::fromTextAndUrl(new TranslatableMarkup('Approve conditions'), Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']]))->toString(),
  '#required' => TRUE,
);

Alternatively, you can put the link in the description.

use Drupal\Core\Link;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;

$form['approve'] = array(
  '#type' => 'checkbox',
  '#title' => new TranslatableMarkup('Approve conditions'),
  '#description' => new TranslatableMarkup('By clicking this checkbox, you approve the conditions', [':conditions' => Url::fromUri('entity:node/10', ['attributes' => ['target' => '_blank']])]),
  '#required' => TRUE,
);

Keep in mind that, as said in the comments for l() and url() are removed in favor of a routing based URL generation API, if the shown code is used in a class using the StringTranslationTrait trait, instead of the TranslatableMarkup class you use $this->t().


You can do that with Views Rules.

Create a view that gives all directly referred children of a node (with the node as contextual filter), give it a "Rules" display.
Now create a Rules component that takes as argument a node, runs a "View Loop" (you'll see what that is as soon as you've installed the above mentioned module) over your newly created view.
To this loop, add an action that adds the current loop item to your organic group. Save the component.
Add a second action to the loop, which is the component itself, with the current loop item as an argument. (I haven't actually tried this.)
You can call this rule component from within other rules that you can trigger in many ways, say by clicking a simple button or by performing a bulk operation.

My two cents:

Be careful with this, since it is recursive. If you have two enterprises linking each other, then this will recurse infinitely and crash. Maybe add as a precondition in the rule component that the node is not yet a member of the group.
Decide whether you want to use entity references or organic groups for this, but don't use both. What you're trying to do sounds a lot like you have a network of enterprises and sub-enterprises and you want to translate your existing network into organic groups. If someone adds new references, you'll have to update your groups, which is annoying. Decide between entity references and organic groups and get rid of the other.


Marius,

When you login using rest api, csrf and logout tokens are generated. use the logout_token generated to logout form your app. Make a post request to

/user/logout?_format=json&token={logout_token}

Sample code to logout from your app will be similar to

 var xhr = new XMLHttpRequest();
 xhr.withCredentials = true;

 xhr.addEventListener("readystatechange", function () {
   if (this.readyState === 4) {
     console.log(this.responseText);
   }
 });

 xhr.open("POST", "http://example.com/user/logout?_format=json&token=logout_token");
 xhr.setRequestHeader("content-type", "application/json");

 xhr.send(data);

Hope that helps.


How to use Solr Handlers when sending requests from Drupal

Ok, we figured out how to do this. In order to choose the handler that is being used by Solr while sending a request from Drupal, we have to edit hook_apachesolr_query_alter() and add the following code:

$query->addParam('qt', 'MyHandlerName');

We did some extra coding to allow us to change the handler directly from back office in order to be able to switch handlers without touching the code.


Printing block on all pages of a contenttype

You can created the page.tpl.php and put a condition to check the content type then print this block.

page.tpl.php API Drupal 7

From node object you can find the content type to check condition.

<?php print_r($node);?>

More specific to your question.

<?php global $node;
    if ( isset($node) && !empty($node) && $node->type == 'type_name') {

            $block = block_load('menu', 'menu-basic-menu');
            print render(_block_get_renderable_array(_block_render_blocks(array($block))));

    }
 ?>


Grouping galleries with Colorbox modules

The content-type "gallery"

First of all, I created a content-type "gallery" which has several fields of my choice and a field "image" with illimited number of images.

The View

If I don't want something too specific, I use the Views module to create a View of all my galleries. I hope you already know that module. If not, go read the basics.

Choose content of type gallery
Set the title and the path of the page, etc...

You can choose which fields to show. If you want something like the site you linked in your question, you can use this configuration:

Format: grid (with number of columns to 4)
Fields:

Title
Image

Image style to thumbnail or whatever you created
Link to content (to land on gallery page when you click on the image)
Multiple value fields settings: display 1

Normally, you have now the equivalent of http://www.hopkinsco.com/portfolio when you open your View page.

The gallery page

The page of the content-type gallery displays all the fields you created for this content-type, in the order you arranged them in the admin. If you want something simple with the Colorbox module, you can go to admin/content-types/gallery/manage display and set the image field config like this (sorry for the french):

Then go click on the little gear on the right to set the advanced config:

Now you've got the equivalent of http://www.hopkinsco.com/portfolio/colonial.

The template and/or the style

Now that you've got the right content in the right place, you can customize the rendering with a little template and/or CSS.


The login doesn't show a username anymore

You could try to disable the module that causing the problem. There are multiple ways of doing that.

Using Drush

  drush dis modulename

Database hack

In the system table find the module and set its status to 0

  UPDATE {system} SET status=0 WHERE name='modulename'


Acquia Dev Desktop and Drush broken with syntax is incorrect

I was also facing the same issue on windows 10 with Acquia Dev Desktop and configured existing Drupal 8 project from a client.
Following three things what I did worked for me.
I simply:

Removed directory vendor/drush
Removed directory vendor/bin
Removed line "drush/drush": "^8.1" from composer.json which is located on docroot directory.

Now, default drush is working for me as you can see the default drush version at C:\Program Files (x86)\DevDesktop\tools\composer.json.
Hopefully, this will help someone else.


You could use the preinstalled theme item_list:

  $form['notes'] = [
    '#theme' => 'item_list',
    '#title' => $this->t('A few notes.'),
    '#list_type' => 'ul',
    '#items' => ['Item i', 'Item ii', 'Item iii'],
  ];

See https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21item-list.html.twig/8.5.x


What does the "Views: Filter by an entity reference view" reference method do?

In your Entity Reference Field settings the Default method will allow all of the entities of the type you specified to be eligible to be referenced.
If you're setting up your ER field to reference Taxonomy terms of a certain vocabulary then all of the terms from that Vocabulary will be able to be chosen inside that field.
If you want more control over which items should be eligible you can use Views to create a Display of type Entity reference.
Views module allows you to build various lists of entities. You can add filters and narrow down the list to the items you need in a specific case.
If you want a list of 10 specific Taxonomy Terms from a Vocabulary that contains 100 terms you can use Views to build it.
Usually you build Views Displays of types "Page" and "Block". But there is also the option to build "Entity reference" Display.
The "Entity reference" Display type has some special settings that other displays don't have, and they control what the list of entities should look like in the context of using that list in an ER field on a CT.
So once you create one Entity Reference Display type in Views, set it to filter the same type of items as an ER field in your Content Type, you will be able to return to your ER field settings and choose that Views Display as the field reference method.
This means that the entities offered to be chosen through the ER field when creating a new node will be only the entities from the Views you had created. If you had narrowed down the list of entities in the ER Views Display to only 3 items, then only those 3 items will be available in the ER field when creating a new node.
The Views Display must be Saved before it can appear in the ER field settings. When creating the View you choose the type of entities that will be listed, for example Taxonomy terms, and after the View has been created you can add a new Display to the Views, choose "Entity reference" from the list of the offered Views Displays (different Views Displays are shown as tabs on the Views Edit page).


Drupal 7 Site Structure - Moving From Wordpress

Views allows to add custom text (with a format, so it can contain html) before and after a view. This could be a possible option.

Alternatively, if you for example want multiple news pages (kind of like news categories although taxonomy might be a better option here), have a look at the EVA project, which seems to be the successor of Views attach. This allows to add a Views to a node (or another entity like a user).

To assign news items to a specific page and only display it there, you could add a node reference field to the news item node type and then pass the node id as an argument to the view (EVA supports that according to the project description). But again, using taxonomy might be a better option for a categorization like this.


Display the amount of the order on the block cart

In Commerce Kickstart, you're actually looking at a view. The footer of the view displays a line item summary:

You can read through the handler's render() function to see how it actually gets that information.


How to get selected value in option id value in drupal form api

Try the following code:

function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

Hope this helps you!


Accordion Menu - Where is the original CSS file of the module?

The Accordion Menu module uses jQuery UI, which is included with core. If the styles you're looking for are in a CSS file, they'll be in /misc/ui/jquery.ui.accordion.css (or possibly one of the more general jQuery UI CSS files).

Bear in mind that jQuery UI is a javascript library, so the styles might be applied directly to the elements at runtime, and may never exist in a CSS file as such.


How to find where are defined tokens for Redirect?

As Clive mentioned, since Redirect is an entity, those tokens are automatically generated by the Token module's token.tokens.inc.

I suggest you read Custom Tokens in Drupal 8 to understand how they are declared & work.


It would be safe with all folders being in 0775 and settings.php in 444.
However, if you would use FTP/SFTP to edit either the themes or any module files You may need to login with the "Owner" user, which may or may not be possible in a shared hosting environment.

So., depending on that you may choose. However, if you use SSh it will be not an issue.


Drupal on IIS 7: URL Rewrite vs. ISAPI Rewrite modules

This should help you out: Clean URLs with IIS

  The best method is Microsoft's URL Rewrite Module for IIS7, available
  via the Web Platform Installer on Windows Server 2008 and Vista.
  Download and documentation are also available on Microsoft's IIS.Net
  site. You can also use third party rewrite modules (see list above).


Managed to find my solution! This thread here is my saviour:
Print primary and secondary tabs separately

In templates/edit/edit-acct-settings.tpl.php page

<?php if ($primary_local_tasks): ?>

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

<?php endif; ?>

In my_theme/template.php

function mythemename_preprocess_user_profile_form(&$vars) {

  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();
}

Hope this helps any other newbies who encounter same issue!
Thanks all~


Drupal overlay is not working for content links

First of all, make sure that the user that is trying to use the overlay has the appropriate permissions to do so (the permission is called: "Access the administrative overlay"). If you are trying to add/edit content as admin, then that's not the problem.

Also, make sure that in admin/appearance page, the option "Use the administration theme when editing or creating content" is selected. Notice, that if a role does not have the permissions to use the administrative theme (or the overlay for that matter), the users with the specific role will be adding/editing content through the default theme of your site.


You can do it by defining a page in a custom module.

Create a page for the category "Page not found" using hook_menu().

function MODULE_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'MODULE_page_not_found',
    'access callback' => TRUE,
  );
  return $items;
}

function MODULE_page_not_found() {
  drupal_set_title('Page not found');
  $cust_err = "";
  $cust_err = $cust_err . "The requested page " . current_path() . " could not be found";
  return $cust_err;
}

The page callback uses current_path() to return the path of the page causing the 404 error.

Go to Admin > Config > System > Site-information, and enter page-not-found (same name as defined in hook_menu) under Default 404 (not found) page.

Now the error page appears like in the following screenshot.

It is clear that it contains all the navigation links, and also the page URL producing the error (very similar to the original page not found). And the module mentioned in the answer above by @Nikhil will output "The requested page could not be found." but does not contain the URL of the page causing the error.


Is Drupal doing something to JQuery delegate or click() that causes the binding to fail?

Drupal.behaviors ensures that the JavaScript code is executed again whenever there are any changes in DOM Elements.

Most JavaScript works by manipulating elements in the HTML DOM. As Such, JavaScript code generally does some extra work to ensure that DOM is fully loaded and elements we want to interact with are available.

The most common way to do this in jQuery is using the $(document).ready() syntax. Placing our code inside this statement will ensure that it is not executed until the DOM has finished loading.

Drupal takes this a step further by using Drupal.behaviors. Along with ensuring that code is not executed until the dom has finished loading, It also ensures that the code is executed again whenever there are any changes in DOM Elements.

So, the Drupal way of handling the click event of a newly added element with a class of nav-button looks like this:

Drupal.behaviors.exampleBehavior = {
  attach: function (context, settings) {
    $('.nav-button',context).click(function(){
      console.log("button clicked");
    });
  }
}


Template page--node--.tpl.php not working

According to Drupal 7 Template (Theme Hook) Suggestions it should be page--node--11.tpl.php (note the double dashes):

  page--[front|internal/path].tpl.php
      base template: page.tpl.php
  The suggestions are numerous. The one that takes precedence is for the front page. The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for. Keep in mind that the commonly-used Pathauto module uses path aliases.

  The front page can be set at "Administration > Configuration > System > Site information." In Drupal 6, at "Administrator > Site configuration > Site information." Anything set there will trigger the suggestion of "page--front.tpl.php" for it.

  The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:

  page--node--edit.tpl.php
  page--node--1.tpl.php
  page--node.tpl.php
  page.tpl.php

  Also see page.tpl.php in the Drupal API documentation for more information.


How can I add a search feature to my Drupal 7 Zen child theme frontpage?

Your probably getting the warning because the function takes its argument by reference and to pass a variable by reference it needs to be defined. You're passing a function call which isn't a variable.

Try the following...

$search_form = drupal_get_form('search_form');
$search_box = drupal_render($search_form);
$variables['search_box'] = $search_box;


How to get Google Analytics to track progress through a multi-page Drupal Webform?

if the url doesn't change, you can use google's single page applications approach to track:

https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

You can set a "virtual" url for each page using javascript. Then create a goal funnel in Google Analytics using these virtual url's. You'll probably need to custom write this js to look for specific fields etc to let it know which page it's on.

I think another way is to use custom fields in the call to ga. Not sure if those are available as goals though.


How to add validation to Drupal commerce checkout submit?

Drupal Commerce's checkout form uses button level validate and submit handlers as opposed to form level handlers. This means instead of just adding a handler to the $form['#validate'] or $form['submit'] array, you need to add it to the correct checkout button itself.

In your case, you'll add a handler to $form['buttons']['continue']['#validate'] via a form alter hook. Note that even if you prevent the form from advancing to the next page, though, that the checkout form is a special kind of form that validates and submits each fieldset independently of the form itself.

I'm not entirely sure how the registration module you're using interacts with the checkout form. However, it's possible what you may actually want is to alter the validate callback for a particular checkout pane via hook_commerce_checkout_pane_info_alter() to supply an alternate validate handler that checks your additional registration requirements and prevents that pane from submitting (which would also prevent the form from proceeding to the next page.


Editing the view could be one solution but you can also do it via jquery i.e. capture the html inside the relevant div or span , then truncate the decimal part and then resupply the altered price value to the div or span. I think that should be very easy to do.


How to fix active-class problem in minicalendar with calendar / exposed filters

Try next, that work without using urls, using second argument:

function YOURTHEME_preprocess_calendar_datebox(&$vars) {
  $arg = arg();

  // If no second argument provided - that's mean today.
  // Please check how argument date supplied for next day: 2014-12-01 or 2014-12-1 and change date() to appropriate.
  $url_date = empty($arg[1]) ? date('Y-m-d') : $arg[1];

  if ($vars['date'] == $url_date) {
    $classes = explode(' ', $vars['class']); // Extract the current classes as a list.
    $classes[] = 'active'; // Add 'active' to the class list.
    $vars['class'] = implode(' ', $classes); // Concatenate and attach the updated class list.
  }
}


Is there a way to hook rebuild permissions?

For Drupal 7, the submit handler for admin/reports/status/rebuild is node_configure_rebuild_confirm_submit, which calls node_access_rebuild.  Just note that node_access_rebuild can take a while (and why it support batch mode).


Copy whole field from one entity to another

That issue and the following code seems to have no bearing on the opening problem. Trying to get property of non-object, it literally means that $entity_fetched is not an object. Dump it into a file to see what it is.


You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter 'A' and B in your view
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter "A" and "B" in new filter group.
Select Operator as "Or" in new filter group and save the form.


How to create a rule to notify administrators of new comments by non-administrators?

What you are trying to do is pretty straightforward. I suspect that you have a Rule that is active and has the following:

On event After publishing a comment

(no condition)

DO

Send an email to user (or whatever you want to be your notification method; it doesn't really matter)

What you need to do is add a condition by clicking on the respective option. In the "Condition to add" option, you need to select: "User has role(s)" and press Next.

In the next page, select "Published Comment Author" in the User option and select all the roles of your site except for the Admin role. Leave the rest unchanged.

Now your admins should be receiving notifications for comments from non-admins only.


The jQuery Update module updates Drupal's jQuery library from 1.4.4 to 1.5.2. If you don't want version 1.5.2 then you just need to uninstall the jQuery Update module and everything will go back to normal.

If you want to use jQuery Update just to update the jQuery UI library to v1.8.11 it looks like you'll have to patch the jquery_update.module file directly, as the version numbers for the base library are hardcoded into the jquery_update_jquery_replace() function using this code:

switch ($version) {
  case '1.5':
    $trueversion = '1.5.2';
    break;
  case '1.7':
    $trueversion = '1.7.1';
    break;
}


Adding rel=canonical meta tag in comment paginated node pages in Drupal 7

Answer to the original suggests Nodewords. And D7 replacement of Nodewords  module is Metatag module, that supports canonical links.

  Meta tags have additional uses like the Open Graph Protocol used by Facebook, specifying the canonical location of content across multiple URLs or domains.


Default value for datetime field definition in content entity?

You need to pass in a callback function that is evaluated when the entity is saved. If you evaluate the time value in YourEntity::baseFieldDefinitions, then the default value will fixed at whatever time the entity type was installed.

DrupalDateTime::createFromTimestamp can't serve as a callback because it expects you to pass a timestamp. The default value callback needs to take two arguments: the entity being saved and the field definition itself:

\Drupal\Core\Entity\FieldableEntityInterface $entity
\Drupal\Core\Field\FieldDefinitionInterface $definition

See the API docs: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldConfigInterface.php/function/FieldConfigInterface%3A%3AsetDefaultValueCallback/8.7.x

So you'll need to create a callback function, e.g.

use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;

// ...

function mymodule_get_current_datetime($entity, $definition) {
  $current_time = DrupalDateTime::createFromTimestamp(time());
  return $current_time->format(DateTimeItem::DATETIME_STORAGE_FORMAT);
}

And then pass that callback as a string.

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start date'))
  ->setDescription(t('Start date in GMT time.'))
  ->setDefaultValueCallback('mymodule_get_current_datetime')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => -3,
    'default_value' => DrupalDateTime::createFromTimestamp(time()),
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);


Documentation or Tutorial on using Batch or Queue Services API Programmatically

I have made an example module to help understanding the Queue API and the Batch API. It also shows how to use them together.

I show you here the files and its contents. I have made a lots of comment, so i think, it is easy to understand.

xml_import_example.info.yml

type: module
name: XML import example
package: Examples
description: "This module helps understanding the Batch API and Queue API with an XML import example"
core: 8.x

xml_import_example.permissions.yml

import content from xml:
  title: 'Import content from xml'
  description: 'With this permission user can import contents from a XML source'
  restrict access: TRUE

xml_import_example.routing.yml

# Get contents from the xml source
xml_import_example.get_contents_from_xml:
  path: '/get-contents-from-xml'
  defaults: { _controller: '\Drupal\xml_import_example\Controller\ImportContentFromXML::getContentsFromXMLPage' }
  requirements:
    _permission: 'import content from xml'
# Process all queue items with batch
xml_import_example.process_all_queue_items_with_batch:
  path: '/process-all-queue-items'
  defaults: { _controller: '\Drupal\xml_import_example\Controller\ImportContentFromXML::processAllQueueItemsWithBatch' }
  requirements:
    _permission: 'import content from xml'

src/Controller/ImportContentFromXML.php

<?php
/**
 * @file
 * Contains \Drupal\xml_import_example\Controller\ImportContentFromXML.
 */

namespace Drupal\xml_import_example\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Queue\QueueWorkerManager;
use Drupal\Core\Queue\QueueFactory;

/**
 * You can use this constant to set how many queued items
 * you want to be processed in one batch operation
 */
define("IMPORT_XML_BATCH_SIZE", 1);

class ImportContentFromXML extends ControllerBase {

  /**
   * We add QueueFactory and QueueWorkerManager services with the Dependency Injection solution
   */

  /**
   * @var QueueFactory
   */
  protected $queueFactory;

  /**
   * @var QueueWorkerManager
   */
  protected $queueManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(QueueFactory $queue_factory, QueueWorkerManager $queue_manager) {
    $this->queue_factory = $queue_factory;
    $this->queue_manager = $queue_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $queue_factory = $container->get('queue');
    $queue_manager = $container->get('plugin.manager.queue_worker');

    return new static($queue_factory, $queue_manager);
  }

  /**
   * Get XML from the API and convert it to
   */
  protected function getContentsFromXML() {
    // Here you should get the XML content and convert it to an array of content arrays for example
    // I use now an example array of contents:
    $contents = array();

    for ($i = 1; $i <= 20; $i++) {
      $contents[] = array(
        'title' => 'Test title ' . $i,
        'body' => 'Test body ' . $i,
      );
    }

    // Return with the contents
    return $contents;
  }

  /**
   * Page where the xml source is preprocessed
   */
  public function getContentsFromXMLPage() {
    // Get contents array
    $contents = $this->getContentsFromXML();

    foreach ($contents as $content) {
      // Get the queue implementation for import_content_from_xml queue
      $queue = $this->queue_factory->get('import_content_from_xml');

      // Create new queue item
      $item = new \stdClass();
      $item->data = $content;
      $queue->createItem($item);
    }

    return array(
      '#type' => 'markup',
      '#markup' => $this->t('@count queue items are created.', array('@count' => count($contents))),
    );
  }

  /**
   * Process all queue items with batch
   */
  public function processAllQueueItemsWithBatch() {

    // Create batch which collects all the specified queue items and process them one after another
    $batch = array(
      'title' => $this->t("Process all XML Import queues with batch"),
      'operations' => array(),
      'finished' => 'Drupal\xml_import_example\Controller\ImportContentFromXML::batchFinished',
    );

    // Get the queue implementation for import_content_from_xml queue
    $queue_factory = \Drupal::service('queue');
    $queue = $queue_factory->get('import_content_from_xml');

    // Count number of the items in this queue, and create enough batch operations
    for($i = 0; $i < ceil($queue->numberOfItems() / IMPORT_XML_BATCH_SIZE); $i++) {
      // Create batch operations
      $batch['operations'][] = array('Drupal\xml_import_example\Controller\ImportContentFromXML::batchProcess', array());
    }

    // Adds the batch sets
    batch_set($batch);
    // Process the batch and after redirect to the frontpage
    return batch_process('<front>');
  }

  /**
   * Common batch processing callback for all operations.
   */
  public static function batchProcess(&$context) {

    // We can't use here the Dependency Injection solution
    // so we load the necessary services in the other way
    $queue_factory = \Drupal::service('queue');
    $queue_manager = \Drupal::service('plugin.manager.queue_worker');

    // Get the queue implementation for import_content_from_xml queue
    $queue = $queue_factory->get('import_content_from_xml');
    // Get the queue worker
    $queue_worker = $queue_manager->createInstance('import_content_from_xml');

    // Get the number of items
    $number_of_queue = ($queue->numberOfItems() < IMPORT_XML_BATCH_SIZE) ? $queue->numberOfItems() : IMPORT_XML_BATCH_SIZE;

    // Repeat $number_of_queue times
    for ($i = 0; $i < $number_of_queue; $i++) {
      // Get a queued item
      if ($item = $queue->claimItem()) {
        try {
          // Process it
          $queue_worker->processItem($item->data);
          // If everything was correct, delete the processed item from the queue
          $queue->deleteItem($item);
        }
        catch (SuspendQueueException $e) {
          // If there was an Exception trown because of an error
          // Releases the item that the worker could not process.
          // Another worker can come and process it
          $queue->releaseItem($item);
          break;
        }
      }
    }
  }

  /**
   * Batch finished callback.
   */
  public static function batchFinished($success, $results, $operations) {
    if ($success) {
     drupal_set_message(t("The contents are successfully imported from the XML source."));
    }
    else {
      $error_operation = reset($operations);
      drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
    }
  }
}

src/Plugin/QueueWorker/ImportContentFromXMLQueueBase.php

<?php

/**
 * @file
 * Contains Drupal\xml_import_example\Plugin\QueueWorker\ImportContentFromXMLQueueBase
 */

namespace Drupal\xml_import_example\Plugin\QueueWorker;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\Queue\SuspendQueueException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\Entity\Node;

/**
 * Provides base functionality for the Import Content From XML Queue Workers.
 */
abstract class ImportContentFromXMLQueueBase extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  // Here we don't use the Dependency Injection,
  // but the create method and __construct method are necessary to implement

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static();
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($item) {
    // Get the content array
    $content = $item->data;
    // Create node from the array
    $this->createContent($content);
  }

  /**
   * Create content
   *
   * @return int
   */
  protected function createContent($content) {
    // Create node object from the $content array
    $node = Node::create(array(
      'type'  => 'page',
      'title' => $content['title'],
      'body'  => array(
        'value'  => $content['body'],
        'format' => 'basic_html',
      ),
    ));
    $node->save();
  }
}

src/Plugin/QueueWorker/ImportContentFromXMLQueue.php

<?php

namespace Drupal\xml_import_example\Plugin\QueueWorker;

/**
 * Create node object from the imported XML content
 *
 * @QueueWorker(
 *   id = "import_content_from_xml",
 *   title = @Translation("Import Content From XML"),
 *   cron = {"time" = 60}
 * )
 */
class ImportContentFromXMLQueue extends ImportContentFromXMLQueueBase {}

So this is the working module, you can test it in you site.

If you visit the /get-contents-from-xml URL 20 queue items are made from a contents array.

The src/Plugin/QueueWorker/ImportContentFromXMLQueue.php contains this annotation:
cron = {"time" = 60}

So if you run cron, the queue items are processed for maximum 60 seconds.
You can increase or decrease this time, with that annotation.

If you remove the cron = {"time" = 60} line, cron do nothing with your queue items.

If you would like to process all the queue items in you browser, you have to visit the following url:
/process-all-queue-items

It will collect all of your queue items, creates batch operations from them, and after that it process one after another.

I hope you and others with the same question understand the usage of the Queue API and Batch API with the help of this module.

Have a nice day!


You may need to implement hook_file_download().


Wordpress Migrate Inline Images looking in wrong folder

Turns out the styles folder inside /sites/default/files was the only folder in there that was not writable by the server so it put the images elsewhere. I rolled back the wordpress import, fixed the permissions, and ran the import again. Everything seems to be good now.


Your module name should not be camel case, but should instead be mymodule (not MenuRender). Your namespace needs to reflect that, too. It should likely live under a folder in src called TwigExtension, and your module name in the namespace should match the directory (i.e. Drupal\mymodule, not Drupal\MyModule).

Here is a module that uses TwigExtension for comparison.

What's likely happening is the application is unable to locate certain things due to the file naming and namespacing.


How do I prevent a product from being added to the cart?

While you probably ought to actually disable the Add to Cart button, you'd actually put logic for determining whether or not a product should be added to the cart in a validate handler.

The first step us to add a form_alter hook that adds a validation handler to the add to cart forms.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Add a validate hook so that the order can be checked to ensure that the
  // our constraints are met.
  array_unshift($form['#validate'], 'MYMODULE_validate_some_stuff');
}

Note: this works because of commerce_cart_forms() which adds the generic form callback instead of requiring us to look for the string in the $form_id.

Now, you just need to implement your logic:

/*
 * Check the product/order against my constraints.
 */
function MYMODULE_validate_some_stuff(&$form, &$form_state) {
  $order = commerce_cart_order_load($form_state['values']['uid']);
  $line_item = $form_state['line_item'];

  if (/* your logic here */) {
    form_set_error('product_id', t('Sorry, you can\'t do that!'));
  }
}

You'll notice that the commerce_order is loaded by the user's UID and you've got access to the commerce_line_item that you can then use to grab the product (use $line_item->commerce_product). Also, there is no need to return TRUE or FALSE. Just set an error.


Drupal 8 Webform - Pass submitted value from one webforms to another

Ok I figured it out - for anyone else who comes across this question.

In the first Webform, I set the Confirmation URL to:

/form/my-form2?value=[webform_submission:values:element_key]

I've bolded the elements in the URL that you will need to adjust for your webforms.

This will result in redirecting the user from my first Webform to the second Webform (which is at the URL www.mydomain.com/form/my-form2) when they click the submit button. It will append ?value=[the value from the webform field] to the end of the URL.

Then in the second form in the field where I want this value to go, I have set the Default value for this field as

[current-page:query:value]

The word 'value' in the above can be anything, but it must match the id used in the URL from the first form.

And hey presto - it works!

F


No need to use field_visibility

try this if using Views 3

Click on the "advanced" tab.
Click on add under "contextual filters".
Choose Content:nid.
Under "when the filter variable is not available, choose "provide default value".
From the drop down menu select "content id from url".
Scroll all the way down to the bottom of the window and click on the "More" link.
Click "Exclude"


This is more a PHP question than a Drupal one...

Global constants cannot be re-declared within the same request (well, short of using an extension: https://stackoverflow.com/questions/8465155/redefine-constants-in-php).

Since everything in Drupal 7 and below is in the global scope, you can't redeclare those variables within the same request.

If it's hard-coded and causing you a problem, a patch to the module in question to allow contextually different API credentials would be the best thing to do IMO.


In drupal 6, the standard way of doing this is by using the following function:

node_load($nid = NULL, $vid = NULL, $reset = FALSE)

However if you want to implement it in Drupal 7, it becomes a lot easier using the Views and the References module. All you need to do is :

Create two different content types say a and b and add fields to them. You MUST add a node reference field(say to b)
A pop up would ask you to choose which node you would like to reference(choose a here)
After that if you wish to look for some advanced settings, you can add Relationships depending on your requirement.


How do I customize the date-submit part in comment section?

You can use format_interval() to do this.

function MYTHEME_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $variables['created'] = t('@created ago', array(
    '@created' => format_interval(REQUEST_TIME - $comment->created),
  ));
}

If you look at the source for template_preprocess_comment(), you are essentially just using format_interval() instead of format_date() to create the timestamps.  In the above, we run everything through t() so that the string "ago" gets translated properly.


How to use same view.tpl for some taxonomy terms

After some try and error and for the hint  Jack-PL tell me i figure this out.

I make a new view with taxonomy terms. I set the Field (taxonomy name and taxonomy id) .Contexual filters i set the Taxonomy term: Parent term >Provide default value>Taxonomy term id from url.

So know i only have to use Displays >Add>Page>And that did the trick!

Now i can theme with one tpl all the taxonomy pages!


Filter View by Entity Reference Value From Current Node

I got this working with this set up:

Contextual Filter: field_venue
-> Provide default value
 ->PHP Code
  -> PHP contextual filter code

  $node=menu_get_object();
  return $node->field_venue_for_catering['und'][0]['target_id'];

"field_venue" is the venue field from "Food"
"field_venue_for_catering" is the venue field from "Package".


Is it possible to get relation in Views to Commerce products?

Make the relationship with commerce product then you will see the related fields in fields list.


Considering how many criteria might have to be considered to determine if a view can be hidden, I decided to make this a configuration option instead.

I see two ways to do this:

The component where the view is embedded can have a configuration option "Hide view if no results". This is what I went with.
One could make a symbolic views plugin for "no results behavior", named "Hide view if no results". Then one could implement e.g. hook_preprocess_views_view(), or possibly another hook, to hide the view if the new no results behavior is present.

I could write a lot more details, but for now I want to share the ideas behind these options, maybe this already helps.

I am marking this as the accepted answer. But if someone can come up with something more convincing, I will change it.


how to fetch result into array or how to fetch 'nid' out of result?

The simplest way would be:

$result = $query->execute();

if (!empty($results['node'])) {
  $nids = array_keys($results['node']);
}

There are a few different ways to get the first nid out of the array if that's what you need; personally I prefer reset() as it's non-destructive to the original array (unlike array_shift() for example).

$first_nid = reset($nids);

If you then need the node objects you can pass that array straight to node_load_multiple():

$nodes = node_load_multiple($nids);


I think the thing to keep in mind here is how the site is going to be used.  If users are not going to log into it, it almost doesn't matter in terms of performance because you use Boost.

http://drupal.org/project/boost

You can also use caching features in panels.  I've never really noted a large hit for using panels on a website, as long as the layout is reasonable and the site does not have an excessive amount of modules on it.  Panels exposes a lot of functionality, and you can pry it out of my cold dead hands.

If you've not used Boost before, do yourself a favor and commit to doing so!

NOTE: In your other question you referenced D7.  Boost may not be ready for D7 just yet but you should keep it in mind.


List nodes of children using taxonomy_select_nodes

I would say these are your problems:

taxonomy_get_children() returns term objects, not term IDs, so that is going to break that query. This I would say is your main issue. Instead you could do this:

  $taxonomies = array();
  $taxonomies = taxonomy_get_children($tid);
  // Get the child term tids.
  $taxonomies = array_keys($taxonomies);
  // Add the parent tid.
  $taxonomies[] = $tid;
  $query->condition('t.tid', $taxonomies,'IN');

Your IN statement with the children won't work currently because earlier in the function is this line:

$query->condition('tid', $tid);

So that will only ever return values for $tid, never for the children unless you remove that line also.

Also I would recommend giving the new $promote parameter a default value, like this:

function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'), $promote = 0) {


Why is my Drupal ajax form not populating the radio buttons

I think you need to reorganize your code.
First you need two ['Private_list'] at the same function Form and at this same function form you need to declare the array variables for each private list.

$list1_options = array(......);
$list2_options = array(.......);

['Private_list1´]: these are the first choice the user need to do: here you use the ajax call back.

['Private list2']: these one have the choices the user need to pick according to the first selection on ['Private_list1´]: at this 'Private_list2' you use the wrapper prefix and suffix.

the ajax call back function should only look something like this most of the times:

function example_change_callback($form, &$form_state) {
  return $form['private_list2'];
}

Your basicly using the call back to identify wich form you need to update on event change.

I recommend you study this drupal dependent ajax example, dispate the example is using dropdown list, you should be able to aply it to radio buttons, just follow the same structure.

I hope i was hepfull, tell us later how it went...
Have a good coding!


How do I get the result from a database and show it?

//here $id value is hard-coded to 1, you can use your own logic to get the value.
$id = 1;
$result = db_query("select name, company_name, geo_location from {data_set} where id=:id", array(':id' => $id));

//To iterate over each row of the resultset use foreach
foreach($result as $ind_data) {
  echo "name is " . $ind_data->name . "
";
  echo "company name is " . $ind_data->company_name . "
";
  echo "geolocation is " . $ind_data->geo_location . "
";
}


How can i set this redirect only for anonymous users?

You can load a user and check for authentication

$currentUser = \Drupal::currentUser();

// Do nothing if the user is authenticated.
if ($currentUser->isAuthenticated()) {
  return;
}


Add the additional form elements in the build function. The build function is rerun on every ajax request. If you don't have other things to do as modifying the form structure, then the ajax callback can be empty and you only need to return the new ajax container.

So you need to change this:

Put the new form elements inside the ajax container (in the first function):

$form['options']['a-add'][...]

And then return the whole container in the ajax callback (second function):

return $form['options'];

You always have to return the outside ajax div, otherwise the ajax callback will not work a second time.


Clean URLS work with http, but not with https

You can try below with changing in .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}


How do I get a nodes authors email address within views?

Create the view of content type or use existing view
Go to admin/structure/views and edit your view
Under advanced section tab add relationship Content: Author
Add the relationship.
Add the email field User: E-mail (E-mail) under field section.
Save the view


Set Image Custom Field as Open Graph Image in Metatags

I used drupal_add_html_head in my case. In my theme template.php.

$og_image = image_style_url('200x200', $node->field_gallery_preview_image[LANGUAGE_NONE][0]['uri']);
// OG image meta property.
drupal_add_html_head(array(
  '#tag' => 'meta',
  '#attributes' => array(
    'property' => 'og:image',
    'content' => $og_image,
  ),
), 'node_' . $node->nid . '_og_image');


In your page.tpl.php there's nothing regarding regions ? You're certainly missing some code like:

<?php if ($page['sidebar_first']): ?>
  <div id="sidebar-first" class="sidebar">
    <?php print render($page['sidebar_first']); ?>
  </div>
<?php endif; ?>

See page.tpl.php documentation.


There are two modules I know of specifically for allowing menu items that are not 'proper' links. There's Special menu items (which doesn't have a D7 release, but there's a patch) and Menu Firstchild (they're not identical in features, but both do what you want I believe).

You might also be interested in DHTML Menu which has a beta1 release for D7.


What's the difference between $user login and access?

The access field is updated in Drupal's session write handler _drupal_session_write. This means it is potentially updated at every page request. If you look at the source code, you'll see that the access field is, by default, only updated every 180 seconds. This interval can be changed by setting the session_write_interval Drupal variable.

// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}


Add a js file and be sure it is executed as last js file?

Using drupal_add_js you can control the order of your JS files by assigning weight through $options array.

  weight: A number defining the order in which the JavaScript is added
  to the page relative to other JavaScript with the same 'scope',
  'group', and 'every_page' value.

  The exact ordering of JavaScript is
  as follows:

  First by scope, with 'header' first, 'footer' last, and
  any other scopes provided by a custom theme coming in between, as
  determined by the theme.
  Then by group.
  Then by the 'every_page' flag,
  with TRUE coming before FALSE.
  Then by weight.
  Then by the order in
  which the JavaScript was added. For example, all else being the same,
  JavaScript added by a call to drupal_add_js() that happened later in
  the page request gets added to the page after one for which
  drupal_add_js() happened earlier in the page request.

Code example:

drupal_add_js($file_path, array(
  'weight' => 10000, // Something higher than the weight of existing items
  'scope' => 'footer', // Make sure the script tag is rendered in the footer of the page, not the header
  'group' => JS_THEME, // JS_THEME has the highest group weight and will be rendered last
));


Why does my site whitescreen with content?

Drupal 8 is still in beta so things are still going to be rough there.

WSOD's are usually a symptom of some PHP error being hidden by the web server (many default PHP setups don't advertise errors). The d.o. page on WSODs gives good advice on how revealing these errors and diagnosing the problem.


How to create a drush command without drupal?

1) Drush only searches certain folders for Drush commandfiles.  Run with --include=/path/to/your/drushcommands, or set $options['include'][] = '/path/to/your/drushcommands'; in your drushrc.php if you'd like to use a directory other than $HOME/.drush.

2) If you have in fact set your bootstrap to DRUSH_BOOTSTRAP_DRUSH, then you should not be getting that message.  Maybe there is something wrong with your commandfile definition; can't guess what it might be from the information provided, though.

For a quick start on writing a new Drush command, see the drushify project.  It will create a template for you very quickly.  Perhaps you could compare the template drushify creates with the commandfile you put together.


How to show descriptions when a user hovers over a form element

The entire tooltip code is found within the Rubik theme in the files core.css and core-rtl.css.  The majority is within core.css.  The specific piece that shows the tooltip is:

.page-content .form-item:hover > .description { display:block; }

But each tooltip has text contained in

, so you can search through core.css/core-rtl.css and find statements regarding .description


Are there any alternate module for qq_import module (Quiz Questions Import Module)?

It turns our that there are some similar existing modules on D7 but not as close as qq_import module. Instead, I just created my own custom D7 quiz question importer. It only imports multiple choice type of questions though


Advanced forum: How to modify template of forum list page?

When I had to do this I found there are lots of template files and it's not obvious what controls what. I ended up putting die() in each one to find out which template file was used for each view, and then a case of trial and error to make the changes I wanted.

When you have worked out which files need editing then you should copy them from:

/sites/all/modules/advanced_forum/styles/naked/advanced-forum.naked.TEMPLATE_NAME.tpl.php

to your theme at:

/sites/all/themes/YOUR_THEME/templates/advanced-forum.naked.TEMPLATE_NAME.tpl.php

Any files here will override the ones in the advanced forum themes folder.


how to let a form field be hidden and at the same time the value be able to acces the id using javascript?

Try this:

$form['hidden'] = array(
 '#type' => 'hidden',
 '#value' => 'Your_value',
 '#attributes' => array('id' => array('your_id')),
);

Now using javascript or jquery you get the value of the hidden field.

In jquery:  jQuery("#your_id").val();


drupal 7: my hook module make my site slow?

I see two possible reasons:

You pass form state by value. It should be passed by reference. It is a really, really big array, so copying it when there is no need to may eat up quite a lot of memory, slowing down everything.
You alter $form['name_list']['#options'] in all views exposed forms. But probably most of these forms does not have name_list element at all. So what you do can generate array items that are bad from form api point of view, slowing down form processing, and generate warnings. Server will not show you warnings, but it will save them to error logs, and writing to disk is slow.


Best way to log clicks on a link of a custom content type

A possible alternative to "record the clicking of such link" is to use the Message module to create a message like so:

Date = date the link was clicked.
User target = the user who clicked the link.
Message type = something like "Link of custom content type clicked".
Message text = whatever you want and possibly using "Replacement tokens" to have any of the tokens that you have available in your rule also included in your message text (should you have any such need).

Since messages are entities, you could add any additional fields you may need to complete such custom logging.

With this approach, you've reduced your question to (eg) creating an appropriate view (and/or chart?) of all such messages that got created.


Slideshow background images in Background

There are few jquery library which are not using images directly. They are using images as css background.

I found one link for you - http://demo.marcofolio.net/bgimg_slideshow/

The following tutorial might be useful for you-
http://www.techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/

This tutorial explains how to use css background images for slideshow.


How do I use the computed twig element to get the value from a custom composite element?

I suppose I can answer my own question.
It didn't work because I didn't use the delta. For this to work, I need to do this instead
{% for data.products as p %}
{{ p.product }}
{% endfor %}

This is because we are using a custom composite element where the products are stored like
$products[0]['product']
$products[1][product']
...

I missed the array key and hence didn't get any value to the element in the custom composite.
FYI: The answer was in the 'Help' section of the module already, but couldn't really understand it well at the time.