How to hide menu settings at content creation for specific content types

You can use hook_form_alter placed in a custom module or in your theme's template.php file for this. Try something like this:

function THEME_OR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  // There's probably an easier way to check if it's an update or create form.
  if (!$form['nid']['#value'] && $form['type']['#value'] == 'page') {
    unset($form['menu']);
  }
}

I'm not completely sure about the $form['type']['#value'] value. You might want to double check that so you won't get any false positives on other pages which also has forms. You could use $form_id for this, but that variable is unique for each content type.


Just use the url() function. It will return aliased path if you have pathauto installed.

Example:

$link = url('taxonomy/term/1');


How to update the language in a existing node entity?

You should be using the get()/set() methods (of the FieldableEntityInterface), sth like this:

// Get the current node's language.
$node->get('langcode')->value;
// Set the current node's language.
$node->set('langcode', 'de');
// Save the node to persist the change.
$node->save();

Hope this answers the question for you.


Call template file, hook_theme() thru theme( hook, $data )

Your code looks fine to me; make sure you've cleared Drupal's caches since implementing hook_theme(), and your preprocess function, as these implementations are cached, and won't show up in the registry until you do.

FYI, the "path" property is not required if the template file resides in your module's folder: Drupal will check there first anyway (this won't be causing the problem though).


How can i give alphabets only validation in webform?

If you want to go for a module, Try the Webform Validation module

This module adds an extra tab to each webform node, allowing you to specify validation rules for your webform components. You can create one or more of the predefined validation rules, and select which webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.
The following validation rules are currently included:

Numeric values (optionally specify min and/or max value)
Minimum length
Maximum length
Minimum number of words
Maximum number of words
Equal values on multiple fields
Unique values on multiple fields
Specific value
Require at least one of two fields
Require at least one of several fields
Minimum number of selections required
Maximum number of selections allowed
Exact number of selections required
Plain text (disallow tags)
Regular expression
Must be empty (anti-spam: Hide with CSS)
Words blacklist
Must match a username


Boost not caching anything. is_cacheable always set to false

Looking at drupal_page_is_cacheable, it appears that there are 4 functions that use the cacheable flag.  drupal_page_get_cache and drupal_page_set_cache are to be expected, and use it simply as a flag.  Unfortunatley, drupal_session_initialze and drupal_set_message set cacheable to false.

In session initialize, if a user has visited your site at all and has a session cookie and any session variables are set then the page will not be cached.  Similarly, if you set any messages during the page generation, it will also not be cached.  While the former may have benefit, the later (IMO) is completely ridiculous.

Also, this issue on Drupal.org, but that really only addresses the first issue of session variables and cookies.

... commenting out the 'return' fixed the issue for me.  404 and 403 still not cached and you can specify other pages to be excluded in the boost settings page.


Automatically create redirect for a file when the file is renamed?

Using hook_node_presave get the url of the old one (foo.pdf) and the new url of the new one (foo_0.pdf) and then create a new redirect as shown by 4k4 here.

To get the orignal value (ex: title), I know in D7 you can with $node->original->title not sure if this still works on D8, have not yet tried it.

Also, since your url ends with .pdf I am not sure if this will work, but hopefully it will.


How to display only Duplicate values with a view

Try using Remove Duplicates

  This module helps the administrator to easily remove duplicate nodes according to one of the node fields.


Need help with import problem on Aquia DEV desktop for Windows

We fixed this with a hammer.I hope we can find a more precise fix in the future.

These are the instructions I gave to our team

Go to root directory of your original localhost Drupal installation  (aka codebase)
Copy all the stand alone files –leaving the folders uncopied
Go to the root directory of your Drupal installation that you are trying to import (aka codebase)
Delete all the stand alone files in the codebase (leaving folders)
Paste in all the stand alone files from the localhost codebase

This should get things working again.


How to download a file from private file system

You just need to call file_create_url().

It will return an URL that will go through Drupal which will then check the appropriate permiss (if you need custom checks, you need to implement hook_file_download)


That only happens when the test is aborted (e.g. fatal error inside the test class) so that Simpletest isn't able to do the cleanup.

There is a button called "Clean environment" at the bottom of the test overview page and a message telling you about that button when a test is aborted.


hook_preprocess_page() is called before hook_preprocess_html(). hook_preprocess_html() would probably be the last one that's run in a page build.

If you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template.

function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'something') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

You can add a custom template for any content type like:

node--[node-type].tpl.php

I would suggest you to use hook_preprocess_page at template.php for this:

function MYTHEME_preprocess_page(&$variables, $hook) {
    if (isset($variables['node'])) {
        if ($variables['node']->type == 'something') {
            $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
        }
    }
}

Note: Don't forget to clear your cache after this :)


How to hide install new module link on http://localhost/admin/modules page?

Why not just remove the Administer modules permission under System for that role?


See permission for this field.

In the admin section: /admin/people/permissions


Do these options affect other modules and possibly core?

This is just fine, this thread describes that it is there by default.

So it is fine to set minimum-stability to dev.

The reason why you can set the minimum-stability, is because that prefer-stable, prefers stable packages over unstable.


How do I add a template suggestion for a Views block?

You need to name your template based on the rules for Views templates.
For example, "views-view--partners--partners--sales.html.twig" would mean:

viewid: partners
view-display-id: partners
fieldid: sales

If this is correct, then all you need to do is clear the cache and reload; the template should be picked up automatically.


Title field input not appearing when creating content type by module

the error is obviously because you use a wrong base
change it to 'ct_conversacion'
see https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_type_save/7
base: A string that indicates the base string for hook functions. For example, 'node_content' is the value used by the UI when creating a new node type.


How to add a tpl file to a block from a custom module

You have to call your theming function:

$block['content'] = theme('tados2_block', array('title' => 'foo', 'content' => 'bar'));


the $query->execute(); return an array of key/value like [KEY => nid1]:
if you are sure you have only one node with that tittle you should get the first element of the array it's your nid try with:
 $query = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->condition('title', 'my node title');
$nids = $query->execute();
// Get the nid in the array.
$nid = reset($nids);
$node = Node::load($nid);


"Article" html tag in body of Basic Page content type: what template is rendering this?

I always clean that part in node.tpl.php, that's the default template for nodes if you don't have one for each content type. So i would try changing the article tag for a div tag on that file.
You can make sure that it works cleaning all caches from your Drupal


How do you import a database through lando?

lando db-import <path to sql or sql.gz or .zip file here> will do that for you.

db-import will drop all tables before performing the import.  it has a --no-wipe flag that can be used if you don't want to drop tables first.

More information in the documentation: https://docs.lando.dev/guides/db-import.html


Facetapi combined filter of city and zip code

I used the search_api_combined.

In the search index, there will be a new tab with the name "autocomplete". Go to that tab and select your view and save the settings.

Then in the view filter, select your desired field and make it expose filter.

And also make that combined field a multivalue field with type full text.


How do I generate-content of a particular type with drush 9.x+

Yeah, it's --bundles now. That's also what the error output is telling you already when echoing all possible options.
drush genc 10 --bundles article,page


Problems trapping AJAX'ed form input click event

Because the form is being loaded via ajax, your click handler is not binding at the right time. You need to use Drupal.behaviors, the context argument, and possibly the one() method to attach this.

Or a less drupally (but better jQuery) solution would be to use delegated events like

$(document).click(function(event)) {
  if ($(event.target).is(".form-submit") {
    alert('test');
  }
});

Note: delegated events are way more elegant in modern jQuery, the on() method is great for this. But the above is probably the best you can do in jQuery 1.4.


Saving file to drupal site using drupalgap

Once you have the File ID, that means you've successfully saved the file to your Drupal site. Next up (typically), you'll want to attach that File ID to a new/existing Entity (e.g. node).

If you are creating a new node, use a POST, if updating an existing one, use a PUT.

New

  /my_endpoint/node.json

{
  type: 'article',
  language: 'und',
  title: 'Hello',
  file_images: {
    und: [ {fid: 12 }]
  }

}

Existing

  /my_endpoint/node/456.json

{
  type: 'article',
  language: 'und',
  title: 'Hello Again',
  file_images: {
    und: [ {fid: 12 }]
  }

}

FYI, the latest version of DrupalGap now supports image fields, so you shouldn't have to write any custom code.


How to display permanent arrows on the left/right of a carousel when using the Flexslider module?

The following CSS will get you started:

.flexslider .flex-direction-nav a.flex-prev,
.flexslider .flex-direction-nav a.flex-next {
    display: block;
    opacity: 1;
}
.flexslider .flex-direction-nav a.flex-prev {
    left: 0;
}
.flexslider .flex-direction-nav a.flex-next {
    right: 0;
}

This will also help:

.flexslider .flex-direction-nav a:before {
    font-family: serif;
    content: "";
}


Drupal 7: Protect entire site in a maintaince mode-esque fashion

Remove the permission that allows users to view published content.  They'll get an access denied message.  Create a custom 403 page with the login info and poof!  Robert's your mother's brother.


Should I edit a closed issue with the issue summary template?

Yes. It's completely appropriate to edit an issue to clarify the findings, solutions, workarounds etc. and make it easier for people who may look to that issue for reference.


There are a variety of content access modules, so you might want to look around to find one that best suits your specific needs but a good start is often https://drupal.org/project/content_access

As for automatic role delegation, there are a variety of ways you can do so, too. Rules is a great place to start https://drupal.org/project/rules but depending on what your requirements are, you might need to write a custom module. There are also a variety of rules-related modules that expand on it's offerings that might help you out. Rules is very capable for many things but sadly, if you have very specific needs it might be a little more complex than point-and-click.


When/where to include my own function library (like common.inc)?

Probably best to put it in it's own custom module, e.g

sites/all/modules/custom/mymodule_common

and enable it as required.

You can make it a dependency of other modules by adding it to those module's .info file, e.g

dependencies[] = mymodule_common

You could also use subfolder and standalone file in sites/all/libraries/common though the module route is recommended.


Problem attaching files to nodes with Services

try adding more data to the attached file (it might be that fid and filename is not enough I can't find the example I used a long time ago, which had a similar problem):

alt (might be required in general or only if marked as required in bundle)
title (might be required in general or only if marked as required in bundle)
uid
filemime
uri
status = 1
display = 1

Some references I could find quickly:

https://stackoverflow.com/questions/5129559/attaching-image-files-to-nodes-programmatically-in-drupal-7
this answer: https://stackoverflow.com/a/19930610/1158887
https://drupal.stackexchange.com/questions/120078/is-it-safe-to-reuse-the-fid-file-id


Twitter module Oauth 'TwitterException' with message 'Unauthorized'

This just started working with no change- I can only assume it was a temporary problem with Twitter at the time.

To some degree a useless answer, but the question gives others a list of things to try in the same situation and allows me to mark this question as resolved.


Force user to fill in at least text area or file

I don't know how you could achieve this with rules. You could however create a small custom module that adds a form validation function to the node edit form. The validator would check that the appropriate conditions are met.

Edit: something like this would work I think for content type page.

/**
 * Implements hook_form_FORM_ID_alter for page_node_form.
 *
 * @see module_validate
 */
function module_form_page_node_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'module_validate';
}

/**
 * Form validator for page_node_form.
 */
function module_validate($form, &$form_state) {
  // This strips HTML tags - to disable, remove the filter_xss() call.
  $body_length = drupal_strlen(filter_xss($form_state['values']['body'], array()));

  // We're assuming the field is called 'file' and we're checking the first file.
  $file = $form_state['values']['field_file'][0];

  // Rather than checking against 300, we should perhaps call node_get_types()
  // and find the configured word limit.
  if (body_length < 300 && !$file['fid']) {
    form_set_error('body', t('Please ensure that you either enter 300 characters into the body field, or upload a file.'));
  }
}


How to add a specific menu item in Panels?

To the best of my knowledge, Panels can only interact which whole menues.

One option is using Menu block to slice a menu into pieces, exposed as blocks. I don't think menu blocks however can pick one item, though I haven't looked at all the advanced options.

If you just want a single menu item, can you just emulate the markup?


Entity reference field definition to auto create entities

The answer is 'you cannot auto-create bundle-less entities in Drupal 8.2.0. I don't know if this is a bug or a feature, but you have to have a bundle for target entity ('all_target_entities' in my example) and indicate that as target bundle in the settings:

$fields[$field] = BaseFieldDefinition::create('entity_reference')
    ->setSettings([
        'target_type' => 'target_entity',
        'handler' => 'default',
        'handler_settings' => [
            'auto_create' => true,
            'target_bundles' => [
                'all_target_entities' => 'all_target_entities',
            ],
        ],
    ])
    ->setDisplayOptions('form', array(
        'weight' => $weight,
    ));
;

I think it was not the case up to some point, so stating the exact version I am having this issue with.


Disclaimer: I've never done this with Drupal 6.

You want to use a menu callback: You create a menu item (which is just a path associated to a PHP function), and point your query request at that path.


7- Disable a block or edit it without access to the admin interface

If you have devel installed, you can edit the default theme by editing theme_default variable.
http://yoursite.com/devel/variable/edit/theme_default

Or deactivate the block in your database

update blocks set status = 0 where delta = 'block';


Displaying the submitted values in a table

You don't need to redirect the form like that: a form submission handler can pass data to the form builder using $form_state; in this way, you don't have any limit for what you can pass back to the form builder.

It's enough the form submission handler uses the following line.

$form_state['rebuild'] = TRUE;

Then it saves in $form_state the values to pass back to the form build, being careful not to use the same index used for other purposes, from Drupal, or your module. Usually, $form_state['storage'] is used for that purpose, as explained in $form_state keys.

  $form_state['storage']
      When building complex forms that require multiple steps for completion (for example, a three-page survey), it's necessary to preserve the data from all steps so that they can be processed together at the end. (And, on occasion, to vary the contents of one step based on the input from the previous one). Any data placed in the 'storage' bin of the $form_state collection will automatically be cached and re-loaded when the form is next submitted, allowing your code to accumulate data from step to step and process it in the final stage without any additional code. Developers who want more control can use their own caching mechanisms to store temporary form data (the user session and hidden form fields are two popular alternatives), but the 'storage' bin is automatically handled for you by the form API.

That is for Drupal 6; for Drupal 7, see drupal_build_form().

  storage: $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

If you really need to print the data in another page, then save the data in $_SESSION, instead of passing that as GET data.


How to pass arguments based on term filter

If I understand your question correctly, here are the steps you'd need to take to override the default taxonomy term view with your own customized one.

Go to the listing of available views on your site at /admin/structure/views and at the bottom of the page you'll see grayed out views that are not enabled.  One of them will be the Taxonomy term view which is delivered by default with the module.  Let's go ahead and clone it, so we can customize to fit our needs.
Hit 'clone' next to that view, in the drop-down options and rename it to something like 'Custom Taxonomy term'

Next, navigate to the 'Page' display and change the Format to display 'Fields' instead of 'Content: Teaser'

Add whatever fields you want.  It sounds like in your case, you'd want to add the Title field.  I would uncheck the label from being displayed (uncheck 'Create label') when configuring the field.

Finally, save and navigate to your view again: www.mysite.com/taxonomy/term/3 and see the change!  Your new view should be picked up and will replace the old one.

Go ahead and beautify and edit as you please from now on to customize the default terms view.  Hope this helps!


How does the new config_exclude_modules setting work exactly?

Enable the module and activate the filter by declaring $settings['config_exclude_modules'] in your settings.php file, eg:

$settings['config_exclude_modules'] = ['devel', 'stage_file_proxy'];

Now, when you export configuration (drush config-export), the selected modules should no longer show up in core.extension.yml and their configuration should not be exported.

Make sure first before doing that to remove these module from core.extensions.yml manually for the first time.

Update:
It seems to be related to a drush issues:
drush config:status does not respect excluded modules #4194


How to insert a hashed password into table users?

I solved it by using user_authenticate($name, $password) (see https://api.drupal.org/api/drupal/modules!user!user.module/function/user_authenticate/7)

Now my code is :

function my_module_connexion_login($username, $password){

$authentification = user_authenticate($username, $password); <======

$log = db_select('users','u');
$log->addfield('u','uid','id_user');
$log->addfield('u','name','username');
$log->condition('name',$username,'=');
$login = $log->execute();
$connexion = array();

foreach ($login as $co) {
    $connexion [] = array(
        'uid'=>$co->id_user,
        'username'=>$co->username
        );
}
if($authentification == false){ <==================
    $response = array();
    return func_succes(3,$response);
}
else{

    $response = $connexion;
    return func_succes(0,$response);
}
}

Thanks


views and contextual filters with entity reference field

In the contextual filter, you can use php to supply the argument.  There, you could put in something like:

$node=menu_get_object();
return $node->field_headliner[0]['nid'];

where field_headliner is the node reference field of your event content type.  The exact syntax above is D6, but I am pretty sure it's the same or at least very similar in D7.

Then, just as long as this view block is being show in/on an event page, the above will return the nid of the headlining band, and if your view is set up to filter on that node nid, you should be set.

You could even get fancy up in there with something like:

$node=menu_get_object();

switch ($node->type) {
  case 'band':
    return $node->nid;
  case 'event':
    return $node->field_headliner[0]['nid'];
  default:
    return 0; // or however you want to return an error
}

and then the same view block display could be used on both types of page.  Then just put this block on band and event pages and you should be all set.


Is it possible to publish/unpublish content by language?

I found the solution.

In your Content type settings
Synchronize Translations --> Status should be unchecked.


How do I programmatically save longitute and latitude?

Try this :

$point = [
  'lat' => $lat,
  'lon' => $lon,
];
$value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point);
$WayPointEntity->field_geo_field->setValue($value);


Fatal error: Unsupported operand types in field.info.inc

Your problems indicate that the copy did not come out right. Rather than try to diagnose the symptom, start over and copy the site again from scratch. If you can use Drush, perhaps Drush rebuild would help.  You could also use the drush rsync and drush sql-sync commands directly.


How do I disable the default node creation form for a particular node type?

A different approach would be to deny access by throwing an exception, which also affects admins:
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_recipe_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  throw new AccessDeniedHttpException();
}

The Form ID consists of ENTITY_TYPE_BUNDLE_FORM_MODE_form. This assumes you use for your specific recipe form a different form mode.  If not, you can check the reference field value in $form_state->getFormObject()->getEntity() before throwing the exception.
By the way, the hook name doesn't contain a form mode because nodes use the form mode default for the add form, which is omitted in the Form ID. The node edit form for example has the form mode edit, so the form alter hook would then be named mymodule_form_node_recipe_edit_form_alter.
Since this approach is not based on entity access permissions it doesn't remove the link from the node add list. You can do this in a separate hook:
/**
 * Implements hook_preprocess_HOOK() for list of available node type templates
 */
function mymodule_preprocess_node_add_list(&$variables) {
  unset($variables['content']['recipe']);
  unset($variables['types']['recipe']);
}


Assuming you're using the default wodby/drupal:8-7.1-3.3.2 container image, the drush launcher is already installed in the PHP FPM container.

Thus, your next step is to update your Drupal 8 composer drush dependency via composer:

composer require 'drush/drush:^9'

When drush launcher executes under your web root it will pick up the version 9 that's installed in your vendor dir.


Changing size of user avatar in template file

This is definitely the command you want to run

theme('imagecache', 'your_custom_preset', $picture, $alt, $alt);

You will have to install imagecache module for Drupal 6.  Its in core for Drupal 7.   You have to define 'your_custom_preset', in the imagecache profiles.

The other place you can theme the avatar is inside the function
[YOUR_THEME_NAME]_preprocess_user_picture(&$variables)  and again use the same line as above. for more information checkout the api.drupal.org documention on this issue


You can get the current menu object with menu_get_object(). From there you can determine if that object is a node or not. Since it defaults to "node" it will be empty if you're not on a node page and will have all the normal node object stuff available if you are.

$node = menu_get_object()


What is the correct way to create a new ImageItem and attach it to a FileFieldItemList?

You don't need any of that. You just set the values, everything else will be taken care of for you.

$node->set('field_gallery', [
  'target_id' => 123,
  'alt' => 'Alt text'
  'title' => 'Title text'
]);

If you want to have multiple items, use `$node->field_gallery->appendItem($values);


How to make a popup on a node's content using the colorbox module?

For creating pop-up's in colorbox, you can simply use Bootstrap Modal Window.

Don't forget to include the below ones:
1. bootstrap.min.css
2. jquery.min.js
3. bootstrap.min.js

FULL WORKING CODE:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Small Modal

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

          <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

This is a small modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


Ofcourse you can...

Make a copy of views-view.tpl.php in your theme.

Then you put your tag around the output of the $pager variable.

  <?php if ($pager): ?>
    <somemadeuptag>
       <?php print $pager; ?>
    </somemadeuptag>
  <?php endif; ?>

UPDATE

  "no that is not what i looking for, i need put html tag inside $pager variable"

You need to use hook_pager_link() in your theme.

Search for 'hook_pager_link' in your sites code directory to see example.


How to display a view of products that are selectable

Save a lot of head-scratching (not all though;) and use Drupal Commerce Custom Product:

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

It's not that you can't do this with 'normal' Drupal, it's just that Commerce Custom Product is set up to do precisely what you want... so might as well use it!

HTH

Steve


I'm getting errors from trying to upload images from 2 different fields, server or module issue?

Most of the time this is hosting issues. Review drupal and php error log to pin point exactly where the issue happens.

Sometimes the upload is successful to the temp folder but it can't move it to the files directory due to permissions ect..


I don't know the exact answer. But maybe this information can get you on the right track.
First the migration process has the ability to update earlier migrated entities, it does this with the help of high-water-marks and timestamps (see Drupal's documentation). Maybe you can do a trick to use this feature. Furthermore there is a lot of good documentation about the migration-process, I recommend this site, an extensive tutorial about the process in 31(!) steps/days, https://understanddrupal.com/31-days-of-migrations or https://www.phase2technology.com/blog/migration-making-it-all-work. Behind it some of the "Drupalstars" from the migration and comprehensibly written. Hope you find your answer there.


How to find all Drupal modules which has dependence

That's really easy to do with Gotta Download Them All. Once you have downloaded all the modules, you can just run a grep command to search the whole contribution space.


How to show both currencies at once in the node page for price field

Commerce Multicurrency does exactly that.

  This module enhances some of the multi-currency capabilities of Drupal
  Commerce.

  Current features:

  UI for fine granular definition of exchange rates.
  (Every currency combination can be defined separately if needed)
  Synchronization of currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled manually.
  Generation of currency specific price fields inclusive generation of rule-set to handle them.
  hooks for easy integration of custom currency exchange rate sources.


How to create a chart about a date range if some dates in this range are missing?

I'm assuming you're using the Charts module and that your problem is similar to what is detailed in Comment nr 12 of Issue nr 2052429. Here is part of what that comment includes:

  ... It's not an issue Google Charts could actually fix, as there is no "labels" sent to Google Charts for the chart addons for it to recognise gaps in the data ...

So at a minimum I recommend you to try the most recent DEV version, and apply the patch attached to that comment, to check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work).

If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.

Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.


This setting only sets the default for nodes, so already created nodes will still have their comments turned on. Easiest way to update all the nodes is with a couple of SQL statements, back up your database first.

UPDATE node SET comment = 0 WHERE type = 'your_content_type';

UPDATE node_revision nrev
  INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
  SET nrev.comment = 0;

then clear cache.

Note that comment can equal the following:

0 = disabled
1 = readonly
2 = read/write.

More details at How to finally disable comments on content type?


How to integrate CAPTCHA in a search form with Views

If you go into the CAPTCHA configuration page, there should be an option to "Add CAPTCHA administration links to forms". If you enable this then visit your views page, an option should appear to add a CAPTCHA next to the exposed filter (the option may be a little mangled depending on your layout, it expands out fine when you click it).

A heads up that this can sometimes generate some extra warnings, see how you go.


How to place the language switch in the main menu bar?

Check your page.tpl file and check where it is, OR, you can check the list of blocks in your site to see where it is placed and move it to your desire position


Once you have preprocessed your variables in theme_preprocess_node() you can print them in node.tpl.php

The best practices would imply to declare one node.tpl.php per content type like this : node--my-content-type.tpl.php replacing my-content-type by the name of your own content.

In theme_preprocess_node() the best way to get the value of a field would be like this :
In template.php the first function is only here so you can have one preprocess function per content type.

/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node(&$vars, $hook) {
  // Optionally, run node-type-specific preprocess functions, like
  // mytheme_preprocess_node_page() or mytheme_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $vars['node']->type;
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

Then you can declare your function for your content type and get the value of your fields with field_get_items() and field_view_value() in order to only get the value and not all the divs all around the field value.

/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node_my_content_type(&$vars, $hook) {
  $node = &$vars['node'];
  $first_name = field_get_items('node', $node, 'field_first_name');
  $last_name = field_get_items('node', $node, 'field_last_name');
  $vars['first_name'] = field_view_value('node', $node, 'field_first_name', $first_name[0]);
  $vars['first_name'] = field_view_value('node', $node, 'field_last_name', $last_name[0]);
}

and then in your node--my-content-type.tpl.php you can print your variable like this :

<?php print render($first_name); ?> <?php print render($last_name); ?>


How to specify Views page as parent for menu link?

Views generates menu link id's with a prefix views_view: and the first page display normally has the id page_1, so the parent should be something like this:

  parent: views_view:views.branch_locations.page_1

There is no error thrown, if parent: doesn't match an existing menu link. It's ignored and the menu link appears in the top level of the menu.

It doesn't matter from which provider the menu links are from, all discovered menu links are treated equally in the menu tree table.


Can i specify an image style in my custom module

There are several options:

Use a view
Use Twig Tweak with a display mode, where you configure the image style
Use this code How to find image style URL from within twig template?

If you don't need more than what is in your question, I would start with 1, because don't reinvent code for things that are in core.


Using the PHP filter in the fields should require you to use <?php ?> tags as part of the content.

The views data (unless its been exported with features) will sit inside the cache_views table in your DB, so you should be able to reliably find views using PHP filter by searching like so:

SELECT * FROM cache_views WHERE data LIKE '%<?php%';

There is probably a more sophisticated way of finding this.. but hopefully its a good start!


I searched for this a while and found some solutions.

The thing is make sure you have rendered the <?php print render($page['content']['metatags']); ?> in page--front.tpl.php


Select users that do have certain roles and do not have others

According to Drupal db_select API Use this to fetch user id and names that user have roleId 13 and not have roleId 14

$query = db_select('user', 'u');
$query->join('role', 'ur', 'u.uid = ur.uid');
$query->fields('u',array('uid','name'))
 ->condition('ur.rid', 13)
 ->condition('ur.rid', 14,'<>');
 $result = $query->execute()->fetchAll();
dpm($result);


I ran into similar problems and managed to fix it by enabling Aggregation on the view plus enabling 'Distinct'.


Calling menu in a certain way from page.tpl.php

You can use menu_tree_all_data function to get all nested menus. And then you can add your own html to display menus with your style

$menutree_produce = menu_tree_all_data('menu-produce');

And if you want to Active current menu on related page you can use menu_get_item and menu_set_item on that page

$menu_item = menu_get_item(drupal_get_normal_path('produce/oranges'));
menu_set_item(NULL, $menu_item);


After discussion with omega8cc, and a bit of testing, the answer is that advanced_cron is not any more compatible with Aegir 3. It is also merged into BOA (by omega8cc) in their core, and it is not back compatible with stand alone Aegir.

There are two options:

port it to work with standalone Aegir 3
use crontab and wget / curl to trigger cron on site


"&" displaying as "&" in Views exposed filter

So I used this jQuery search & replace to fix it client side, I still want to find & fix the issue the proper way & will update this when I do. Here is my resulting jQuery snippet:

(function ($) {
$(document).ready(function(){
    $("form#views-exposed-form-maps-page select#edit-destination option").each(function(){
        var text = $(this).text();
        text = text.replace("&amp;", "&");
        $(this).text(text);
    });
});
}(jQuery));


You don't need to create a content type for each different page. You need some tools for site building. I think in your case Paragraphs will be the best solution.

You can for example create different paragraph types with a reference field, one to a content type with one input and one to another content type with unlimited inputs. You can define as many paragraphs types as you want.

Then you put a paragraph field in the page content type and the user can fill this field with the paragraphs he needs to build the content, so that each page can have a different layout.


What are the differences between the various OpenID widgets available?

The first and the last link you provided takes to the same project page.

The OpenID Selector module replaces the OpenID login form provided by openid.module (an optional Drupal core module) with the same OpenID selector used, for example, on Stack Exchange sites. Though additional modules, it integrates with login provided by:

Facebook
Twitter
LinkedIn
vkontakte.ru
mail.ru
Windows Live ID

The Loginza module replaces the Drupal core module for OpenID, as it implement OpenID authentication, and it allows to authenticate users using the login provided by the following sites/services:

Google Account
Yandex
Mail.ru
Vkontakte
Facebook
Twitter
Loginza
MyOpenID
WebMoney
Rambler
Flickr
Last.fm
Verisign
AOL
Steam

The other difference between the modules is that the Lorenza module is for Drupal 7, while the OpenID Selector module has versions for Drupal 6 and 7.


You need to create a route, and a controller that builds the response on that route - in your case a form.


How do I display a block on the checkout page based on the product type?

Around the time some Item1 (or Item2) is added to your cart, grant that user access to a role like "HasItem1InCart" (or "HasItem2InCart"). Use the Rules module to grant such access, using a Rules Action like "Add user role".

Within the block visibility settings for Block1 (which you want to show if Item1 is in the cart), only show that block to users with roles ... you probably guessed it .... HasItem1InCart (same for Block2 and HasItem2InCart).


Dynamic link in nodes to hidden Quick Tabs tab

In Drupal 7, you can achieve it by using jQuery

Without reloading page :
Just create a Dynamic link using ID attribute or some other attribute, by using these attribute just click the TAB using jQuery.
Dynamic link like

Link text OR

Link text OR

Link text

  jQuery("#dynamic_link_ID").click(function(e) {//OR by using other attribute
    e.preventDefault();//it will not redirect when link is clicked
    jQuery("#quicktabs-tab_ID").click();//OR use any selector as per you requirement
  });


$language variable causes a lot of notices as non-object

For your issues you can refer

these links have given some patch for these notices

https://www.drupal.org/node/1907684
https://www.drupal.org/node/1104822
https://www.drupal.org/node/1853170


Drupal Search - Not searching for menu items

As a work around I would try to creat a "funny" content type for each Menu Item and them redirect it to the original page link of each Menu Item.


How to override the menu_tree without affecting the admin menus

You should use theme_menu_tree__MENU_NAME().


How can I only show the first image of an image field in the teaser?

Create a custom image formatter by copying the default ImageFormatter.php from the image module into a new custom module, rename everything properly and then add only one simple break; at the last line of the foreach in viewElements(). Choose that formatter under display settings for your teaser view mode of your content type. Works in views, too.

Done that for you in a quick custom module: image_first_formatter.


"Accept answer" button for Advanced Forum comment

Answers module as a possible alternative

To implement something like "the poster of the question can accept one of the answers" (as in your question), you'll need something to allow one or more answers to be posted, and also have a way to create a (visual) relationship between the answer(s) and the question.

To do so, you might want to have a look at the Answers module (disclosure: I'm a (co-)maintainer of it). Either to actually use this module, or to get inspiration from it to see some of its features at work.

Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Since a picture is worth more then 1000 words, here is a sample screenprint of it (head over to its project page for more details):

About the Answers module

At its core, this module exists of 2 typical content types: Question and Answer (what other names would you expect ...).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module (and supports voting, which in this use case may not be needed, unless you want users that evaluate offers to use it).

To be complete:

You can use the "Best Answer" submodule for implementing something like "Node author can accept". And you could make the Rules module trigger all sorts of subsequent things to happen "when an answer gets marked as best answer".
It also comes with a "subscribe" feature (based on the "Message stack", with the amazing the Message module at its core).
Since the module is using (2) standard content types, all sorts of the typical standard Drupal facilities are also available, or can be enabled. E.g. if you want, you can also use a text format like "Markdown text", provided you first enable/configure the Markdown filter module.
... (there is really a lot, not just a bit, more).

Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

These views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).

Try it out

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x version). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Release recommendation

To decide between the 7.x-3.2 and the 7.x-4.0-rc2 release, I would recommend the 7.x-4.0-rc2 (which also has the shiny new theming stuff ...). Even though it is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. Pretty soon an rc-3 (the last 'rc' release?) should become available also, which will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).


How to add auto create feature to custom taxonomy_term field while creating custom entity

I did it using below handler setting

setSetting('handler_settings', ['target_bundles' => ['question_sub_category' => 'question_sub_category'], 'auto_create' => TRUE])


Overiding homepage template problem. "page__front.tpl.php" won't be loaded

The template filename should be "page--front.tpl.php"; you should use hyphens, not underscores.


Show a block within node content (field template) based on context/taxonomy?

you can do what i did before :

-1 install computed field module and enable it.

-2 you have to call the specific views that you want in computed field like this way

<?php
$view = views_get_view('your_views_name');
$view->set_exposed_input();
$display_id = 'default';
$view->set_display($display_id);
$view->render();
$entity_field[0]['value'] = ($view->preview());
?>


I added following lines in modules/image/image.module, on line 1056 and it started working.

// Create derivated image if it doesn't exist.
  if (!file_exists($file_url) && !file_exists($uri)) {
    if (file_exists($path)) {
      $current_style = image_style_load($style_name);
      image_style_create_derivative($current_style, $path, $uri);
    }
  }

FYI: This change comes with a risk of when Drupal core updates, this will get removed. Also, I found it affected the performance of search in our platform. So, need a permanent solution.


Views Page Showing Root Title in Window (not views title + root title)

The title for a view does not show up in window title.   The Window's title is determined by the browser, independent of Drupal. The view title is used as the title before the body of your content in the content display area of the window provided you have configured the view to display the title.


You will need FileField Paths. See ImageField Tokens for tokens in default values for alt and title attributes as well.


Access denied or format unknown on field in Services Views

You just need to uncheck the "Use field template" inside the "STYLE SETTINGS" of your 'publish_date' field.


How can I add {% if %} for a field name?

You copied field.html.twig to a new file, field--field-additional-text.html.twig. After clearing the cache, Drupal will only use this new file for that field only. Now you do not need logic in either template.

So you now can make changes, for example:

{% for item in items %}

{{ item.content }}

{% endfor %}

^ This means, for every item in this field (single or multiple values), print each value wrapped in this div, with this class. However, within a field template, you cannot output different fields as one, the sole purpose of a field template is to render the current field.

Read up on theming Drupal fields for more information.


How can I get the form builder service using dependency injection?

AJAX form test mock module's AjaxFormBlock.php is quite a nice example for getting both in one, the form builder and the form interface! Look how it implements FormInterface, ContainerFactoryPluginInterface to then provide the form from within the block and injecting the form builder via dependency injection to then be used to get the form in the block's build() method at the same time.
Of course, when you only need the form builder, you don't need to implement the FormInterface! Then you just need the ContainerFactoryPluginInterface.

namespace Drupal\ajax_forms_test\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an AJAX form block.
 *
 * @Block(
 *   id = "ajax_forms_test_block",
 *   admin_label = @Translation("AJAX test form"),
 *   category = @Translation("Forms")
 * )
 */
class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactoryPluginInterface {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new AjaxFormBlock.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $form_builder;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('form_builder'),
      $container->get('messenger')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return $this->formBuilder->getForm($this);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ajax_forms_test_block';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['test1'] = [
      '#type' => 'select',
      '#title' => $this->t('Test 1'),
      '#required' => TRUE,
      '#options' => [
        'option1' => $this->t('Option 1'),
        'option2' => $this->t('Option 2'),
      ],
      '#ajax' => [
        'callback' => '::updateOptions',
        'wrapper' => 'edit-test1-wrapper',
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  /**
   * Updates the options of a select list.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The updated form element.
   */
  public function updateOptions(array $form, FormStateInterface $form_state) {
    $form['test1']['#options']['option1'] = $this->t('Option 1!!!');
    $form['test1']['#options'] += [
      'option3' => $this->t('Option 3'),
      'option4' => $this->t('Option 4'),
    ];
    return $form['test1'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger->addStatus('Submission successful.');
  }

}

Another nice example is core's SearchBlock.php.
Also worth checking out the docs on Dependency injection in Plugin (Block).


Instead of adding a wrapper div, you could use !important.

img {
    float: left !important;
    height: 150px !important;
    width: 90px !important;
}

This would override the style added in CKEDITOR. You could do the same for alignment using classes, adding them directly to the image through CKEDITOR.


If you look at the default Taxonomy Term view provided with views, you'll see that it has a contextual filters Content: Has taxonomy term ID (with depth) and Content: Has taxonomy term ID depth modifier. Both are needed. If you look at the description for the Depth field for the first filter you'll see the following:

  The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).

In your case fruit is applied and apple is, for example, Geometry. So if you specify a depth of 1 or higher you should get the behaviour you want.


Map generated from custom address fields

You could use the Geofield and the Geocoder modules. The fist module allows to store geographic data in a field; the second one to extract the geographic data from another field, including an image field.
When you add a new field to an entity (for example, a node), you need to select Geofield as field type, and leave Geocode from another field as widget.

Clicking on the Save button, you will be then asked to change the field settings (which just allow to change the storage backend). After clicking on the Save field settings button, you can choose from which field the geographic data are extracted, including an image field.

The Geocoder module once allowed to select multiple fields from which the geographic data would be extracted, but that was a bug, reported in
Geocode from field allows multiple selections and fixed. If you are reading blog articles or tutorials that suggests you can select multiple fields from which the geographic data are extracted, they are all referring to older module versions.


I was confused by $view->setExposedInput saying it accepts $filters as argument, but it actually works for sorting as well. So with that function you can set your exposed filters AND sorts

$view->setExposedInput([
  'your_filter' => $your_filter_value, //your exposed filter
  'sort_by' => 'your_field', //your exposed sort
  'sort_order' => 'ASC',
]);

Use above code before you execute view.

And make sure you exposed your filters and sorts in your view.


Your site was unable to contact Apache Solr server

Some days ago I had a similar problem.

I've download the SolrPhpClient in the .zip file and Search API was not able to connect to the Solr Server (I don't know Apachesolr, I don't use it).

But if I download the .tgz version of the client.. it works. I think that in the .zip version there is some problem with permissions.

So: if you've download the .zip version, try the .tgz.

And obviously try also the r60 version, I use it alwyas.


Is there a way to see all the available variables inside content?

Normally it works that way but Views templates may be different.

Enable Twig debugging.
Add Devel and Kint: composer require drupal/devel kint-php/kint
Enable Devel: drush -y en devel
Inside the template put {{ kint(content) }}, flush caches, visit the page and you should see what else can be found inside content.


Site internal links should always use URIs relative to your base URL. This would avoid your specific issue. (File entities actually do use URIs relative to the configured public files folder, so that - depending on how you created your file URLs within CKEditor - clearing your caches might help already.)

However, in a mirrored multi-site environment, you can also use the sites.php file to define the base URLs and their respective target site paths. If not configured otherwise, your files folder should use the configured target sites path and all your environments will use the same files location.

Place a sites.php file in your [DRUPAL_ROOT]/sites folder (e.g. by copying and renaming the existing examples.sites.php file) and configure the $sites array keys to your requirements. Example:

$sites['site1.com'] = 'site1.com';
$sites['site1-testing.com'] = 'site1.com';


Commerce Feeds failing to import due to missing bundle property

So, apparently this may be an issue inside of the importer, but what is happening was I was trying to map product_id on to product_id when there was no such field within the product itself that was mappable.


No, you can't truncate a table and leave data in it at the same time. That would be a contradiction in terms.

You'll need to do a standard delete

DELETE FROM users WHERE uid NOT IN (0, 1)

(it's important to make sure the anonymous user, ID 0, remains there too).

If you use the direct approach, be 100% sure that you know what you're doing. Unless you know different, there will probably be related data that doesn't get cleared out by simply removing an entry from the users table.

The best way to delete users is through the API: user_delete_multiple()


drupal 7: new field with dynamically generated select list from PHP code

I think your best bet would be http://drupal.org/project/entityreference module and the entityreference_view_widget. PHP filter is still there in D7 but you have to enable it under modules.


How to reuse existing images in field type "Image"

Projects are built from the start to use the Media module and reference entities instead of files directly. That is how Entity Browser can help.

Here is how it's usually done:
https://www.drupal.org/docs/8/modules/entity-browser/how-to-configure-an-image-widget-to-re-use-existing-files.

More useful resouces:
https://www.drupal.org/docs/8/core/modules/media/faq-transition-from-media-entity-to-media-in-core
Is there any way to reuse the same file or image?

There's a way to convert your files into entities, there is the Migrate File Entities to Media Entities module, and some useful info about it:
Migrate File Entities to Media Entities in Drupal 8,
How do I migrate file entities into media entities?


Got it.

The 'hostname' is not a property of the alias. The way to get the aliases is:

$aliases = \Drupal::entityTypeManager()->getStorage('domain_alias')->loadByProperties(['domain_id' => 'my_domain_id']);

Note that 'my_domain_id' is specific to the domain that you are trying to get the alias for.


The file reference has been deleted, i.e. the record in the file_managed table; the file itself will be deleted later during the system_cron run.

See the 10 or so lines under this comment in that function:

// Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.


webform: additional options for components

Please have a look to the new hook implemented in web form: hook_webform_select_options_info().

function mymodule_webform_select_options_info() {
  $items = array();

  $items['days'] = array(
    'title' => t('Days of the week'),
    'options callback' => 'webform_options_days',
    'file' => 'includes/webform.options.inc',
  );

  return $items;
}

The documentation for that hook describes it as follow:

  Define callbacks that can be used as select list options.

  Return value

  An array of callbacks that can be used for select list options. This array should be keyed by the "name" of the pre-defined list. The values should be an array with the following additional keys:

  title: The translated title for this list.
  options callback: The name of the function that will return the list.
  options arguments: Any additional arguments to send to the callback.
  file: Optional. The file containing the options callback, relative to the module root.


The correct way to change the name of the language in the language switch

Check, if the variable is set, to avoid the error:

function theme_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title'] = '中文';
  }
}


I think you have to load sid like below

// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);


how to save uploaded file in a custom user registration webform in D7?

I believe 46 is the File ID or FID in Drupal. You can load it via file_load() and re-save, move it or attach it to a user profile however you like.

Webform has already saved the file in the system somewhere. You can find out where by inspecting the $file object after $file = file_load(46); and doing a print_r or vardump on $file.


Reestablishing development workflow with GIT after doing it wrong

Commit the changes on the live site to the master git branch and then branch off this to create a develop branch.

The master branch should mirror live and development takes place on individual branches, when you're ready merge or pull request onto the develop branch. When ready to go live merge or pull request into master.


Need full Taxonomy URL to be valid else redirect 404

If you are using contextual filter, then there is validation criteria in settings of taxonomy term name you have selected.

Then add filter value type as taxonomy term name and add action as page not found.

You will get the result.


I think your ternary statement is off in that code.

I would also suggest an alternative approach.  You can use hook_preprocess_comment() in a template.php file or in a custom module.  With this you can hook into the comment before it's rendered to the page, run each comment through an logic test and add a class to the entire comment, or add an html chunk before or after the comment's html.  See more on hook_preprocess and render arrays.


Contextual links for nodes displayed via views

Solved it myself.

Steps:

Enable Global: Contextual Links and Content: Edit Link fields
Exclude Content: Edit Link from display
In Global: Contextual Links settings, select the Content: Edit Link

However this works correctly and fine only while in preview mode, when watching the actual page in action the links nor the cog icon does not appear. As I understand this is some kind of a bug.

To fix that, you need to add additional CSS to your theme, which is (in my case):

.views-field-contextual-links {
  position: relative;
}

And now everything works fine, every element has it's own drop down cog/link.


Pre-select language (instead of "Language neutral") when creating a node?

The option for it is available in admin/config/regional/entity_translation

The Entity Translation configuration page provide an interface to select default language for all content types separately


If you can get your terms into CSV format you can use the excellent Taxonomy CSV import/export module:

  This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.

It has support for importing hierarchical trees like yours, and even supports drush.

It also has good documentation to get you started.

EDIT

You could also try the Taxonomy import/export via XML module which does the same thing but for XML (if you find it easier to get your data into that format). It's only in dev release at the moment but its worth a try.


Need to alter response headers for error pages

You could use a template_preprocess_maintenance_page() invocation in your theme's template.php so that when you go to maintenance mode (or the DB is down) it will trigger your needed status code:

function MYTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_http_header('Status', '504 Service unavailable (with message)');
}


Display taxonomy terms and nodes together

You can use the Views module.  Views provides a view by default that overrides the taxonomy term paths.  Enable this view (or clone the view if you anticipate making a lot of changes and want to reference the original; then enable the clone).

Then edit the view by adding the relationship Taxonomy term: Content using Name_of_my_vocabulary.  You will then be able to add the fields from the product nodes that you want.


How to show a form in Dialog Modal jquery?

There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

  CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup.
I'll add some example code here in case there's some interest.

Link to the form:

'.t('Send message').'

Javascript code to open the linked address in a popup:

if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

In the theme template file:

function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('
'.var_export($form_state['redirect'], TRUE).'
');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}


how to develop features delivered by drupal if there is no cms

The first one is easy.

  How do you develop the same features that you did, if there is no CMS
  (Drupal)?

With a MVC framework like Symfony, CakePHP or Zen.


How to pass a variable about sufficient User Points to a Rules condition in another rule?

There is no Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


Best practice for displaying multiple views in a single page

You can try panels to display multiple views on a single page:

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Panels includes a pluggable caching mechanism, so it could be a good and easy option for you.


Remove specific stylesheets from a given page

This seems to be the cleanest way, in hook_preprocess_page():

$css = drupal_add_css();
unset( $css['screen'] );
$vars['styles'] = drupal_get_css($css);


Inline Entity Form - start with first new node open

I read the codes in the inline_entity_form.module, and found the inline_entity_form_single is always displaying a form, so i copied its code to my module and it works:

function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  $field = $context['field'];
  if (isset($field['field_name']) && ('FIELD_NAME' == $field['field_name'])) {
    if (empty($element['form']) && empty($element['entities'][0])) {
      $element['actions'] = array();
      $instance = $context['instance'];
      $settings = inline_entity_form_settings($field, $instance);
      $controller = inline_entity_form_get_controller($instance);

      $parents = array_merge($element['#field_parents'], array($element['#field_name'], $element['#language']));
      $parent_langcode = entity_language($element['#entity_type'], $element['#entity']);

      $ief_id = $element['#ief_id'];

      $element['form'] = array (
        '#type' => 'container',
        '#op' => 'add',
        '#parents' => array_merge($parents, array ('form')),
        '#entity_type' => $settings['entity_type'],
        '#parent_language' => $parent_langcode,
        '#ief_id' => $ief_id,
      );
      $bundle = reset($settings['bundles']);

      $form_state['inline_entity_form'][$ief_id]['form settings'] = array (
        'bundle' => $bundle,
      );

      $element['form'] = inline_entity_form_entity_form($controller, $element['form'], $form_state);
    }
  }
}


How do I interact with $title, $breadcrumbs, and $action_links within a process or preprocess function?

This is how I manipulate breadcrumbs in page preprocess function. You can actually do this somewhere else, where you think it fits according to your needs.

/**
 * Implements hook_preprocess_page().
 */
function extremes_preprocess_page(&$variables) {
  // You can use preprocess hooks to modify the variables before they are passed
  // to the theme function or template file.

  //define breadcrumbs array
  $breadcrumb = array();
  $breadcrumb[] = l('SS','<front>');//add homepage first
  //if we are on one of my dynamic pages, we do this
  if (arg(0) == 'node' && is_numeric(arg(1)) && !empty($variables['node']) && _is_dynamic_type($variables['node']->type)) {
    if (!empty($variables['node']->field_term_reference)) {//we are gonna depend on a term ref field
      //get all parent terms
      $parents = array_reverse(taxonomy_get_parents_all($variables['node']->field_term_reference[LANGUAGE_NONE][0]['target_id']));
      //and add them to breadcrumb array
      foreach ($parents as $parent) {
        $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
      }
    }
    //set the breadcrumb
    drupal_set_breadcrumb($breadcrumb);
  }
  //if we are on a term listing page
  else if (arg(0) == 'taxonomy' && is_numeric(arg(2))) {//you can also check here, which vocabulary you want
    //easier this time
    $parents = array_reverse(taxonomy_get_parents_all(arg(2)));
    foreach ($parents as $parent) {
      $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
    }
    if (arg(3) && $type = taxonomy_term_machine_name_load(arg(3), 'vocab_name')) {
      $breadcrumb[] = l($type->name, request_path());
    }
    drupal_set_breadcrumb($breadcrumb);
  }

}

This sample uses taxonomy_machine_name.module which uses the same system with pathauto and is very useful for loading taxonomy terms from url if you set up correctly.

For title, you can go with drupal_set_title() and for action links hook_menu_local_tasks_alter().


Displaying follow up fields for a content type

Drupal 7 introduced the #states property for form elements. It:

  Adds JavaScript to the element to allow it to have different active states.

Here's a short example that applies to your use case:

function MYMODULE_my_form($form, &$form_state) {
  $form['my_radios'] = array(
    '#type' => 'radios',
    '#title' => 'Radios',
    '#options' => array('no' => 'No', 'yes' => 'Yes'),
    '#default_value' => 'no'
  );

  $form['textarea'] = array(
    '#type' => 'textarea',
    '#title' => 'Textarea',
    '#states' => array(
      'visible' => array(
        ':input[name="my_radios"]' => array('value' => 'yes')
      )
    )
  );

  return $form;
}

The above assumes you're building the form yourself; if you're not, you can combine this logic with a hook_form_alter() function. This example assumes you're adding it to a node add/edit form for the Basic Page content type:

function MYMODULE_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['textarea']['#states'] = array(
    'visible' => array(
      ':input[name="name_of_radios_element"]' => array('value' => 'yes')
    )
  );
}

If you're using the second method you'll need to do some digging into the $form array to find out exactly which element you need to target. If you don't already have it I recommend installing the Devel module and using it's excellent dpm() function for your debugging.

There's more information on the various different options for #states on the drupal_process_states() docs page.


Views in Drupal 8 has pretty much the same template options as in Drupal 7. If you are in doubt, what suggestions are offered, you should turn on twig debugging (settings in service.yml). You will get the suggestion output as HTML comments. Unlike in Drupal 7, Views in Drupal 8 does not have a button to see the templates files being used along with suggestions.

This might be added later as Drupal 8 is still in beta, at the time of this writing.


Try hook_menu_alter() to alter the menu,  https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7.

Moreover, entity_translation_node_menu_alter() is not a hook and it is a function called from entity_translation_menu_alter().


How to create internal links during user navigation

Relations module was built exactly for use cases like this. But be warned that it has a little steep learning curve.

Relations Add Module can significantly reduce your work and also has an auto-complete feature that is user friendly.

  This module provides a field that can be used to create/delete/update
  the relations from within the node/entity forms, with a generic
  autocomplete for each endpoint, and relation fields.


Is there a Grouped Product listing type in Drupal Commerce

Drupal Commerce does differentiate between products and product variations same as other systems, but the feature you're looking for hasn't been ported to Drupal 8 yet. It's easy enough to create a table with individual Add to Cart buttons for the variations in Drupal 8, but to have a single Add to Cart button for all variations on a product page, you'd need this module upgraded for Drupal 8:

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


How to enable Database search & autocomplete live search?

You'll probably have to write a custom module for this.

Here's the basic idea:

You should decide with which search mechanism you want this to work. For the sake of simplicity, I'll use the core Search module as an example.
Declare a new autocomplete field with your custom callback path; it might work if you just alter the search field type, turn it into autocomplete and add your custom callback path. I'm not sure if this will work in D8 though.
Whenever user changes the input, your module should query the database and see if there are any matching keywords stored in the search module. You can include any additional logic here, e.g. limit the search to nodes only, give some criteria higher visibility, exclude some keywords, etc.
Return back the similar keywords so user can choose some of them.
When search is submitted, display search results from core search module. If it's possible, the best would be to alter the search input field, so you don't have to much else to handle form submission, etc.

I didn't check much, but this should get you going. For more info on D8 form API, check this out. If you need to see how is this done in the core, check out the code for referencing the users (e.g. author field in node forms).

Hope this helps.


How do you enable translation for a field which was defined by a contrib module?

After a bit of struggle and research, here is the approach taken -

custom_module.install file -

/**
 * Enable translation for workbench_reviewer field.
 * Implements hook_update_n.
*/
function hook_update_xxxx() {
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition_node = $entity_definition_update_manager->getFieldStorageDefinition('workbench_reviewer', 'node');
  $field_storage_definition_node->setTranslatable(TRUE);
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition_node);

}

custom_module.module file -

/**
 * Implements hook_entity_field_storage_info_alter().
 */
function hook_entity_field_storage_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

Once running drush updb I can see the field appearing in translation UI with the checkbox enabled.


Added items to registration form and get "Notice: Undefined property: stdClass"

Never, ever patch core like that. This is not how Drupal works. That said, you didn't specify whether you are using Drupal 7 or not; I presume you do. Instead of doing this, use the field UI module to add the relevant fields to users under Administer > Configuration > People > Profiles.


How to combine 3 line charts in a single chart, using the Views integration of the Charts module?

After diving into deep on visualization with Drupal, Charts module gives us the opportunity to do this, either by using the Views integration of Charts (to create charts without coding PHP snippets), or by using the Charts API (used as a developer module that provides a unified API for the integration of various charting solutions into Drupal).

This is from the Readme.txt file, incuded with the Charts module:

  Creating Multiple Series and Combo Charts in the UI

  When using Views to build your charts, you may find it difficult to
  retrieve more than a single set of data generated by a COUNT() query.
  For example if you wanted to retrieve the age of all your site users,
  but display "Male" and "Female" values in a column chart at the same
  time, constructing the underlying table of data is quite difficult.

  To solve this problem, you can combine multiple charts on top of each
  other. The "parent" chart provides the global information, such as the
  height, width, title, and other properties. Charts that are "children"
  provide only data and (optionally) a secondary axis. After you've
  assembled the first series of data in your chart according to the
  instructions in the "Creating Charts in the UI" section, add a new
  display to the same view of the type "Chart Add-on". The "Chart
  Add-on" type is added the same way you would add a new Page or Block
  display, from the "+ Add" menu at the top of the view configuration.

  After this new display has been added, find the setting for "Combine
  with parent chart" and change this value to point at the parent chart
  you have already assembled. Then adjust the settings for the child
  chart to pull in different data (often by overriding the filter
  settings). Now you can go back to your parent display, and see that
  the results from the child chart have been merged into the results
  from the parent chart. You can even use this approach to combine
  different types of charts, such as a line chart over the top of a
  column chart. Note that not all chart types can be combined together
  and invalid combinations may cause your chart to throw errors.


Create users on the frontend, without 'administer users' permission

Can you not simply give user permissions to create users of specific roles (via the administerusersbyrole module) and then use the existing user creation form at /admin/people/create? If you do go with administerusersbyrole, make sure you follow the two steps on the project page for assigning the configuration.

If you must have a custom form via another page, you probably want to do it via a proper form definition function by setting the menu 'page callback' to 'drupal_get_form', and then passing the function that provides the form definition in 'page arguments'. See this particular comment for a code example. This way you'll be able to do proper form validation and a for submit handler too. Even if you get your current snippet working, the form still needs to submit somewhere to work.


Unable to display Drush cache-clear theme registry

The Drush code looks like this:

  $types = drush_cache_clear_types(drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL));

If the parameter to drush_cache_clear_types is TRUE, then the missing cache types shown above are included in your selection list.  Your Drupal site is not bootstrapping all the way up to the 'FULL' level, which means there's probably something wrong with the Drupal site.  Try running drush status --debug, and see if you can determine from the log messages why the bootstrap is stopping.

Update: See MPD's comment below. I thought the exact same thing as I was driving in to work this morning: this situation can also arise if you have told Drush where your Drupal root is, but have not specified your sites folder.  The Drupal root is specified via --root, or by using cd to switch to a directory anywhere in your Drupal installation.  The specific site is selected via --uri, or by using cd to switch to the same directory that contains settings.php.  If you cd to the folder that contains settings.php and run drush cc all, that might fix your problem.


Which module for relationships in my particular case?

Both Entity Reference and Relation modules would do the work, but in your case I would suggest to go with Entity Reference module, since you don't have very complex relationships.


What could cause remote drush commands to fail with ssh errors when ssh works in all other cases?

Put this line in your drushrc.php file:

$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/id_rsa';

This will cause Drush to pass these options along to ssh any time it calls your remote system, so you can continue to call Drush via sudo, and still use your login user credentials.


There is indeed an API function: EntityFieldQuery, which has lots of example use cases scattered around this site.


Which hook will use for checking taxonomy term page

You may implement  hook_taxonomy_term_load  in your module


How to show a view page but hide all the content in the view for certain roles?

For a quick and easy solution use panels.

Use panels to display your view on the page for that specific user role.
Inside the variant portion, swap the panels to a general text area for anonymous users.

very useful links:

Creating Different Versions of Same Page Variants (watch all the free videos)

Can one apply a panels layout to a view page?


Add a "class selection" field to content item via CCK?

// This code will add a class to the node based on a field in that node
function THEME_preprocess_node(&$vars) {
$node = $vars['node'];
$output = '';

switch($node->type) {
  case 'advertisement':

  // Set class based on editor color selection; code duplicated for clarity.
  $field = field_get_items('node', $node, 'field_background_color');
  if($field) {
    $theme = field_view_value('node', $node, 'field_background_color', $field[0]);
    $term_name = $theme['#title'];
    $term_name = str_replace(' ', '-', $term_name);
    $css_name = strtolower($term_name);
    $vars['classes_array'][] = $css_name;
  }
  break;
  }
}


Is there a module or functionality to export/import roles and permissions?


How do I get masonry to run again once twitter widgets have rendered?

I went through the twitter documentation and found a way to call functions on twitter widget events:

// Load the twitter widgets script
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

// Bind an event to rerun the masonry layout when a tweet is rendered
twttr.ready(
  function (twttr) {
    twttr.events.bind(
      'rendered',
      function (event) {
        jQuery(function($) {
          $('.view-content.masonry').masonry();
        });
      }
    );
  }
);


URL mappings can be altered with two hooks: hook_url_inbound_alter() and hook_url_outbound_alter().

hook_url_inbound_alter() is used for paths that Drupal is responding to.  See drupal_get_normal_path().

hook_url_outbound_alter() is used for paths constructed by url().

Whether or not you can accomplish this will require some experimentation, as I don't know how the theme registry will complicate matters.


Views Sort Criteria: Contextual Filter Multiple Value Order

I guess some other people had the same idea I had.

The Views Arguments Extras module handles my situation perfectly. I used the version for 7 (duh :) ), but there is a drupal 6 version as well.


How do I format a picture field as raw source url in a view

I found that "there's a module for that", Image URL Formatter:

  This module add a url formatter for image field. Then you can output
  image url directly.


The varnish module handles clearing the cache for you when a node is update via a socket connection to varnish. It can also be configure to clear the cache based on a lifetime period. If you still need to clear the cache based on your own custom requirements the module also provides a helper function such as _varnish_terminal_run that allows you to send commands to varnish from your php code.

Also in regard to the bullet point checkout the drupal_page_cache_header_external in pressflows bootstrap.inc file

There is also more documentation of varnish with pressflow over at fourkitchens wiki


How to flag or unflag an entity with multiple flags at once?

Is there a way in Rules to Flag a user with multiple flags all at once? For example fetching a list of all Flags based on a Flag property, and then setting all of the flags in this list to "Flagged" for the specific user?

Yes there a way in Rules to Flag a user with multiple flags all at once (as in your question), and maybe even by some kind of fetching as you described. However, you can for sure use the Conditional Rules module to flag a user  with multiple flags all at once. Here is a sample rule to illustrate how such rule would look like:

{ "rules_flag_a_user_with_multiple_flags" : {
    "LABEL" : "Flag a user with multiple flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_superuser" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT flag_flagged_user" : {
                "flag" : "follow",
                "user" : [ "flagged-user" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_flaguser" : {
                  "flag" : "follow",
                  "user" : [ "flagged-user" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "NOT flag_flagged_user" : {
                "flag" : "friend",
                "user" : [ "flagged-user" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_flaguser" : {
                  "flag" : "friend",
                  "user" : [ "flagged-user" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Some details about the above rule, which uses flags with machine names superuser, follow and friend:

Rules Event: A user has been flagged, as "superuser".
Rules Actions:

If the flagged user is NOT flagged with flag "follow", by the flagging user, Then flag the flagged user, with flag "follow", by the flagging user.
If the flagged user is NOT flagged with flag "friend", by the flagging user, Then flag the flagged user, with flag "friend", by the flagging user.

If you adapt the machine names of the flags to fit your own flag names, you should be able to import it in your own site (provided the Conditional Rules module is enabled also).

So with that, a user that gets flagged with superuser, and which is not yet flagged with follow, will also be flagged with follow. And the similar for the friend flag.

BTW, even though this answer is about entities of type "user", you can use a similar technique for any entity.

Easy, no?

PS: I'm assuming this question is about D7 ...


Match JSON POST data with custom node fields

The function json_encode(); from my understanding.


How to make menu link show for certain roles?

In D8 this is a menu link class, which you can add to a menu in *.links.menu.yml:

mymodule.links.menu.yml

mymodule.logout:
  weight: 10
  menu_name: mymenu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

This class shows Log in or Log out for user roles authenticated or not:

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('Log out');
    }
    else {
      return $this->t('Log in');
    }
  }

and links it to the corresponding route:

  public function getRouteName() {
    if ($this->currentUser->isAuthenticated()) {
      return 'user.logout';
    }
    else {
      return 'user.login';
    }
  }


How to use the Charts module for creating charts using Views?

Here's what I used (running a brand new drupal 6.25 install):

Views 6.x-2.16
Views Calc 6.x-1.3 (required for Charts)
Charts 6.x-1.0

The Charts module comes with a few chart providers (SD Image Chart and Google Charts). You need to enable one of them in the module list to use in views. I enabled Google Charts for this example.

Then, I created a new view. I set the Style option to "Chart". To demo the chart, I just added a Node: Nid field and created some dummy nodes. The chart provider you selected will  render the chart in the preview for you. You can configure the Style Plugin settings and the fields to get the kind of chart you want.


This is a known issue, see:
https://www.drupal.org/node/1269780 regarding a longterm resolution.

In general it looks like going forward +FollowSymLinks should be replaced with +SymLinksIfOwnerMatch, but refer to the issue queue item above for a definitive answer.

Typically per host, and definitely with Shared Hosting plans it's up to your webhosts documentation as to what Apache Overrides are allowed by your (system) user account. There is a certain amount of trial and error is seeing if -Indexes for example is allowed on your webserver.

This is why when you upgrade Drupal they recommend backups of your projects .htaccess and robots.txt file as per webhost and project these files are highly likely to be modified.


hook_user_insert() can only be implemented in a module, not a theme. Themes are just for styling/marking up content that modules produce, they shouldn't contain advanced logic like that.

You'll need to add a custom module and implement the hook in there to continue.


Is there a way to edit/write templates from the user interface?

As far as I know, the best you could do in Drupal from the admin side is alter the layout using Display Suite, Panels, and to some extent, Field Groups (Bootstrap Field Group can come in handy). Advanced functionality will still require code access (i.e. adding custom layouts and layout CSS). That's usually what you end up doing with templates most of the time, just moving things around.

It's rare that you edit the widgets and field outputs (you write formatters for those, which then can be changed via admin once installed). Also, editing widgets using templates instead of formatters is a maintenance nightmare and full of surprises.

  Even for devs who know what they are doing

Devs who know what they're doing store changes in version control, and therefore code. ;)