How do you add type-property schemas from Schema.org into 8 sites?

Yes, there's a Drupal 7 module of the same name, schema.org.

  This project is a drop-in solution to enable the collections of
  schemas available at schema.org on your Drupal 7 site. The major
  search engines including Bing, Google and Yahoo! have agreed to
  recognized these in order to improve the display of search results.

Along with the core module, there's a UI that makes it pretty easy to setup; you specify the schema.org type on the content type settings page & then you specify the schema.org property names on the field settings page. It also has support for address field & fivestar fields.

In Drupal 8, the project has deferred to the RDFUI project, to provide the UI component, now that other parts of the module have been ported to core.

  The default RDF mappings of Drupal core have been updated to include
  schema.org in Drupal 8. Also, a lot of the backend code of this module
  was ported into Drupal 8 core. The User Interface allowing to set the
  mappings lives in the RDF UI, which is based on Sachini's Google
  Summer of Code project.


This is a user template from Drupal 8. Check detail here or below code.

{#
/**
 * @file
 * Theme override to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 */
#}

<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

Please see the comment code. If you want to render your custom field in template, just content.<your_custom_field>.
With your example is content.field_author_bio.

In case your field's content when rendering is not your expectation, you maybe need to use template_preprocess_user() for preprocessing content before rendering in the template (Search more about this function if you need).


Change navigation (sublinks) according to main menu (headlinks)

The easiest way will be to create a menu for each top level menu page.

Then put all those menus as blocks in your sidebar region, with a rule so they only appear on the correct page, or subpages.

E.g.

Menus:

Top Menu:  Home | News | Blog
    // show on all pages

Home Menu: Info | About
    // show on home and home/*

News Menu: Current | Archive
    // show on news and news/*

Blog Menu: My Blogs | Other Blogs | Archive
    // show on blog and blog/*

Pages

/home
/home/info
/home/about
/news
/news/archive
/blog
/blog/other
/blog/archive

So, step by step instructions would be:

Create a main menu for your site.
Add items for Home (URL: /home), News (URL: /news) and Blog (URL: /blog) to your main menu.
Create another menu called Home.
Add pages info (URL: /home/info) and about (URL: /home/about) to this menu.
Add this menu to your theme in a block. Set the block visibility to only appear on "home" and "home/*". This is the clever bit because the submenu for home page will appear on the main /home page, and also any subpages of that as long as you follow the url structure.
Repeat same process for the news and blog menu so now each of your sub-menus only appear on their specific pages.
Do a little dance (can even have a sing if you want).
Done.


Override _user_mail_notify() to NOT send email on user_save() if user status is changed

Maybe you should take a look at drupal_mail function

// Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
drupal_alter('mail', $message);

// The original caller requested sending. Sending was canceled by one or
// more hook_mail_alter() implementations. We set 'result' to NULL, because
// FALSE indicates an error in sending.
if (empty($message['send'])) {
  $message['result'] = NULL;
}

Then hook_mail_alter

From description

  $message: An array containing the message data. Keys in this array include:

  'send': Set to FALSE to abort sending this email message.

  'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before
  hook_mail_alter() is invoked.

Parameters usually contain $message['params']['account'], so you can abort e-mail sending by role or other way.

Example (not tested) aborting any e-mail to account with specific role:

function MY_MODULE_mail_alter(&$message) {
  $role = 'CUSTOM_ROLE';
  if (!isset($message['params']['account'])) return;
  $account = $message['params']['account'];
  if (is_array($account->roles) && in_array($role, array_values($account->roles))) {
    $message['send'] = NULL;
  }
}

There is an issue then sending custom e-mails, $account contain sender account object, not receiver. But for default notifications this should work. So don't forget to check $message['key'] for default notification types from _user_mail_notify, it always provide $account object mail is sending to:

'register_admin_created': Welcome message for user created by the admin.
'register_no_approval_required': Welcome message when user self-registers.
'register_pending_approval': Welcome message, user pending admin approval.
'password_reset': Password recovery request.
'status_activated': Account activated.
'status_blocked': Account blocked.
'cancel_confirm': Account cancellation request.
'status_canceled': Account canceled.


Showing a message for specific content type

$node->type is a reference to the node type config entity - it's not a string.

You can use NodeInterface::getType() instead, e.g.:

if ($view_mode == 'full' && $node->getType() == 'test_content') {

}

Incidentally you could also use $node->bundle(), or even $node->type->entity->id(). But getType() is probably most appropriate for your specific needs.

You also have the function signature wrong - it should be:

function test_module_node_view(array &$build, \Drupal\node\NodeInterface $node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)


Identify what template it is using with Themer. Override it and use t() function to wrap those strings needed to be translated.


How obtain the uid of the logged user as a related field in a view?

You can't without some custom module providing such a data field (such as views php as you've seen).

Unless the uid has some relations to the content type you're displaying (e.g. a user reference field, the node uid, etc.), there's no way to retrieve the current UID. Views is designed to pull in data from a base table (e.g. nodes, users, taxonomy, etc.) and display the fields directly attached to it or related to it through a relationship.


Try:

$ drush ev 'print ini_get("memory_limit");'

This should print the memory_limit value set for Drush.  -1 means no limit.


Colorbox trigger builds clunky html instead of array

This is unfortunately just the way the colorbox module works.

Because it is possible to put any content in a views colorbox it is set up to handle anything in a very generic way, which means it doesn't handle single images in the most effective way and the trigger field way of configuring things is more complex than is needed in some cases.

I opened a similar issue about resizing the colorbox based on images, which you also cannot currently do because of the same issue of the way it has been implemented.

It is something I believe the module maintainer could fix though.
I would recommend opening a feature request issue on drupal.org at https://drupal.org/project/issues/colorbox?categories=All


How do you strip HTML from the node summary that appears on taxonomy node listing pages?

Within node--taxonomy.tpl.php, you could isolate the field data for your teaser or any field, depending on how you have that template set up, and apply the php strip_tags to that field data.

For example:

$teaser = render($content['body'][0]);
$textteaser = strip_tags($teaser);

This video is a great starting point for learning about the theming templates if that is new: Theming Fields and Nodes with Templates

One other idea is to isolate the div that wraps each teaser (if possible) and use jQuery to transform the content using the relevant CSS selector using .text() method.


How to translate the description, and abstract metatag for the front page in a multilanguage site?

My solution was to install and enable  the Translation table module. Then follow these steps

go to admin/config/regional/translate/translate
then filter by metatag and it will show all the metatags that you can translate.

That’s what it worked for me. If you have better solution please add it.


You can remove local actions within hook_menu_alter().

If this is a generic action it will be removed on all of those forms. E.g. local actions for nodes - changes would be seen on all content types.


Hiding menu item depending on specific access

I found by myself my mistake.

The menu items are always shown for super user.

The menu items are hidden/shown correctly for others users.


How can I render multiple values which belong to the same field?

Just don't use first() - that gets the first item.

if ($field = $node->field_contact_person) {
  foreach ($field->getValue() as $value) {
    $item_value = $value['value'];
  }
}


In your node--blog.tpl.php add unset ($content['links']['blog']['#links']); instead of hide($content['author']);


How can a field be rendered as a  element?

try to return drupal_add_html_head array directly

<?php

function THEMENAME_field__field_test($vars) {
    return drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');
 }


I just want to move this login button up above the create new account and request new password. How?

You can use hook_form_FORM_ID_alter in your custom module and change the weight of the links

function MYMODULENAME_form_user_login_block_alter(&$form, &$form_state){
  $form['links']['#weight'] = 100; //define weight as such the links moves below  submit button.
}

Replace "MYMODULENAME" with the name of your custom module.


I think the trouble comes from your browser. See the answer from this question :
How can I create a link to a local file on a locally-run web page?

  Some browsers, like modern versions of Chrome, will even refuse to
  cross from the http protocol to the file protocol, so you'd better
  make sure you open this locally using the file protocol if you want to
  do this stuff at all.

Maybe another approach is to make a script witch will get the file from the server side and send it to the client in streaming.


Why is a new post not shown in the Latest Topics Block after updating Advanced Forum?

Some problems get resolved just by being patient for a while. Some of those problems are caused by either of the following:

You should have cleared the cache.
Something required a cron job to run.

If such kinds of actions are not performed (eg because you're not aware they are needed), it is just a matter of time to get such problems resolved automagically ... as illustrated in this specific comment (last paragraph) also.


How to alter node body content through Views pre render hook?

What variable are you modifying? When I modify Views results I usually use hook_views_post_execute. I then modify the appropriate element in $view->result. You may be able to do the same from hook_views_pre_render (I don't use that one often especially in this type of case).


views contextual filter by current year missing granularity

I think you need to use specific granularity field that you wish to add.
like there are multiple option given in contextual filter which are as under.

Created year >> Content Date in the form of YYYY.

in that field you can specify in "Provide default value"  as "current date".


Is there a way to tell a browser to not cache a particular custom page?

If I understand your expectation correctly, it's less of a Drupal and more of a browser thing. When the user presses the Back button, if you don't want the browser to show a copy of the web page that it might already have, the Cache-Control header in your initial response must have no-store. Drupal by default, doesn't have this. You can confirm this by checking the definition of this function.

Simply overwriting the Cache-Control header seems to fix this on Opera 16, Firefox 23 and Chrome 30. However, on Safari 6, it doesn't. Turns out that it might be a known issue. So, we might have to turn to a Javascript hack for that.

In summary, including the snippet below in your page callback should do the trick for you. I have assumed Drupal 7.

// Add no-store in Cache-Control.
drupal_add_http_header(
  'Cache-Control',
  'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  FALSE
);
// Hack for Safari
drupal_add_js('jQuery(window).unload(function(){});', array('type' => 'inline'));

This seems to work on a fresh Drupal 7.22 install for an authenticated user. If the page in question has been asked to be stored in the Drupal cache or if you are using a contributed module that also messes with the response headers, this might not work as is for you.

Useful References

https://stackoverflow.com/questions/866822/why-both-no-cache-and-no-store-should-be-used-in-http-response
http://madhatted.com/2013/6/16/you-do-not-understand-browser-history
https://developer.mozilla.org/en-US/docs/HTTP_Caching_FAQ
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
https://drupal.org/node/197786#comment-1055633


Hooking a JS script at node submission to alter data submitted

You can look into either https://www.drupal.org/project/sanitizable or
https://www.drupal.org/project/pasteformat both does the job.

and if you are looking hook based solution, i would suggest you hook_node_presave worth looking their documentation.


In Views, how can I show only the results for content that has been tagged with two taxonomy terms?

I'm not sure why are you using Relationships for this. Simply, from "Contextual Filters" section, create a "Content: Has taxonomy term ID". In that filter's settings -> "More" settings -> Check "Allow multiple values" which:

  If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

i.e. go to view_path/29,34 will filter results by both terms.

Hope this helps.


For the autocomplete search box, there is a fantastic module Search Autocomplete with a detailed installation guide, and also has functionality such as integrating Views and Transliteration modules (which will overcome special characters/capitilisation etc.)

There is also a Patch for an exposed filter that may be of some assistance (if you are using a custom search box that you have made) that will help with the "contains" or "contains any word" operator.


I got it to work! My issue was that $nid = $node->nid ='nid' should have been set to $nid = $node->nid ='new'.

I also added module_load_include('inc', 'book', 'book.pages'); to call the function book_outline_form();


Sounds like a case for

Private file mode on a file field
A custom hook_file_download


Blocking is hard. Honeypot is a good deterrent, but if you allow anonymous users to click links that add products, then having spam orders might be your new reality. Removing useless, old carts is easy.

We use Commerce Cart Expiration on a number of stores. Also, sometimes its preferable to delete orders outright based on some criteria. For that, you can use Commerce Order Cleanup utility module.


Language specific menu items when adding content

My experience is that user 1 (admin) sees all menu items no matter their language setting, but i'm not sure if it's meant to be or if it's a bug.

Better have a look at the Issues of i18n and in particular at Drupal 7 & i18n: Only current language items visible in Menu Settings / Parent menu item


Get NID of newly created node from entity_metadata_wrapper

You can simply use the entity_metadata_wrapper's integrated method to get the ID:

$wrapper->getIdentifier()


Theme "seven" – how to allow regular users edit content with this theme?

Checking the permissions "View the administration theme" fixed my problem.


How do I allow a free product into a cart, but only if cart net value is above $10?

Take a look at the Ubercart Restrictions module.

  This module will do its best to prevent the wrong sort of people from
  ordering the wrong sort of goods, or to ship them to the wrong kinds
  of places.

  For example, some products cannot be ordered by minors, or some
  products cannot be shipped to certain states


Want to delete some custom user data while delete any user in Drupal8

Use hook_entity_delete().

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_delete/8.6.x

function mymodule_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType() == 'user') {
     ...
  }
}


Comment subject field too large breaks the page layout

All right I got it. I fixed it in the style.css file

WAS:

.form-text {
    border: 1px solid #ACACAC;
    border-radius: 3px 3px 3px 3px;
    color: #949494;
    padding: 4px 5px;
}

IS

.form-text {
    border: 1px solid #ACACAC;
    border-radius: 3px 3px 3px 3px;
    color: #949494;
    padding: 4px 5px;
    width: 75%;              /* <-- added line */
}


unset form elements with hook_form_alter()

Notification does add its own form elements in its own hook_form_alter(), which is probably executed after yours.

Check the module weight in the {system} table, and set your module to a higher value to have it run later.

Note: Instead of using unset() to hide form elements, you should instead set the #access property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.


Programmatically enable another language

Assuming your environment is Drupal 7 (or 6 may be OK, too?), you can use locale_add_language() function (defined in locale in the core). For example, if you want to enable French, run locale_add_language("fr") and the job's done.

Then, you can check the result via language_list() to make sure.


Here's how you can clear cache of specific view:

cache_clear_all('ctools_export:views_view:' . $NAME_OF_YOUR_VIEW, 'cache_views', TRUE);
cache_clear_all($NAME_OF_YOUR_VIEW, 'cache_views_data', TRUE);


All content types displaying in "Show only items where" search

Yes. You can alter the form's select box with a hook_form_alter() invocation. All that's needed is to remove the options that aren't relevant to the user.

For example, if you wanted to remove content types where the user didn't have the Edit any TYPE content or Edit all TYPE content permissions, you could do the following:

function token_form_node_admin_content_alter(&$form, $form_state, $form_id) {
  global $user;
  $types = &$form['filter']['filters']['status']['filters']['type']['#options'];
  foreach($types as $type => $type_name) {
    if($type != '[any]' &&
       (!user_access("edit any $type content", $user) &&
        !user_access("edit own $type content", $user))) {
      unset($types[$type]);
    }
  }
}


Can regions be printed within a node template?

You can print regions inside any template, but they aren't available out of the box in the node.tpl.php template. To make them available, you'll create a new variable for use in your node.tpl.php template that'll contain all the region content.

Creating new template variables is done by using a preprocess function. In your theme's template.php file, create a function that looks like this:

function mytheme_preprocess_node(&$variables) {
}

Replacing mytheme with your theme's short name. Now, in order for Drupal to recognize this new preprocess function, you need to rebuild your site's theme registry. This is as straightforward as going to Configuration → Development → Performance and pressing the "Clear all caches" button at the top.

Now, the way preprocess functions work is that $variables contains an array that corresponds to your template's available variables. For example, in node.tpl.php, $submitted contains the author byline. In the preprocess function above, it's found in $variables['submitted'].

To mimick what you have in page.tpl.php, where you have an array called $page that contains all the regions, you'd want to populate $variables['page'].

The problem is that $page in node.tpl.php is already populated with a true/false value that lets you know whether you're looking at the node by itself or in a listing.

So to avoid that name collision, populate $region instead:

function mytheme_preprocess_node(&$variables) {

  // Get a list of all the regions for this theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {

    // Get the content for each region and add it to the $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then, in your theme's node.tpl.php template, you can render any region by doing the following:

<?php print render($region['sidebar_first']); ?>

Where sidebar_first is the name of the region you want to render.


How to use Rules to redirect a user based on URL argument?

Well, if you're planning on doing it solely via rules, you can create a new rule for each if in your logic and then just set them to be actions one after the other. Something like this:

Action:
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>

This would effectively work like an if-elseif-else statement (assuming that the redirection is using drupal_goto().

But really, this sounds like a job for a custom action that takes the parameters and includes your own custom logic. It'd probably be a lot cleaner in the long-run.


Something like this should do it:

  $permissions = array('administer content', 'access content');
  $query = db_select('role', 'r')
    ->fields('r', array('name'));
  $alias = 'rp';
  foreach($permissions as $perm){
    $query->innerJoin('role_permission', $alias, 'r.rid='.$alias.'.rid');
    $query->condition($alias.'.permission', $perm);
    $alias = $alias . 'a';
  }
  $result = $query->execute()->fetchAllAssoc('name');

It's doing separate inner joins with the role_permission table for each permission, to ensure that the role has all the permissions.


The value of the cookie needs to be kept a secret, otherwise as you point out, someone can 'hijack' the session and perform actions as the original user.

Under normal circumstances an attacker wouldn't be able to get the value of this cookie from your browser, if they can, then they're into your machine, and can probably do what they like. Game over.

That leaves man-in-the-middle attacks as a way to get the value of this cookie, and you avoid those by running the site over HTTPS, so that the value of the cookies is encrypted in transit, and only readable by the client and the server.


Sorry, it was caused by

$host = $_SERVER['HTTP_HOST'];
$config['language.negotiation']['url']['domains']['cs'] = $host;

in my settings.php file. Thanks all!


How to add page restrictions for blocks in frontpage?

Your suggestions both involve using the PHP setting for block visibility, which isn't available by default and isn't recommended for security reasons. If you already have PHP filter enabled and want to use it, you can probably use the code:

<?php
  if (drupal_is_front_page() && !isset($_GET['page'])) {
      return TRUE;
  }
  return FALSE;
?>

The option I would recommend (which avoids using PHP filter) would be to install the context module (with this patch https://drupal.org/node/904416) and position the blocks using that. You can set it to appear in all circumstances except when on the home page with query string '*shs_term_node_tid_depth=*'.

If you don't know how to use context module, there are lots of tutorials and it's fairly simple.


How to resave content so that teaser thumbnails are generated

The image style files won't be generated when you save the node, only when the style URLs are requested for the first time.

You can generate the styles manually but I think it'll take some custom code. Without knowing more about your setup it's tricky but the following should get you started:

// Get the ids of nodes you want to generate styles for.
$nids = db_query('SELECT nid FROM {node} WHERE type = :type', array(':type' => 'my_type'))->fetchCol();

// Load the node objects
$nodes = node_load_multiple($nids);

// Setup a list of fields to generate styles for
$fields = array('field_image', 'field_image2');

// Setup a list of styles to generate
$styles = array('thumbnail', 'small');

foreach ($nodes as $node) {
  foreach ($fields as $field_name) {
    // Extract the fields items to get at the file ids.
    $image_items = field_get_items('node', $node, $field_name);

    foreach ($image_items as $image_item) {
      // Load the file
      $file = file_load($image_item['fid']);

      foreach ($styles as $style_name) {
        // Get a URI for the image style.
        $derivative_uri = image_style_path($style_name, $file->uri);

        // Create the derivative
        image_style_create_derivative($style_name, $file->uri, $derivative_uri);
      }
    }
  }
}


How to add an autocomplete field with pure javascript

Thanks to Clive for his help ! To active the autocomplete, I should re-attach the autocomplete behavior after added my new element.
nodeSelectorWidget: function (args) {

      // Adding the autocomplete field
      var createField = function() {
        var input = document.createElement('input');

        input.classList.add('form-autocomplete');
        input.setAttribute('data-autocomplete-path', '/fr/autocomplete/custom');

        return input;
      }

      var container = document.createElement('div');
      container.className = 'nodeselector-widget';

      container.appendChild(createField());

      // Re-attach autocomplete behavior to active the autocomplete on the added input
      Drupal.behaviors.autocomplete.attach(container);

      return container;

    }


How to export field collection with Drupal 7 views data export plugin?

If you only need the first result you can add a relationship in the view. Search for the name of the field collection. Once you add this relationship you should be able to access the field collection items and add them to your output.

If you want all the values you need to search add the field collection to your view rather than the fields directly. You then have the options of how to display the results but these options are limited.


If you define a region you would normally then do the following in your page.tpl.php file...

<?php if ($YOUR_REGION): ?>
    <?php print $YOUR_REGION; ?>
<?php endif; ?>

You should have some similar examples setup already especially if you are using a theme that ships with Drupal.

You can create specific page templates...

function YOURTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'my_page') {
    $variables['template_file'] = 'page-my_page';
  }
}

Template suggestions

See: http://drupal.org/node/1089642

Context module

Also, the Context module is brilliant for this sort of thing if you intend on having different regions for different pages you can use Context layout.

http://drupal.org/project/context


Error 404 when upload image in profile installation

Try add:

rewrite ^/core/install.php/(.*)$ /core/install.php$1;

to the config/nginx/drupal8.conf about line 16.

Adapting from:

https://github.com/kalabox/kalabox/issues/1767


Adding extra info to each Node -> Taxonomy Term relationship

Imho, the simpliest way to achieve associations of data with field value without coding is to use Field Collection.

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is
embedded in the host entity. Thus, if desired field collections may be
viewed and edited separately too.

You will then be able to set, each time you tag one or more terms, additional informations in other fields of your field collection. Plus, you can have multiple field collections of the same type on your content.


Trying to display data from a module's table in views

you should map your data to views, so it will be available from views admin UI

check This tutorial where you will find the basics for describe custom data and tables to views.


How can I restart the PHP environment installed with Drush for Windows?

Drush works using CLI. It means it is not dependent on web server you are using. "Restarting environment" simply does not apply, Command Line Interface PHP is started each time you call drush, and stops when drush finishes it's job, that's all.


How to extend a module hook from another module?

You can use the following code to solve your problem:

//clone the node
$new = clone $node;
//set the node to new
$new->is_new = true;
//unset the nid and the vid
unset($new->nid);
unset($new->vid);
//setting the new language
$new->language = 'fr';
//save the new node
node_save($new);

Reference: Programmatically create a new node from an existing NID


For "the view" you should add a menu style default menu tab with View URL: example.com/view/the-view and a parent menu item with URL: example.com/view.
For "the sorter" you should add a menu tab menu item and have the View URL be example.com/view/the-sorter.

This is easier to do than to explain. You might need to fiddling around to get it, but this is the gist of it.


In Drupal 8 you should use hook_entity_update().
This hook runs once the entity storage has been updated.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_update/8.3.x


Strategy for deploying Panels with features

We have very similar problems - not only with features but in other areas as well. The best solution we came up with so far is close to your second one:

Drupal 6 & 7 - Yin/Yang Multisite Staging
https://www.drupal.org/node/942540

So here you'd switch with the new DB version into the Staging system and use the Staging as the new Live version. But I don't feel too comfortable about this + it might not work everywhere if the two Servers are different.

In a way less complex evironment with small changes I'm doing the following: Every night the DB will be copied from Live to Dev. In this environment I'm sure I only have small changes in Dev which take usually minutes to an hour max. and I've got a fresh DB every day and can start from there.


WYSIWYG module w/CKEditor not working drupal 7

In order for the CKEditor menu to appear you must select your preferences. After you have assigned an editor to the input format (full HMTL, filtered HTML, etc.) click the edit button to the right. Then select buttons and plugins and tick the items you want to use. Then the editor toolbar will show above the summary. Drove me insane for a month until I figured this out!


Create a file ex : YourBlock.php in   Drupal\mymodule\Plugin\Derivative\YourBlock.php

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class YourBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $results = \Drupal::database()->select('mymodule_blocks_data', 'n')
                  ->fields('n', array('delta','title', 'content_type'))
                  ->condition('n.form_type', 'Add', '=')
                  ->execute();
        foreach ($results as $result) {
            $this->derivatives[$result->delta] = $base_plugin_definition;
            $this->derivatives[$result->delta]['admin_label'] = t('Title: @name content type: @ctype ', array('@name' => $result->title, '@ctype' => $result->content_type));
        }

        return $this->derivatives;
    }
}

  Also add the necessary annotation to display all the dynamic block instances in

Drupal\mymodule\Plugin\Block\YourBlock.php

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Display all instances for 'YourBlock' block plugin.
 *
 * @Block(
 *   id = "mymodule_block",
 *   admin_label = @Translation("Your block"),
 *   deriver = "Drupal\mymodule\Plugin\Derivative\YourBlock"
 * )
 */

Rebuild the cache as well


How to migrate users and keep their IDs unchanged?

Here is the solution (see image)

Uncheck DNM in 'Option:...' row
Enter 1 as default value
Save
Edit again
A new row will appear for 'Existing user ID'
Select Source field, i.e uid.
Save

This works...


You might want to use rules 'After updating existing content of type typename' in events and 'set data value' timestamp to created date will accomplish your task easily.


How to redirect user for specific pages not found

You can try by going on "admin/config/system/site-information"page. There you can give links where to redirect on the "Default 403 (access denied) page" and "Default 404 (not found) page". For example if you type "node", it will take you to front page.


How do I provide one-time access to a downloads page to anonymous users?

You need write a module to do this job,
I wrote a module that do something like this ( count download times )

<?php

/**
* Implements hook_menu();
*/
function bicuk_downloadounter_menu() {

    $items=array();
    $items['download/%']=array(
        'title' => 'increase Download counter ',
        'description' => t('callback url for increse Downloading count'),
        'page callback' => 'downloadcounter_tickup',
        'page arguments' =>array(1),
        'type' => MENU_CALLBACK,
        'access callback' =>true,

    );
    return $items;
}

/* call back function to increase counter
 * @param $fid , file id
 */
function downloadcounter_tickup($fid){

   if(!is_numeric($fid))
              drupal_goto();
   $file=file_load($fid);
   if(!isset($file->fid))
            drupal_goto();
   $acceptable_ext=unserialize(variable_get('bicuk_downloadounter_valid_extensions'));
   $file_path=file_create_url($file->uri);
   $pathinfo=  pathinfo($file_path);
   $extension=$pathinfo['extension'];
 if(!in_array(strtolower($extension), $acceptable_ext))
             drupal_goto();
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
if($count)
{
    $query=  db_update('bicuk_downloadcounter_counter')->fields(array('count'=>$count+1));
    $query->condition('fid',$fid, '=');
    $query->execute();
}
else
  {
    $query=  db_insert('bicuk_downloadcounter_counter')->fields(array('name','count','fid'),array($file->filename,1,$fid));
    $query->execute();
  }
   drupal_goto($file_path);
}

/**
 *
 * @param type $fid fid
 * @return type int count
 */

function downloadcounter_get($fid){
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
   return $count;
}

you can  get idea from this code to achieve your job,instead of counting download time try to check downlading time by IP and do your limitation


Join table query in hook_views_query_alter not selecting field from joined table

There a typo in your SQL query: instead of

field_data_field_gm_tanknummer.field_data_field_gm_tanknummer_value

you need to specfiy:

field_data_field_gm_tanknummer.field_gm_tanknummer_value


Can I safely use the same UUID on independent sites?

This is a perfect use case for Features. You can export shared sets of functionality and configuration without worrying about UUID stripping or collision.

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.

  Examples of features might be:

  A blog
  A pressroom
  An image gallery


insert data into database using web service

Create a Custom Drupal Module

Create these empty files in the new directory:

my_module.info
my_module.module
my_module.install
my_module.resource.inc
my_module.services.inc

Place this code in the my_module.info file:

name = My Module
description = My custom Drupal module.
package = Other
core = 7.x
dependencies[] = services
dependencies[] = rest_server

Place this code in the my_module.module file:

<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_module_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_module.services.inc'
    );
  }
}

Place this code in the my_module.services.inc file:

<?php

function my_module_services_resources() {
  $resources = array(
    'my_module_resources' => array(
      'actions' => array(
        'insert_into_database' => array(
          'help' => t('Insert Database Example.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'my_module',
            'name' => 'my_module.resource',
          ),
          'callback' => 'my_module_insert_into_db',
          'args' => array(),
          'access arguments' => array('access user profiles'),
          'access arguments append' => FALSE,
        ),
      ),
    ),
  );
  return $resources;
}

Place this code in the my_module.resource.inc file:

<?php

function my_module_insert_into_db() {
  $id = db_insert('example_table') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
))
->execute();
  if ($id) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Change the access arguments as per your permissions settings..

Call the service

http://www.example.com/?q=serviceendpoint/my_module_resources/insert_into_database.json


Other related content block using taxonomy

I finally figured it out.

Add the fields to your view (title, body, etc)
add a relationship to "Taxonomy terms on the node" (do not check required)
add the arguments (now contextual filters) the "Taxonomy term: Term ID" (use relationship)
set "Provide default value" to "Taxonomy term ID from URL"
uncheck (to save on the load, optional) "Load default filter from term page"
check "Load default filter from node page, that's good for related taxonomy blocks"
set the "Limit terms by vocabulary" and pick the vocabularies
select "Filter to items that share any term"
Scroll down to the "More" section and check "exclude" that way all TIDs will be shown, but the one on the argument.

Note: I also added the exclusion on the NID of the node where I am showing the block with the other related nodes tags with terms from the same vocabulary.

Thank you.


Programatically adding new CKeditor instance

You're not supposed to use the CKEditor API directly. You could do that if you want to use CKEditor on something you control. But your DOM ID (edit-comment-body-0) indicates you're trying to do this for a "Formatted text" field in Drupal 8, which uses the filter system.
If you'd want to attach CKEditor manually, use the JS API provided by core/modules/editor/js/editor.js.

The integration between Drupal 8 and CKEditor is very solid/deep, in that Drupal 8 automatically configures CKEditor to match the text format's filter settings. And that integration is not tightly coupled to CKEditor: there's the Text Editor (editor) module that allows any text editor to integrate in a similarly deep way. But it means you should always use the APIs that editor provides.

For API docs, see:

https://www.drupal.org/developing/api/8/editor
https://www.drupal.org/developing/api/8/ckeditor
https://www.drupal.org/developing/api/8/filter

For the concrete relevant code, see TextFormat, editor_element_info_alter() and \Drupal\Editor\Element::preRenderTextFormat.


I just had this issue myself.

The way I got around it was to add them to the Extra Allowed Content in the profile edit form.

You'll also be pleased to note that while the definition list tags are being presented as p tags they are still stored as the original tags in the db. You won't need to rebuild your definition list.


Views: group by content type in an arbitrary order

When you want to do arbitrary sort, U must be having your own sorting routine/algo/criteria?
When you have that then you can add a "global php" field in sort criteria and then u can use a setup code(if required) and then you can write your sorting logic in "sort code".


Modal Error Messages Displaying on Main page

I know this is pretty old so hopefully you found another solution by now. Since I happened to come across this near the top of my Google search for a slightly different issue though...

In your form_alter hook for the modal, you will need to add something like this:

$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
];

Then the callback function for your form that closes the modal and such will need to look something like this:

$response = new AjaxResponse();

// If there are any form errors, re-display the form.
if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal-form', $form));
} else {
    //Close the modal.
    $command = new CloseModalDialogCommand();
    $response->addCommand($command);
}
return $response;

This will tell it to apply the error message to your #modal-form div instead of the form in the background.


If you want to do this yourself, quick and dirty, it would be something like this:

function yourmodule_init() {

  $foo=drupal_get_path_alias($_GET['q']);
  $bar=explode('/',$foo);

  if ($bar[0]=='this-string-to-redirect') {
    $bar[0]='redirect-me-here';
  }

  $baz=implode('/',$bar);

  drupal_goto($baz);

}

You might also want/need to throw in a weight of -1 to make sure your module runs early by putting:

function yourmodule_install() {
  db_query('UPDATE {system} SET weight = -1 WHERE name = "yourmodule"');
}

in yourmodule.install but a quick look just now shows globalredirect's weight at the default of 0 so this may be unneeded.


Is there a way to disable the js of the Views Display Tabs module without hacking the module?

The standard practice for adding javascript is to use Drupal.behaviors to execute your modules code when appropriate.

This gives an easy way to override modules javascript by redefining that modules behavior. For Views Display Tabs I took a look at their javascript source to see that the behavior was called Drupal.behaviors.viewsDisplayTabs.

So now you can add your own javascript to override this:

//Override Views Display Tabs javascript
Drupal.behaviors.viewsDisplayTabs = function() {}


in views, how to get the replacement pattern of the URL of the link field

The raw replacement pattern isn't available, but you can customize a new hidden field to be the replacement equivalent:

Add a new link field

Check the Exclude from display, URL only, Show URL as plain text options to have your field be available.

Add a new title field

Uncheck Link to the Content
Use {{ title }} in the rewrite options to render title field with a link to your link field URL


load files to the public files dir via admin panel?

Since my user case was only one image, I ended up putting the file in the theme folder.
for future and larger number file loads I'll be using the media module


Every module on your site can be found in the list on /admin/structure/menu.
just click 'list links' and then 'add link' to add a link to a menu.


How to reveal the admin password when logged in with one time login link?

The short answer is: no.

A Drupal password is saved to the database after getting hashed, and the hash is not reversible in any sense that you're hoping for.

An alternative solution would be to try to reset the password to something you know.  Drupal has a description of an SQL approach if you can't use the "reset password" function.

If you don't have command line access you can try using a PHP method to reset it.  However, that is really a last resort kind of situation because of the security implications.  Super last resort.


How to print how many nodes of a specific type a user has created?

The simplest way would be to extend the query from the other question you linked to and add the user id as an extra parameter:

function yourtheme_get_node_count($content_type) {
  $query = "
    SELECT COUNT(*)
    FROM {node} n
    WHERE n.type = :type
    AND n.uid = :uid";

  // Get the node object for the current page.
  $node = menu_get_object();

  $params = array(':type' => $content_type, ':uid' => $node->uid);
  $amount = db_query($query, $params)->fetchField();

  return $amount;
}

Be sure to only call this on a node page as menu_get_object() will only return a node object when you're on such a page.


Yes, you can get errors when you delete the module files without disabling it first. It's best to completely uninstall the module, which allows the module to clean up after itself (eg. delete configuration from the database). After that, you can safely delete the files.

If you already deleted the files, the easiest way to get rid of bits and pieces left in the database, is to restore the files (download the module again and put the files back where they were), follow the uninstall process, and delete the files. Make sure you download the exact same version of the module you had installed earlier.

So how do you know which module version you had? Ideally you are already using a version control system (such as Git) to manage your code, so you can always look back in the history to find out which module version you were using. If you don't have version control, you can try to find the version number in the database as described in this answer. As a last resort, try to remember when you installed or last updated the module and look in the module's releases list to find a version close to that date.


How do you render a View with arguments using a Computed Field?

The long way:

$args = array(ARGUMENTS);
$view = views_get_view('VIEWNAME');
print $view->preview('block_1', $args);

The short way:

print views_embed_view('my_view', 'block_1', $arg1, $arg2);

Also keep in mind since this is dynamic data, you will need to uncheck the checkbox on the field settings page or else it will try to store the data thats generated upon saving the node.


My preferred way to do this is.

Add the button to your form like so:

$form['options']['reset'] = array(
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('MY_MODULE_FORM_ID_reset'),
);

Then create the reset function like so:

function MY_MODULE_FORM_ID_reset($form, &$form_state) {
  $form_state['rebuild'] = FALSE;
}

No Javascript, no markup.


That error most commonly occurs if an order is being double-saved, by calling $order->save() within a hook_entity_presave() or a matching event, including pre/post transition events.

If you need to modify the order during a state transition, do it in a pre-transition event and let the system take care of the rest.


Why do I get a Drupal\Core\DependencyInjection\ContainerNotInitializedException exception error?

I had the same problem with Drush throwing an exception for a test site on localhost. I was able to access the site from the browser, from where I didn't get any error message, not even a message from a exception handler. This puzzled me, since the site was clearly working.

It started to work again when I changed the file permissions for the Drupal files. The user account I was using to execute the command line was missing the permission to write in some directories.


How to access node field content in a custom module?

Assuming you mean Drupal 7, just off the top of my head, implement  something like hook_node_view() and attach the Javascript via the #attached element. I am frequently silly in my hook options, so someone may have a better one to suggest.


Cannot update core with composer after switching to core-recommended

I tried again with composer require drupal/core-recommended:8.9.1 --update-with-dependencies and it started to update core. Unfortunately drupal/core-composer-scaffold was not touched so I had to update it directly with an extra composer command.
Also I noticed that both of these were updated, I hope it is right:
- Updating drupal/core (8.9.0 => 8.9.1): Downloading (100%)
- Updating drupal/core-recommended (8.9.0 => 8.9.1)


After a bit of digging around I found that this is resolved by adding the URL to the Cache Expiration setting as follows. Go to » Administration » Configuration » System >> Cache Expiration, the under Node Expiration tab, then in the section 'What URLs should be expired when node action is triggered?', tick Custom Pages, then add the URL of your pages that are created with Views, in my case its just the word News. There may be a way to add conditioning on this so it only expires the News page when nodes relating to it are amended. If anyone finds that out, can they let me know. You can also tick under Module Status in the Debug section at the bottom 'Watchdog + site message ', it will display a message show which urls have been expired (cleared).


To answer the question title and the comment of @Leigh, without going into the details of the complexity of the specific View:

How to cache a view for all users of a role?

Views are cached like any other rendered content. When rendered a View bubbles up the cacheable metadata of Views plugins, like filter or sorting plugins and the rendered content itself.
Additionally there are the three default contexts, as defined in the service container:
core.services.yml:
  required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

The context user.permissions is a hash of all of the user's permissions, which is the result of the roles assigned to a user.
So in the end a View is cached for user roles by default.


I think you need editablefield module. once this module is enable you can set any fields editable in your view. So when you visit your view page or block you can edit the field value there itself..
Nice Ajax is implemented in here, so it works very nice.. You can set it like double click to edit..

NOTE - I am not able to link the module with original URL at drupal.org so you can search for it in google with same name.


As of newer versions of Drupal 8, the "js"-key (or "css") is not allowed anymore in the #attached-array. Use "libraries" instead.


Send custom user fields to twig template

collectionmanager_preprocess_html() prepares variables for html.html.twig template. For page.html.twig the of the function name should be collectionmanager_preprocess_page(). The same pattern should be used for other theme hooks (view, block, field etc).


What is the "Category" argument in user_save for?

As you see in user_save function it tells that

  category: (optional) The category for storing profile information in.

It basically used in below lines of code inside user_save function

user_module_invoke('presave', $edit, $account, $category);
user_module_invoke('update', $edit, $account, $category);
user_module_invoke('insert', $edit, $account, $category);

So, the information is just passed to all presave, update, insert hooks so that they can take contextual actions.

In user_module_invoke function $category is defined as

  $category: The category of user information being acted upon.

So, from above it clarifies that is used as a value to tell all hooks that we are saving user details and on which part of user information we are acting upon. Something like if we change the user organic groups that he belongs to then we can specify that $category as "organic_group" .

For Example if you see hook_user_presave in user module

/**
 * Implements hook_user_presave().
 */
function user_user_presave(&$edit, $account, $category) {
  if ($category == 'account' || $category == 'register') {
    if (!empty($edit['picture_upload'])) {
      $edit['picture'] = $edit['picture_upload'];
    }
    // Delete picture if requested, and if no replacement picture was given.
    elseif (!empty($edit['picture_delete'])) {
      $edit['picture'] = NULL;
    }
    // Prepare user roles.
    if (isset($edit['roles'])) {
      $edit['roles'] = array_filter($edit['roles']);
    }
  }

  // Move account cancellation information into $user->data.
  foreach (array('user_cancel_method', 'user_cancel_notify') as $key) {
    if (isset($edit[$key])) {
      $edit['data'][$key] = $edit[$key];
    }
  }
}

You can see the use case of $category above where they check for account or register !

In your case just make it as an optional and don't assign any value :-)


Append an  tag to entity field view hook

You can theme individual fields: https://api.drupal.org/api/drupal/modules!field!field.module/function/theme_field/7

You can either have a theme function in template.php or a tpl.php template file, the former is preferred for performance reasons.

Using a theme function you could do something like:

THEMENAME_field__link($vars) {
  $output = '';
  foreach ($vars['items'] as $delta => $item) {
    $link = l($item['#title'], $item['#href']);
    $output .= '
' . $link . '&nbsp;</>
';
  }
  return $output;
}

Though you'll have to check $vars for specifics.  As for checking the widget I think you can get a clue from $vars['element']['#formatter']


form validation messages are not rendered immediately

The problem is that Drupal has already finished setting messages for the current request when it gets to processing your form. To get things working properly call drupal_get_form in template_preprocess_page:

function myThemeOrModulename_preprocess_page(&$variables) {
  // For node templates.
  // $variables['node']->my_form = drupal_get_form('form_name');
  // For page templates.
  $variables['my_form'] = drupal_get_form('form_name');
}

Then render the form in your template file:

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

There was another issue for which I don't know the cause of currently, but adding $variables['messages'] = theme('status_messages'); (see theme_status_messages) inside the same preprocess_page function solved it.


How I can pre-populate a webform field with the node title and node link?

Use the PrePopulate module and Tokens to build dynamic links on your pages. When clicked, the link's content will be entered into those fields automatically.

https://www.drupal.org/project/prepopulate

There's an example on the project page.


Default to MyISAM instead of InnoDB in Drupal 7

The quickest and dirtiest way to get all Drupal data into MyISAM perform the following:

Make a backup of /var/lib/mysql before doing these steps

step 1. mysqldump all data out of mysql

step 2. remove all folders and files from /var/lib/mysql, but leave the /var/lib/mysql/mysql alone because it contains user grants.

step 3. add this line in /etc/my.cnf

[mysqld]
skip-innodb

step 4. service mysql restart

step 5. reload mysqldump file back into data into mysql database

UPDATE 2011-10-04 04:28 EDT

step 1. Set Default Storage Engine to MyISAM

add this line in /etc/my.cnf

[mysqld]
default-storage-engine = MyISAM

step 2. service mysql restart

Give it a Try !!!


I get an AJAX error when I install Drupal 7: Why?

The problem is the  maximum execution time being exceeded. To fix this, you should change the maximum execution time in your php.ini file. Click on the Wamp icon on the taskbar, select PHP -> php.ini, find "max_execution_time" and change it from 30 to like 100-300, to make sure even the slower scripts get their job done before the timeout.

Remember to restart the server after you change the settings.


How to send the views record in an email to admin at regular time interval of 8 hours?

Option 1: Using Rules and Rules Scheduler

Use the Rules module and Rules scheduler (submodule of Rules). What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1 hour).

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

Option 2: Using modules Rules and Rules Once per Day

There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way to understand/read this is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 am, another one around 2 pm and the ast one at 10 pm. Adapt the 6am to any other timestamp you'd want, and do the same with the one from 2 pm and 10 pm


This can be done using a combination of Editable Views and Entity Reference.

You will need to create an entity reference field on one of the content types that points to the other. Then create a view of that content type.

Using editable views you can have a select list to add an entity reference on the company node to the event node. If you set up the entity reference field to allow multiple values, you will be able to have one company attending multiple events.

You can also create a view that shows all entities that reference the the event in order to show a list of all companies who will be attending an event.


want to make user-login before view contain

you can go for LoginToboggan module .

 The LoginToboggan module offers several modifications of the Drupal login system
 in an external module.

    Allow users to login using either their username OR their e-mail address.

    Allow users to login immediately.

    Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

    Customize the registration form with two e-mail fields to ensure accuracy.

    Optionally redirect the user to a specific page when using the 'immediate login' feature.

    Optionally redirect the user to a specific page upon validation of their e-mail address.

    Optionally display a user message indicating a successful login.

    Optionally combine both the login and registration form on one page.


Is it possible to import custom XML files with the Feed Import module?

Yes it is. You need the Feeds Xpath Parser module


How to put "Advanced form block" in a twitter bootstrap modal?

The problem was that the Advanced Form Block, has a CSS class of .node-form and this is not encapsulated in the standard block content div .block-content. So when the Twitter Bootstrap Modal Block module tries to add the .modal-body CSS class to the .block-contents div, it will not find the div and the form will be left outside the modal body.

For me the easiest way to solve this was to edit Twitter Bootstrap Modal Block JavaScript file, i.e. sites/all/modules/twitter_bootstrap_modal/twitter_bootstrap_modal_block/twitter_bootstrap/modal_block.js, as follows:

Change the line that reads

$(this).children('.block-content').addClass('modal-body'); //line 29

to

$(this).children('.block-content, .node-form').wrapAll('<div class="modal-body" />');

This will put the advanced from block into the modal body.


jQuery not functioning in Chrome regardless of core/custom code

This is an issue with CloudFlare and Chrome:

https://support.cloudflare.com/hc/en-us/articles/200169456-Why-is-JavaScript-or-jQuery-not-working-on-my-site-


Programmatically Change Pager "Items to Display" value?

im not sure of any 3rd party module that allows easy "override the # of items per page". I've done this task a few times for View displays using core drupal apis.

Basically:

you use hook_views_pre_build to programmatically alter the view.
Use a custom variable to store your items per page value.
Make a simple admin page to allow a site administrator alter the value.

EDIT: amended to different views hook function.


7 allow cross-origin framing CORS module

https and http -- even if the host is the same -- are considered different domains.

The way you can deal with that when your site can be viewed with both https and http, is instead of referencing files
https:// or http://
just use //
It will defer to the protocol that you are on.

The only time this would cause problems would be if a certain resource only got served up under secure or insecure. But this does not sound like it would be a problem for you in this instance.

EDIT:
In order to change existing content, which it sounds like doing by hand is impossible. You could try a module like https://www.drupal.org/project/scanner -- being careful to backup, test, and make sure you are only looking at the correct URLs (you don't want to change the urls where changing the protocol would be).

One other possible way to make it work is to just make your path references root relative -- strip out http://yourdomain.com - and just leave /your/path/to/file

The other thing to do is just cherry pick the content that people are looking at most.


Solution posted here:

basically:

  You need to generate the javascript settings for the form, and send
  them to the browser to be merged with the existing settings. Without
  doing this, any AJAX on your form will not work.

https://drupal.org/node/2009252


How to load the immediate parent link in a preprocess function?

I think you can do it with the 'plugin.manager.menu.link' service:

$link = $this->menuActiveTrail->getActiveLink();

if(!empty($link->getParent())) {
  $parent_link = Drupal::service('plugin.manager.menu.link')->createInstance($link->getParent());
  $menu_item = MenuLinkContent::load($parent_link->getMetaData()['entity_id']);
}

This way you don't have to replace the prefix.


The $variables argument is passed by reference so you can name it whatever you want. There are two common conventions in Drupal for $variables in hook_preprocess functions:

Name it $vars
Name it $variables

I suspect you found some code that you want to use that used $variables; but your existing preprocess function uses $vars. Simply change the references to $variables to $vars in your code above and remove the $variables argument:

/**
 * Implements THEME_preprocess_node().
 */
function salamat_preprocess_node(&$vars) {

  if ($vars['node']->type == 'article') {
    // Remove Add comment link from teaser.
    unset($vars['content']['links']['comment']['#links']['comment-add']);
    // Remove login/register to comment link.
    unset($vars['content']['links']['comment']['#links']['comment_forbidden']);
  }

  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser';
    $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser';
    $temp = drupal_get_query_parameters();
    if(isset($temp['show_mode']) ) {
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['type'].'__teaser__'.$temp['show_mode'];
      $vars['theme_hook_suggestions'][] = 'node__'.$vars['nid'].'__teaser__'.$temp['show_mode'];
    }
  }
}


Hierarchical Select with taxonomy in Views

You can achieve this by combining Simple Hierarchal Select and Views Dependent Filters. So you use SHS for selecting the taxonomy term, and then set a dependency that if a term is selected on the first taxonomy, show the second taxonomy.

Add your first/primary taxonomy that you will be using to determine the secondary options. Don't select any terms, expose filter.
Add your secondary taxonomy, expose filter.
Add a Global: Dependent Filter to your list of filters.
Your Controller Filter is the first taxonomy that will be deciding which second field/taxonomy will showing up.
The Controller Values are the values from the taxonomy selected for the Controller Filter. Pick the term which when selected will show the dependent taxonomy. The dependent filter is the secondary taxonomy that you want to show up.

There does need to be some specific ordering going on, like the dependent taxonomy needs to be above the Dependent Filter, but I can't remember exactly. I'm sure you can figure it out from there.


There is the Troll module, which seems to do what you need; it isn't looked after.
For other options you also have the Cave your trolls module, which hides user's posts from anyone other than themselves, or the Misery module, which makes the site unusable for certain users.


How to get archived events based on end date for a content type with a start date and end date field?

Archived events get based on an end date.

Go to view named archived events. Then click the end date exposed filter in FILTER CRITERIA. Check Filter type to expose is single filter. Then below operator drop down box choice is less than. Next drop down box choice enter relative date. Below now shows Relative date text box give now.
Then click on Apply button.


Is it possible to login to Drupal with a custom user field, instead of username/pass?

This is the code you need. In the Drupal site create the following module:

Update:

function my_special_login_menu()
{
    $items['authinticate-by-customerid'] = array( // or any other custom path you choose
        'title' => 'Login by customerid',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'my_special_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function my_special_login_function($customerid)
{
    // post the data to /authinticate-by-customerid as json with a parameter / property named customerid holding the customerid
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_customerid', 'value', $Data->customerid, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

For this code to work you need Entity API module and you should serve the site over SSL in order to encrypt the data transferred between the two sites.


Unable To See Admin Dashboard, How to Manually change the admin theme

This is the easiest method to reset your admin theme in a Cpanel.

Update your settings.php to have:

// If your admin theme is Bartik.
$conf['admin_theme'] = 'bartik';

Warning with using $conf as you cannot set the theme via Appearance page anymore.

If you prefer SQL query method...

Access PHPMyAdmin.
Select the Drupal database and run this query.

UPDATE variable SET value='s:7:"garland"' WHERE name = 'admin_theme';

Where 7 is the total number of strings your theme has. Example, if your theme is adminimal. Then your query should be like this.

UPDATE variable SET value='s:9:"adminimal"' WHERE name = 'admin_theme';

Please see the documentation on Drupal.org.

Take note that if you are using Context module the $conf is not helpful as it will always respect the theme assigned via Context.

Hope this helps.


How can I print something only when cck field has certain value on node.tpl.php?

The following should work:

if (isset($node->field_color[0]['value'])) {
  //If you want the field value to be displayed
  print $node->field_color[0]['value'];
  //If you want some custom text to be displayed
  print 'It has colour';
}
else {
  print 'Empty Text';
}

Or with ternary operators:

print (!empty($node->field_color[0]['value']) ? $node->field_color[0]['value'] : 'Empty text';

You'll probably either want to put in some logic to make sure the field exists though, or create a node-TYPE.tpl.php for your specific content type.

EDIT

This should sort out your red or blue issue:

if (isset($node->field_color[0]['value'])) {

  $colour_value = $node->field_color[0]['value'];

  if ($colour_value == 'red' || $colour_value == 'blue') {
    $colour = $colour_value;
  }
}

print (isset($colour)) ? $colour : t('Empty Text');

I've only put the field value into a variable to save space - you don't have to do this if you don't want to :-)


How to handle free and paid orders with post processing?

You would be better to implement a custom payment method that can be active when the order has a 0 balance.

If the order has payment required, use the standard payment method.
If the order has no payment required, complete checkout.

e.g: https://drupal.org/project/commerce_no_payment


Custom contraint validator: show an error message with a link

You shouldn't chain up placeholders / use HTML inside placeholders. And for URLs use the :placeholder notation with double dots
 $notUniqueURLBasis = 'The basis URL needs to be unqiue but the set basis URL %basisurl is already in use: @link_text';

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/class/FormattableMarkup/8.2.x
and
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8.2.x


Which field type should I use for a telephone number, and how can I ensure each entry is unique?

For a basic telephone field without validation you could just use a text field, and set the maximum length to something sensible for telephone numbers in the regions you're targeting.

If you want a more advanced telephone field, check out the Phone module. There's a stable release for Drupal 6, but only a dev release for Drupal 7.

To make sure fields are unique, you can use the Unique Field module.


You can do that with:

hook_url_outbound_alter

Keep in mind all URLs run through that function so your hook implementation should be as fast as possible.

Example from locale module:

  Rewrite outbound URLs with language based prefixes:locale_url_outbound_alter

See also: Language Negotiation API


request new password link does not work if not logged in

Drupal 7's core handling of password reset can seem a bit cumbersome, since it uses a one-time link to a one-time login reset page which can be confusing to users. I recommend using the Simple Password Reset module which streamlines the process and makes it very easy for users. It works great right out of the box.


When checking out, redirected to front page and not payment page

It looks like the order ID isn't being saved for the session.  Add this:

$_SESSION['commerce_cart_orders'][] = $order->order_id;

Just make sure you do this before you save the final version of your order.


Either you don't need, or you can't:

If this was translated to HTTP header, and browser "knows" not to ask for the page again, nothing you would try to do about it will have any effect, because browser simply won't contact your server anyway, so it will not download any remedy you might try.

If it affected only server-side systems, tuning it down and clearing caches should be enough already, and server shouldn't send "304 Not Modified" to your clients.

Hard to tell which case is it without knowing your caching setup, but I'm afraid "fix it and wait" is the only way either way.

Unless, for some reason, you can identify uncached JS file included on affected pages. This would be a bug, so I don't expect it to happen, but if, it might be a bug you could use - ask for it on Stack Overflow, then, as this is much less Drupal-related.

If your front page isn't cached that way, you can alter all affected links. It will not help people having issues with bookmarked pages, but it will direct regular users to current content.


How do I avoid unwanted users create accounts?

It depends on what kind of control over user accounts you want.  By default Drupal allows visitors to register new accounts.  If you want to disable that, you can set Who can register accounts? to Administrators only at /admin/config/people/accounts.


Views SQL-query slow with big dataset and exposed filters

Try denormalising the database by storing the relevant node objects in a single caching table. You can model your database schema on that of the core caching tables. That should speed up the query by reducing the amount of joins. Also, put indexes on any columns used in where clauses. If you insert/update rows in your caching table on update/insert of nodes using hook_nodeapi, your caching table should remain fresh. You could then either replace the view with a db_query in a custom module, or you could expose your table to views.

I haven't tried it, but you may be able to achieve this using the D6 object cache module.


Drupal 7 check logged in user has both roles in tpl file?

It would be simple as:

global $user;

if (in_array('administrator', array_values($user->roles)) &&  in_array('moderator', array_values($user->roles))) {
    // is admin
} else {
    // is not admin
}


How to use admin table theme with multistep form?

I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:

$form['table'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#empty' => 'Empty List - No Entries',
  '#header' => $header,
);

or

$form['table'] = array ('#value' => theme('table', $headers, $rows));

You can use this in multistep form also.

If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:

$form['table'] = array ('#theme' => 'output_table');

$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);

Within 'theme_output_table', generate your $headers and $rows to feed to 'theme_table' by calling 'drupal_render' on the relevant form elements that are children of $form['table'].


The module is pretty borked.

Beebee is right.  When you install using Drush, you will get the latest non-dev Wordpress_migrate and the latest Migrate - clash!  You also get no warning about needing migrate_extras features and media.

So the trick is install the latest Migrate with Drush but as of today's date, download the latest dev version of Wordpress_Migrate.

I was able to download my blog from its url. It did hang and I exited expecting a mess but all the content is there.  As I am trying to sort out content, that suits me.

So the principles --
--download migrate, migrate_extras, media, features and ctools
-- manually download the dev version of wordpress_migrate

If your blog is large, be patient. If the download borks, then try to increase the execution time or try exporting your blog to a file from inside Wordpress, use the Wordpress file splitter and try uploading by file.

Thanks Beebee.


Need help finding source of CSS in Drupal code

This sounds like a file permission problem on your production server for the library you added to your all/libraries folder. I.e. that some read access to those files in that folder is not granted.

Another reason MIGHT be that your library folder name (within all/libraries) is NOT named share42 (case sensitive, so Share42 would NOT be ok). Variation of that could be that "share42.js" and/or "icons.png" cannot be found in that folder (eg beause it got renamed to something else).


If you want a single php file you can use a drush shell script:

#!/usr/bin/env drush

use Drupal\user\Entity\User;

    $user = User::create(['name' => 'testuser', 'status' => TRUE]);
    $user->save();

For more information see https://github.com/drush-ops/drush/blob/master/docs/shellscripts.md

A better approach might be to use REST, see https://www.drupal.org/node/2754633


How to alter a form of content-type to prepopulate FieldCollection of EntityReference fields?

Short answer is : You can't via hook_form_alter

Long answer : there is a workaround there : https://www.drupal.org/node/1337804


Move, style or remove title in taxonomy template

Option one might be to change the template tpl for your taxonomy page. You can also create a new view for your page.


You should use entity references for this. The end result will be that when you view a parent node, the products show up in a block (or panel pane).

Set up a parent node content type and add an entity reference field to the products content type.
When you create products, reference the parent node.
Create a block view and add a contextual filter for content: referenced (or maybe referencing). your entity reference field. ?
In that contextual filter's settings, click provide default: content id from url ?
Add fields for the products content type and maybe additional filters as needed.

When you place the block in a region, the products will show up if they reference that node.


ajax_render() - CSS not adding/updating in IE

The solution for me was CSS aggregation in Drupal: It needs to be on to work.
When it is disabled, it uses @import, which IE does not like if that is used to append to the head. When it is enabled, it appends links instead, which then works with IE.

The same problem is described here.


Benefit of running custom query over views

Not really. you should stick to using Views; it will provide you more benefits. To name a couple:

Less custom code to maintain; it's one of the mostly heavily used modules and will be part of D8 core. There's much less worries of security holes, bugs, etc.
The versatility of the Views features: caching, multiple view displays, filtering, a UI to change all this, etc.

I'd say the only exception to this would be the instances where your query is going to be hit very often, in which case you'd might be able to squeeze more performance out of an optimized SQL query.

For your needs, a block of 10 latest nodes, views will do everything you need it to, not be a burden on performance, and will take much less time to complete than creating & maintaining possibly bug ridden custom code.


Displaying all fields of a custom content

I think you use wrong theme template. This way you need use node.tpl.php and  exactly is node--slider.tpl.php. You can see template suggestions. Or you don't want use node template i think better you can use hook_preprocess_page()

function YOURTHEME_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $node = $vars['node'];
    $field_images = field_get_items('node', $node, 'field_image_slider');
    //dpm($field_images);
    if (!empty($field_images)) {
      $output = '';
      foreach ($field_images as $key => $images) {
        $output .= '

Hi

';
      }
      $vars['slider'] = $output;
    }
  }
}

and in page.tpl.php

<?php if(isset($slider)): ?>
  <?php print $slider; ?>
<?php endif; ?>


Why not use the existing user edit form, and use hook_form_alter() to add your fields. That way, you get all the built in functionality, such as password changing etc.

It would also make sense to make the user registration alterations the same way, instead of creating your own flow, unless it for some other reason makes sense to do it that way.


List returned by drush site-alias is correct, but drush @sites finds an incorrect list

The drush maintainers avoid multisite, so there is a possibility that some bugs might exist here.  The version of Drush that you are using is very old, though; upgrading to Drush 6 would be advisable.  @sites might even work for you then, as some work has been done for multisites and symlinks since Drush 4.

The best thing to do, however, would probably be to make an alias group.  Make a file called /etc/drush/groupname.aliases.drushrc.php, and define aliases 'e1', etc. as you show above, one for each of your multisites, all in the same alias file.  Then, simply:

drush @e1 status - show status on just one site

drush @groupname status - show status on all sites defined in the aliases file 'groupname'


Change content "Author" to the last "Editor"

If you have a custom module to use, or aren't afraid to make one, then a hook_node_presave is the first method I would try.

function yourmodule_node_presave($node) {
  // php5 passes objects by reference
  // so this should not need a & or return
  global $user;
  $node->uid = $user->uid;
}

If you do not want to go with code, then try the Rules module.  Rules has a trigger for node about to be saved.  Set the condition that the current user is not anonymous (because rules likes you to confirm in a condition any data you want to use in the actions) and then set the author field in the action to the current user.  All done in the ui, no new code needed.


Is it possible for an administrator to delete pending user relationship requests (between users)?

No, there is no special administrative pages for managing other people's relationships, but this would be a useful feature.

Have a look at user_relationships_load in user_relationships.module. You could use that to create a list of all of the pending relationships site wide by passing in user_relationships_load(array('approved' => FALSE));. You can further filter that by passing in additional information such as the relationship type. UR's views integration doesn't really take an administrators needs into account but you could build this list with views as well.

Once you have that list you can generate delete links that call user_relationships_delete_relationship. Calling that function with the proper RID (relationship ID) will delete those pending relationships for you.

If you don't want to build an admin page to come back to, there is nothing wrong with doing a little clean up directly in the database as long as you're careful and back up everything first.


Ask for the actual security report.  They often contain explanations about what the problem really is, as well as offering a solution.

I believe this will take care of the password autocomplete issue; I have a client who requires this and have it deployed on a few sites.

function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  // http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms

  if ($form['#id'] == 'user-login') {
    $form['#attributes']['autocomplete'] = 'off';
  }
}


Is Drupal cache as set in the core enough for simple sites?

No it would be unlikely to be as fast as plain HTML, because the default caching is still using the database and some PHP.

However you can improve the speed significantly with a module or two. It is highly dependent on the speed of your servers - if you have a fast database server but a slow filesystem you might be better using the database although that is an unlikely situation. At minimum I recommend installing Advagg - correctly configured that will reduce load times for a lot of sites by around 25%.

Depending on the site, Boost can also vastly improve performance although I have not found it as universally applicable as Advagg. Also depending on your setup an external cache like Varnish may be better although it requires careful configuration and some server admin knowhow.


Let Users Make a Feedback before Download File

Depending on your Drupal coding skills I would use a custom form with a modal using the OpenModalDialogCommand. In the modal you can attach a form with a textarea and a submit button. On clicking the submit button the feedback from the textarea gets stored, the modal gets closed (CloseModalDialogCommand) and a BinaryFileResponse gets returned.

I don't know of any contributed modules that provide this functionality.

P.S. I am assuming that you are using Drupal 8 here.


Does Entity Autocomplete has database leak?

Known bug:
https://www.drupal.org/project/drupal/issues/2826826#comment-12376276

  As mentioned in IRC, the problem with adding even just the entity
  id/UUID to those options is that we create entity * entity reference
  key value entries.

  The key is based on the hash, so an ID/UUID in there results in a
  different hash for every entity. At the very least, we would need to
  switch to an expirable key value store, so we can clean them up but it
  is still a non-trivial overhead that is being added.

https://www.drupal.org/project/drupal/issues/2826826#comment-12644652

Seems to fix it for me:

    // Don't serialise the entity, it will be added explicitly afterwards.
if (isset($selection_settings['entity']) && ($selection_settings['entity'] instanceof EntityInterface)) {
  $element['#autocomplete_query_parameters']['host_entity_type'] = $selection_settings['entity']->getEntityTypeId();
  $element['#autocomplete_query_parameters']['host_entity_id'] = $selection_settings['entity']->id();
  unset($selection_settings['entity']);
}


Go to Content type > Manage fileds > Field Group.

In the filed group you can find settings icon beside.

Clicking on that will give you a field to add description to.


How do I install Drush 9 on Windows 7 with Composer?

The Drush 9 documentation is pretty clear: Install Drush locally, in your Drupal site, using composer. You can install Drush Launcher in addition if you want it more convenient.

Without Drush Launcher, you can use the site local Drush be running

vendor\bin\drush some-drush-option

from your Drupal site root. No need to modify any paths.

If you install the Drush launcher (and use Windows), create a suitable bat file.

NB! Adding C:\Users\Md. Shafiq Hossain\AppData\Roaming\Composer\vendor\drush\drush to the path is plain wrong. If you really want to modify the path (to get the convenience of using just drush without installing Drush Launcher), the correct path is [...]\vendor\bin.


Change autocomplete path with hook_form_alter()

On a stock installation of Drupal 7 and references 7.x-2.0-beta3 I was able to use the following form alter to successfully change the autocomplete path for a node reference field on the article content type:

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['field_node_ref'][LANGUAGE_NONE][0]['nid']['#autocomplete_path'] = 'another/url';
  }
}

Another option is to ignore the form and use hook_menu_alter to change the callback for node_reference/autocomplete/%/%/%. Your callback should accept $entity_type, $bundle, $field_name which you can use to filter out which requests you want to respond to.


How do I set up Search API index as cron task?

You are right insofar as a node will only get reindexed when it is updated. Someone viewing the node isn't seen as an update, so incrementing the number of views won't cause the node to be reindexed.

It's not normal to rebuild the entire index on a schedule. Cron only re-indexes those nodes that have been marked as needing to be indexed.

There are two ways I can think of you might schedule a nightly rebuild of the index.

If you have access to the server at command line level you could run the drush command "search-api-reindex" via a custom cron job. Run it as the same user as the web-server (eg. apache or www-user) and use the -l option to specify the url so the cron line would be something like: 0 23 * * * cd /var/www/home && drush sapi-r default
Otherwise you could write your own cron hook in a custom module to do the same. The module elysia_cron would help with scheduling it for the right time. You'd need to call search_api_index_reindex('default'); to have the same effect as the cron job in point 1.


How to scrape specific elements of the Drupal theme to a file?

I solved the issue, and it may have been related to

// the zero here is necessary because simplehtmldom returns a collection
$topbar = $html->find('#header-wrapper', 0)

Here is my sample code - I am thinking about contributing a module for this function, with some admin settings

// get the header code and write it to a file
function module_name_global_header_write() {//dpm('raw_html');

    // there may be an issue if we are processing this function while viewing the same url as $sourceDomain
    // perhaps we will need to create a page or URL that is not viewed but can supply the HTML for the header
    $sourceDomain = 'http://site_name.com';
    $sourceMenuId = 'superfish-1';

    // initialize simplehtmldom objects
    $html = new simple_html_dom();
    $responsive_desktop_css = new simple_html_dom();
    $global_styles_css = new simple_html_dom();

    // load files into simplehtmldom
    $html->load_file($sourceDomain); // the generated HTML
    $global_styles_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/global.styles.css');
    $responsive_desktop_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/responsive.desktop.css');

    // #header-wrapper and #nav-wrapper are the ids of the header and menu
    $topbar = $html->find('#header-wrapper', 0); // the zero here is necessary because simplehtmldom returns a collection
    $navbar = $html->find('#nav-wrapper', 0);

    // prepare Cross Origin Resource Sharing header
    $header = "<!-- This header necessary using CORS http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ -->
    <?php
    header('Access-Control-Allow-Origin: *');
    ?>";

    // some more CSS rules that are not in the css files
    $morestyles = '#google-appliance-block-form{width:100%;height:30px;text-align:right}#block-google-appliance-ga-block-search-form .container-inline div{display: inline;}.element-invisible, #block-google-appliance-ga-block-search-form label, .url-textfield{display:none!important;}#nav-wrapper ul li a, #menu-bar ul li a {padding: 5px 8px;}#nav-wrapper ul li.last, #menu-bar ul li.last {
    border-right: none;}';

    // prepare the CSS style tag; in case we do not want css, we only have to unset the $global_styles_css var
    $cssStyles = $global_styles_css ? '<style>' . $global_styles_css . $responsive_desktop_css . $morestyles . '</style>' : '';
    // replace relative image urls with absolute
    $cssStyles = str_ireplace("../",$sourceDomain . "/sites/all/themes/adaptivetheme/site_namedaptive/",$cssStyles);

    // assemble output from components
    $output = $header . $topbar . $navbar . $cssStyles;

        // create directory if not exists
        if (!file_exists('public://global_header')) {
                mkdir('public://global_header', 0777, true);
        }

    //write the file that will be fetched by the script tag embedded in the target site
    $filename = "public://global_header/raw_header.php";
    file_put_contents($filename,$output);
}

here is the code in the js file:

//cross-browser see http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){ //IE
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}
var sourceURL = 'http://site.com/';
var request = createCORSRequest("get", sourceURL + "/sites/default/files/global_header/raw_header.php");

if (request){
    request.onload = function(){
    // do stuff if request is successful; if it fails, there is no replacement of existing HTML in target site
  // look first if a container with id #header-id exists, if not use the existing #topbar container
    document.getElementById('header-id') ? document.getElementById('header-id').innerHTML = request.responseText : document.getElementById('topbar').innerHTML = request.responseText;
    // change a relative image URL into absolute
    document.getElementById('branding').getElementsByTagName('img')[0].src = sourceURL + '/sites/default/files/image.png';
    // change relative Google Appliance Search action into absolute
    document.getElementById('google-appliance-block-form').action = sourceURL + '/';
    };
    request.send();
}

example script tag:

<script src="http://site.com/sites/all/modules/custom/module_name/module_name.js"></script>


What I did instead: Since all I really want to know is when e-mail fails, I went the watchdog rules route instead. Combining watchdog rules with the Slack API allowed me to create a rule that sends a slack message whenever one of our sites has an smtp error.


How to programmatically embed iframe in a page

Unless you provide an absolute URL, Drupal will treat it as relative. So yahoo.com becomes https://example.com/yahoo.com, which explains why you're seeing your own site embedded.

To solve, just use an absolute URL:

'#context' => [
  'url' => 'https://yahoo.com'
]


Simply you need to create a custom resource as described here.

In the call back put the piece of code answered here

taking args int he resource, But I suggest using field_info_field as it only takes the field name and returns all details as an array that you could choose what you need to return


I have the same issue and I think this is not possible: The destroy() method was implemented in the Superfish jQuery plugin since version 1.7, but the Superfish module uses version 1.4.8 of Superfish jQuery plugin.


On this time scale, a cache TTL probably isn't the way to go, since the age is counted from creation time without respecting calendar years. You know exactly when the cache should expire (midnight on New Years') so instead of giving it a one-year maximum age it may be better to just actively clean it with a cron.

To avoid throwing away the entire cache (which can lead to significant performance degradation on some sites), you can use a cache tag:

$render['#cache']['tags'] = ['date:year'];

And then, in the annual cron, just invalidate the date:year cache tag like this:

function custom_cron() {
  $last = \Drupal::state()->get('system.cron_last');
  if (date('Y') !== date('Y', $last)) {
    Cache::invalidateTags(['date:year']);
  }
}

(Note that this solution does the absolute minimum of cache invalidation. If you find that your site performs well even if you completely purge the cache every day, that's fine.)


Horrible frontend performance on large CCK forms = poor UX. What are my options?

I have exactly this problem and I can confirm answer #1 - using a multi-step form improved performance, although it was still slow.

The problem is that when the Ajax fires, the entire form is rebuilt in the background. This appears to make huge demands on the server CPU if the form is large.

A multi-step form is a good way of improving things but unfortunately will not always be appropriate - in my case, the client rejected it because they felt it was too annoying to have to progress through the form in a step-by-step linear way. They wanted to be able to jump from tab to tab without saving in between.

Other than fixing Drupal core so that rebuilding the form does not require 20 seconds of max CPU, the only solution I can think of is to try the site out on a high-CPU hosting package, e.g. on Amazon AWS. This will be my next step.

Without knowing much about Drupal core and Ajax, I would call this a bug of sorts. I have heard that the performance of Ajax is being improved in Drupal 8 so I seriously doubt much effort will go into resolving this in D7.

If I had known all this at the start of my project I might have tried solutions such as combining several node forms on one tabbed panel - to break up the server load in more creative ways.


How to display Meta tag description for Views genereated page

You need to enable the metatag_views module, that already comes with the Metatag bundle. Once you install it, you will see a new section on the page where you edit views, and you can update description there.

The section is called "Metatags", and there you can override the defaults for a specific view.


How to change the logo image dynamically when user change language?

paste in page.tpl.php some condition like

if ($user-> language == 'ru') $logo_url = '../rus.jpg'

etc


Implementing redirection on node viewing without affecting solr search indexing

How about doing this in hook_init() instead, eg, something along the lines of...

function YOURMODULE_hook_init() {

   $mgo=menu_get_object();

   if (!empty($mgo->type) && $mgo->type=='THE_TYPE_YOU_ARE_LOOKING_FOR') {

      if (!arg(2)) { // eg so we ignore node/###/edit etc
        if (!empty($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value'])) {
          drupal_goto($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value']);
        }
      }
   }

}

Caveat:  I've never used apachesolr, so you may need to wrap this with further logic to make sure you are running when a user actually goes to the page, eg, arg(0)=='node' and is_numeric(arg(1)) kinda stuff.

ADDITION:

You might be able to just check args inside nodeapi() as well, eg:

if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
  // do your magic
}


You can't create a new value to non-existing field, since the data has no place to save to the database. Ideally you should create a hidden field for your data and modify it in your handler on presave event or use hook_ENTITY_TYPE_presave. If you have multiple values to add, serialize it or save into JSON and assign to the hidden value.

You can also use Computed token field where you can define and place your custom token (with any dynamic data) into value of that computed field which can fetch and store the data dynamically.

Related: Is there a webform way to store additional data on a submit handler?


Suddenly unable to add a field to a new content type

It turns out a configuration change is the cause of this error. Disabling APCu caching and using the ChainedFast cache backend was the cause.

More detail can be found: https://www.drupal.org/node/2722615