How to programmatically set permissions for a custom content type created in a module?

The problem is that the user_permission_get_modules function fails to get the permissions at the point of install (too early in the process, not all the caches have been reset). So you would have to copy the user_role_grant_permissions function to your new module, it should look something like this:

/**
 * Custom user_role_grant_permissions function
 * does the same thing as user_role_grant_permissions
 * but it can run at install time
 * @see user_role_grant_permissions
 * @param int $rid
 * @param array $permissions
 */
function _my_module_grant_permissions($rid, array $permissions = array()) {
    // this line doesn't work on install / enable hooks
    // $modules = user_permission_get_modules();
    // Grant new permissions for the role.
    foreach ($permissions as $module => $permission_list) {
    foreach ($permission_list as $name) {
        db_merge('role_permission')
        ->key(array(
            'rid' => $rid,
            'permission' => $name,
        ))
        ->fields(array(
            'module' => $module,
        ))
        ->execute();
    }
    }

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
}

This is slightly different than the user_role_grant_permissions module in that the permissions are keyed to the module, so you call it like this:

function my_module_enable(){
    $permissions = array(
        // module key
        'my_module' => array(
           // permissions in the module
           'do module things',
           'modify module things',
        ),
    );
    _my_module_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}


Drupal SEO module - Error on the setup wizrad and on dblog

Hopefully this helps the next user.

I was having this issue and stepping through your code I noticed it sends a time stamp. Our server time was off by 12 minutes. Once I corrected it everything worked.


Adding ASCII characters to HTML links in Drupal

You can use the Menu HTML module for that.

It uses a bunch of alter hooks, which means you could theoretically reproduce the same functionality in a theme if you really want to. So yes, it's possible to solve without using a module per se.

Modules are the proper way to add such functionality, though, hacking this into a theme is bad application design in my opinion. Drupal is, intentionally, a modular system; don't be scared of installing modules to add functionality, that's what you're supposed to do :)


Hide menu backend side for different roles/users

You can use Menu item visibility module to hide the item for specific user role.

  This module exposes configurable and extendable visibility settings
  for menu links. For example, if you want to create a 'My account' link
  that points to /user, both anonymous and registered users have access
  to the /user path, so both will see the link, even if anonymous users
  do not technically have an account. Using this module will allow you
  to only have your 'My account' link visible to registered users, and
  hide it from anonymous users.


What can break quickedit, and how do I fix it?

If there is not an obvious error in php or javascript, see the comment from @mradcliffe, then there are probably some attributes missing, because they were removed in twig templates.

The quickedit links are not delivered in html, they are build in javascript. For this the attributes to identify the involved entities and fields need to be present.

Look especially for the attributes data-quickedit-entity-id in node templates and data-quickedit-field-id in field templates.

This is the correct way to add attributes in twig:

{%
  set classes = [
    'red',
    'green',
  ]
%}
<div{{ attributes.addClass(classes) }}></div>

Source: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates


How to make a direct admin-visible URL to a private file in: sites/default/private/

Use file_entity_download_uri() in view php field

function file_entity_download_uri($file) {
  $uri = array(
    'path' => "file/{$file->fid}/download",
    'options' => array(),
  );
  if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
    $uri['options']['query']['token'] = file_entity_get_download_token($file);
  }
  return $uri;
}


How can I tell drush to use another php.ini file?

I copied my php.ini file to my home directory, and then ran:

$ PHP_INI=~/php.ini drush status

The "PHP configuration" line accurately reflected the new location of my php.ini file, so I believe this is still working on Drush 6.x and master.


Use a 3rd part library when uninstalling a module

Not knowing what "operations" you are performing with this composer lib, I suggest you might want to just think of when you actually want to perform these operations. Doing it on Uninstall seems like a bad idea. Why not utilize hook_disable, instead of hook_uninstall, which should allow you to do things just before the module gets disabled.

If you really want to do it in a hook_uninstall, then you can load your .module file using drupal_load() and call the functions in your .module file from hook_uninstall.


drupal_add_css does now work when in cache mode

While you are using the version 7 drupal_add_js, the snippet you posted appears to be using the Drupal 6 arguments for drupal_add_css. You might also need to set the every_page option to true so that it is aggregated. Maybe try:

drupal_add_css('sites/all/libraries/gips/css/gips.css', array('type' => 'file', 'media' => 'all', 'preprocess' => true, 'every_page' => true));

You could also have a look at the group and weight settings on the api page linked above to see if they will help.


Username display overidden by customer profile name

Found it!

commerce_kickstart_user_username_alter() is overwriting usernames with the name provided in their addressbook.

I implemented my own hook_username_alter() to simply return $account->name.


Adding a drop down field to user registration

It sounds like you've found where you can add user fields (under Administration >> Configuration >> People >> Account settings). Once you've clicked the + Add Field button, you can select List (text), add your Label, and click the Save and Continue button to configure the options you can add to your country select list.

Here is where you add your list of items. The Allowed values list text field is where you can add your selectable items. You can add each country you want, once per line. Once finished, you can click the Save field settings to continue to the final configuration page.

Customize the remaining settings and click the Save setting button to finish adding the country select box for your user account.


If I using Ubercart and "PayPal Website Payments Pro", Can customer pay with credit card directly?

yes. With Paypal Pro, users remain on your site and the transaction is completed underneath by Paypal. There is no visible relationship between the two for the end user.


Is there a way to add profile2 forms in multistep registration

yes definately we can create profile2 field as a multistep form for this we can use Field Group
By field group module you can include all fields in multipage group and after that create multipage group as per you need and include relevant fields in each break.


Drupal 7 Views, paths, node associations via taxonomy

Sorry for a general answer, but it may get you in the right direction anyway.

What you seem to need is to establish relationships in views. By adding a relationship, you just add an object you would like to refer to. Once you add a relationship (on the right hand side, in Advanced panel), additional fields appear in the Add Field and Filter dialogs. Note the dropdown list that appears in field-related dialogs that contains relevant relationships that you have defined. You may also have a cascaded relationship (a relationship that uses another relationship).

All that translates later into the WHERE clause of the final query which filters what you want to show/hide.

To use the elements of the path, you want to use Contextual filter where you specify which part of the URL means what.

One thing to remember is that, even though you have clean URLs turned on, there is an "unclean" URL query behind the scenes which contains stuff like term IDs or node IDs. Perhaps it'd be useful for you to turn the clean URLs off for a moment, and play for a while just to see what kind of URLs will be used by views contextual filter. Or put <?php print $_GET['q'] ?> somewhere in the page.tpl.php for testing convenience.


adding adwords tracking to a Click instead of a page load using goog_report_conversion

General advice: don't use "simple" modules for non-simple tasks.

No easy way here, you need to inject your JavaScript code, and attach additional behavior to that button. Worse, you would need to make sure there is enough time for function to process. My colleagues use thank you page if feasible for that very reason - browser will do it's best to minimize time between button click and page load. On thank you page that is not an issue.


Drush on windows - Command pm-enable needs a higher bootstrap level to run

This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.

Looks like your pwd (present working directory) is on your desktop. Which i'm going to make a quick assumption that that directory isn't where your drupal install is located at.

  As a side note, whats the easiest way to get drush with the bash
  working on windows? Any good tuts?

I highly recommend looking into installing/using Cygwin on windows; as it's a slight improvement.

From there you'll be able to do more things with Drush. The sql-sync and several other functions i hear don't totally work reliably. For even more bonus points you may want to move to a linux or mac environment (something that has a terminal built in).

If you must stay with windows, please consider a drupal project called, quickstart, that creates a virtual machine that allows you to run ubuntu through a remote desktop terminal.


Media library widget: Table instead of grid?

In response to your second question, there is a core issue open regarding editing media items within the field widget:  https://www.drupal.org/project/drupal/issues/2985168
There is also a contrib module Media Library Edit.
One problem is that you will edit the media entity itself, affecting all usages of the media item.


Ubercart 2.x: Given a product nid, retrieve its manufacturer

In Drupal 6 taxonomy terms are linked to the node object, Ubercart just piggy-backs off the way Drupal core handles this.

You can use the very handy taxonomy_node_get_terms_by_vocabulary() function to grab all of the terms associated with a node in a certain vocabulary. You would use it like so:

$vid = 1; // Vocabulary ID
$nid = 1; // Node ID

$node = node_load($nid);
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);


Replace tables with divs in pages generated by views

The short answer is to edit the View and change the Style Settings from table to unformatted.


Having different theme elements for different pages

Check out Context module - it will allow you to structure the website based on the node type, URL or other parameters. Depending on this, you can have different blocks displayed, or use different layouts.

See also Display Suite and Panels modules for even more possibilities.

If you want to avoid using additional modules, you can achieve similar functionality through code and preprocess_html or preprocess_page implementations. You can specify special templates that will be selected dynamically, e.g.:

function MYTHEME_preprocess_page(&$variables) {
  // Make sure we are on the single node page.
  if (arg(0) == 'node' && arg(1) && !arg(2)) {
    // This will allow you to have separate page.tpl.php template used only
    // for single nodes. You should have page--single-node.tpl.php file in
    // your theme to see this in action. You can combine this with any
    // additional number of conditions, e.g. node type, user role etc.
    $variables['theme_hook_suggestions'][] = 'page__single_node';
  }
}


I guess the slash is not in the end. It is the way you styled your breadcrumb thats why you are seeing it in the end. You can aid it using CSS, just tweak it a bit so you can hide it.


Only show first entity reference in views

This is how i did it :

In Views, under Advanced, add Entity Reference:Referencing entity relationship via your reference field id.
In Views, under fields add the field(in this case - Body) and add the above relationship .

Note: If there are nodes of content type B that reference same nodes of content type A, those same nodes of content type A will be duplicated in the views with different values of the fields of content type B that is referencing them.

Update: To remove such duplicates, you can use Views Distinct module and then in Views under fields, select Title field(Content Type A) and under Views Distinct Settings, change to 'Filter Repeats' for Filter/Aggregate this field and save.


How can we autocreate an organic group during registration

Creating a group is really just creating a node.

Create a rule that reacts on "After saving a new user account".
Add Action: Create a new entity.

Set content type to: Group.

You can set the title of the node (the name of the group) to the new user's name or any value you want using available tokens.

Set the author of the node to the new user (it's usually called "account" in rules) and the new user will be the owner/manager of the group.


How can I assign pages to templates like in WordPress?

What I would do, is to create a Vocabulary called "template" (using the Taxonomy module in Drupal core) and add some template names to it as taxonomy terms. This will allow you to 'tag' your nodes with the template name for that node.

Next, I would create a preprocess function for the node template in my theme's template.php file and add template suggestions based on the taxonomy term. Roughly the preprocess function would look like this (not working code, just an outline):

function MYTHEME_preprocess_node(&$variables) {
  // Get the Term ID from the "template" vocab for the current node.
  $template_tid = ... // (figure out where that data is in the $variables)
  if (!empty($template_tid)) {
    // Tell Drupal to use the node--[template_tid].tpl.php template if it exists.
    $variables['theme_hook_suggestion'] = 'node__' . $template_tid;
  }
}

Note that I'm suggesting to add template suggestions based on term ID, not term name. If you build it like this, you can always change the term names without breaking your template files.

For more information about template suggestions, see Working with template suggestions.


How to update table taxonomy_index when adding a node referencing a term?

I ended up figuring this out. here is what I did:

$result=db_query("SELECT nid FROM node WHERE type = 'lesson'");
foreach($result as $row){
    $node=entity_load('node', $row->nid);
    $result =  taxonomy_build_node_index($node);
}

This ensures that my lesson node is tracked in the taxonomy_index table. I should probably start learning the class-based approach, but for now this works.


There's a module called Views Bulk Operations.

This will update more than thousand node at a time without memory limit exception.


How to embed a node's NID in the title of a node?

You need to do two step:

Step one: auto generate the title and hidden form. use hook_field_widget_form_alter() with code

function MY_MODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $bundle = $form_state->getFormObject()->getEntity()->bundle();
  // You can check with other bundle
  if ($field_definition->getName() == 'title' && $bundle == 'page' && $element['value']['#default_value'] == '') {
    $element['#required'] = FALSE;
    //hidden title
    $element['#type'] = 'hidden';
    $element['value']['#required'] = FALSE;
    // Set default value
    $element['value']['#default_value'] = 'Default Title';
  }
}

with step one you can cross submit form.

Step two: Override new title with default value. Use hook_node_insert()

function MY_MODULE_node_insert(Drupal\node\NodeInterface $node) {
  if ($node->bundle() == 'page') {
    $new_title = 'New title ' . $node->id();
    $node->setTitle($new_title);
    $node->setNewRevision(FALSE);
    $node->save();
  }
}


You should be able to use 'in' operator to get around this issue. Try something like:

{% if 'mysite/news' in url %}

some text

{% endif %}


Redirecting Pages from Standard Node page to views page

Chaos tool suite (ctools) has a sub-module called Page Manager.

  Page manager is a critical tool for Drupal development. It's a
  sub-module of Chaos Tools that enables you to change the paths of
  pages, even some of those defined by Drupal core. While it won't
  change the appearance of a node, it can change the context of it. With
  Page Manager you can control who has access to pages, and how they get
  to the pages, including nodes that are part of other pages. Working
  hand-in-hand with other modules like Panels, Page Manager can help
  give you great control over the user experience.

Using it you can do redirects on a specific content type to your view and pass along the context such as the nid. No need to worry about aliases.

You do it as follows:

Activate Page Manager
Go to admin/structure/pages
Enable /node/%node to override it.
Create a variant with a 301 redirect
Create a selection rule on Node Type = Your node type
Set the redirect destination to your-view-path/%node:nid


Go to /admin/people/permissions and check assign the appropriate permission("Administer comments and comment settings") you'd like to the that role.
Check https://www.drupal.org/node/777696


How do I include a JavaScript library without using a module?

It doesn't sound like you need to hook the theme system or deploy a module, why not try including the paths to Light Box's dependencies in one or more of your template files?

Better yet add the CSS and JS file paths (relative to the theme folder) to your theme's info file.

Stylesheets

Scripts


Determining the $POST variables of a submitted form

The submitted values are available in your custom validate/submit handler in the $form_state['values'] or $form_state['input'] (with the later one storing raw and unvalidated user input). I think this is considered better practice than accessing the values through the $POST variable.


How to get url path info into a form variable

How to store the data depends on what you want to achieve with that data or how you want to process it afterwards. The easiest solution for that is probably using watchdog() after form submission:

watchdog('myblock', $url);

To get the current path there is current_path():

$url=current_path();

Please beware that you must disable caching for that block to have the code in your block processed all the time. Here is an answer on how to create a block programmatically in Drupal.


custom generate pdf with the header displaying only in the first page

This might only be possible if you are printing multiple individual nodes to one PDF by overriding the provided print themes.

A solution that will work no matter what is to add your own class that extends the PrintTCPDF class. You should ideally do this in your own module, but I will show you here how to hack the print_pdf_tcpdf module.

Add a new file to the folder print_pdf->lib_handlers->print_pdf_tcpdf and name it

print_pdf_tcpdf_no_headers.class.inc

Add the following contents to that file:

<?php

class PrintTCPDF_No_Headers extends PrintTCPDF {
  public function Header() {
    if ($this->page > 1){
      return;
    }
    parent::Header();
  }
}

Open the print_pdf_tcpdf.pages.inc file and change line 65 - 66 from this:

// create new PDF document
  $pdf = new PrintTCPDF($orientation , 'mm', $paper_size, TRUE);

to this:

// create new PDF document
  $pdf = new PrintTCPDF_No_Headers($orientation , 'mm', $paper_size, TRUE);

Open file print_pdf_tcpdf.info and add the following:

files[] = print_pdf_tcpdf_no_headers.class.inc

Clear your cache and your pdf's will print with a header on page 1 only.

If you want to also print other nodes with headers on all pages you will have to implement some conditional logic in print_pdf_tcpdf.pages.inc file which creates the class needed ( PrintTCPDF or PrintTCPDF_No_Headers)


Retrieve File Url from Upload Form When Form is submitted

found the solution here.I am not sure what is the core issue but below is the solution

This was the comment in the above link where I found solution.

  More than likely eveyone who is having a problem here has been
  developing on their local computer, then are tryng to migrate their
  system to a remote server. When you do this, you are probably moving
  your setting for directory paths along as well.

  For example the temp path for your images is probably different than
  the image temp path on your host system.

  I recommend this test in Drupal 6.14. goto /admin/settings/file-system

  and look at your temporary directory... if its glaring red, then try
  renaming it to something like: /tmp. if that does not work, try
  renaming to just tmp ( no forward slash)

  Next step to test this will be to upload an image or file. I tested it
  by uploading a new logo. But remember, that if you do a FULL DB dump
  from phpmyadmin from your local computer to the new host, you will
  probably see this problem again.

For Drupal 7 guys I just went to admin/config/media/file-system , so basically find out where the file system is in your config area and I change the '/tmp' to 'tmp'.

After changing it was able to print the file object :)

stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image [field_replacement] => stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image ) [fid] => 3102 )

Hope it help someone.


How do I place super-fish or nice menus in Zen theme main menu?

Once you have installed Superfish, you must define a number of superfish blocks to be available at /admin/config/user-interface/superfish
Then go to the block admin screen and select one of the superfish blocks /admin/structure/block/manage/superfish/1/configure
Define the "Menu Parent" under superfish settings to "Main Menu"
Define the region you wish to have the menu placed in "Region settings"


Facebook "like" button fetch wrong data on views

Read about og (open-graph) meta tags.
As I know, metatag module supports this kind of meta-tags.


D7: Change Drupal "Link" field to store node url instead of alias for internal links

I use pathauto. it should automatically keep up with your node name changes and point to the right internal ref, right?

Then there's Node redirect?

Extended path alias might be promising, too. Extended path aliases


Alter field content inside modules hook_node_view

In HOOK_node_view() you can alter your fields like this:

function MODULE_node_view($node, $view_mode, $langcode) {
  //be sure to be in full page mode, but you can also user 'teaser'
  if ($view_mode == 'full' && node_is_page($node)) {
    //kpr($node); => use devel module and kpr() to inspect your node.
    //Change the title of the node
    $node->title = 'New title';

    //Change the "text" field
    $lang = field_language('node', $node, 'field_text');
    $node->field_text[$lang][0]['value'] = 'New field text value';

    //Change the "body" field which has a slightly different syntax
    $lang = field_language('node', $node, 'body');
    $node->body[$lang][0]['value'] = 'New body value';
  }
}

Note the usage of field_language() to retrieve the correct value for each field.


You can look up the structure of the view result in your question Get result view with formatter programmattically. (there was no feedback, did it work?)

If you want to use this in twig, it would look like this:

{{ view.field.field_name.value(view.result[0]) }}


how to customize my views-view-table.tpl.php?

The best way is to use field_info_instance($entity_type, $field_name, $bundle_name)to get information about specific instance of a field. The label of the field is contained in the array returned from that function.

The general code :

<?php
 $info = field_info_instance($entity_type, $field_name, $bundle_name);
 print $info['label'];
    ?> :

in my situation :

<?php
 $info = field_info_instance('node','property_photo','property');
 print $info['label'];
    ?> :

OR

by Using this Code :

<?php print $header['$field_name']; ?> :

in my situation :

    <?php print $header['property_photo']; ?> :

that's it .


How to add a CSS class to some certain pages depending on the path alias?

You should be using Drupal's arg function:
https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7

Something like this should work:

function mytheme_preprocess_html(&$vars) {

    if (arg(2, drupal_get_path_alias()) == 'foo') {
        $vars['classes_array'][] = drupal_clean_css_identifier(arg(2, drupal_get_path_alias()));
    }
}

Added drupal_get_path_alias() as an arguement of arg() as suggested by @koivo


Drupal 7: Webform: Send Email Custom PHP on Webform submit

It's possible that you could use either hook_webform_submission_presave or hook_webform_submission_insert in a custom module, check for the your webform component value (i'd assume it's in $submission) and then fire your email.

In a custom module, add your hook like so.

function mymodule_webform_submission_insert($node, &$submission){
  // Use devel to investigate the variable
  dsm($submission);
}

Creating custom modules for Drupal 7 or Drupal 6. Tutorial.

Use Devel module to investigate your variables, as seen in my example above.

Jason.


Override the region.tpl.php template for an internal path

I would personally not use the method you currently have as it would seem to be overkill.

You can use your template.php file of your theme to set a different template file to use under your given conditions.

Like this, in your theme's template.php file (Note: this is adapted from the Zen theme):

/**
 * Preprocess variables for region.tpl.php
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */
function THEMENAME_preprocess_region(&$variables, $hook) {
  // Use a template with no wrapper for the content region on the path VIEWPATH.
  if ($_GET['q'] == 'VIEWPATH' && $variables['region'] == 'content') {
    // Allow a specific template to override the content region.
    // The template file will be region--no-wrapper.tpl.php
    array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
  }
}

Then to your theme add the region--no-wrapper.tpl.php file with the wrapper markup stripped out.

Then clear the drupal cache.


The template.php file should contain the presentation code; the "logic" code, such as the theme functions, or other code that computes the value of a variable, should be in the template.php file.

To make an example, code similar to the following one should not be in the template file, but it should be put in a function contained in the template.php file, and which return a value to the calling code, which then uses the returned code:

  if ($user->uid) {
    $class[] = 'authenticaded-user';

    if (user_access('administer content')) {
      $class[] =  'content-administrator';
    }
  }
  else {
    $class[] = 'anonymous-user';
    $class[] = 'anonymous-' . strtr(ip_address(), '.', '-');
  }

  if (isset($class)) {
    print ' class="' . implode(' ', $class) . '"';
  }

The code in the template file should just print (or render) values, but not compute those values; clearly, it's perfectly fine to use code similar to the following one (the code is taken from a Drupal 7 theme):

    <?php if ($logo || $site_title): ?>
      <?php if ($title): ?>

<a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>

      <?php else: /* Use h1 when the content title is empty */ ?>

<a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>

    <?php endif; ?>
    <?php endif; ?>

The difference is that, in this case, the code is verifying if the variable contains a useful value, and eventually avoid to output the markup, when it's not necessary.


the solution found in http://www.dibe.gr/blog/drupal-7-create-users-and-roles-programmatically in the author comment , so i'm set only the permissions array of my custom module in hook_install() user_role_grant_permissions($role_rid,array_keys(module_invoke('my_module', 'permission')));


You may want to give it a try to use the NOT commonly known/used alternative available for the Computed Field module, i.e. the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


global $user;
if($user->roles[1] || $user->roles[2]){
//Do Something
}


Simple Panels question on where the panels get placed on the page

Panels places the panel into the 'content' region of the selected page.

If you want to place it somewhere else on the page, try using mini-panels to create a block and place it that way.  No need to write custom PHP code for that.


Search api solr: The Solr server could not be reached

@see "Your site was unable to contact the Apache Solr server"

I follow this article https://www.lullabot.com/blog/article/installing-solr-use-drupal ,some day comes this errors after I reconfig of my site& apache.
but I sloved like this


Reference to an Image of a different content type

Have you tried to use Entity Reference?

With this module, you can first add a connection between to entities, and then you may be able to create a contextual view of selected field of the connected entity where needed.


Taxonomy menu - link to first node associated with term?

I figured it out; here's the solution in case anyone else needs this functionality.

Forget the Taxonomy Menu module. We'll build the functionality with a view.

Make a taxonomy term view (under Show when creating a view).
Under Advanced, add this Relationship: Taxonomy Term - Representative Node.
You can leave all the settings the same, but I suggest checking 'Require this
relationship' so empty terms will not get linked
Also Under Advanced, change Use aggregation to Yes
Add a filter for Taxonomy Vocabulary (with whatever vocab you want)
Add a Content:Path field, exclude it from display and check 'Use absolute link'
Add a Taxonomy Term:Name field and check Output this field as a link. For the Link Path use the Path Replacement Pattern from the Path field we just added (usually [path]).


"Drupal way" is to collaborate, not compete. It means that anyone wanting to write his own cloning solution will be asked to cooperate with author of existing one to provide what he finds lacking. Only if that's not possible, and some basic differences in approach or expected results are found, community will welcome new module. Otherwise it'll just die silently, unloved.

That said, you can use node exporting and importing tools to export nodes, edit them or not and import again, possibly under new nid. Node export is example of modules that can do that. Probably there are other ways to get content duplicated, and if you can think of basically different scenario, there is a big chance someone got that implemented.


Blocks are considered configuration, not a content. Thus, there is no separate privilege you can give your "normal users" to allow them to edit blocks.

There is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block" or "edit any block".

Just be sure no one have "delete" permissions on them, as it would remove block you placed from your page, and that should be admin-only task.

Other way is to use Views module. With Views, you can define a block and make it to show user's content, using various filters and orders. You could, for example, make a Views block that displays content of type news from users with role reporter, unless it's Friday in Iceland, and when it is, display content of type joke. Order by random, by date, by user's reputation, by anything you want :)


"Parameter expected to be reference, value given" error in menu page callback

I got the answer from the support list, and all I needed to do was remove the reference for the node object in my callback function signature:

function monographs_node_check($node, $type)

$node is passed as an object anyway, so I don't need to mark it as being by reference in the signature.


How to enable Drupal site to be in an iframe?

Since Drupal 7.50, core is now protected against clickjacking by default (X-Frame-Options: SAMEORIGIN).

So by default, your Drupal site can only be embedded into a site on the same domain.

To change those settings, assuming of course you understand the associated risks, follow the advice in the change record:

  If you are using a module such as Security Kit that already writes the X-Frame-Options header on its own, that setting will be automatically respected (pending the patch at #2661644: Integrate with Drupal core clickjacking defense) and Drupal core will not overwrite it. The Security Kit module provides an administrative interface for setting this header, so it's a good choice if you need to override the default Drupal core behavior and aren't sure exactly how to do it.
  Alternatively, set the 'x_frame_options' variable via any standard method, for example in settings.php:

// Turn off the X-Frame-Options header entirely, to restore the previous
// behavior of allowing the site to be embedded in a frame on another site.
$conf['x_frame_options'] = '';

  or

// Set the "DENY" option to prevent the site from ever being embedded in a
// frame at all, even on this site itself.
$conf['x_frame_options'] = 'DENY';

  See https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Frame-Options for more information on the various options this header can take.

  Removing the header (as shown in the first example code snippet above) should not be done lightly, or else your Drupal site could be embedded on other sites and then the user tricked into doing actions they don't want.
  If you want to remove the X-Frame-Options header in hook_page_alter() or theme preprocess functions that run later you can remove the header like this (requires PHP >= 5.3):

header_remove('X-Frame-Options');


How to export all feature components with drush?

Hmm ... did you try drush's built in Help topics?

I am running drush --version:
Drush Version   :  6.2.0

The help output for features-export is:
drush help fe

Export a feature from your site into a module. If called with no arguments, display a list of available components. If called with
a single argument, attempt to create a feature including the given component with the same name. The option '--destination=foo'
may be used to specify the path (from Drupal root) where the feature should be created. The default destination is
'sites/all/modules'. The option '--version-set=foo' may be used to specify a version number for the feature or the option
'--version-increment' may also to increment the feature's version number.

Arguments:
 feature                                   Feature name to export.
 components                                Patterns of components to include, see features-components for the format of patterns.

Options:
 --destination                             Destination path (from Drupal root) of the exported feature. Defaults to
                                           'sites/all/modules'
 --version-increment                       Increment the feature's version number.
 --version-set                             Specify a version number for the feature.

Aliases: fe

And drush help fc:

List feature components matching patterns. The listing may be limited to exported/not-exported components.

A component pattern consists of a source, a colon and a component. Both source and component may be a full name (as in
"dependencies"), a shorthand (for instance "dep") or a pattern (like "%denci%").

Shorthands are unique shortenings of a name. They will only match if exactly one option contains the shorthand. So in a standard
installation, "dep" will work for dependencies, but "user" wont, as it matches both user_permission and user_role.

Patterns uses * or % for matching multiple sources/components. Unlike shorthands, patterns must match the whole name, so
"field:%article%" should be used to select all fields containing "article" (which could both be those on the node type article, as
well as those fields named article). * and % are equivalent, but the latter doesn't have to be escaped in UNIX shells.

Lastly, a pattern without a colon is interpreted as having ":%" appended, for easy listing of all components of a source.

Arguments:
 patterns                                  The features components type to list. Omit this argument to list all components.

Options:
 --exported                                Show only components that have been exported.
 --not-exported                            Show only components that have not been exported.

Aliases: fc

So you should be able to use wildcards like % or * to select all types of a component. Eg, drush fe newfeature views_*. Your mileage may vary ...


How to configure my local Drupal site to contact my local Apache Solr server?

You haven't added any cores to Solr and you need to add at least one core and adjust the connection properties.

You will probably need the Solr 7 config from Search API Solr Search, as Apache Solr Search only has config for 5.x. The commands you need to run are: (replace CORE with the actual name)

cd /opt/solr/server/solr
sudo mkdir -p CORE/conf
sudo cp -R search_api_solr/solr-conf/7.x/* CORE/conf
cd /opt/solr
sudo -u solr ./bin/solr create -c CORE -d server/solr/CORE/conf

This should take the config files and create a core with those files. Then adjust your connection to http://localhost:8983/solr/CORE


Can Drupal be used for hierarchical multi-site?

This is a very vague question in that it doesn't give any semblance of the relation between the sites, or how they link to each other.

There are at least 3 different ways to make a unified site using multiple domains/subdomains using drupal:

1) Organic Group/Taxonomy/User based subdomains.

Each Group, Primary Taxonomy, or User gets their own subdomain, and their content is listed there.  Cross domain login issues are relatively mild, and just a matter of fixing the cookie domain as .domain.name, where the subdomains would be group.domain.name or user.domain.name or term.domain.name.

2) Domain Access based domains

This is more an "affiliated network of sites" concept.  Content is assigned to a specific site, and can be shared among all sites, or specific only to one. You link sites together using modules like Views as you can select content in any way you please, and give each site an individual look, or maintain a more consistent network theme.
  This can be implemented either as domains or subdomains, so cross-domain login issues are possible here, and can be difficult to mitigate effectively if you're trying to give an integrated feel.  SSO is one possible way to solve the issue, but other tweaks, such as pulling the login id across domain boundaries is also possible.  (This takes a little bit of technical wizardry)

3) Drupal sites based on a single install

All the sites share a code base, but each has their own database.  Automated links between the sites would need to be done through communication channels like RSS or RPC, or else maintained manually. As the user databases are separate, there are no common logins across sites.  SSO is probably a must in this case.

What solution fits your specific needs is not apparent from the question you're asking here, so please narrow the scope of your question by providing details as to what you mean by "site hierarchy".  What specifically makes otherwise unrelated host names (or domain names) into a hierarchy?


How to add unique class to each checkbox elements

I think the Form Options Attribute module will solve this for you.  It allows you to add option attributes in the form element render array.  Below is the example from the module page.  It also supports checkboxes as well.

$form['states'] = array(
  '#type' => 'select',
  '#title' => t('States'),
  '#options' => array(
    'AL' => t('Alabama'),
    'AK' => t('Alaska'),
    'AZ' => t('Arizona'),
    'AR' => t('Arkansas'),
    // ..
    'WI' => t('Wisconsin'),
    'WY' => t('Wyoming'),
  ),
  '#options_attributes' => array(
    'AL' => array('class' => array('southeast'), 'data-bbq-meat' => 'pork'),
    'AK' => array('class' => array('non-contiguous'), 'data-bbq-meat' => 'salmon'),
    'AZ' => array('class' => array('southwest'), 'data-bbq-meat' => 'rattlesnake'),
    'AR' => array('class' => array('south'), 'data-bbq-meat' => 'beef'),
    // ...
    'WI' => array('class' => array('midwest'), 'data-bbq-meat' => 'cheese'),
    'WY' => array('class' => array('flyover'), 'data-bbq-meat' => 'bison'),
    ),
  '#attributes' => array('class' => array('states-bbq-selector')),
);


Try the dev version at Drush-on-Windows-Installer GitHub.

Some key functionality, such as remote sql-sync, is not working yet. You could also try running drush under Linux using a Virtual Machine on your Windows box.


Altering select elements to include data-img-src

Looking at:

http://api.drupal.org/api/drupal/includes%21form.inc/function/form_select_options/7

It appears there's no way to add your own attribute to the select option from the form builder.

You may need to override theme_select to call a custom select_options handler instead, that checks some of the form data and adds the attributes to the option element.

http://api.drupal.org/api/drupal/includes!form.inc/function/theme_select/7


How to schedule an action to reliably be performed once every 5 minutes?

Using Rules and Rules scheduler (submodule of Rules) seems to me "a" valid approach.

What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 5 minutes (instead of only after 1 hour). And you need to run cron every 5 minutes also (not hourly as in that tutorial).

And as explained also in that tutorial: Initially execute the component manually (from then on every other 5 minutes the rule will be executed again).

Note: How to schedule a regular job using Rules in Drupal 7 is another tutorial that covers this topic.


Why is webform submit handler not working in form alter?

Maybe you can try this :

  function MODULENAME_form_alter(&$form,$form_state, $form_id) {
    if ($form_id == 'FORMID') {
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = 'MODULENAME_form_submit';
        }
      }
    }
  }

  function MODULENAME_form_submit($form, FormStateInterface $form_state) {
    kint($form_state);
  }


How to use domain access module for localhost

Regarding module configuration, use your localhost address as domain alias for each domain. /admin/structure/domain/view/1/alias

Of course you need to have those aliases configured for your virtualhost on server too.


Ignore "invalid" or incorrectly formatted Emails addresses (on Signup/User Import)

Better will assign some email (e.g. unknown_XXX@garbage.com, where XXX is row number of csv) to email of unassigned users. There's tonn of software that work with CSV.
After importing, you can run sql update command that will assign to emails '' value for that garbage email.

p.s. Also you can setup Rules module, that check if email equal to garbage email and warn him to change his email.


Correct way to render a modules output through a template?

To be honest, aside from the use of extract() (which is obviously bad in and of itself), I think the code is perfectly valid, and respectful of Drupal's processes/conventions.
There are two different ways to pass variables to theme functions in Drupal 7, both provided as an argument to a theme definition in hook_theme(). They are variables and render element.
I can't possibly explain the difference between these two better than the hook_theme() docs:

Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element.
Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style; in this case, the variables not supplied by the calling function will be given default values and passed to the template or theme function.

In your case you're theming a render array, rather than calling theme() directly, so render element is the one to use.
When you use a #theme property on a render array, the entire element (in your case $block['content']) is passed through to the theme function/template file. The name of the variable that you have access to in the template file is the name you have given to render element in the hook_theme() definition.
So if your hook_theme() defines 'render element' => 'my_lovely_var', you'll have access to the render array as $my_lovely_var in the template file.
I suspect that the author of your code was just taking a small shortcut so he/she didn't have to access the $element array directly with code. Without the use of extract() the template file would/should have looked like this:

<?php print $element['dataA'] ?>

<?php print $element['dataB'] ?>

<?php print $element['dataC'] ?>

Just for posterity, this is the same code re-written to make use of variables instead:
The same code using variables would look like this:
// ------ Actual USE of #theme -------
$args = array('dataA' => $dataA, 'dataB' => $dataB, 'dataC' => $dataC);
$block->content = array(
  '#markup' => theme('MODULE_more_information', $args)
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  return array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
      'variables' => array('dataA' => '', 'dataB' => '', 'dataC' => ''),
      'path' => drupal_get_path('module', 'HOOK') . '/templates'
    )
  );
}

// ------ Actual template -------

<?php print $dataA ?>

<?php print $dataB ?>

<?php print $dataC ?>

You could even use the following, slightly different, method to build up the block content when using variables:
$block->content = array(
  '#theme' => 'MODULE_more_information',
  '#dataA' => $dataA,
  '#dataB' => $dataB,
  '#dataC' => $dataC,
);
return $block;

This second method makes the block more re-usable as the theme function hasn't already been called, and other parts of the system can still alter the individual elements of the block.


I've been surprised by the lack of documentation and general information about Drupal RESTful services.

The best resources out there are from Tyler Frankenstein, the creator and maintainer of Drupalgap. Much thanks goes to Tyler as I started with his article here. Unfortunately, the documentation is rather old and no longer works with the current version of Services.

I highly recommend Drupalgap to any newbies that are looking to put a simple site on an Android/IOS app. It's a great tool that is well-maintained and constantly growing.

That being said....Drupalgap is great but ultimately I want the ability to expand beyond a framework requirement (i.e. Drupal). Understanding how JavaScript interacts with RESTful services is key to that point. After much effort I finally scraped together data from different sources and came up with a solution. Keep in mind that this worked for me. I'm sure there are better ways to do this but I only know this one.

Creating a PhoneGap app that Connects with Drupal 7 & Services 3.5+

My Environment:

Ubuntu 14.04
Cordova 3.5
Android SDK Manager 23
Apache 2.4.7
Drupal 7.28
Services 7.x-3.7
JQuery 1.11.1
jQuery Mobile 1.4.3

1) Setup your environment

Install Apache, Drupal, Phonegap, etc. I installed drupal to a sub-directory (localhost/drupal). Remember to setup your Services endpoint and enable resources for it. I use cordova to build the scaffolding for my Phonegap app:

 cordova create MyApp
 cd MyApp
 cordova platform add android
 cordova build

I have a symbolic link from my phonegap www folder to my apache root so I can test my mobile app on a browser before deploying.

2) Enable CORS for testing

Testing locally is a big requirement as the JavaScript console gives a developer so much more insight into what is actually happening with the code. Enabling CoRS was a requirement to get testing working. Getting CORS to function proper was a pain. Keep in mind that I'm testing from a local server (localhost) and CORS is configured to match, update your configuration accordingly:

1. Enable mod-headers,mod-setenvif
2. Add:
    Header add Access-Control-Allow-Origin "*"
   to the Apache Directory Directives (example.conf)
3. Add:
    SetEnvIf Origin "^(https?://localhost|https://[a-z]+\.my\.base\.domain)$" ORIGIN_SUB_DOMAIN=$1
    Header set Access-Control-Allow-Origin: "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
    Header set Access-Control-Allow-Methods "GET, PUT, POST, OPTIONS"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Headers "Authorization, Origin, Content-Type, X-CSRF-Token"
   to the .htaccess file at the root of your Drupal installation
4. Reload/restart apache

3) Create jQuery Mobile app
I followed Tyler's initial instructions and used jQuery Mobile to develop my application. The JavaScript was taken from a post in the Services issue queue here. This is a VERY basic app - just takes a login and outputs your username...but once you understand how the token is passed you can extend this to do ANY request.

Here's my index.html file:

<!DOCTYPE html>

    <title>Hello World</title>

        <link rel="stylesheet" href="css/jquery.mobile.css" />

Home

Shopping List App

                My Name
                <input type="text" id="page_login_username" />

                Username
                <input type="text" id="page_login_name" />

                Password
                <input type="password" id="page_login_pass" />

            <input type="text" id="page_login_token" />
            <input type="hidden" id="page_login_session_ID" />
            <input type="hidden" id="page_login_session_name" />
            <fieldset>

<button type="button" data-theme="b" id="page_login_submit">Login</button>

            </fieldset>

Here's my script.js file:

$(document).ready(function(){

function setToken(){

// Get a Token from the site
$.ajax({
url: "http://localhost/drupal/my_services/user/token",
type: 'POST',
dataType: 'json',
//crossDomain: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Error getting Token
console.log('Get Token Failed');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
// Set the Token Value in a textfield
$("#page_login_token").val( data.token );
}
}); // End Ajax
}

function doLogin( tokenid ){
var tokenValue = $(tokenid).val();
$.ajax({
url: "http://localhost/drupal/my_services/user/login",
type: 'POST',
dataType: 'json',
crossDomain: true,
data: {"username":$("#page_login_name").val(),"password":$("#page_login_pass").val()},

beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( userdata ){
$("#page_login_session_ID").val( userdata.sessid );
$("#page_login_session_name").val( userdata.session_name );
$("#page_login_username").val("Welkom SUPER" + userdata.user.name +"You are my Hero!");

// Get and Set a new Token after Login!!!
setToken();

}
});
}

function doLogout( tokenid, session_id, session_name ){

$.ajax({
url: "http://localhost/drupal/my_services/user/logout",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", jQuery("#page_login_token").val());
},

error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$("#page_login_session_ID").val("");
$("#page_login_session_name").val("");
$("#page_login_username").html("");
$("#page_login_token").val("");
}

});

}

function testConnect( tokenid ){
var tokenValue = $(tokenid).val();
var gorge = tokenValue.substring(14);
$.ajax({
url: "http://localhost/drupal/my_services/system/connect",
type: 'POST',
dataType: 'json',
crossDomain: true,
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", tokenValue);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert( 'Error with Connect.json' );
alert( gorge );
console.log( 'Error with Connect.json' );
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function( data ){
console.log( data );
alert( data );
}
});
}

$(document).on("click", "#page_login_submit", function () {
    //alert("Goodbye!");
    setToken();
    //testConnect( "#page_login_token" );
    doLogin( "#page_login_token" );
});

});// End document ready

4) Test with Poster and Chrome

Firefox was a bit of a disappointment in the testing arena; except for Poster. This allows you to test Drupal Services directly by using Get/Post. Very handy for testing. Chrome developer tools came in very handy - they were the first to tell me what was actually wrong with my CORS configuration.

I hope this helps you! Feel free to add any comments/advice. I can update this in time and make it better.


Content created using field and content created using , and effect on website performance?

I'd recommend just using one field and changing the "Number of values" in the field settings. This will allow you to add as much as you want and yet only maintain one field.

In case you have different requirements, here's my opinion on the two approaches you are thinking of.

Here are the differences between the two approaches:

10 fields

you have many fields that each go through the preprocess, process, field_alter, and any other hook that might affect a field.
Assuming they are similar fields any maintenance you would do would have to be done on each on individually.
If the fields will eventually have different values then this approach allows you to easily modify them.

1 text area

you only have 1 field that does through the whole hook process. Which makes things go faster.
You only have 1 field to maintain.
It does not make sense to store multiple values in one textarea since it makes curating difficult and prone to typos. Imagine missing a closing div. Boom, layout gone.
Also, if in the future you have a case to migrate your content, you will have to make additional effort to migrate these since there are multiple values in the data.

All this said, the two options do not have a HUGE impact on performance if you're just loading them up for display and not doing massive preprocessing.


How to make Drush rsync @dev @staging exclude some directories?

It's not so simple like just don't send the directory.

Actually, you're synchronizing SQL and directories. If you want avoid some directories (specially modules) you should also avoid their tables and configuration sync.

The best way its, from my point of view, to sync them and after to dis and pm-uninstall them in the staging process.


PathProcessorEntityResourceBC Class not found error after updating to Drupal 8.4

I have fixed the error by replacing the 'core' directory with the latest 8.4.0 version. I then checked the git log and differences which were found in these files:

modified:   core/scripts/drupal.sh
modified:   core/scripts/password-hash.sh
modified:   core/scripts/rebuild_token_calculator.sh
modified:   core/scripts/run-tests.sh
modified:   core/scripts/update-countries.sh

The differences were similar for each file, for example:

--git a/core/scripts/update-countries.sh b/core/scripts/update-countries.sh

I'm not sure exactly how and why this fixed the missing class, but it seems like I have some differences between the 2 versions of the site.

I then added the changes into git on a new branch and after switching between the 2 branches I don't get the fatal error any more (with or without the updated files).

It's possible that something was cached and as my site and drush was broken I was unable to clear the cache, refreshing the core files must have fixed it.


Can PHP pages be ported into Drupal "easily"?

Well, you don't really. If you are accessing the database in anyway you should be using the Drupal database API. There are a lot of things that you should do using Drupal API's if you are going to use Drupal. However, with that said, you can run any PHP you want in any Drupal node. So, there is nothing special you need to do in order to write your PHP code to work within Drupal. However, you really should think through your implementation before you being and determine which parts should use Drupal.

Also, it only takes about 3 minutes to setup a Drupal installation. So, you could just setup a dev site in no time flat and develop inside that. Even if you don't have a server you can download a few applications that will act as a server like XAMPP which will give you Apache, PHP and MySQL so that you can install Drupal and begin working.


How do I enable an onclick event in a link on a form?

You don't need the #href to prevent the event.

$form['test'] = [
  '#type' => 'link',
  '#href' => '#',
  '#title' => t('Show'),
  '#attributes' => [
    'onclick' => "alert('hello');return false",
  ],
  '#id' => 'myid',
];

In the above example, I removed the #href and the onsubmit handler and added return false after the alert() function in the onclick handler.
I don't know what  you're trying to achieve in your code, but the above example is working for me.

UPDATE:
I update the #href in my answer.


template associated with views style-plugin, and then customized for particular view: views does not find template

Drupal by default doesn't scan for more specific templates in modules directories, but views allows you to do it by adding 'template path' to hook_views_api(), see: https://api.drupal.org/api/views/views.api.php/function/hook_views_api/7.x-3.x


How can I use CKEditor for teaser text on a long form text field?

This is core limitation right now.

I would recommend that if you want an editor on a teaser/summary field, you simply create a separate field, that also gives you options like having a separate text format for it.

The text long with summary field type might eventually get removed in Drupal 9 or so.


In the views image field settings, under Multiple Field Settings, there is checkbox for "Display All Values in the Same Row" which is checked by default.  If you uncheck this box it will place each image in a new row and it will work as you require.  I know views has had this feature since at least version 2, but it might be called something slightly different in older versions.

I like doing it this way for simple slideshows, I can rearrange all of the images on one node/edit page. But for more complex slideshows, like where each image links somewhere or has alternate text, your best bet is probably still to use one node per row.


if you installed any module that alters with the drupal paths or jquery_update module version can cause the issue.


jquery in select (views module) -- change submit click to link

The image above shows an exposed form generated by Views in the file views_plugin_exposed_form.inc.  Line 242 in the function exposed_form_alter reads       $form['#attached']['js'][] = drupal_get_path('module', 'ctools') . '/js/auto-submit.js'; so the js looks to be in ctools however, I believe that script is being called whenever a change is made on the form.  If you want to modify the form note that views is managing the form in this file. Selecting the 'Apply' button calls exposed_form_validate and exposed_form_submit which are tapping into the Drupal form API (php not JS). Go to api.drupal.org to find out more about the various hooks available to modify the forms


Install the devel module and then Web Profile module which is bundled with it. You will then see the Symfony web profiler bar below the browser screen. Click on a Request gear icon, and it will show you the route and the controller class. You can start there.

You can also search your code base for that route name and see, if there are additional cases when it is handled.


views_get_view in combination with i18nviews only translates part of header

Using the following code triggers i18nviews correctly:

$view = views_get_view('viewname');
$view->set_display('page', array($type));


Slow loading of text in WYSIWYG with TinyMCE 3.5 in Chrome Browser

turned out to be an issue with CSS_Injector module, this is the fix.


This is not an answer, just advice: Drupal 6 has been unsupported since February of 2016 - close to 4 years now. I strongly suggest you spend your efforts upgrading to Drupal 7 right now, if nothing else because of all the security fixes (which are super important on an e-commerce site!).

The D6 -> D7 upgrade is relatively easy to do for most sites. I do not recommend going directly to Drupal 8 right now because that will be very long and painful process especially if you have little Drupal experience. If you want to move to D8, it would probably be easier to rebuild the site from scratch.


If I only display the node in colorbox
  (which is installed and used for other
  features) then I miss out on the
  multistep block.

A "quick-and-dirty" solution that I can think of, is to embed the multistep block in the node using the Insert Block module. Notice, that if you are using D7, you can check this, which is a community submitted port of the module.

If this is not what you need, please add a couple of screenshots of the form and the multistep block so that we can understand exactly what you are trying to do here.


This line is wrong:

$form_state['values'] = $foo;

No idea what you are trying to do here, but you must not mess with $form_state['values'] directly.

And what you are trying to do with the #default_value shouldn't be necessary either. Form API should automatically re-use an already entered value, without you having to set it as the default_value.


How can I get the fivestar module to submit the page url to the database?

what about something like this:

create a hidden field to include the path of the current node
using Rules, set an event after node save to populate that field with the nodes path
filter in views based on that field

I'm not certain if Rules will be able to pick up the new path, but I think it would trigger far enough into the process that the node path would be set.


How to retrieve default Title in custom module block

I think you should use hook_block_views_alter(&$data, $block).

Var $data['subject']; will have the title info of the block as per my knowledge.


How do I display fields from a Commerce Cheque transaction using Views?

You can create a view of of Payment Transactions and filter by Payment Method = check.

The check reference number is stored in the field called Remote ID. Just add that field to the view.


ShippingOrderProcessor not registered well?

In this case, you'll want to run this before the commerce_shipping.early_order_processor, set priority to 300
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingProcessor
    arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
    tags:
      - { name: commerce_order.order_processor, priority: 300 }


How to create pop up window for login page

1)use this module
https://www.drupal.org/project/modal_forms

2)create a block and put this code in it :

 <?php
global $user;
 global $base_url;
if($user->uid == '0')
{
?>
<a class="ctools-use-modal" href="<?php print $base_url; ?  >/modal_forms/nojs/login">Login
 <?php
}
else
 {
 echo '
Logout
';
}
?>


Highlight the argument passed in the exposed filters

I was able to create a solution for a regular Taxonomy: Term ID (no depth) filter, so this may not be applicable for you (the filter with depth was behaving erratically for me).

This code will set the dropdown element to the term provided in the argument, and will defer to the dropdown selection if one is chosen.

Add this to your custom module and then flush caches:

function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'name_of_view') {
    if(!isset($_GET['tid'])) {
      $arg = arg(1);
      if(isset($arg)) {
        $selected_value = array_search($arg, $form['tid']['#options']);
        if(isset($selected_value)) {
          $form_state['input']['tid'] = $selected_value;
        }
      }
    }
    else {
      $form_state['view']->args = array();
    }
  }
}

You can try changing every instance of 'tid' to 'term_node_tid_depth' if you are going with a Taxonomy With Depth filter (use a dpm($form) to verify the filter name).


How to give to the users the opportunity to change role as desired

You can do this with rules.

Event: After saving user profile
Conditonal: field has value
Action: Assign role to user

Something long these lines. You will need to create a new rule for each role unless you do some special field-value handling. You will also need to create a few checks in here to prevent the rule from re-assigning a role to a user.


Select list in entity reference in VIews

You need an additional module for that:

Entity Reference Exposed Filters

This might also help: Views field select filter

I'm not sure if this one supports exposed or only normal filters: Views Entity Reference Filter


Best practice for building modules using classes

A module is not a class by Crell is what you should read first.

The biggest OOP part in Drupal 7 is the new database abstraction layer (designed by the very same Crell and others). That implements many patterns which can and should be re-used.

For example:

Define interfaces for anything that could be switched out, only work against the interface internally. Example: SelectQueryInterface
A single class represents a single "thing". For example SelectQuery is a SELECT query, DatabaseConnection is a connection to the database and so on. See http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Use of inheritance to allow to overide a certain implementation. Most classes in DBTNG can have a driver specific subclass, which is automatically used and included if existing. For example SelectQuery_mysql. How that is done.
Extenders, which are an implementation of the Decorator pattern to add additional functionality to the SelectQuery Class. Extenders can have driver specific subclasses too.

Something that is still controversaly discussed is Information hiding. DBTNG implements that by making class properties protected and disallowing direct access. On the other hand, we have hook_query_alter() and they can be changed almost freely with various by reference getter methods.


How to override theme() part in page.tpl.php file?

You can override theme_links__system_secondary_menu() in template.php. You will name it MODULENAME_links__system_secondary_menu(), and the original code can be seen here: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_links/7.x

Copy that code, and modify it as necessary.


Why is unchanged and new value always the same in my Rules condition?

Rule refinements

Entity has field

Make sure to add a Rules condition Entity has field (related to your additional profile2:user:profile-directory-information:field-verified-field in your Rules condition). And make sure to add that Entity has field condition BEFORE the condition you already have.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

Add ":value" to your fields

Adapt your rule by adding :value to both of your fields, so that they look like so:

profile2-unchanged:user:profile-directory-information:field-verified:value
profile2:user:profile-directory-information:field-verified:value

Rules debugging

If none of the above helps, then move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your profile2:user:profile-directory-information:field-verified).


Views, if image field exists show it, else show this

You can use "Rewrite the output of this field", can put an token inside the output and if I'm not wrong there's an check-mark "if the field has values".


D8 How to create custom configurational form translatable?

You need a schema yaml file in the module folder /config/schema to make configuration forms translatable:

  What are schema files used for?

    The primary use case schema files were introduced for is
  multilingual support. We need to have a tool to identify all
  translatable strings in your shipped configuration so when you ship
  with your own settings as well as default Views, additional user
  roles, menu items, etc. we can offer those up for translation as part
  of your module/theme release on http://localize.drupal.org. The
  nesting levels and types would be enough for this use case.
    We also use schemas to provide actual translation forms for
  configuration based on your data. This use case is where types gain
  more importance and labels become crucial. The core Configuration
  translation module uses schemas to generate translation forms and
  save translations. The two most important built-in translatable types
  are 'label' for one-line text input and 'text' for multiline text
  input.

Source: https://www.drupal.org/node/1905070


Properly building array and using with drupal_json_encode()?

drupal_add_js(array('markers' => drupal_json_encode($markers)), 'setting');

Should be

drupal_add_js(array('markers' => $markers), 'setting');

See https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7. You will probably want to remove the drupal_json_encode($markers); as well.

Also noted that you should use db_query instead of mysqli_connect/mysqli_query https://stackoverflow.com/questions/11369447/drupal-7-db-query


How to programmatically add/modify a rule?

You have to create new Rule via the provided APIs and HOOKs from the Rules module.

From creating rules through the UI you have seen their configuration attributes, such as

Rules Event
Rules Condition
Rules Action etc.

Now you have all the useful HOOKs to create new ones. If you want to add a new Rules event to your System then go for hook_rules_event_info()

/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_custom_event' => array(
      'label' => t('A custom event happened in your application'),
      'module' => 'your_module',
      'arguments' => array(
        'param1' => array('type' => 'user', 'label' => t('The user object')),
      ),
    ),
  );
}

You can invoke this event also from custom code in your module as

rules_invoke_event('your_module_custom_event', $param1);

If you want to add some custom conditions to a pre defined rule then use
hook_rules_condition_info()

/**
 * Implements hook_rules_condition_info().
 * Checks if the given user is male or not.
 */
function your_module_rules_condition_info() {
  return array(
    'user_is_a_male' => array(
      'group' => t('test'),
      'label' => t('If user is male'),
      'parameter' => array(
        'user' => array(
          'type' => 'user',
          'label' => t('Validate registered users if male'),
        )
      ),
    ),
  );
}
function user_is_a_male($user) {
  // your custom condition to return boolean TRUE or FALSE
}

To alter pre-defined Rules you might use hook_rules_component_alter or hook_default_rules_configuration_alter but again depending on needs these will vary. Go through via the link above and you will find all.

FYI, you can export Rules via Features module with your custom HOOKs as well.
And these custom HOOK's should be placed on a file as "your_module.rules.inc" so Rules module will include these automatically.


How to update Drupal custom module after changing .install file

Visit /update.php on your site when logged in as admin, or use drush updatedb
Note that in addition to changing the table in the hook_update_N(), you must also change the schema of the cca_findings table in hook_schema() so that new installs of your module will have the proper table structure. Update functions are not used on new installs of your module.


function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
            if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
              $term = Drupal\taxonomy\Entity\Term::load($tid);
              $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
            }
          }

Create template file "page--taxonomy--VOCABULARYNAME.html.twig" in template folder and you can customize the page with the help of template file.


hook_form_alter won't save options cck field from custom form

Ok, new answer, replace:

$new_website->field_operators['und']['value'] = $operators_for_site;

with this

$new_website->field_operators['und'][0]['value'] = $operators_for_site;


Add a views exposed filter block into my theme using template.php

You're actually having an error if you check the php logs:

PHP Fatal error:  Call to a member function get_exposed_input() on a non-object in
.../sites/all/modules/views/views.module on line 1950

You can't just call drupal_get_form('views_exposed_form') because drupal wouldn't know which exposed form you want to render. Remember that a view or view display have its own exposed form.

If you check where the error is, you'll see that it's caused by not having a view object in the form_state variable.

What I suggest you do is use the Admin Block UI (/admin/structure/block) and just restrict which node types where you want to display the exposed filter.


I've managed to solve this issue.

I was using display suite to format my node and without realising I was using the Display Suite's theming file.  Once I renamed my node--gadget.tpl.php to the Display Suites theme name ds-1col--node--gadget.tpl.php it worked!

Cheers,


*.module file not included, even after cache clear

Here are my own observations. It contains some details that were not mentioned in @kiamlaluno's answer.

Things that need rebuilding

There are two "caches" that need to be rebuilt, if a *.module file with hook implementations was just created, in a module that previously did not have such a file.

The "container.modules" container parameter, which we can inspect with dpm(\Drupal::getContainer()->getParameter('container.modules'));.
Each entry has a ['filename' => *] key, which can be either null or 'MODULENAME.module'.
If it is null, then Drupal has not found the *.module file yet, and will not include it when looking for hook implementations.
The hook implementations, which we can inspect with dpm(\Drupal::moduleHandler()->getImplementations($hook_name));.

Operations that rebuild those things - or not

The first part, the container parameter, is not rebuilt on devel cache clear, or on drush cr. This has been the real problem.

The second part, the module_implements cache, is not rebuilt on devel cache clear, but it is rebuilt on drush cr.

To rebuild the first part, the container parameters, one can, as suggested by @kiamlaluno, uninstall and re-enable the module with the new hooks. But this can be quite impractical, because uninstalling can cause data loss.

Solution:

Luckily there is an easier solution: Enable any other module that was previously not installed, and then uninstall it again.

E.g. for me it was "statistics" module. But can be any other.

drush pm-list | grep "Not installed"
drush en statistics
drush pmu statistics

EDIT: NOT SO FAST!

I have to correct myself, for now:

The above method of enabling and uninstalling any other module does fix the container parameter 'filename' setting, at first.
However, flushing the cache again afterwards removes the 'filename' setting again.

This means that this setting is stored in a more persistent place somewhere.

The reason: APCu file cache: cli vs web

ExtensionDiscovery uses a cache to store discovered extension files.
In my case, this is Drupal\Component\FileCache\FileCache, with a Drupal\Component\FileCache\ApcuFileCacheBackend apcu backend.

The problem: The APCu cache has isolated realms for cli and for web.
This means, if the file cache is cleared on cli, e.g. via drush, the entries in web are still there.

This problem seems to apply only to the file cache in ExtensionDiscovery. Other caches are not affected. Probably this is because this file cache sits on a lower level within Drupal bootstrap.

Another part of the problem, possibly, is that the file cache is never cleared completely. At least, I cannot find such a place. Instead, individual entries are deleted by key.


Does {Your drupal site}/admin/config/search/search_api show a "working" (Green tick/check mark) next to your server settings? If so press 'edit' and this should provide you with a connection link to your solr installation being served by tomcat.  The URL should be something like

  http://{IP of server with Solr on}:8080/solr

If in a browser you do to http://{IP of server with Solr on}:8080/solr/admin you should see a solr web query page that will allow you to query the solr server directly.

This should help indicate if solr is indexing the drupal content or not.  On my localhost server a URL to return everything would be

  127.0.0.1:8080/solr/select/?q=%3A&version=2.2&start=0&rows=10&indent=on

In the event you can't contact the tomcat server (And assuming your firewall is correctly configured, not all systems allow 8080 through by default) I found the article very helpful for installing and configuring Solr on Tomcat 6.


You can get to that screen via the 'Administration' page, which you'll find at yourdrupalroot/admin . You'll need to drill down through the subpages there differently depending on your Drupal version; in Drupal 7 it will be under Structure > Menus > Main menu (the renamed version of 'Primary links').


Tag users in a content field to create user-specific content listings

This task can be done in the next way:

Download References module
Install User Reference module from this package
Add User reference field to your content type
It the view, that will display videos add a Contextual filter by created earlier user reference field
In the filter settings choose "Provide default value" -> "User ID from logged in user"


how can I use jquery autocomplete in drupal 7

Yes, jQuery UI is available in drupal core.

To include libraries like that you need to call the drupal_add_library() function to load the required js & css.

For exmaple:

drupal_add_library('system', 'drupal.autocomplete');

So where you are adding your javascript, add that first.

For example:

// Add the jQuery UI autocomplete library.
drupal_add_library('system', 'drupal.autocomplete');
// Load the custom js for this module.
drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/js/SCRIPT_FILE.js');

The caps lock parts need to be changed to suit your module.

As for where you would put this, I can't say unless I know where you are putting your code. It could be in your theme or in a custom module.

If it is in your theme then the drupal_add_js() part would be drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . '/js/SCRIPT_FILE.js');

I'm also assuming your scripts are in a js sub-directory.

You also need to make sure that any custom js you have is inside a drupal behavior (or $(document).ready() at the very least). Otherwise your javascript will run to early in the page load before the text field even is on the page, so it will do nothing.

It will be like this:

(function ($) {
  Drupal.behaviors.yourThemeAutocomplete = {
    attach: function (context, settings) {
      // Your code goes here.
    }
  };
})(jQuery);

For more info see https://drupal.org/node/756722#behaviors (the whole page is useful info)


Remove "submitted by" text on teaser only

That setting is checked and the information added in template_preprocess_node().

Which means that there is no other way than a preprocess function to change this. However, there is nothing stopping you from adding a preprocess function to a module, that works perfectly fine. You just need to make sure that your module runs after node.module by setting the weight in the system table to something higher than node (probably 0).

Code example by will:

In your .install file:

db_update('system')
  ->fields(array('weight' => 1))
  ->condition('type' => 'module')
  ->condition('name' => 'moduleName')
  ->execute();

And then in the .module file:

function moduleName_preprocess_node(&$variables) {
  // Do not display post information on teasers
  if ($variables['teaser']) {
    $variables['display_submitted'] = FALSE;
  }
}


You can use the trick from the module File Force Download. You can check it in the their code repository https://cgit.drupalcode.org/file_force/tree/file_force.module?h=7.x-1.x


Using an admin account as the sender for an action rule instead of site:current-user

I was able to select the wanted sender User by typing in the USER ID when the form is in direct input mode. To get to this "direct input mode", use the button "switch to direct input mode", as shown here:

After doing so, the form will look like so:

So in the end, the result of doing so is that if you read your private messages, then the sender is not the new user anymore, but the user you selected by ID manually (as shown in the above form).


You can put the not mandatory field in a group installing Field Group.
The group have a 'collapsible' option.


Create a real taxonomy with drupal taxonomy and pathauto

You can configure URL pathauto alias for taxonomy terms as :

[term:vocabulary]/[term:parents:join-path]/[term:name]
for creating url aliases for taxonomy taxonomy hierarchy.

Explore more using replacement patterns for specific taxonomy terms.

Please refer this image for url aliases configuration page


Views Search API with Search API database, sort handler

In case you are using Search API Database Search as a backend for the Search API you can solve the problem by using hook_search_api_db_query_alter hook:

/**
 * Implements hook_search_api_db_query_alter().
 *
 * Preprocesses a search's database query before it is executed.
 *
 * @param SelectQueryInterface $db_query
 *   The database query to be executed for the search. Will have "item_id" and
 *   "score" columns in its result.
 * @param SearchApiQueryInterface $query
 *   The search query that is being executed.
 *
 * @see SearchApiDbService::preQuery()
 */
function custom_module_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  $db_query->orderby('ISNULL(field_field_name)', 'ASC');
}

This solved it and moved items with NULL values to bottom of the view. Cheers!


Add payment method surcharge on single page checkout

You need to be careful here. Obviously you want to share with your customer that their order total will change, even slightly, before they pay. Often, most payment gateways strongly discourage passing on their fee to the customer, or flat out do not allow it.

But let's assume you want to charge more for "Cash on Delivery."

According to the commerce_fee documentation, you have to use two pages.

  Notice: if using fees based on payment type, be sure to move the payment type pane to a screen before the review pane on admin/commerce/config/checkout so that customers can see the fee before accepting.

This requirement would prevent nearly all normal payment gateways that require an off-site-payment-redirect step after putting payment details into a form from functioning correctly, if at all.

One way to create a single page, with ajax is the following recipe:

Ingredients

Commerce Checkout Field Group
Field Group
Commerce Payment Methods Field - (I just created this module because it didn't exist, just gives you a field that is populated with payment methods available to that order).
Commerce Checkout Ajax

Directions

Add a payment method field to your order. Use field group and checkout field group to add this field to a checkout page. Use Rules to make only a pre-selected payment method available based on the field on orders (might require a custom rule condition?). Use Rules to calculate your fee based on that field selection and not on the actual payment gateway selected. Use Commerce Checkout Ajax to re-load panes as needed.


Redirect loop, add-{type}-node redirects to add-{type}-node for non-admin users when parent type not availab.e

The Rules module that can be used to perform redirects also. So check if your sites uses this module. If so, verify if you have any "Active" Rules (and/or Rules Components) with a Rules Action that issues a redirect.

If no such Rules can be found, then it is not Rules causing your issue. If such Rules (and/or Rules Components) do exist, then temporary disable all such Rules and check if the redirect loop still happens.

If the redirect loop no longer happens, then re-enable the temporary disabled Rules again, one by one, until the problem (loop) starts again. Then disable that Rule again and use Rules debugging facilities to find out what the (customization related) problem with that rule is. For more details about debugging facilities in Rules, refer to my answer to ""How to loop through comments using the Rules module?".


How can I achieve this functionality to allow url prefixes without hacking the core?

Use i18n. It does this for you.

You have the possibility to choose how the content is served (from the module configuration page), between a subdomain for ex. "au.mysite.com/post-name" and prefixes like "mysite.com/au/post-name".

You will have a language field for your content-type, and you can easily set different content for different languages.


I added a new module and it breaks Javascript from my theme. How can I fix?

The screenshot in your question shows an error regarding the jQuery live() function, this was added in jQuery 1.3 and Drupal 6 comes with 1.2.6.

If you want to use a newer version of jQUery (needed by some modules), you can user the jQuery update module or see this tutorial: Using Newer Versions of jQuery with Drupal 6.


Access denied when trying to import single configuration item

OK, so this one was determined to be an Akamai issue for sure. There were some measures that it takes if it thinks it is a denial of service attack and for some reason that was what was happening. Our admin adjusted some settings and the error went away.
THANKS


Allow non-members of an OG to post group content

You need the OG permissions overview menu (admin/config/group/permissions). You can find there permissions to let non-members post content.


Sorry to hear that. The steps you should take are as follows:

If you have drush access, install drupalgeddon by typing drush dl drupalgeddon.
Run drush drupalgeddon-test. You will likely find several accounts which you did not create. Remove them.
Install hacked to find out which (if any) files have been changed.
Read this article.


How do I avoid the text on my site is selectable?

Try adding this code into your template.php file

/**
 * Implementation of hook_preprocess_page().
 */
function <THEMENAME>_preprocess_page(&$vars){

    drupal_add_js("(function($){
        $.fn.disableSelection = function() {
            return this
                     .attr('unselectable', 'on')
                     .css('user-select', 'none')
                     .on('selectstart', false);
        };
    })(jQuery);", 'inline');
}

You can try css methods also

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

A JavaScript solution for IE is

onselectstart="return false;"

See 826782


Enable a flag automatically for specific users using Rules

I achieved it by writing a new rule, in that i wrote a loop for getting all the selected users.

thanks


Commerce: save quantity button removing products

The issue is that I had written some javascript to change the value attribute of the "save" input to "update". After changing it back to "save" the button works just fine and nothing is removed from the cart.

To confirm, I went to a different theme and changed the value attribute of the "save" button to "foo" and it started removing line items from the cart.


How to allow anonymous user for checkout process?

You may need to check the permission, under Admin > People > Permissions : "Access checkout" for anonymous users.

If the user does login, their anonymous order will be added to their authenticated user cart.


TinyMCE image float, automatic set margin

If the styles WYSIWYG button shows image right or image left try applying that and save your edit. If that applies ok you can use Firebug to see the CSS class it adds to the image and just alter the css rules to your needs.

Or else, you can supply your own css styles to a wysiwyg profile. They are typically of the form:

wysiwyg_option_name=css_class_name

for example:

ImageRight=img-right

you then make an image right class in your themes css file:

.img-right { padding: 0 0 5px 5px; }

I believe both TinyMCE and/or the WYSIWYG module both support these features.


How do I block access to forum landing page, forum containers and forum posts?

To control access top level forum containers, forum topics and forum content, you should use the forum_access module (you mention it for blocking containers, but it can also be used to block access to forum topics and content).

However, after installing this and denying the anonymous user role access to forums, this user still has access to the forum landing page (he or she will see a message that it is necessary to log in to access forums).

If you also need to block access to the core forum landing page, you need to add a small custom module that uses hook_menu_alter to set up a custom callback function to check the user id.  Since the anonymous user is assigned uid 0, you can use this to only grant users with a uid that is not 0 access to this menu item.

Here is all that is needed, stick this in noforumforanon.module:

/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function noforumforanon_menu_alter(&$items) {
  $items['forum']['access callback'] = '_accesscheck';
}

/**
 * Callback to disallow access for anonymous users.
 */
function _accesscheck(){
  global $user;
  return $user->uid;
}

And this in  noforumforanon.info:

name = No Forum for Anonymous
description = Blocks anonymous from accessing the forum landing page.
package = Access control
core = 7.x

Put both files in a directory named noforumforanon below site/all/modules, enable and refresh cache, and the landing page shall be gone for anonymous.


Pathauto does exactly that.

All new user aliases generated after enabling the module will look like users/[user:name] (obviously this could be changed in module configuration - Configuration / URL aliases / Patterns).

You can use "Bulk update" to generate aliases for already existing users (and other type of content).


Entity reference : show fields instead of Label

Might want to check the display settings (IE: Manage Display) of both the referencing and referenced entity.  Haven't used it in a while, but definitely worth a look.


How to set a field's 'translatable' property

Entity translation exposes a checkbox which allows to set the translatable property.

It also provides a user interface to actually use field translation, there isn't much you can do with translatable fields without that module anyway.


Clearing the render cache after being programmatically logged in

You need to add cache contexts to your block. Cache contexts tell Drupal that the block needs to be cached differently for different circumstances. In your case, whether or not the user is logged in. you can read more about it here: https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts


How to use a div class to wrap some selected fields of a grid views view

It's really simple by using the Field overwrites.

First, set the (author) User: Picture and (author) User: Name fields to "Exclude from display".

Then open the settings for Content: Post date field, and open "Rewrite results" fieldset.

Check "Rewrite output of this field". This will reveal another fieldset "Replacement Patterns" which should show you the tokens for all the fields above the current field. All you need to do is put a <div> wrapper in the textbox and copy the tokens you want in between the div tags.


You would need to use JavaScript to make this happen. You're not going to have a good time with users doing this in CKEditor though, as they'll likely break this functionality when they use the editor and alter the content in it (the JS will be invisible to them, unless they're in source mode, and they could easily delete it without knowing it).

I have achieved similar behavior using a dedicated field called "YouTube Video Link". The user pastes a link in there and then I have a play button execute that link in an iframe overlay using Fancybox.

The JavaScript (jQuery) that you'd want to use is:

// When a user clicks the link...
$('.video-link').click(function(e) {

  // Don't let the browser open the link like normally.
  e.preventDefault();

  // Capture the link's HREF attribute in a variable.
  var youtubeLink = $(this).attr('href');

  // Set the HTML (the content) of the "video destination div" to = your iframe, including the youtubeLink that the user original saved into this node.
  $('#the-video-destination-div').html('');
});

Where your video link has class="video-link" and somewhere on the page you have a

.

Please add a comment to this answer to help funnel the nuances of what you're trying to do and I can edit my answer to reflect.


You can do it by setting up a view of product line items, adding both the product and order relationships, filtering by order state, turning on aggregation, grouping by Product ID and summing on the line item's quantity field.

Else try the https://www.drupal.org/project/commerce_reports commerce reports module.


$main_menu_tree = menu_tree('main-menu');
foreach ($main_menu_tree as $key => &$main_menu_item) {
    if (is_numeric($key)) {
        $main_menu_item['#below']['#theme_wrappers'][0] = 'some_other_theme_wrapper';
    }
}
print drupal_render($main_menu_tree);

If you have array of main menu active trails you can use foreach to loop through the array print menus and their sub menus.


How can I get a custom module's file path in a preprocess function?

A Drupal URI starts with a stream wrapper like "public://" that indicates to Drupal how to handle that resource. Typically, the "public" stream wrapper is defined as "treat this resource as a local file within sites/default/files."
Your module assets are not located within sites/default/files, so they cannot use the "public" stream wrapper.
Drupal doesn't actually come out-of-the-box with a registered stream wrapper for module or theme assets. You might try installing https://www.drupal.org/project/system_stream_wrapper, which would then allow you to make a URI like module://tableau_partners_sync/images/premier-technology.png.


Does removing fields also removes submitted values?

As webform elements are deleted, all related submission data is deleted.