How do I set variables for variable_get()?

Maybe you hope to learn that variable_set is the magical way to store all kinds of structured data in your database, and that variable_get is the way to get it out again. Unfortunately, it is not.

The "persistent variables", as they are often called, are meant for relatively simple key-value pairs that should persist across requests, users and sessions, often until a site admin changes the value. A good example is the site name.

So how does it work?

When Drupal is bootstrapped, all variables are read from the cache (if available) or from the variables table. (See variable_initialize for the exact code.) The variables and stored in the global $conf variable, a huge array. Drupal does this because it's more efficient than doing a database query every time a variable is needed. (It's also the reason why variable_set is not suitable for large blobs of data: they would be loaded on every request!)

Whenever you use variable_get('variable_name', 'default_value'), the variable name is looked up in the $conf array. If it exists, the value is returned; else, the default value is returned.

Finally, there is a third member of the family: variable_del. As the name implies, this deletes a variable from the variables table. This function is often used in hook_uninstall implementations, deleting variables when a module is uninstalled.

If you are looking for ways to store more complex custom data structures in the database, check out hook_schema and drupal_write_record, or use the Drupal entity system and Entity API.


Checkout Cache page based on cookie value and URL

Long story short what you want can be done. Depends on how you want to do it :)


How to create websites in shared folder using quickstart?

I found my answer on how to control where to store code. Trick was to use "--codepath=..." parameter.
Controlling where files are to be stored
drush qc --domain=d7tries.dev --codepath=/home/drupalpro/websites/REPOSITORIES/my-drupal-experiments/d7tries.dev --makefile=/home/drupalpro/.drush/d7.make
Help at: https://drupal.org/node/819398


Replace Views prev/next pagination with image arrows

You can use the theme_pager_link function to override the core pager link. Or you can have a look at this article that may be helpful: https://www.drupal.org/node/318565


Set amount of fields on an existing content type

If I understand you correctly, you're trying to change the cardinality of a field based on user input. You can do this by using field_update_field():

$field_name = 'field_bar';
$field = field_info_field($field_name);

$field['cardinality'] = 10;  // Change to number you want

// field_update_field() throws an exception on failure
try {
  field_update_field($field);
}
catch (Exception $e) {
  drupal_set_message(t('Could not update field.'), 'error');
}

As you can see, cardinality is actually a per-field setting: if you wanted to do this on a per-instance basis (so, separate cardinality for the field for each content type/bundle), you actually need to create an entirely new field for each bundle.

This would likely cause a number of issues, particularly if you wanted to do things like display the values in a view (each field would be handled separately, even though the only thing different is the name and the cardinality).

Instead, what I'd do is just set the cardinality of the field you want to be dynamic to "unlimited" (FIELD_CARDINALITY_UNLIMITED in code): out of the box you get a fancy widget that lets users add as many values as they'd like.


How do i run node save in background process

You can instead of saving the node directly, modify the node object with attributes from the form and then add it to a queue so you can use the Drupal queue system to do the actual node_save() operation on it.


Adding custom form to form_alter -- help please

Anything with a # preceding it isn't an element, it's a property. Properties are not rendered.

To fix, just give your submit button a unique key without the #, e.g.

$form['foo_submit'] = array(
  '#type' => 'submit',
  ...
);


The problem in this case is caused because results query differs between iterations.

You should replace:

$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0', $sandbox['current'], $nodes_per_pass, array(':type' => 'event'));

with

$result = db_query_range('SELECT nid FROM {node} n WHERE n.type = :type AND n.status = 0 ORDER BY n.nid ASC', 0, $nodes_per_pass, array(':type' => 'event'));


Okay, I figured it out. After setting the services.yml file debug to "true" and enabling comments in my Firefox console, I was able to get the theme output for the particular set of divs that was adding the unwanted markup (I tried this earlier, but I think I forgot to rename default.services.yml to services.yml).

Anyway, I found that the markup was coming from Bootstrap's container.html.TWIG template. Of course, this is one of the templates that doesn't come with override suggestions, just the hook theme_container() theme function. So I copied the default function into my [subtheme name].theme file at the top of my subtheme's directory and modified it thus to suit my needs:

<?php
// Implements hook_container().
use Drupal\Core\Template\Attribute;

function vatheme_container($variables) {

  $request = \Drupal::request();

  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }

// Special handling for form elements.
$element = $variables['element'];
 // Ensure #attributes is set.
$element += array('#attributes' => array());

        if (isset($element['#array_parents'])) {
            // Assign an html ID.

            if (!isset($element['#attributes']['id'])) {
                $element['#attributes']['id'] = $element['#id'];
            }

            // Add the 'form-wrapper' class.
            $element['#attributes']['class'][] = 'form-wrapper';
        }

        if($title == 'Contact Tech Support'){
            return $element['#children'];
        }
        else{
            return '<div' . new Attribute($element['#attributes']) . '>' . $element['#children'] . '</div>';
        }
}

So, that seems to do the trick. This was my first stab at doing theme work in Drupal 8 and there are a lot of not insignificant changes from Drupal 7 here, so I thought I'd go through the details of my solution. Hopefully this helps someone else out there.


I think No Sssweat comment is right in that this requires custom code.. And you should include some extra details regarding Pierre's questions.

Assuming that you want it like Tinder, I think triggering a hidden flag on each node for each swipe event could be the easiest option. Then on refresh, a views filter would hide flagged content by that user.

This answer describes a method for doing similar. I haven't tested it myself yet but it's an accepted answer and quite recent so it should still work.

It's hard to give a more thorough answer for this without knowing more about the slideshow. And my jQuery is rudimentary at best. If this is a viable approach, post some more details and hopefully myself or another user can help with getting the event. If not, I'll remove this.


Qiuck tabs shifts the Openlayers map background layer

This is the css/jquery issue .inside a quick tab the map doesn't get load because it is display none initially .when you click on the locations tab it tries to get load but dos not get loaded . you need to play with jquery a little.


Assuming it's a textfield, I think the simplest way would be via a preprocess on theme_textfield:

function MYMODULE_preprocess_textfield(&$vars) {
  // Identify the element and remove the name property (which will always be present)
  if ($vars['element']['#foo'] == 'bar') {
    unset($vars['element']['#name'];
  }
}

Bear in mind that Drupal won't be able to process the value for that field correctly if you submit the form, but I guess you're submitting this offsite anyway.

If it's not a textfield you should be able to use the same principle with the the theme function for whatever element type you're using.


How to store/manage/display data sets in Drupal without using the node/entity systems?

Have a look at the Forena module which can be used to display (= query, not update) data stored in databases external to Drupal. It comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgres or any PDO compliant variation.

For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the Forena Documentation.

The Sample reports and graphs are fully functional, such as the drill downs available on the Master Summary with drill down. To filter data (by the users), you'd typically use "report parameters", which you can see in the sample report "Users in cities". On top of that, using Forena "skins", you can also use the amazing "dataTables" (and its widgets, such as sorting by selected columns).

It also includes a UI for either creating your reports (the WYSIWYG Report Editor) and/or for creating your SQL queries (the WYSIWYG Query Builder).

Disclosure: I'm a co-maintainer of Forena.


Programmatically get the product name from $order

In ubercart uc_products table stores the product details. You can get product id from the $orders array and can fetch the required product data from
uc_products table.

$query = "SELECT * FROM uc_products WHERE nid = ". $pid;

Refer the links for more details
https://www.drupal.org/node/1940926


Use an exposed filter in Views to list all nodes with same title

It is possible that your other two nodes have spaces at the end of the title. Check that, and if it is not the issue - try changing your exposed filter operator to Contains instead of Is equal to and see if you get 3 nodes as the result.


GMaps page with a marker pin on your location based on address we supply

To make a marker for a corporate contact page, I think it will be good to put just HTML code provided by Google Map in the template file.

Or else you can create a block and put script in block body and render it using Full HTML.

To generate HTML code create marker on Google map, Click on the Button right to Print and it will give you the code for iframe


The title set with drupal_set_title() is both the page title, and the browser window title.
If you are looking for a module that can change tHE window title, you can look at Page Title.

If you want to be able to do it from A CUSTOM module, you can implement hook_preprocess_page(&$variables) to modify the content of $variables['head_title'], which contains a modified version of the page title to use in the <title> tag.

function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}


How to create node twig template suggestions for one content type?

You need to get the values first you want to work with. For example the node object is inside $variables['elements']['#node']. In the sample below field_foobar is a text field. Depending on what your field type is you may need to get the value you want a little bit differently. And also maybe sanitize it first before you use it in a template suggestion (replace spaces etc.).

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];
  if ($node->bundle() === 'page') {
    if (!$node->get('field_foobar')->isEmpty()) {
      $value = $node->get('field_foobar')->first()->getValue()['value'];
      $view_mode = $variables['elements']['#view_mode'];
      $suggestions[] = 'node__page__' . $view_mode . '__' . $value;
    }
  }
}


Go to the Attachment details of the Glossary view
Under Contextual Filters (you may need to click Advanced to see it) click on "Content: Title"
Uncheck "Display record count with link"


Configuration syncronization not importing everything

It appears as though the issue I had relates to this issue: Display mode configurations don't get updated with new fields https://www.drupal.org/project/drupal/issues/2915036

I haven't tried the patch yet, but after saving the individual display modes the fields then get put into the export and sync properly.


Views Table Grouping not working if group field is blank

I had a similar issue. If the field I was grouping by was empty in all the nodes under another grouping, no results would show. In my case it was State->Administrative Area, and if none of the nodes in the state had administrative areas no results would show under the state.

The solution that ended up working for me was to uncheck the 'Hide rewriting if empty' box in the Configure field: Content: Administrative Area->No Results Behavior section. 'Hide if empty' was already unchecked so I didn't fool about with it.


What may be causing "fails the check integrity"?

Possible reasons
Some reasons (pretty sure it is an incomplete list ...) that may help to pinpoint the reason for this typical message are like so:

Some module is missing "now" (which was there when the rule was added). It could well be a recently disabled, or uninstalled module.
The rule (or Rules Component) refers (in a Rules Condition or Rules Action) to a machine name of a field that is "no longer there".
The rule (or Rules Component) refers to a Rules Component that is no longer there, or, as a variation, something changed in a Rules Component (eg the data type of a parameter) so that it is no longer compatible with the way some Rule is trying to execute that Rules Component.
The rule (or Rules Component) refers to a content type (or more generic an entity type) that is no longer there, or a role that was removed.
The rule (or Rules Component) has a Rules Condition or Rules Action, which is provided by some module, based on some logic in that module. A good example of this can be found in the Content Access module: the ACL module seems to be a weak module dependency of the Content Access module, i.e. the Rules Action with machine name content_access_action_user_grant is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that has such content_access_action_user_grant action will show such "... fails the integrity check".

Possible resolutions
Depending on what the actual reason is, these are possible remedies for it:

Re-enable recently disabled modules:

if any such module adds an extra content type with some related fields, and any of your rules still refer to them, then that would cause the typical error message.
if the existence of any such module is used to provide some extra Rules Condition or Rules Action, then any of your rules that still refer to those conditions/actions would cause the typical error message.

If you know/remember which entity some field (which got deleted) referred to, then manually adding that field again (with identical machine name) should make the error message go away.

...


Views Grid Display Images Thumbnail Sequently using jQuery

First check if your jQuery file is properly called, if its called than you can add jQuery.noConflict(); first and than replace $ sign with jQuery.


Is there a way to call a drupal ajax function on a multistep form without causing the form to resubmit?

The ajax call has a callback function that has a few commands including what it needs to render again. In this care i image it starts rendering the whole form again. You will see someting like this in the callback.

$commands[] = ajax_command_replace('#form', drupal_render($form));

And you want something like this

$commands[] = ajax_command_replace('#form .ajax-section', drupal_render($form['ajax section']));


Where do I find the block id for Twig Tweak module

I think your block id is a machine name of a block that you added here: Admin > Structure > Block layout (/admin/structure/block).

When you edit some block you will see the machine name. Besides, a disabled block is also allowed.


Add the view mode to the CSS classes used for the body

If you are using sub theme of bootstrap theme then you can possibly add class to body tag of the node.

Go to SubThemeDirectory/and open template.php and add this hook_preprocess_html()

function THEMENAME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['body_attributes_array']['class'][] = 'mode-' . $vars['page']['content']['system_main']['nodes'][$node->nid]['#view_mode']; // Node ID class
  }
}

I hope this'll at least give an idea how to add class attribute.


Why would some images be saved to field_image / some maintain href after on import from Blogger?

The issue you described with some images not importing (keeping the blogger URL) is caused by the regex not identifying the image URLs as blogger hosted images. This regex can currently be found in the same file batch.nodes.inc on line 213 :

      if (preg_match_all('/(href|src)="(http:\/\/.*?\.blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(http:\/\/.*?\.blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

The code that worked for me is follows :

      if (preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogspot\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)
      || preg_match_all('/(href|src)="(https?:\/\/[0-9a-z\.]+blogger\.com\/(.*?))"/', $node->body[LANGUAGE_NONE][0]['value'], $matches)) {

This could be improved but worked for me.  It allows for http and https.  And the .* was grabbing too much text before an image if there was a link above the image.

For the image quality, note that blogger uses different quality of image for displaying within the post and when clicking on the image.  Note the number contained within the URL s200 is low resolution, s1600 is high resolution.  Other numbers could be used for different size image.  You will have to decide which image to save or create a field to save two versions of each image.


if i have no right use the flag "Accepted",please hide it

I just added this to my sites/all/themes/mytheme/template.php file and it worked after clearing the theme registry:

function mytheme_preprocess_flag(&$variables) {
  // Do something here
  dpm($variables);  // Pretty print $variables if you have the Devel module installed
}

That should give you a nudge in the right direction.


How to display physical dimension fields on node--product.tpl.php?

Have you set the field to be displayed under display settings for the content type?

Above is how the Field UI looks, maybe your product dimension field is hidden?

There is a guide here, on how to customize the Drupal commerce product display.

If you want to print the field in node--product.tpl.php you should first drag it so it is visible in the field UI.

Then you need to add render($content['product:field_width']);


How to change path of public files Drupal

You can change the path using below step.

Go to Administration -> Configuration -> Media
Click on 'File system' link
Change the directory in text-field 'Public file system path' and save the configuration.


First you need to create a view page
Display & filter those information which you want to export
Click on +Add & select Data Export
Under format you get an option to change to unformatted list
Save & check

For detailed description click on the LINK.


I solved a similar problem with the Flag and Rules modules. I created a flag called 'Published' for nodes and two rules that are activated when content is flagged/unflagged with this flag. These are my settings:

'Published' flag

Bundles: Article
Display in entity links: Display link as field
Link type: JavaScript toggle

If you need the flag for (an)other content type(s) too, you simply have to check the box in the flag settings.

'Published node' rule

Event: A node has been flagged, under 'Published'
Action: Publish content: Parameter: Content: [flagged-node]

'Unpublished node' rule

Event: A node has been unflagged, under 'Published'
Action: Unpublish content: Parameter: Content: [flagged-node]

If you want to, you can add some extra actions to the rule (e.g. display a message).


Error: Maximum function nesting level of '512' reached when injecting custom service to webform (6.x) handler

The problem is that you're instanciating the Ecomail object into your Ecomail constructor $this->ecomail = new \Ecomail($this->config->get('api_key')); which is kind of a fork bomb.
Your Ecomail is creating an Ecomail itself creating another Ecomail, etc.
That's an infinite loop


Display number of tagged nodes for each term in a view?

First you have to make sure you can get the nodes tagged with each term to display, and then we'll get them so their COUNT is listed.

Add the 'Taxonomy term: Content with term' Relationship to your terms view (under the 'Advanced' section)
Now you should be able to see, in the list of fields, things such as Content: Title, etc.  Add the content title, and make sure it's set to use your newly created relationship.

This should get all the nodes tagged with each of your terms to be displayed under the term.  But how to count them??

The way you can do that is by enabling the use of aggregation for your view!  Under the 'Advanced' section of your view, locate the 'Use aggregation' setting and make sure you enable it.  It's disabled by default:

Once you've done that, you'll see by all of your fields a new 'Aggregation settings' field, which you can set to be 'Count' for the node title that relate to each taxonomy term.

That should do it!  Let us know if you get it working!  :-)


Here am altering the submit handler of the article content type while creating new article type contents

  /**
     * Implements hook_form_alter().
     */
    function example_module_form_alter(&$form, FormStateInterface $form_state,$form_id) {
   // dsm($form_id);

      switch ($form_id) {

        case 'node_article_form':      // New article nodes.
        // Attach our custom submit handler.
     array_unshift( $form['actions']['publish']['#submit'], 'example_module_node_article_form_submit');
          break;

      }

    }

    function example_module_node_article_form_submit($form, FormStateInterface $form_state) {
      drupal_set_message('custom submit ...');
    }

Source


If the default image was set correctly then the newly saved article nodes should pick it up. Check if the website's log show any related error messages.

If you want to go with another method then just:

Copy node.tpl.php in your website's themes folder to node--article.tpl.php;
Open node--article.tpl.php in editor and place the following code just before print render($content);:

<img src="/path-to/image/image_file_name.ext">

Save.
Clear your website's cache and revisit any article node.


Force Drush8 to Download Drupal 8 Module on a Remote D7

I was going to suggest --default-major. Since that does not seem to work, I can only recommend to download the module outside of a Drupal site and then move it into place.

drush dl composer-7 --destination=/tmp && drush rsync @self:/tmp/composer @remote-dev:sites/all/modules


How do I edit the CSS based on node, page, or placement on page?

This isnt a Drupal API question. It's more of a CSS and how does that work in the browser question. That being said there are docs on how to theme drupal 6 and 7. Since drupal is a web application they cover topics such as:

Working with CSS
Standard Drupal Core Styles and Classes

Within (2) it describes the .node and .node-title CSS classes:

  .node

  A wrapper div around all of a node, including its title.

  .node-title

  The title of the node.

Depending on the theme your using you may or may not have those exact classes, every theme is slightly different. Basically in your theme you want to use Firebug or Chrome Developer Tools to look at the HTML markup and CSS classes and IDs attached to things. You can then target a page or node title, and create a rule to target specific page urls if need be. As an example Drupal page (using AdaptiveTheme subtheme):

The <body> tag has a million css classes on it including page-node-2 that specific CSS class would target only this node (by its NID). You can inject other more useful body classes into any theme using hook functions and template files -- but thats beyond this writings scope.

In this case you can also see the node title has an ID of h1#page-title

A general CSS rule to target this 1 page's title you could put in global.css is body.page-node-2 h1#page-title { color: red; }

For your theme it would be the same process:

examine the body tag in your Theme and find a useful CSS class to specifically target the page(s) with a CSS rule.
examine the Section Header tags within the page to find the exact CSS classes/ids to target just that element as well.

Lastly, I dont think every theme has a global.css file ... though most probably do. My exact CSS rules herein will likely not work for your usecase, they're just examples of what you could do. See the documentation pages listed above to better understand Drupal Themeing.


Change max length of link field link text

If you go for module then you can check Maxlength module.

  Maxlength allows you to set maximum length of any field on any form
  making use of the form API. This includes fields created using the UI.
  (Example: any text field on a node)


Migrating csv data as array into multi-field

I figured it out.
The issue was the plugin. Rather than * array_build*, I should have been using the get plugin, as follows:

process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count:
    plugin: get
    default_value: 0
    source:
      - 1960
      - 1961
      - 1962
     .
     .
     .

That migrates the value of the array indexed by those years into the field_count field. And because the field has multiple cardinality, each row is written in as a new value.


Configure a block view via block settings

Views UI: Edit Basic Settings may meet your needs.

  "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.


How do I use the Password Policy module?

Please see the reference link below which has information about how to use this module for Drupal 8

https://opensenselabs.com/blog/tech/drupal-password-policy-module

There might be other modules like PRLP (Password reset landing
page) or other relevant password setting modules that might not be allowing the policy to be enforced.
You can check by uninstalling them and see if the created policy is
being enforced on the default user form.


Entity reference default value to first value

You can do easily using jQuery

$("#target").val($("#target option:first").val());


Drupal 7 Custom Page shown only for logged-in users

You are creating a custom page, so you should use user_is_anonymous() in the calback of the page.

For example:

$form['custom_path'] = array(
  'page callback' => 'some_random_function',
);
function some_random_function() {
 if(user_is_anonymous()) {
  //call the login block
 }
 else {
  // What ever u want.
 }
}


Geofield Map - Filter attachment result by clicking marker

So You have 2 views on the Page
1 view is the Map
and another view is the "attachment"

You need to look in to how to use Contextual filters look at the Url Arguments in A view (see https://www.youtube.com/watch?v=aVwclF9TfBo | and https://www.youtube.com/watch?v=zbdQghFj0lU)

A Very Quick Way to get this done is, in your Map View
add 2 new fields Content id and a Global: Custom text field
then in your new custom field view add

 Quick View

where /map is the path to your map page,

Then open your Map FORMAT Settings and scroll until you see

"MAP MARKER AND INFOWINDOW"
in Marker Infowindow Content from select your new field

Then save the map view.

Open Your "attachment" view and add a CONTEXTUAL FILTERS

selecting "ID" in the Content Category.

config like

tick Provide default value

Type = Query parameter

Query parameter = show

this will give you

this is not 100% exactly what you want but then you can start to add a  custom js file to target the marker click event and auto trigger the window link - good luck !


How to implement bulk pricing/discounts with Drupal Commerce?

Maybe you should use the Commerce Discount module. Quote from its community documentation:

  The Discount UI (available under Admin → Commerce → Store → Discounts) allows creating and editing discounts. Each discount consists of two related entities: Commerce Discount and Commerce Discount Offer. The Discount allows you to choose what type of entity this discount this will apply to i.e. "Order Discount" or "Product Discount" (line item). The Commerce Discount Offer denotes the result the discount produces. The module provides 4 discount offers out of the box.


What type of text field did you choose for your field? Regular text field?

If you want to be able to add comas. When you add a new field to your content type you need to select INTEGER as your field type, not text.

Then View's will detect that its an integer field (numbers only) and give you the comma option.


Pull data into a list for custom content type?

You can use the Entity Reference module to create your 'author name' field, which will reference your authors content type.


Alter Existing Route - Bypass/override entity permission

Drupal uses both route access and entity access. You need to add your access check in hook_entity_access() because the media entity module is denying create access. Use route access for non entity pages.


What exactly is "Overridden", "Needs review" & "Revert component" in Features?

Both needs review and overridden statuses mean that the feature in the database does not match the feature in code. Running "drush fr" (feature revert) will replace the feature in the database with the feature in code.

Now lets see "Revert" vs "Update"

Revert:(drush fr)

This operation changes your site configuration (living in the database) to match up with the definitions in the feature module code.

Update / Recreate:(drush fu)

The update operation will produce a modified version of your feature module, which matches up with the configuration found in the database.

  Remember, revert for Drupal features means copy configuration from
  code into the database.

If you want to go in detail with simple explanation, then please follow below links

Modifying, updating and reverting Features
Revert and update a Drupal feature module


In /sites/all/modules/facetapi/plugins/facetapi/url_processor_standard.inc there's a function setBreadcrumb() (around line 61).

Simply comment it out or put a return; on line 62.

A better way is to create your URL Processor which implements FacetapiUrlProcessor::setBreadcrumb()


How can I hook into an entityform submission?

If I understand your question right, you should use the following hook to capture a submission:

hook_entityform_insert($entityform)

As described in the comments at the top of entityform.api.php:

* Entityform and Entityform type are standard entities using the Entity API module.
* The standard Entity hooks are availabe for them.
* Including
*  ...
*  hook_entityform_insert

Hope this helps

Addition:

here is the sample code I used:

function mymodule_entityform_insert($entityform){
  dsm($entityform);
}

and it did get triggered as soon as I submitted an EntityForm.


Search API returning no results even though nodes have been indexed

What type have you selected for your indexed fields?
I think search_api_page only handles fields using fulltext indexing, and wouldn't be so useful for numeric fields like nid, or text fields indexed with the string type.

You could also try using Views with search_api


Help understanding Drupal form creation/content creation

You probably need to explain what you mean by "background processing", i.e. are you looking to save content or do something else?

At any rate, if you really need to template your form to be table based, this is possible by implementing hook_theme. An example entry for a form with an id of example_search_form (this is the argument passed to drupal_get_form() or can be found by looking at the id of the generated form by viewing source) and a template file called example-search.tpl.php looks like:

  $hooks['example_search_form'] = array(
    'arguments' => array('form' => NULL),
    'template' => 'example-search',
  );

  return $hooks;

Then in your example-search.tpl.php you can render individual form items however you would like.


Right way to add JS and CSS to node/edit and other forms

If you wish to add JS and CSS to the node edit page in particular (or any form in general), the best and the right place to do so is the hook_form_alter() and the property you should be using is #after_build.

This comment on DO tells you exactly what to do - http://drupal.org/node/1253520#comment-4881588

Hope this helps :-)


How to remove taxonomy term reference field from simplenews newsletter HTML

Go to

  Home » Administration » Structure » Content types » Simplenews
  newsletter

Go to Display and customize it

There will be Newsletter category - you can change it's format to Hidden

But first activate needed display type on that page in

Full Content fixes the node display. Email HTML fixes it on the email itself.


Two ways here. The fields all have CSS that is unique to them. All CCK fields start with "field-" you can absolutely position the items or make them inline and then float the image on the left or the right.

I found a good blog post on this from my bookmarks.

http://zroger.com/2009/06/theming-cck-fields-the-right-way/

You can also make a custom tpl file that drupal will call when it opens the given node type. The link to that is below. The prose used is interesting and shows their frustration over making these.

http://www.advantagelabs.com/drupal-colonoscopy-or-how-theme-cck-field-drupal-6


How do I do a file upload with other form data in Drupal 6?

My guess is that there's an error. Have you looked at your watchdog log? Is the temporary directory setup and writable by the web server?


Not sure what you are asking here, you can override theme_pager() like any other theme function in Drupal. It is however quite a bit of code.

It's also relying on global functions, so you probably can't simply call the original fuction with reverted arguments.


Translated taxonomy term in contextupal filter not validating

I had to set the taxonomy vocabulary type from "Localize" to "Translate".


Try the Empty fields module. I didn't use it, but look like that's the module you need.

  This module provides a way to show empty fields that would otherwise be hidden.


The Message Subscribe module is part of the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Just looking at the available documentation it's not obvious to get going with it. But if you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.


You don't go into any detail about what the page won't load means.  Is there an error that is being displayed by the browser?  If so what is it?  In this case it is likely that you are getting some kind of http error code back from the server, or the request is timing out.

You may want to look at your server's fail2ban log.  If Fail2ban is enabled, it is possible that your ip address has been blocked.

Is there an error in a web page?  Do you get a blank page?  If so, does viewing page source show anything?

Errors in the web page are much more likely an sign of something coming from drupal.  Though http error codes could easily be coming from drupal too.

If you use the developer tools in whatever browser you are using to look at the request and response headers what do you see?

This will give you a clearer view of what is being requested and what the server is answering?

Do you see anything in your server's error log?  Does anything show up in the access log?  This will give you a clearer view of whether the request is reaching your web server at all.  If you see no request in either the access or error logs, it is a reasonably good bet that you are being blocked at the firewall level (this includes fail2ban) or that you have some local dns setting that is causing your request to go to the wrong place.  (This could be something in your /etc/hosts)


Having actually read the fieldCondition documentation the fourth property turns out to be $delta_group which allows specifying dependent conditions. So it turns out all I needed was the below:

$current_date = date("Y-m-d H:i:s");
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=', 1)
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=', 1);
    ->execute();


Dont want to redirect after registration, possible?


All is right what you are doing.

You cannot pass additional parts randomly with URL without adding them to menu registry and associating with callback.

Drupal uses $_GET['q'] for default URL path and makes it SEO friendly. $_GET['q'] can contain 9 parts in total in Drupal 7 (7 parts in Drupal 6). Each part can be accessed via arg(n) function.


Is there a ready made gruntfile available for Drupal Bootstrap Child Theme (SASS)

module.exports = function(grunt) {
grunt.initConfig({
compass: {
 dist: {
    options: {
      sassDir: 'sass',
      cssDir: 'css',
      environment: 'production',
    },
  },
},
watch: {
  css: {
    files: ['sass/*.scss'],
    tasks: ['compass'],
  },
},
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('default', ['compass']);
};


What are the advantages or disadvantages of using reference based modules instead of taxonomy module?

There are also other solutions to your problem.

Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the Issue and Magazine are going to be Field Collection type, Issue is a field of Article and Magazine is a field of Issue. I have experience of implementing such structure. In my case the requirement was a Library that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

Entity View Attachment

Also known as EVA module.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an Album. The album contains singer (with some information about each one) and songs that contains a File, Title, Rate and ... . So I created a View of type EVA and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags.

Taxonomy allows you to use free tagging (it can be disabled using Content Taxonomy module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in Entity reference vs. taxonomy). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a Very Reliable Tool for you.


Views conditional referenced field depending on user taxonomy term

I believe your explanation is describing the Reference Field Option Limit module:

  This module allows reference fields of several types to have their
  widgets' available options limited by the values of other fields in
  the current entity.

  This is best illustrated by examples:

  Example 1: countries and cities Suppose you want to label articles (or
  products, or businesses, etc) by both city and country so both can be
  used for filtering and searching. You could use a hierarchical
  taxonomy with city terms as children of country terms, but that
  doesn't make sense when you come to set up Views filters.

  With this module, create two separate taxonomies for country and city
  (or content types, or whatever entity you want to use). Then add a
  reference field so that each city points to its country: eg, the term
  'Paris' has a reference to 'France'.

  Then when editing an article, selecting 'France' in the country field
  will cause the city field to update to show only cities in France.

Give it a try and let me know how it works. The module currently supports Taxonomy terms and Entity Reference Widgets.


How to always print submenus from menu module?

One of the solution is to use Menu Block. It allow you to display any menu items based on depth. So you have all the control. To list all the menus, in Menu Block you can change the "Maximum depth" to Unlimited.

--- Updated 07/06/15 10:25am ---

You may need to use the Advanced options in your situation. Then check the "Expand all children of this tree". See below screenshot for details.


connect to mysql with unix socket instead of tcp

I quickly figured this out after posting. To connect using a socket use 'unix_socket' => '/tmp/mysql.sock', not .socket.

This allows me to connect to mysql using the unix socket instead of the networking IP address, 127.0.0.1. This may be an issue with core since I think by default Drupal should connect on this default socket.


How do I migrate file entities into media entities?

I ended up chosing to do it slightly different - I create a regular file import, set that migration as the source for my media entity reference field, and then applied a second process plugin 'MediaGenerate' to translate the FID to the new media target_id

<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media_entity\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration
 *       source: files
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
if (!isset($this->configuration['destinationField'])) {
  throw new MigrateException('Destination field must be set.');
}
// First load the target_id of the file referenced via the migration.
/* @var /Drupal/file/entity/File $file */
$file = $this->entityManager->getStorage('file')->load($value);

if (empty($file)) {
  throw new MigrateException('Referenced file does not exist');
}

// Creates a media entity if the lookup determines it doesn't exist.
$fileName = $file->label();
if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
  return NULL;
}
$entity = Media::load($entityId);

$fileId = $file->id();
$entity->{$this->configuration['destinationField']}->setValue($fileId);
$entity->save();

return $entityId;
}

}


Try the Visitors module to either use it or help you with your code. It provides many features concerning visitors info and among them is the "unique visitor" feature you are interested in. A similar approach would be also the Counter module.


How can I override the page title using contextual filters?

Most themes output the main page title also into the <title> element in the HTML <head>, usually with the site name appended.

The title you see in the browser tab should be the same as the main title you see on the page, unless your theme does something different (unlikely) or you're using a module that changes the Page title (for example Metatag).

The Override title option is only activated When the filter value IS in the URL or a default is provided. If this option isn't kicking in when it seems it should (either in page title or in the browser tab) then there is no contextual filter or it doesn't validate in some way. This is most likely a problem with your contextual filter configuration.

If you're still having problems please post your Contextuals configuration and what steps you're taking to test it.


Add a new field collection item to an existing field collection

You can try code:

<?php

use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[....]

$node = Node::load(1);

$field_collection_items = $node->field_ckt_info_child2;
$fieldCollectionList = $field_collection_items;
if (count($fieldCollectionList)) {
 //update
  $field_collection_item = FieldCollectionItem::load($fieldCollectionList[0]->value);
}
else {
  //create new fieldconlection
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_ckt_info_child2',
    ]
  );
  $field_collection_item->setHostEntity($node);
  $field_collection_item->set('field_eng', 'HELLO');
  $field_collection_item->set('field_maths_ckt_child2', 'WORLD');
  $node->field_ckt_info_child2[] = ['field_collection_item' => $field_collection_item];
}

$node->save();


Why isn't my controller returning AccessResult::forbidden()?

There is a syntax error here Drupal::currentUser()->id() should be \Drupal::currentUser()->id() and also explode("/", $_SERVER["REQUEST_URI"])[2] gives you only people not the user id, to use User::load.


In admin/structure/types/manage/your_content_type/display  (drupal 7 path) make sure field Body has format "Default" selected. If you have any other format those will remove the div ids and classes from the body.


Is it fine to use hook_entity_view_mode_alter() to intercept an entity view to change the view mode based on an attached field value?

I know it's been a while since you asked...

As far as I can say, if you want use your own module, and not a contributed one, you have to define the view modes using hook_entity_info_alter, for example:

function mycustommodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['mycustommode'] = array(
  'label' => t('My custom view mode'),
  'custom settings' => FALSE, //Or true if you want to allow a certain role to modify it
  );
}

After that, you can use the hook_entity_view_mode_alter from your custom module (not working if you are trying to use in from your template.php in your theme). Hope that helps to anyone coming here from search as I did.


Multisite - Put one alias in maintenance mode

If your multi sites have separate databases than you can simply put whichever (sub)domain you desire into maintenance mode without effecting the other domains.

If you are using the Domain Access Module, you should navigate to that domain's maintenance page and put it in the mode you desire at subdomain.example.com/admin/settings/site-maintenance - see my screen capture


It's an old question but by now this seems to be the module that you needed:
Image desaturate formatter


How do I add an extra css class to my Views rows?

Add the field "Content: Type"
Check "output machine name"
Check "exclude from display" for the type field
For the row class, enter [type]


How to set available/unavailable dates in date webform component?

You may want Date Restrictions module. It restricts allowed values in date fields, and datepicker popup widget, based on several criteria.

The module is still under initial development but may fit your needs. In any case please submit an feature request in the modules' issue queue if there's some missing functionality you find useful.


Code comments in template file show on page

Try

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


Smart IP Not showing Country of the user

To address your edit about the Views filter requirement, there's a submodule included with the main module, called "Smart IP Views Bridge". It has the functionality you're looking for. An extract from its README:

Smart IP Views Bridge exposes Smart IP visitor's location details to
Views field (coordinates, country, ISO 3166 2-character country code,
region, region code (FIPS), city and zip) and filter (country, ISO 3166
2-character country code, region, region code (FIPS), city and zip).

Enable that module and the filters you need will become available in Views.
The README goes on to provide full installation and configuration instructions for Views integration, so it's worth reading it thoroughly.
If solving programatically becomes a requirement:

It's right in the module description:
Other modules can use the function smart_ip_get_location($ip_address) in Drupal 6 and 7 and \Drupal\smart_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code.


You could look at

http://drupal.org/project/textimage

  Textimage adds text to image functionality using GD2 and Freetype, enabling users to create crisp images on the fly for use as theme objects, headings or limitless other possibilities.


This sounds very much like a permission issue. Please check the permissions of

  /home/user/public_html/sites/default/files/2017-02

The directory must be writeable for Drupal. Set its permissions at least to 710. You might want to set them for testing purposes to 755 or even 777 to see if your error messages disappear.


Rewriting the output of a file download field

The "File download fomatter" you're using doesn't output just the path to the file, it's a more complex formatter and you can't use it in your case as a path to download the file.

In Drupal 8 there is a separate Field in File Views called URI that you need to use.

Depending on which Drupal 8 version you're using you'll see only the formatter File URI and you need to tick the option Display the file download URI to get the link you can use in an anchor href attribute later when overriding fields.

Do not enable Link this field to the file download URL, this outputs complex anchor HTML, not just the path that you're after.

You can exclude it from display, position it above the image field and Rewrite results for the image:

{{ image_field }}

or let Drupal link it:


Use Arrays in Twig Template from Custom Block

There is a syntax error in your hook_theme. Use this instead:

function mymodule_theme($existing, $type, $theme, $path){
return array('header' =>
    array(
        'variables' => array(
            'header_title' => 'Default Title',
            'header_size' => 'h1',
            'text_align' => 'center',
            'uppercase' => FALSE,
            'grid_size' => 12,
            ),
        ),
    'product_display' =>
        array(
            'variables' => array(
                'imageurl' => [],
                'product_title' => [],
                ),
            ),
    );

}

The # sign in a render array is used to differenciate a key that has a meaning in the rendering versus an element. It shouldn't be included in the theme definition.


I believe you start with a fresh form in mymodule_member_search_form(), i.e. with $form = array();. Is it correct? If so, your $form['results'] are not in the form returned by mymodule_member_search_form(). You should either do the processing in form callback itself or fetch results from the form prior to redefining it.


Drupal 7 menu translation and url aliases

Setting up a menu per language (as stated in other answer) seems to me more like going around the problem rather than fixing it. I created an issue for it at https://drupal.org/node/2051041 and attached a patch.

Using that patch you don't need to the unnecessary hassle of setting up tons of menu items per language just because the href doesn't render as expected.


Youtube video does not play after clearing the cache

You just need to enter url in the embed_video_field. Following is the sample url
http://www.youtube.com/watch?v=BRWKsjaEtKs

You can set other parameters like height, width using embed video field configuration.


Permit user roles to see node (not via view) based on a taxonomy

You can do your own implementation of hook_node_access in a custom module. It passes you the node and the user object, so you can check for certain criteria, and limit access appropriately.

http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7


Implementation of drupal behaviours in drupal garden sites

Drupal behaviors are just javascript functions, so the answer is pretty simple:

If the service you're using allows you to add javascript to your pages, then yes, you can use behaviors. If it doesn't, you can't.

Syntax will be identical unless the service uses a patched version of Drupal core. If you have reason to believe they might do, it would be wise to get in touch with them directly and ask.


How to search for complete SKU like "K-00019" (without splitting it at "-" and without removing leading zeros)

I made a workaround: I added a computed field to the product type , copying the SKU, removing the dash/hyphen and saving this value. Instead of including the real SKU in the index, I included this stripped version.
At the form part, I added a validation function that removes dashes/hypens from the search input automatically. Just for sake of documentation:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#validate'][] = 'sku_search_validate';
  }

function sku_search_validate($form, &$form_state) {
  if (isset($form_state['values']['my_sku']) && !empty($form_state['values']['my_sku'])) {
    $new_value = str_replace('-', '', $form_state['values']['my_sku']);
    $form['my_sku']['#parents'] = array('my_sku');
    form_set_value($form['my_sku'], $new_value, $form_state);
  }
}


Module to separate the links of menus by language?

I found it, it's a sandbox project though: http://drupal.org/sandbox/TimBrandin/1835360


How to move views pager to different region as a block?

The easiest is probably the comment from @No SSsweat
Another easy option is to place the view in each region and hide the pager/content using CSS depending on region.
The javascript option may be possible depending if you have anything already in place, as you can move the DOM pager element programmatically.
The neater solution is to use some php code, the drupal way, probably someone has already done this for you, so look for a drupal contributed module related to view and pager or paging, and layout, those would probably be my keywords for a search.


Display all comments of node without pager (300+ comments)

It's stored in a variable per content type, you can override it like so:

variable_set('comment_default_per_page_CONTENT_TYPE', 500);

Where CONTENT_TYPE is the machine name of the content type.

If you want to change the options in the UI, you can do it through a form alter:

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node_type'] == 'foo') {
    $new_options = drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300, 500, 1000));
    $form['comment']['comment_default_per_page']['#options'] = $new_options;
  }
}


How to bulk delete Orders in Drupal Commerce module

If you've got 65,000 orders that you need to wipe, VBO isn't an option. You can try this:

TRUNCATE commerce_customer_profile;
TRUNCATE commerce_customer_profile_revision;
TRUNCATE commerce_funds_transactions;
TRUNCATE commerce_funds_user_funds;
TRUNCATE commerce_line_item;
TRUNCATE commerce_order;
TRUNCATE commerce_order_revision;
TRUNCATE commerce_payment_transaction;
TRUNCATE commerce_payment_transaction_revision;
TRUNCATE commerce_paypal_ipn;

TRUNCATE field_data_commerce_customer_address;
TRUNCATE field_data_commerce_customer_billing;
TRUNCATE field_data_commerce_customer_shipping;
TRUNCATE field_data_commerce_line_items;
TRUNCATE field_data_commerce_order_total;
TRUNCATE field_data_commerce_price;
TRUNCATE field_data_commerce_product;
TRUNCATE field_data_commerce_shipping_service;
TRUNCATE field_data_commerce_total;
TRUNCATE field_data_commerce_unit_price;

TRUNCATE field_data_commerce_coupon_order_reference;
TRUNCATE field_data_commerce_display_path;
TRUNCATE field_data_field_order_deliveryinstructions;
TRUNCATE field_data_field_order_flags;
TRUNCATE field_data_field_order_id;
TRUNCATE field_data_field_order_notes;
TRUNCATE field_data_field_supplier;

TRUNCATE field_revision_commerce_customer_address;
TRUNCATE field_revision_commerce_customer_billing;
TRUNCATE field_revision_commerce_customer_shipping;
TRUNCATE field_revision_commerce_line_items;
TRUNCATE field_revision_commerce_order_total;
TRUNCATE field_revision_commerce_price;
TRUNCATE field_revision_commerce_product;
TRUNCATE field_revision_commerce_shipping_service;
TRUNCATE field_revision_commerce_total;
TRUNCATE field_revision_commerce_unit_price;

TRUNCATE field_revision_commerce_coupon_order_reference;
TRUNCATE field_revision_commerce_display_path;
TRUNCATE field_revision_field_order_deliveryinstructions;
TRUNCATE field_revision_field_order_flags;
TRUNCATE field_revision_field_order_id;
TRUNCATE field_revision_field_order_notes;
TRUNCATE field_revision_field_supplier;


Restrict forum access based on user (user list)

If you use views or panels to display the forum, you can use their access controls which are quite flexible. Doesn't look like AF has built views for everything, so I think the easiest way would be to use Panels.
Create a page and under the page settings you have access rules that can be quite elaborate within the UI. You can use a naked layout and then just had the forum entities as content to display and render the full node.
Second Look:
Take a look at the Drupal Module Flexiaccess. It looks like exactly what is needed and has a nice UI to manage the users that have access to the individual forum with out writing/maintaining custom stuff:

The Flexi Access module will provide a simple and flexible interface
to the ACL (Access Control List) module. It will let you set up and
mange ACLs naming individual users that are allowed access to a
particular node.
The module let you manage access to individual nodes. The
administrator may grant individual users the right to: View (read),
update (edit/write), and delete the node.
The main idea behind Flexi Access is to allow flexible per user access
control for nodes without the complexity (or features) of Organic
Lists, and without having to create a lot of (overlapping) roles.

I see you using Flag to set up the "subscription request" then a moderator looks at the flagged users with the Flag and if approves add em to the ACL with flexiaccess?


There is an issue with streaming video from the private folder because Drupal handles the permissions rather than apache. Use the resumable download module to overcome this. You should be able to enable the module and you are good to go.


D7 Rules - User Profile Field in Send Email Action

I might try the Rules Token module (if you haven't already). It might contain what you need


How can I use Entity API to integrate my entities with views?

You dont create views integration for bundles but for entities. The reason is that each bundle by definition stores it's core data the same way.

Think of node types = bundles. When you create a view you select to use nodes (Content) not if you want to use articles, pages, blog posts etc.


Installed a module, broke my site. And now I have no way to turn it off

Just remove the module folder and the site will work again. And do a clear cache. I'm not sure if it leaves any orphaned entries in the Database. If so, how would one delete them?


Custom module with custom node type, error Trying to get property of non-object en comment_node_type_delete()

I believe the problem is that it's expecting an object, and you are passing a string. Try changing this:

node_type_delete($ournewtype);

To this:

$node_type = node_type_load($ournewtype);
node_type_delete($node_type);

One other thing, instead of this:

$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
    $nodeids[] = $row->nid;
}

You can simplify it by using this:

$nodeids = db_query($sql, array(':type' => $ournewtype))->fetchCol();


How to use date_make_date() in drupal 7?

The alternative to the date_make_date function in D7 is the DateObject, which extends the PHP DateTime class.

To make your code work properly, you'd do something like this (untested):

$local_date = new DateTime($dateTxt, $timezone); //$timezone can be string or object
$iso_date_string = $local_date->toIso(); //returns the ISO string for the date
$utc_date = clone $local_date; //don't want pass by reference
$utc_date->setTimezone(new DateTimeZone('UTC')); //set the new timezone to return
$utc_date_iso = $utc_date->toIso(); //returns $local_date converted to UTC as an ISO string.

I'm not totally sure what you want to do, but this, hopefully, will get you on the right path.


How to hide webform label from email only?

It would take quite a bit to edit the email templates. The truth is that this is design behavior, because labels

The better way to do what you want is to put that text in the help/description field of the component and then style it with CSS. That text is not included in the email.


In the javascript you should format the data as an object:

data: 'js=1'

replaced with

data: {js: 1}

The problem with the redirect is most likely an JS error caused by the returning value of the ajax callback. To be able to spot it you can hardcode the url in development and change the link simple be xx, that would prevent a new page from loading in case of JS errors and would give you the possibility to read the error log from tools like firebug. Another options would be to insert breakpoints in your JS code, which can be a bit more tricky.


My pager disappears when I use hook_views_pre_execute

if query exec is too long (for pagination views must return total count of rows at all pages and correspond it to rows per page ) pagination not returned by views.

nid of nodes returns from one table in database and this queries is very simple & fast

another fields (cck, ubercart, stock) returned from another db tables and it can be too long. for this views just returns first page to prevent timeout


here is a rough sketch of how you could go about this:

iOS Side: Add a node using DIOSNode's add

Drupal Side:

Create you own custom content type, e.g. CustomMessage, with a UserID field for collecting the target user of each message. This could be a simple text field, or an Entity Reference field, single or multi-valued.
Create a Services View that will use a user's UID as a contextual filter, in order to display all messages targeted at a specific user.


How to implement access permissions per individual field and individual nodes?

Not sure if it is going to be the best/most elegant solution, but here is "an" approach that might work:

Use the Entity reference module to replace your file field in your existing content type with a reference to some other content type (say Resource).
Attach your files to nodes of content type Resource (so not in your already existing content type nodes).
Use the Content Access module to implement the refined access that you are looking for, but applied to that Resource content type.
Create some testcase(s) to verify how that refenced Resource node is going to be shown in your original nodes.

Get the idea? Pretty basic Drupal techniques (to KeepItSuperSimple, aka KISS).

I haven't tested it (yet) while writing this answer, but I bet functionally it will behave exactly as what you'd want. And guess what: no need for the field permissions module to make this work.

FYI: the above is a D7-equivalent of how I used to create such kinds of related content in D6 already (also using the Content Access module, and I believe in D6 it was "node reference" or something like that).


Ubercart Ajax change attributes on checkout

This may not be the best/proper way to do it, but I have manipulated product attributes in

function uc_cart_view_form($form, &$form_state, $items = NULL)

it is located in uc_cart.module

$items is filled with products and you can loop through and review/assign attributes.


How to migrate fields attached to files?

You need to specify the bundle type when registering the dynamic migration:

  $image_args = array(
    'machine_name' => 'images',
    'class_name' => 'MyModuleImageMigration',
    'description' => t('Migrate images'),
    'user_migration' => 'users',
    'default_uid' => 1,
    'source_dir' => 'http://example.com/sites/default/files',
    'destination_dir' => 'public://',
    'skip_pictures' => TRUE,
    'bundle' => 'image', // Need to add the bundle type
  );
  Migration::registerMigration('MyModuleImageMigration', 'images', $image_args + $common_args);


How do I programmatically translate a string?

you have find and add your translation string here : admin/config/regional/translate


So I found a solution that works for me.

Modules used:

Display Suit
Display Suit Extra
PHP filter
(I hope I didn´t forget one)

Here is how I did it ...

1.Go to a Profil

2.Click on "Edit"

3.Switch to the tab "Manage display" (right upper corner of the overlay)

4.scroll down to "custom fields" and click it

5.click "Add a code field"

6.check "User" on "Entities" and change the Text format in the "Field code" to "PHP code"

7.Now type the following in the "Field code" (Add/Change the Roles You have)

<?php $account = user_load(arg(1));?>

        <?php foreach($account->roles as $role): ?>
            <?php if($role != "authenticated user"): ?>
<?php //--------------HERE YOU NEED TO ADD/CHANGE THE ROLES YOU HAVE------------------- ?>
                    <li class="user-role- <?php
                    if($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }
                    elseif($role == '[Your Role]'){ echo 'user-role-[your role]'; }?>">
<?php //------------------------------------------------------------------------------- ?>
                    <?php print $role; ?>

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

Press "Save"

That´s it. I hope it works for You too.

(Again I apologize for my bad English. It can gladly edit for correcting my grammar)


You will need to implement mytheme_preprocess_rate_widget() and write your own version.

Notice how $variables['buttons'] is set halfway down the function in the original question. Since preprocess functions for a particular theme ALL get run, you can't (that I know of) stop the rate module running its preprocess function, but by re-assigning $variables['buttons'] in your own mytheme_preprocess_rate_widget() function, you will be able to control the output there. I would suggest something like:

function mymodule_preprocess_rate_widget(&$vars) {
  extract($vars);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', 'my custom text here', $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $vars['buttons'] = $buttons;
}


how to upgrade drupal 7 site to universal analytics

I found out that there will be no effect in the meantime on the existing google analytics behaviour, just that the new UA functionality will not be available.


How enable PHPMailer to write complete persistent log?

It's not clear from your question what Drupal version you are on. But the Maillog / Mail Developer module might be handy here. Some more details about it (from its project page):

  ... provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the Devel dpm() facility.

But you might get integration problems, since it's not easy and highly Drupal version dependent to get more than one email module at a time working.


Is there a way to check if a custom form element exists in application

You can invoke the hook yourself to check for the existence of a specific element type:

if (in_array('some_element_key', array_keys(module_invoke_all('element_info')))) {
  // The element type exists.
}


Private Files System - Media upload works, but image is not displayed

For the image to be displayed, you would have to have access to the private folder, but since you're an anonymous user to the webserver, it won't display.

Images being served on your website should be in a public folder.
Downloads could come from a private folder if the webserver/Drupal moves them to a temp directory before downloading them.


hook_form_commerce_checkout_form_checkout_alter() changes are not reflecting on checkout page

Should it not be that the arguments are passed by reference?
You are not returning anything, therefore any changes you make within the function will have no affect outside it's scope.

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id){
....
}


How do I assign variables from FormatterBase-Interface to hook_page_attachments()?

No, you don't want to do this.

You can set #attached everywhere. hook_page_attachments() is just the global hook that allows to add attached things to all pages.

But you don't need this if you want to use #attached for own structures, just add them to your render array that you return.


During checkout, why is the customer skipping the payment step?

With Commerce Paypal, I ran into the same issue.
I believe the fix for me was to the move the Payment Information (currently disabled) into the Order Information section. Might also work if you move into Review or Payment section, not sure.
Also, since you're using Paypal, I think you need to disable payment process.
Here is my working setup. Note: I didn't want users to login nor register.


How to pass computed data from Theme preprocess functions to Twig templates?

$variables is an array, not an object.

But yes, it's the one and only way to pass additional data to the template. Anything you put in there is available in the template then. $variables['hello'] = 'world'; can be printed with {{ hello }}.


Order Total not updating after I change the line item price

The solution was to use commerce_price_add_component()

    $line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
    $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
        $line_item_wrapper->commerce_unit_price->value(),
        'base_price',
        array(
                'amount' => $booking_price,
                'currency_code' => 'AUD',
                'data' => array(),
        ),
        TRUE
);
}


How to let site member to access vertical tab?

It depends on which tab you're talking about. The highlighted one, Menu settings, is controlled by the Administer menus and menu items permission. Many of the vertical tab items is granted by the Administer content permission.


Drupal aligning blocks and content next to each other

You can make use of  Panels Module to achieve any kind of Complex Layouts


Variables are missing on page--node--add.html.twig

if ($node = \Drupal::routeMatch()->getParameter('node')) {

There's no node ID in the route at /node/add/foo, so there's no node available, and that condition will always be false.

You need to create the node yourself, e.g.

// Get the desired type from the route.
if ($node_type = \Drupal::routeMatch()->getParameter('node_type')) {
  $node = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->create([
      'type' => $node_type->id(),
    ]);

  $form = \Drupal::entityTypeManager()
    ->getFormObject('node', 'default')
    ->setEntity($node);

  $variables['node_form'] = \Drupal::formBuilder()->getForm($form);
}


How to sign-in a user based on custom HTTP headers in Drupal 8?

That sounds like a very insecure way of allowing admin access to your site.  Seems like a hacker just has to fake the header in the request to get access.
That said, you probably want to look at the various http authentication modules for Drupal 8 (E.g. google drupal 8 http authentication).  Some quick starter links about this in core are:
https://www.drupal.org/docs/8/core/modules/basic_auth/overview
https://www.drupal.org/docs/8/api/authentication-api/overview
As with most open source systems, the best way to figure out how to do something like this is to find code that does something similar and modify it to meet your needs.


Exposed date select list in descending order

You can do this via hook_form_alter().

function myModule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'FORM-UNIQUE-ID') {
    $form['field_MY_FIELD_value']['value']['#process'][] = date_select_desc_element_process;
  }
}


Alright, so this is slightly hackey, but I got this to work. I totally gave up on trying to set a default value in the render array, and instead did the drupal_render and set it to a variable. I then modified the html directly in the variable. The code I originally posted now looks like this:

if(isset($id) && is_numeric($id)) {
  $newrender = drupal_render($newdata);
  $newrender = str_replace('value="'.$id.'"', 'value="'.$id.'"  selected="selected"', $newrender);
}

$commands = array();
$commands[] = ctools_modal_command_dismiss();
$commands[] = ajax_command_html('#measure-data-source', $newrender);
print ajax_render($commands);
exit();

If anyone on here has a more elegant solution, I'd be happy to know the "correct way" of doing this, but this produces the desired result.


Show modal modal message on form success

Here is what i came up with (many thanks to @4k4):

    public function ajaxCallback(array &$form, FormStateInterface $form_state) {

        drupal_get_messages(); // Hide messages

        $form_state->setRebuild(TRUE);

        if ($errors = $form_state->getErrors()) {

           return $form; // Simply Return the form
        }
        else {

         $response = new AjaxResponse();

         $title = 'Consectetur adipiscing elit';
         $text  = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

        $response->addCommand(new OpenModalDialogCommand($title, $text));

        // Or add the $form as parameter to an HTML command.
        $response->addCommand(new ReplaceCommand('#my-form-wrapper', $form));

        // Do notice i added a wrapper to my form in the buildForm() method:
        // $form['#prefix'] = '
';
        // $form['#suffix'] = '
';

         return $response;
    }


How can i populate data from a reference node into another content type?

Take a look at entityreference_autofill

  The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


You need to use theme_menu_item_link()

The following is an example that I pulled from an old site:

function THEME_menu_item_link($link)
{
    if (empty($link['localized_options']))
    {
        $link['localized_options'] = array();
    }

    //Give this menu item a unique id
    $link['localized_options']['attributes']['id'] = 'menu-item-' . $link['mlid'];

    //Not sure if this is the cleanest method, but it should allow us to follow
    //the active-trail across menu items, based on path.

    //Get the start of the current path (e.g. admin/build/modules would be admin)
    $base_path = preg_replace('/^([A-Za-z0-9_-]+)\/(.*)/', '${1}', drupal_get_path_alias($_GET['q']));

    //Get the current link we're looking at
    $this_link = drupal_get_path_alias($link['href']);

    //If the
   if($base_path == $this_link)
   {
       $link['localized_options']['attributes']['id'] = 'menu-active-trail-' . $link['mlid'];
   }

   return l($link['title'], $link['href'], $link['localized_options']);
}


My theme CSS uses relative paths, but Advagg or another module seems to be rewriting them to absolute paths. Core aggregation uses relative paths

This is an intended feature of AdvAgg, see Mike (one of AdvAgg maintainer)'s issue on Drupal.org where a 'do not convert' option has been raised as a feature request.


This is how to disable the field:

$form[$key]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';


Drupal doesn't support HTML e-mails out of the box.  To do this, you can download either:

Mime Mail

or

HTML Mail

You will also need the Mail System module.  On my own site, I use the Mime Mail module with a PHP template that I designed (following the instructions in the Mime Mail documentation) to attach my logo to outgoing e-mail messages.


How can I change a page's title for each page individually?

You can use a module that allows you to change it each time or use a different pattern than default Drupal:

Metatag

This module allows you to control a lot more than just the Page title.


The easiest option would be to add an ID to each link like link_printer and then use jQuery to parse the url, get the last fragment, and click any links that match.

var splitURL = window.location.href.split('/');
var link_id = '#link_' + splitURL[splitURL.length - 1];
if ($(link_id).length > 0) document.querySelector(link_id).click();


add condition in apache solr serch query

You can use hook_apachesolr_query_alter()

  Alter the query after it's prepared and cached.

Example from the docs page

function hook_apachesolr_query_alter($query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}


You can read more about db_query() here.

$result = db_query("
  SELECT title
  FROM {node} n
  WHERE n.type = :type
    AND n.uid =:uid
", array(':type' => 'outlets', ':uid' => $uid));

foreach ($result as $record) {
  // Perform operations on $record->title, etc. here.
  // in this example the available data would be mapped to object properties:
  // $record->nid, $record->title, $record->created
}


Let authenticated users (non-admin) reorder uploaded images using the 4-way arrow

Turns out the draggable link is present, but only the bottom 10% of it, and the 4-way icon does not get rendered, even though the background is set in css.

This problem is due to the import of scaffolding in the the bootstrap scss file.


I personally use tinyMCE on my sites, it's not heavy, and you can use the IMCEbridge.

This module will install the WYSIWYG API, then follow these instructions for adding TinyMCE or any other you want.

The IMCE Bridge module can be found here and is compatible with CKEditor, FCKeditor and TinyMCE.


File in field_file disappears after saving a node

The File module enables you to upload and attach files to content and to manage these uploads if you have the appropriate permissions. This module is responsible for validating file content and managing uploaded files. It also provides options for displaying file content.

As a site administrator you will be able to control what type of files can be uploaded and their maximum size.

File module provides its functionality by defining a File field type for the Field module. File attachments are defined at the content type level (or other entities). To learn how to define a field and add it to a content type, see Working with Field UI.

Uses
Adding a file field to a content type

Navigate to the "Manage fields" tab of the content type to which you wish to add the file field (Administer > Structure > Content types, and the link manage fields for your specific content type).

Select the field type file, give the field a label and machine name, click-and-drag it to the place you want to have it among your fields, and hit the save button.

As when adding any new field, you are first required to set the field specific settings. These apply for all places where you use the field. These cannot be changed per entity.

When checked, the Enable Display field option allows users to choose if a file should be shown when viewing the content.
The Files displayed by default option makes the display file option checked by default, when users upload files to this field.
The Upload destination by default only has the public files option available – making the files available right from the server (without Drupal checking any access). If you want to use private files, you must first change some settings at the file system administration page (Administer > Configuration > Media: File system). See below for details.

The next step is to set the field settings for this instance only. This can be changed between different content types (or other entities).

You can add validation options for the File field when you configure the content type. You must list all of the file extensions that the final user will need to be able to upload. The optional file directory where the files will be uploaded is a sub-directory of the file system path defined in the file system administration page (Administer > Configuration > Media: File system). You may specify a maximum file size for each file uploaded.

Managing attachment display

Once a file has been attached to content, you can specify whether it will be displayed in the list of attached files or not. Listed files are displayed automatically in a section at the bottom of the content; non-listed files can for example be embedded in your content, but are not included in the list. (Embedding a file in your content means you copy the path of the file and manually embed it where you want, for example, to insert in the content as a link tag. Note that the text format "Filtered HTML" by default refuses any image tags..)

Additional options for managing the display of the file list are available in the "Manage display" tab of the specific content type's administration page (Administer > Structure > Content types and the link field display for your content type).

For reference: Working with files in Drupal


How to programmatically search content with a specific taxonomy term with Search API?

Yes that's right to do addCondition here's a page with some examples https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

So you'd just need to do the machine name of your indexed taxonomy field

$query->addCondition('my_indexed_field', $myvalue)


Send a context from a panel page to a view integrated in it?

First thing to do is fix your view. In order to have author ID as a filter you need to add the "Content: Author" relationship. After adding that you will see a lot more options for User in the fields and filters. You can now chose "User: UID" for your contextual filter.

Next thing to do is to edit your panel. Add a user context to your panel and chose "Select a user" for the context type. Type in the username of the user and check "Reset identifier to username."

Now go to your panels content and edit the view settings. You should see the "User: UID" context at the top. Choose the "User ID" from the drop down.

You should now only see content from the user you chose in the context when viewing that panel page.


Can't populate integer value in title field using rules

Title is a string, that's why, in your rule, before setting title value, add a variable, then set variable value to the integer value, then add an action: "convert a data type": your variable, from integer to string, then set a data value, your node title as variable name. else leave the same as it is.


If anyone else lands here looking for an answer, after going around in circles for many many hours, I found out the solution.

When I gave up and was about to recreate a core component in order to overcome this issue, the first thing to do was to delete this taxonomy term, however, Drupal flagged to me that it'd affect the Access Scheme / Taxonomy Main. Interesting, so I decided to Google it, I found out this text came from a component called Workbench Access, which among other things could manage a Scheme for Taxonomy. Looking into installed modules, I indeed had it installed. Bingo. However, I had no access to it (that's why I never actually found it).

The old developer (which I no longer had access to), made me "Admin" of the system as part of his handover. However, this component was hidden for all users, but his.

After copying my hashed password, replacing his with mine, and logging in as him, I could see this component on his user homepage, which was just a matter of disabling it for State Owner and voilá. Working like a charm.


Comment author name = user name by default?

Well, correct me if I'm wrong, but from what I know (and based on a check I've just done in D6 sandbox) logged-in users do not have option to change their name, they see their username displayed in normal text instead of form textfield. So that's exactly the behavior you're looking for?


You might consider using Open Calais or Auto Tags to tag all your content. Open Calais will require a little configuration. It works wonderfully with Similar Terms.


You could just shrink the database by optimizing every MyISAM you have

You can use to monitor how much space you database is taking up (in MB):

SELECT
    IFNULL(dbtb,'Total') tablename,
    (datsize+ndxsize)/power(1024,pw) table_size
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb,
    data_length datsize,index_length ndxsize
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A,(SELECT 2 pw) B
GROUP BY dbtb WITH ROLLUP;

This will add up all used data and index space.

I have other queries for measuring the amount of used space for MyISAM and InnoDB

https://dba.stackexchange.com/a/1307/877
https://dba.stackexchange.com/a/5708/877
https://dba.stackexchange.com/a/18952/877

If there is significant difference between in these queries' output and what your OS says you are using, try shrinking each individual table as follows:

SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') OptimizeCommand
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A;

Export the output of this query to a SQL text file and run it:

SQLFILE=/tmp/OptimizeSQLScript.sql
SQLCMD="SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') FROM ("
SQLCMD="${SQLCMD} SELECT CONCAT(table_schema,'.',table_name) dbtb "
SQLCMD="${SQLCMD} FROM information_schema.tables WHERE table_schema NOT IN "
SQLCMD="${SQLCMD} ('information_schema','mysql','performance_schema')) A"
mysql -u... -p... -ANe"${SQLCMD}" > ${SQLFILE}
mysql -u... -p... < ${SQLFILE}

An even faster way without fancy parsing would be to mysqldump the entire dataset and reload it

mysqldump -u... -p... --all-databases --routines --triggers > mydata.sql
mysql -u... -p... < mydata.sql

Give it a Try !!!


Can you temporary grant a user permission to avoid captchas in drupal 7?

There are basic problems with your approach:

All anon users are one user for Drupal. They share common UID 0, so they are one user. And HTTP is a stateless protocol, so you can't decide "it's the same user" basing on connection. In Drupal 7 sessions are not guaranteed for anonymous users, so you can't use them reliably for that purpose either.
If you will try to modify $user->roles, it will add a role for current http call all right, but it will not regenerate caches, like admin/reports/status/rebuild or views caches based on roles.
hook_init docs says: This hook is not run on cached pages.

So, this is no-go by design, and if you need to give some privileges or options by browser session, you need to implement your own solutions, like cookies. There is a list of modules that works that way, you can use their code for reference.


Changing the default "View" page when user logs in?

I think the Login Destination module may help you.


What does "The provided host name is not valid for this server" mean?

This error message is coming from a feature that was added to Drupal 8 to protect against HTTP Host header attacks.  The feature is also described in the change record that was generated for the patch.

Essentially, it was possible to spoof the HTTP Host header for nefarious purposes, and trick Drupal into using a different domain name in several subsystems (particularly link generation).  In other words, the HTTP Host header needs to be considered user input, and not trusted.

To combat this, a new setting, $settings['trusted_host_patterns'], was added to Drupal 8 to configure a list of "trusted" hostnames that the site can run from.  The setting needs to be an array of regular expression patterns, without delimiters, representing the hostnames you would like to allow to run from.

For example, if you are running your site from a single hostname "www.example.com", then you should add this to your settings (usually found at ./sites/default/settings.php):

$settings['trusted_host_patterns'] = array(
  '^www\.example\.com$',
);

Note the ^, \., and $.  These are PCRE Syntax.  These just mean that you want to match "www.example.com" precisely, with nothing extra at the beginning and end, and that the dots should be treated as dots and not wildcard characters.

If you are running from "example.com", then just use:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
);

If you need to run a site of multiple domains and/or subdomains, and are not doing canonical URL redirection, then your setting would look something like this:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^.+\.example\.com$',
  '^example\.org',
  '^.+\.example\.org',
);

This allows the site to run off of all variants of example.com and example.org, with all subdomains included.

Once you adjust $settings['trusted_host_patterns'] to the proper value, you should be able to browse to your site again.

You can also check on the status of your trusted host settings from the status report page, which is at admin/reports/status

If you remove the setting altogether, the trusted host mechanism will not be used, and you will see an error on the status report page.  In addition, your site may also be vulnerable HTTP Host header attacks.

If you have this setting configured and are seeing this message, then it probably means you have messed up the regular expression syntax.  In this case, take the first example, and copy/paste into your settings, and then edit it to reflect the hostname your site runs from.


I had the same problem. Solved it by editing the content of the block.
(we logged in as admin you see a button in the right upper corner, click it and select Edit). It appeared the the translated content was not published.


You can implement template_preprocess_user_profile

In your theme's template.php file add:

function MYTHEMENAME_preprocess_user_profile(&$vars) {
  $vars['user_profile']['last_login'] = array(
      '#markup' => t('Last login') . ': ' . format_date($vars['user']->login, 'medium'), // prints the actual last login time using the medium date format
      '#weight' => 99, // defines location
  );
}

Clear the cache and check the user profile page (e.g. /user/1)


The users table doesn't have an auto-increment constraint on the primary key (or any field).

The recommended way to add users is using the API (user_save() etc), that will handle the ID for you.

Failing that, just query for the maximum ID in the table before you perform the insert; after the first insert, assuming you have exclusivity on this database while you're developing, you can maintain the increment in your code (no need to check the table each time).

Drupal does exactly the same thing in user_save():

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());


Add a New [content type] on each content type

In the hook that return the block content, call a function with a code similar to the following one.

function mymodule_node_add_link() {
  $node = menu_get_object();

  if (!empty($node->type)) {
    $types = node_type_get_types();
    return l(t('Add a new @name', array('@name' => $types[$node->type]->name)), 'node/add/' str_replace('_', '-', $node->type));
  }

  return '';
}

The hook calling this function should always check the value returned from the function. In the case the showed page is not a node page, menu_get_object() doesn't return a node object, and this function returns an empty string.

Notice that every string shown in the user interface should be passed to t(). When passing a string to t(), you should avoid concatenating string, but you should use the placeholders the function supports, as in the code I shown.


Because of the new Proudly Found Elsewhere standard, Drupal doesn't have its own client.

It does however include Guzzle, a well respected library. You can use that to make your REST calls, or of course include and use another library if you wish.

You can get to the Guzzle client in a default Drupal 8 install through the http_client service:

$httpClient = \Drupal::httpClient();

And the docs for Guzzle are here.


I had to do something similar recently. I created a views page and outputted the same Date field twice. I also had two different date formats set up. One showing only Month and Day, and the other format only showing time. Then I assigned the first "Date" field the date format, and the other the "time" format. Afterwards I was able to style them as I pleased.

In the field date settings, I had it to where it also showed multiple, but only first and last with a " - " seperator in order to output "September 11 - September 14" for example. The same can be done for the time formatted field.