I have scoured the web, banged my head on the keyboard a few times, and finally settled to the fact that there is currently no viable way of achieving this with taxonomy menu.

A simple solution that should work though I have not tried it is using views to achieve the desired effect. I quickly googled that up and came across someone with the same/similar requirement here; http://drupal.org/node/165417. Their questions seem to have been answered and I will therefore try my hand in that direction tomorrow.

Hope this helps.

Edit: Tried using views but had to upgrade to using the 6.x-3.0-alpha3 version. After that it worked perfectly. I used content taxonomy for the relationships with the settings to update core taxonomy vocabularies. Then, using views, I selected HTML list as the style and grouped by the cck taxonomy field.


try in search API > your index > search your field and then in the column type, select STRING.

Also maybe you can hook your field:

function HOOK_facet_items_alter(&$build, &$settings) {
   if ($settings->facet == "YOUR_FACET_NAME") {
       foreach($build as $key => $item) {
          $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
        }
    }
}


How to implement module dependencies in a theme and package modules with a theme?

Up to Drupal version 7, themes do not allow to have the typical directive for module dependencies in their info files. Because themes are supposed to be module independent.

However, for D8, there is the issue about dependencies[] for themes, so they can depend on modules (created back in 2009 ... current status = needs work).

For D7, Comment #3 in (Drupal core) issue 647014 contains a possible work around that you may want to consider, something like so:

<?php
function mytheme_preprocess_page(&$vars)
{
  ...
  if (!module_exists('needed_module'))
  {
    // No needed_module means we need to add it, let everyone know.
    //
    print "
"  . t( 'mytheme requires that module needed_module is installed')
        . "
"
        . "
"  . t( 'warning generated in file: %f', array ( '%f'=>__FILE__ ))
        . "
";
  }
  ...
}
?>


Add user to Organic group after commerce product order with rules

I was able to do this finally by tweaking the tutorial posted on this site: http://s1l.org/selling-access-organic-groups-drupal-commerce. I removed the loop in the components since my field only takes one value and I removed the condition to check if the order has been paid and now it's working.


The link/button "Add content set" was disappeared (Drupal6)

Solved by installing the migrate module of version with 1.x

http://drupal.org/node/966190


Why do I need to remove old files first when upgrading Drupal or its modules?

By deleting all the directories you're ensuring no files are left over that shouldn't be there anymore. A simple overwrite won't always do that.


How to import user address profiles into Drupal Commerce?

Migrate module is the best way to import those things.


Testing site with login access AND login inside

Use the Secure Site module. This module allows you to authenticate users with a browser-based password (HTTP Auth). Giving you the "outer" authentication layer. Then use Drupal core's login for the "inner".


Cannot install Composer because it doesn't contain any .info.yml files

IMPORTANT EDIT (2020-04-28):

You are trying to install this project:
https://www.drupal.org/project/composer

But that is not Composer -- it's a Drush extension for managing Composer.

From the project documentation:

  Composer is a PHP package management tool to help manage your project or libraries' dependencies. This project allows use of Composer from Drush.

Installing this module on the server will not allow you to manage your Drupal 8 project using Composer. You need to set up your Drupal 8 project correctly using Composer in the first place, and worry about getting it onto the server later (whether you use the modern DevOps way using git hooks to deploy, the old-school sysadmin way using rsync to deploy, or the stone-age way using SFTP with Filezilla or a similar GUI file transfer utility.)

ORIGINAL ANSWER (2020-04-26):

Welcome to Drupal Answers!

Since you just started from scratch, you won't lose much work if you start from scratch again.

First, install Composer on your local computer: https://getcomposer.org/

Don't try to install Composer on the server. Depending on your hosting, it may be possible to do that, but it is seldom the best way to do things. Composer is a well-known memory hog, and many web hosts will not allow you to run composer install on the server. Even if it is allowed, it's a terrible misuse of RAM and CPU cycles on a production server. Don't do it.

Next, install a new Drupal 8.8 site on your local computer (here called "my-project") using the drupal/recommended-project template:

composer create-project drupal/recommended-project my-project

At this point, I recommend using git init to put your project in version control.

Then use Composer to manage project dependencies such as installing contrib modules:

composer require drupal/phone_international

You can create a .gitignore file to tell git to ignore the core, contrib and vendor directories, which will be recreated afresh whenever you run composer install (from instructions in the composer.json and composer.lock config files). This keeps your git repo and pull requests small by excluding hundreds of thousands of lines of open-source code that are common to all plain-vanilla Drupal 8 (or 9) projects.

Finally, you'll want to set up some method of deploying the code from your local computer to the server. For tips on that, see my other answer:

https://drupal.stackexchange.com/a/292006/80164

Note that you will probably want to see the local Drupal site in a browser before deploying the code to the server. There are many ways to accomplish this.

Personally I like to use Lando to manage my Drupal projects in Docker containers, but other options include Docksal, DDEV, Vagrant/Virtualbox, LAMP (Linux), MAMP (Mac), WAMP (Windows), XAMPP (Linux, Solaris, Windows, and Mac), and others.

There's a lot to learn, and many of your questions will be outside the scope of this forum (which primarily focuses on issues specific to Drupal core and developing custom module and theme code with Drupal APIs). You might get better support for general questions on Drupal Slack.

Assuming that you want to try Lando, you can install it with all its dependencies using the Hyperdrive installer script for Mac or Linux. Then navigate to the my-project directory you created with composer create-project and execute something like this:

lando init --source cwd --recipe drupal8 --webroot web --name my-project

That would set up Docker containers for your appserver and database with a default configuration suitable for a Drupal 8 project. Then you'd just type:

lando start

Then you can view your local site in the browser at http://my-project.lndo.site to finish installing it and configuring it. After this, you can use Lando to manage your project inside the Docker container. Type lando on a line by itself to see what tools are available (including Composer, Drush, Drupal Console, MySQL CLI, log viewer, and tools to import/export database backups.)

Make sure that every time you change the code, you commit it to git and test it locally before deploying it to the server. (Later, you might end up setting up different servers for Dev, Test and Live environments.)

Good luck, and happy Drupaling!


If subject is a simple textfield on webform and token module is enabled then you can set this textfield's default value using token.


How do you change the default value on a CCK text field that is part of a field group via hook_form_alter()?

You should be able to do something like this:

function EXAMPLE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id=='profile_node_form') {
    $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';
  }

  // all other form alters here...

}

or

function EXAMPLE_form_profile_node_form_alter(&$form, &$form_state) {

  $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';

}

directly from whichever form_alter() style you like.


See a list of fields and what content types they are attached to

You should be able to go to Admin > Reports > Field List and see a list of fields in the system and their types and what is using it.


Display flash, video, photo in slideshow

The Views Slideshow module can loop through more than just Images.  You can even have it look through rendered nodes or custom content.

By using the Views theme and template features and views slideshow you should be able to mix nearly any content you want.

There is a video by Bob Christenson that gives a very good intro to the Views Slideshow module.  Though it is for D6, most of the content is similar enough to be useful in Drupal 7.


Use getRevisionId(); The revision identifier of the entity, or NULL if the entity does not have a revision identifier.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21RevisionableInterface.php/function/RevisionableInterface%3A%3AgetRevisionId/8.2.x


Your understanding about theme is right. It is for wrapping data with html elements. Advantage is that you can seperate view part and logic part. There are also default theme which you can use out of box


How do I sort a date field in views without the time?

you can change the granularity of the sort under the settings for the sort criteria:


Views not found on disabling Page Title module

The page_titles module sets a lot of variables. I don't know if that would cause an issue like you are seeing, but it's best to remove these variables. Disabling the module will not remove them, but uninstalling it will. With page_title disabled, go to admin/modules/uninstall, select the module, and click uninstall. This will unset all variables that were set by the module.


Showing "Explanation or submission guidlines"

The "Explanation or submission guidelines" set on the edit/create content type form is actually displayed using the "System help" Block. So you just need to add the "System help" block to a region in your custom theme and it will be displayed there as long as you are actually printing the region in your theme.

I figured this out using the Theme developer module, which really is an extremely useful module for this kind of stuff. When you enable Theme developer, it adds a checkbox labeled "Themer info" to the bottom of each page. Check that box then click on any element in the page and you'll see information about how that element was themed. For example, enable Theme developer and use one of the default themes where the "Explanation or submissions guidelines" content is displayed correctly. Check the "Themer info" box and click on the submissions guidelines text, it will popup a box with information about how the submission guidelines where themed, like the image below. This should give you all the information you need to figure out how to theme something, or at least where to start looking.

NOTE: The Theme Developer module can actually end up breaking parts of your theme when enabled. It injects lots of <span>s to do it's magic. If something looks broken in your theme, disable Theme Developer and check again. Also, don't enable Theme Developer on a live site.


How to embed views in a particular custom block template

Ok, I have found a way to do so from another post, tested and it works ! So basically..

1) Create a new variable in mytheme.theme file located in your default theme folder.

function mytheme_preprocess_block(&$variables) {

  $variables['view1'] = views_embed_view('view_name', 'block_news');

}

'block_news' is your views block's machine name actually.

2) And then use this twig in your block template.

 {{ view1 }}


How to override/implement a module's hook

You must create a custom module and add a custom hook function to it. The function name will be modulename_query_alter ().  Drupal maintains a list of all included hooks by searching the enabled modules for functions following that pattern.

Instructions for creating one are here.  This is the basic means for introducing custom behaviors to your site. The hook system is discussed here and you should look at using the hook_query_alter function here.

This will get you started and no doubt lead to further questions.


Numbering the content list in drupal (as simple as it sound) - possible via the UI?

Looks like you might be looking for number of nodes by content type (among other things). If that's the case then you may want to consider the Charts module. It comes with a sample view that gives you both a tabular overview and a chart of these numbers.

The (accepted) answer to the question Views and node count for taxonomy terms contains another (views) based example.

The question Count of nodes by type contains some code snippets that may help to write your custom module to calculate these counts.

If you don't want to install/enable the Charts module permanently, you may want to temporarely enable it to (eg) look at the view for the tabular format display, and then create a clone of that view to perfectly fit your needs (and then uninstall the Charts module again). Of course the "Views" module is yet another module. But it's rare to find a site that does not use the views module, so that's maybe an acceptable compromise to consider (you might have Views available already)?


Using ImageField to add an inline image (save thumbnail, and when clicked open with colorbox)

If you enable core File and Image modules you can add image upload fields to different nodes/entities and create image styles (to get thumbnails). The number of allowed image uploads can also be set. The image uri will be available in the node.tpl.php file which means you will have full control over how it appears. Here's example code showing about how it could look like in the node.tpl.php file (with colorbox module 'Colorbox load' enabled - alternatively just use javascript):

<?php if (!empty($node->field_image['und'][0]['uri'])): ?>
  <?php
  $full_img_url = file_create_url($node->field_image['und'][0]['uri']);
  $thumbnail_url = image_style_url('thumbnail_style', $node->field_image['und'][0]['uri']);
  ?>
  <a class="colorbox-load" href="<?php print $full_img_url; ?>"><img src="<?php print $thumbnail_url; ?>" alt="Image" />
<?php endif; ?>

The code is not tested so there might be mistakes, but it should still be helpful. You'll have to set the image field hidden via 'manage display' or unset/hide it in the template file otherwise you'll get a duplicate printed with $content.


Have you checked the css file route (Chrome will show that in the dev tool) that the website is reading? I use superfish as well, there are some css files for the menu bar in '.../sites/all/superfish/css/', but I also have my overriding style in my custom theme folder. Are you sure the browser is linking to the css file that you think it is linking to?

And, that happened to me once, probably is not your case, but I once forgot to save my css after editing it :P

Good luck.


You could subclass EntityFieldQuery and add a having() method, or (probably quicker) you can add a tag to the query, and use hook_query_TAG_alter() to alter it when it's a standard SelectQuery:

function MYMODULE_query_my_tag_alter(QueryAlterableInterface $query) {
  $query->having('some_field > :val', array(':val' => $some_val));
}

To use that with your query:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->fieldCondition(...)
  ->addTag('my_tag');


How do I modify the "Formats" dropdown in CKEditor

I would use Styles instead of Formats, because styles are fully controlled by you, from admin interface, no need for editing files.

When you add it to the toolbar you can configure it and add as many elements as you wish.

Here is an example config:


How to add and remove tabs from/to My Account page

For your first question answer remove the  from page.tpl.php or you can alter it by hook_menu_alter. Use type MENU_NORMAL_ITEM.

For you view you need to create one hook_menu_alter and add type as MENU_LOCAL_TASK.


Use mobile phone number as account ID so users dont have to register?

If I get you right you want detect that a user is recuring user? Generaly this can be done with a cookie.

Tecnicaly there is no reason to use a phone number. As far as I know there's no possibility for a web application to get the phonenumber automatically. A solution could be an app as frontend which delegates to the website.


That is the cause of admin_menu.module.  Upgrade it to the the most current version; it will be fixed.  That problem was fixed one or two versions ago.


How To add user name and profile picture to Superfish menu

I found a somewhat unnecessarily complex, but working, answer.

Install Menu Views module.
Create a View User List Block and add a relationship User:Profile.
Add a contextual filter user:uid and set Provide default value as User ID from logged in user.
Add 2 fields, User: Picture and User: Name
Change Access to Role and choose all roles that should see this View.
Add CSS classes and style

Note: At this time a issue exists with Menu Views and requires a fix found here.


Add drop down selection to shipping method

I resolved the issue by adding a field to the order type and then instead of using
Order interface
$this->order->setData('field_omniva_parcel_machines', $val);

i used FieldableEntityInterfaces' set
$this->order->set('field_omniva_parcel_machines', $val);

and i accessed the value in the commerce-order-receipt.html.twig by using
      {% if order_entity.field_omniva_parcel_machines.value %}
         {{ order_entity.field_omniva_parcel_machines.value }}
      {% endif %}

Thanks again, Berry, for getting me started with this!


This is how batch works (Based on my Understanding)

1. Initialize

Initialize the batch processing. Based on the clients(Browsers)  configuration on whether JavaScript is enabled or not.
JavaScript-enabled clients are identified by the 'has_js' cookie set in   drupal.js. If no JavaScript-enabled page has been visited during the current  user's browser session, the non-JavaScript version is returned.
If JavaScript enabled Batch uses ajax request the keep the connection alive across the request.
If JavaScript is not enabled Batch uses sets a meta tag in html to make regular refresh  intervals to the keep the connection alive across the request.

(This is how the progress bar is updated on the progress of the Job Done.)

Batch Process

For starting the process, Batch creates a Queue and adds all the operations(functions and arguments) that you define in the batch array like,

$batch = array (
'operations' => array(
  array('batch_example_process', array($options1, $options2)),
  array('batch_example_process', array($options3, $options4)),
  ),
'finished' => 'batch_example_finished',
'title' => t('Processing Example Batch'),
'init_message' => t('Example Batch is starting.'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('Example Batch has encountered an error.'),
'file' => drupal_get_path('module', 'batch_example') . '/batch_example.inc',
);

Additionally it also assigns  a batch id which is unique across the batches.
Now Batch calls claims the Queue items one by one and executes the function defined with the arguments that are defined in it.
This is a crucial part, The function(Operation) that implements the batch operation should chunk the data and process the data very efficiently keeping in mind of PHP's Memory limit, Time out. Failing to do so will end up in your problem.

  I ran into a timeout issue using migrate the other day and started to wonder how the batch API works internally.

The Batch Function

The functions that implement Batch should take of the following things very carefully,

Number of Items within the operations to process like,

if (!isset($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
}

Limiting the number of items to process in one function call like setting up a limit,

// For this example, we decide that we can safely process 5 nodes at a time without a timeout.
$limit = 5;

Update on the process to post-processing like,

// Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $node->nid;
    $context['message'] = t('Now processing %node', array('%node' => $node->title));

Informing the Batch engine whether the Batch is completed or Not like,

// Inform the batch engine that we are not finished,
// and provide an estimation of the completion level we reached.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
 }

Most of the Above Points are taken care of the Drupal's Core batch operations if it is Missed in the Implementing function. But it is always best to define in the implementing function

Batch Finished callback

This is the last call back called when defined in the batch array Usually a report of how much processed etc...

ANSWERS

  If the page with the batch request is closed does the batch processing
  stop? Will it restart when the same url is opened again? The migrate
  module sometimes continues but it's probably using queues?

Yes, Ideally it should restart the batch and as said above it is based on the function you implement.

To solve your problem of PHP Time out use Drush batch which is available in migrate module, But first dig out migrate's batch functions and try to chunk your processing data.


How to hide node title while in edit without automatic nodetitle module?

Use hook_form_alter and unset($form['title']) in a custom module (since the node create / edit form will usually be displayed in your admin theme this will be a better approach than adding the function to your themes template.php file.

So create a module with a basic mymodule.info file.

Create a mymodule.module file and add:

function mymodule_form_alter(&$form, $form_state, $form_id) {

   // 1.NODE TYPE FORM
   if ($form_id == 'NODE_CONTENT_TYPE_node_form') {
     unset($form['title'];
   }

 }


Dealing with hook_cron when configuration is required

If you require configuration, then you shouldn't provide a default value using variable get (You provide an empty default value instead). If the no value is set, you should make a log using watchdog and exist without doing anything, since the conf was missing.

If you can provide a default settings that would make everything work, that would be a better option, since the user don't have to do any setup, be can if he wants to.

The checks should not really happen in cron, but in the function actually doing whatever needs to be done.


Drupal changes my markup in full html mode

By default the Full HTML format has the

  Convert line breaks into HTML (i.e. <br> and <p>)

option selected. If you don't want that behaviour, just go to http://mysite.com/admin/config/content/formats/full_html and deselect that option:


how to display avatar in forum-list (advanced-forum)

You may include the picture of the author of the forum topic by configuring the corresponding view:

admin/build/views/edit/advanced_forum_topic_list

HTH


How to search for string in Drupal database and replace

You don't say which version of Drupal you are using.  If it's D7, there is the scanner module which can probably do what you want.

If it is D8, I'd suggest writing a drush script to update the content.  The standardization of entities and methods makes that fairly easy. Here's a snippet of code from a script I used to grab all text from our site that needed to be translated.  You can modify it to do what you need.

use \Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;

$entity_type = 'node';
$bundle = 'article;
$fields = [
  'field_header' => 'paragraph',
  'field_summary' => 'text',
];

$entities = gen_i18n_get_entities($entity_type, $bundle);
foreach ( $entities as $vid => $id ) {
  $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id);

  gen_i18n_parse_entity($entity, $fields, $page);
}

/**
 * Find the entity ids for the specified type and bundle.
 *
 * @param string $entity_type
 * @param string $bundle
 * @return array
 */
function gen_i18n_get_entities( $entity_type, $bundle ) {
  $query = \Drupal::entityQuery($entity_type)
    ->condition('type', $bundle);
  if ( $entity_type == 'node' ) {
    $query->condition('status', 1);
  }
  $results = $query->execute();
  return $results;
}
/**
 * Walk thru the entity fields to get required information.
 *
 * @param EntityInterface $entity
 * @param array $fields
 * @param array $page
 */
function gen_i18n_parse_entity( EntityInterface $entity, array $fields, array &$page ) {
  global $field_num;

  $field_num = 0;
  foreach( $fields as $field => $field_type ) {
    if ( !in_array($field_type, array('alias', 'menu'))) {
      $field_def = $entity->getFieldDefinition($field);
      if ( $field_def != NULL ) {
        $label = $field_def->getLabel();
      }
      else {
        print "** Could not find field {$field} in {$entity->bundle()} {$entity->id()}\n";
        continue;
      }
    }
    else {
      $label = $field_type;
    }
    switch ( $field_type ) {
      case 'text':
        gen_i18n_parse_text( $entity, $field, $page, $label);
        break;
      case 'paragraph':
        gen_i18n_parse_paragraph($entity, $field, $page, $label);
        break;
      case 'metatags':
        gen_i18n_parse_metatags( $entity, $field, $page, $label);
        break;
      case 'alias':
        $field_num++;
        $page['en']["{$field_num} - URL"] =  $entity->toURL()->toString();
        break;
      case 'menu':
        gen_i18n_parse_menu($entity, $field, $page);
        break;

    }
  }
}


What is the right way to use a different base theme for some pages when applying custom theme?

How can I make the UI appearance of these special pages stay in
  "seven" theme?

Seven is the default theme for admin paths in Drupal. To mark special pages like the user login as admin path use the module Admin Login Path.

You can add your own paths in a custom route subscriber like the one from the module:

<?php

namespace Drupal\admin_login_path\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Define the routes we want to use the admin theme.
    $login_routes = ['user.login', 'user.register', 'user.pass'];
    foreach ($collection->all() as $name => $route) {
      if (in_array($name, $login_routes)) {
        $route->setOption('_admin_route', TRUE);
      }
    }
  }

}


Allow file access to specific users in Drupal (not roles)

Create a new content type and add fields according to your
requirement or user reference field
Disable its Front page publish option.
Create new user Role like "client".
Create view of files and add relationship or contentuxal filter
against user loggin id.
Create block view assign this block into specific region.


How to learn JQuery coming from a Drupal background but with little to no knowledge of Javascript?

Understanding basics of Javascript is very important to effectively use and extend jQuery. http://www.youtube.com/watch?v=v2ifWcnQs6M


If domain name is changed for new server, you need to clean cache entries. Try using truncate commands for cache tables and confirm back.
You need to have database backup before cleaning tables as well.


Render image programmatically based on field content

You have two primary things avaiable in a node template.

content: That contains rendered markup. Use it to print stuff.

node: This contains the node object with the raw values. Use this for comparisons and accessing the unformatted values. The same raw values would also be accessible through #items in content, but it's much more complicated to access.

So in your case, access the value with node.field_resource_type.value.

Note that this contains the key of the list field, and not the displayed label. I would recommend to always specify explicit keys (e.g., put datasheet|Datasheet in the allowed values field). Then you can also reliably translate those labels if you have a multilingual site and your template doesn't break.

Unless you actually have multiple values in there, you also don't need a loop. But if you do, you can loop over it with for item in node.field_resource_type and then use item.value.

See also http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet


Add fieldset with add more button using ajax

This is easy to achieve with a content type and the Field collection module.  With that you can set up a qualification field of type field collection, then go to admin->structure->field collections and add the individual fields (School / College / Course).  If the qualifications field has a "Number of values" setting of "unlinmited" then you'll automatically get the "Add more" functionality as you described.

You may need to also use Field Group or Field Collection Fieldset in order to make the fields appear in a fieldset.


How to check if entity id exists or valid?

You can check if the entity object isset() or is not NULL, and use get() only if the condition passes.


Programmatically download last module version

It's dangerous process what you're looking for.

What if the user has a older CCK version ?
What if the user patched is CCK ?
What if the latest version of CCK won't works ?

Also, it's not fair to download modules without letting knowing the user what you're doing. From my point of view, the best solution it's to add dependency in the info file and with the hook_init you can check the version of CCK and display a message to as the user download the latest version of CCK.


Drush uses the database to determine what versions of modules are installed; therefore, Drush believes the second frontend to be up-to-date, even though the code is still at an older version.

To update your site:

Do not update live. Make a local dev environment by copying one of the frontends and the database.  Update the local dev environment
After updating and testing the local system, push the new code to the live systems.
Run drush updatedb on both frontends


Why is 'render element' sometime 'element' and sometime 'elements'?

Because it wasn't standardized.

The safe approach is to check the info array for the render element key.

There is actually an issue with the field groups module that ignores everything but form & elements.


Get parent entity in media preprocess hook

i have ended up doing:
function hook_preprocess_media__picture__image_without_link(array &$variables) {
   $media = $variables['elements']['#media'];
   $parent = Drupal::entityTypeManager()->getStorage('paragraph')->loadByProperties([
    'field_paragraph_image_ref' => $media->id()
  ]);
   $parent = reset($parent);
   var_dump($parent->get("field_paragraph_image_link_page")->getValue();
}


Views webform filter based on the current node field value

So I have found the awesome way to achieve this and it's using Views Contextual Filter, Content pane arguments and Panel pane arguments(automatically added when you add an argument in Views contant pane).

In the View, add a Relationship w/c is Webform Submission Data where it's set to the Webform and field you want to get from the contextual filter.
Add a Contextual filter for the relationship you have created.
Select provide default value and choose Raw value from URL and just choose 1.
Go to the view content pane argument and click edit. You should see a field to reference the contextual filter you have created and add a label you want.
Go to the panel pane's setting you want to get the data from.
Go to it's settings and you will be presented with a field where you can place the tokens provided by you panel page.


How are you providing the location of the files?  IIRC, you can give it an absolute path ( /home/www/drupal ) or a URL ( http://www.example.com ).

In either case are you including a final '/'?  If so, try removing it.


Module to Automatically Create URLs from Article Titles for Drupal 8

Yes, just use the Pathauto module with Token. Pretty straightforward.


Glossary option in Search API indexed nodes

To my knowledge the Search API does not support making a Glossary listing in a Contextual Filter. The best it can do is provide Facet Searching (after a search is performed).

Solr may support this using Shingles or something to help create the Glossary item, but no such Drupal submodule exists at the moment.


Last hook to be called after entity save?

The various wrapper functions (node_save(), user_save(), etc.) are responsible for resetting the entity cache after the save method has been invoked on an entity controller.

If you take the user_save() function as an example, this cache reset happens after the function invokes the various entity hooks (same goes for node_load())

That in mind, I think the question then becomes "What is the last hook to be called during an entity save"?...and the answer is hook_entity_update() / hook_entity_insert(). But, they are called before the cache is reset (for obvious reasons).

The entity_save() method just invokes the save handler for that particular entity type, and doesn't invoke any hooks of its own, so really your only options are:

Roll your own entity controller for the various entities you need to intercept, changing the save() method to invoke a hook after the cache has been cleared.
Hack/patch the existing entity controllers with the same code.

Neither are particularly attractive options but unless there's a solution available at a higher level that I'm not seeing, I don't think you've got much choice.


I think the Ajax Docs gives a pretty good example. Here are the pseudo steps:

You render your view block with 5 elements with "read more" submit as a form. The wrapper is is "my-ajax-block".
Clicking on the submit will create an ajax call (with help of built in ajax mechanism of Drupal).
You will make a call for all the items you need (50 pieces in your case), hopefully with the same service you provide the 5 one.
And you just send back the ajax response which will override the "my-ajax-block" with the fetched content.


Show initially 4 fields for Text field with unlimited value

Check Multivalue Settings Module

  Warning: this module is still very buggy. Actually, it only works in
  very few use cases. I suggest to only attempt using it with core
  fields (not fields from contrib modules). Even this may not work. I'm
  working on fixing things, but don't have much time. Help is welcome.

Functionality:

Number of values allowed
Number of values required
Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra)

Though the module is buggy but can be a good starting point for building a custom solution or patching the same module.


Hide node "edit" tab for certain content types and roles

I had the same issue and could solve that using template_preprocess_page(&$variables).

Open template.php under [yoursite]/themes/[your-theme]

For example if you're using bartik theme and want to hide tabs (View and Edit) for Article content type for Editor role.

Paste the following code in your template.php

/**
 * Remove tabs on article content type
 */
function bartik_preprocess_page(&$variables, $hook)
{
    if (!empty($variables['node']) && $variables['node']->type == 'article' && in_array('editor', $variables['user']->  roles))
    {
    $to_be_removed = array('node/%/edit', 'node/%/view');
    foreach ($variables['tabs'] as $group_key =>$tab_group)
        {
            if (is_array($tab_group))
            {
                foreach ($tab_group as $key =>$tab)
                {
                    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed))
                    {
                    unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

Clear your site cache and test.

This removes the View and Edit tabs on Article node pages for editor roles users. But they can access those pages via URL.

Hope this helps.


Revert a Feature Component programmatically

Here are a few thoughts though on resetting your features programmatically or as add-on install scripts.

You could use Drush to reset the Feature:

drush features-revert [feature name]

Another thought would be to use features_revert() during the install process:

features_revert(array('module' => array('component')));

The Strongarm module could be useful as well to force your Feature to retain its default state I think.

I have to agree with @Letharion in his comment on your OP.  I would want to know that other important things aren't being mistakenly modified during the install process.


Try the Administration Views module:

  Replaces administrative overview/listing pages with actual views for superior usability.

It will let you replace the standard content admin page with a view, to which you can add as many filters as you need.


how do I get the parent node of an entity reference node

You should be able to do this:

$loaded_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_node_reference' => $node->id(),
]);
$parent_node = array_pop($loaded_nodes);

Replace the field name with your actual field name.


How to change images without removing and re-uploading via GUI back end?

Derivative images (the files that result from using Image Styles) are auto-generated; you need to replace the original image file, then flush the images already created for the style(s) you're interested in, so the derivatives be re-generated next time they're requested.

For the example path you've given, the originals will be in the root of the public file system (/sites/default/files), so just replace those with the new images, and flush the styles that use them.

Probably the easiest way to do the last part is to install the Image style flush module.


I have tested on Drupal vanilla installation 7.50 and simplenews version 7.x-1.1 stable release, the link works perfect to add simplenews nodes.

I would recommend you

 -  Re install simplenews module
 -  Check if you see simplenews content type under structure>>content types
 -  Check if you see any error in your error logs.
 -  Check if you are using dev version of simplenews module


How to create bootstrap subtheme using sass?

Create a New Sub-theme

Copy bootstrap/starterkits/sass folder into sites/all/themes or a respective sites/*/themes folder.
Rename the folder to a unique machine readable name. This will be your sub-theme's "name". For this example and future examples we'll use subtheme.
Rename subtheme/sass.starterkit to match the folder name and append .info (e.g. subtheme/subtheme.info).
Open subtheme/subtheme.info and change the name, description and any other properties to suite your needs.
Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into the root of your new sub-theme. After it has been extracted, the directory should be renamed (if needed) so it reads subtheme/bootstrap.

Compile Sass

Override default bootstrap variables in subtheme/sass/_default-variables.scss.
Edit subtheme/sass/overrides.scss as your fit to properly integrate with Drupal
Compile subtheme/scss/style.scss to subtheme/css/styles.css.

More Information : Read Drupal-Bootstrap Documentation


How to consistently style the titles of Views in my Panels sidebar?

You just need to target it with css.

.pane-region-class .pane-title h2,
.pane-region-class .pane-title h3 {
  font-size: 16px;
  etc.
}

I think you can add classes to panel regions. And do the above without h2 / h3 to style the general title.


How to limit term reference autocomplete to a certain branch in hierarchical vocabulary (D7)?

I use Workbench Access for this. I think you need to use the dev release, but for me, it is stable on a production site. It allows you to define which user roles and individual users can see which parts of taxonomy.


How can I use the MySQL FIELD() function within a SelectQuery object in Views?

I got this working! I couldn't find any way to get the orderBy working in hook_views_query_alter(), so I tried to do this in the raw hook_query_alter(). In my particular situation, I couldn't get any result when I filtered against the table that Views had already joined with (I can't explain why) and so I added my own join. Voila, it works.

function mymodule_query_alter($query) {
  if ($query->hasTag('my_view_id')) {
    // Remove the current sort order.
    $order =& $query->getOrderBy();
    $order = array();

    // Join with the table that we need, giving it a custom alias.
    $query->join('field_data_field_listing_status', 'custom_status', 'custom_status.entity_id = node.nid');

    // Add our cool FIELD() function to push all 'sold' nodes to the very back of the list.
    $query->orderBy("FIELD(custom_status.field_listing_status_value, 'sold')", 'ASC');

    // Add any other ordering that we need...
    $query->orderBy('node_created', 'DESC');
  }
}


Random page rendering error: A stray renderRoot() invocation is causing bubbling of attached assets to break

The error is caused by Renderer::renderRoot() in a wrong place, see the docs:

  Renders final HTML given a structured array tree.

  Calls ::render() in such a way that placeholders are replaced.

  Should therefore only be used in occasions where the final rendering
  is happening, just before sending a Response:

  system internals that are responsible for rendering the final HTML
  render arrays for non-HTML responses, such as feeds

  (Cannot be executed within another render context.)

Look for renderRoot() in custom code. Check if you need to render at all (most times you need not) and don't render too early, only in theming when there is a render context collecting the bubbled up metadata. Then replace it with Renderer::render().

The random behavior is probably because of caching.


How to get the default value of radio button from database?

As the radios are separate field in itself, default value should be as easy as follow

foreach ($check-box-options as $key => $value) {
        //A. A function to query database to get default value
        $default_value = _my_module_helper_get_default_radio_option($key);

        //B. Or if its a system setting form, all values are inside the variables, in that case all you have to do is variable_get()
        $default_value = variable_get('radio_'.$key);

        // Depending on form type use option A or B.

        $form['radio_'.$key] = array(
            '#type' => 'radios',
            '#title' => t('abc'),
            '#options' => $filter_radio_options,
            '#default_value'=> $default_value,
            '#states' => array(
                'visible' => array(
                    ':input[name="filter_criteria_options['.$key.']"]' => array('checked' => TRUE),
                ),
            ),
        );
}

// In case option A is what you needed.
function _my_module_helper_get_default_radio_option($key) {
  return db_select('your_table','yt')
         ->fields('yt',array('field_name'))
         ->condition('yt.field_is',$key,'=')
         ->exectue()
         ->fetchField();

 }


You can use an access callback for that sort of thing:

function mymodule_menu() {
  $items = array();
  $items['mycontent/%my_object/my_place'] = array(
    'access callback' => 'mymodule_foo_access',
    'access arguments' => array(1),
    ...

  );
  return $items;
}

function mymodule_foo_access($object) {
  // Contrived example, use something better
  return $object->flag === TRUE;
}


For Drupal 8 you could run the following command:

drush uinf $(drush sqlq "SELECT GROUP_CONCAT(name) FROM users_field_data")

The output will loke something like the following:

 User ID       :  1
 User name     :  admin
 User mail     :  info@example.com
 User roles    :  authenticated
                  administrator
 User status   :  1


How can I create a time counter by aggregating a view?

Disclaimer: I'm a total hack with Drupal

I would use the View type of "Table",  then create a views-view-table--VIEWNAME.tpl.php

You'll see that it's set in to a real easy to read loop through the rows.   Modify the HTML structure to suit your needs,  but also add in a simple $var++; and then place that at the end of your rows.


How to use $config->get for #default_value when multidimensional

I have tried unsuccessfully

'#default_value' => $config->get('section.field_name')

Probably because you didn't set it first with section.field_name otherwise you can't retrieve it if you have not set it with that name.

Field names are supposed to be unique, so nothing different.

It really depends on what you do in set, you could give it whatever name you like

$config->set('lalalala', $form_state->getValue('field_name'));

and then retrive it with $config->get('lalalala'),

but convention is to give it the field name:

$config->set('field_name', $form_state->getValue('field_name'));


If I need to display a view in popup, then I will use ctools module.
Ctools provide Modal dialog functionality to display element in modal.

You need to follow below step for the same:

Create a custom module.
Create Menu item which will interact with ctools modal.
Define ajax callback for the menu item and return HTML of the modal using ajax.

You can check working example (http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7)


Migrate multilingual Drupal 7 users to Drupal 8

Looks like your migration configuration needs to be re-installed. When I had that issue I deleted the map table (in your case migrate_map_custom_user_translations) and then re-installed the config (I used the config_devel module).


Displaying nodes and forms in a block for processing

The Form Block module lets you easily create "block versions" of your add node forms. These block versions are still forms like any other in Drupal so you can use hook_form_alter to change the Submit button text to whatever you like and/or add any submit/validation handlers as required.


Create a page with database data in a module

if all the uploaded Zips contain similar data you could expose the custom table to Views using hook_views_data and then make a View path with a contextual filter to show the content of a given table.

If you really need a link look at the hook_menu function and make a menu entry that loads a custom page ... which can then load a custom View to show your data on a page.


How to import Term reference (autocomplete term widget) inside field collection with Feeds & feeds tamper

A couple of things.

You are using a very old patch. In my implementation I am using the one in #102 (I see its now up to #119)
https://drupal.org/node/1063434#comment-7395840
You need to tell feeds that it is ok to create new terms for you. Once you've added the target in Node processor > mapping for the term reference you can change it's target configuration (the cog icon). There is a checkbox there 'Auto create'

[edit] Please use the new patch in #121 https://drupal.org/node/1063434#comment-7792223 which corrects your issue.


Update entity properties fetched with entityTypeManager()->getStorage

You can actually use loadByProperties as that filter, you just need to extend your search:

$apples = \Drupal::entityTypeManager()
  ->getStorage('fruit')
  ->loadByProperties([
    'status' => '1',
    'name' => 'Apple'
  ]);

If you need to filter an existing, broader list, then just use foreach, array_filter, etc; Drupal doesn't have any special methods for it.


How can I add a custom currency to commerce?

Have a look at the Commerce Userpoints module. Some details from its project page:

It allows users to create commerce_line items with negative points value, behaving like a discount system in the order process.
The user can choose how many points he wants to use, they will be automatically taken from his userpoints account.


Radio buttons triggering an AJAX callback to load form elements are pre-selected after navigating back to form in browser

OK after a bit of searching I found this: http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors

Specifically it mentions Drupal 7 integrates the Jquery Once plugin into Drupal 7 core.

Therefore I can modify my Drupal.behaviours.attach to the following:

  Drupal.behaviors.uncheckRadioButtons = {
    attach : function(context, settings) {
      $('body').once('deselect_radios', function (){
        $('input[type="radio"]:checked').attr('checked', false);
      });
    }
  };


Pop-up calendar option does not display when I add Date field in webform

The Popup Calendar option in Webform is entirely separate from the Date module, so it should always work regardless of whether you have installed Date module (or Date Popup module).

Make sure you've added a date component to your Webform, then under "Display" there is a checkbox for "Enable popup calendar". This option is enabled by default. Now a little calendar icon should appear next to your date component when viewing the node.


Should be something like getting the nid of the current node and then being $nid the node id of the current node and $sqid the queue id:

$pos = nodequeue_queue_position('work_order', $nid);
$nodes = nodequeue_load_nodes($sqid, FALSE, $pos+1, 1, TRUE);

It's untested so maybe you need to tweak the position and so.


In Activity Stream, how is the 'active group' determined when a node has multiple organic groups assigned to it?

I believe the active group is just the group context which is present when content is created (i.e. if you're 'in' group B and post a node into groups A and B, it'll only go into the stream of group B). So it's not great for cross-posting.

You shouldn't use the patch in that issue because it was never finished, it's out of date, and has bugs and bad code that would most likely break your site.

If you plan to keep using Commons 6.x, best to post a feature request in the Activity log queue requesting default rules that would work to create multiple log messages when content is cross-posted across groups. Otherwise, wait for Commons 7.x where it's not planned to use activity log.


Get node id for page which is set for 403 and 404

You need to use

variable_get('site_403');
variable_get('site_404');

It will return a string like "node/1", then you just have to parse this string to get back the node ID.


Drupal.behaviors function can't detect Views object when user is Anonymous

I found that solution that works for me even under anonym.
Stars - changes

(function ($) {
    Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {

        **var viewName = 'ajax_test';**

        // View is Ajax enabled,
        // and is available as a property of the Drupal object
        // like so...
        **var instances = settings.views.ajaxViews;**
        var targetedView;

        // iterate thru the various
        // views instances name to find your views
        $.each( instances , function getInstance( index, element){
                    if(**element.view_name** == viewName ){
                            targetedView = '.view-dom-id-' + **element.view_dom_id**;
                    }
        });

        // Define your button click here...
        $('.viewsrefreshbtn').click( function(){
                if(typeof targetedView !== 'undefined'){
                    $(targetedView).trigger('RefreshView');
                    console.log ('Clicked refresh btn on view. View Refreshed');
                }
                else {console.log ('Can\'t find viewName on this page');}
        });
    }
}
})(jQuery);


How to use Drupal Code Sniffer in windows?

On the project page there are instructions for each IDE.

The one you're after (Eclipse) is here.

In case anyone uses something else, the other instructions are as follows:

Vim, Sublime Text, and Komodo

Netbeans

PHPStorm (install the Codeing Standards globally first, as described here, then Drupal should be available in the list or rulesets.

You won't get this working in Notepad.

On another note, I'd probably also just stop using Notepad.  If you must use a basic tool, then Notepad++ is a million times better.


Show menu link descriptions for a custom navigation menu

Here are two things that may help you get this going:

It looks like you're calling the theme_links() rather than the theme_link() function in your page.tpl.php file, so make sure that the call and theme function implementation match.
You could add additional information to your links when you theme them to distinguish them from other links.  For example, notice how I'm adding an id in the 'attributes' section below, so I can check for it later, in my theme_links implementation

Does that help?

 print theme('links', array(
  'links' => $secondary_menu,
  'attributes' => array(
    'id' => 'secondary-menu',
    'class' => array('links', 'inline', 'clearfix'),
  ),
  'heading' => array(
    'text' => $secondary_menu_heading,
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));


how to include .inc files in drupal8 in custom form

The procedural function for include files seems still to exists module_load_include(), but you shouldn't use it in a form class. Normally you would refactor the code inside of the form class in multiple class methods. If you want an extra file, then create a new class and include it in your form class with an use statement. Each class has it's own file, which is autoloaded with PSR-4, see https://www.drupal.org/docs/develop/coding-standards/psr-4-namespaces-and-autoloading-in-drupal-8

A Trait is an alternative option. You would put the refactored methods in an extra Trait file, but logical the methods remain class methods and at the same time are reusable by other classes. The Traits are also autoloaded. See https://drupalize.me/blog/201503/dependency-injection-traits-drupal-8


Is it possible to override a field module's implementation of hook_field_validate()?

There is hook_field_attach_validate(), which is invoked by the single function that invokes hook_field_validate(), namely field_attach_validate(), which is called by field_attach_form_validate().

I did not find an obvious way to get rid of the original validation function, but a quick hack would be to remove the errors, that the original validation function produced, from the $errors array in your hook_field_attach_validate() implementation.


Why does my content type need to be reviewed before it can be saved?

In Drupal 7, you can manage this via admin/structure/types/manage/CONTENT_TYPE in the Submission form settings:

In Drupal 6, you manage this via admin/content/node-settings:


Services Views and combine different field values into one?

Try taking one field and hiding it with views then if the next field is empty pull that one in there?


Connect to Intersystems Cache DB via ODBC

As @Bala said you want to try to install the PHP ODBC driver. Drupal does not use this driver by default (a drupal install may use MySQL, Postgres, or I believe MsSQL on install if those drivers are found by PHP).

Once the ODBC driver is installed for PDO, you can inform Drupal of your 2nd database by following the Multiple Databases Documentation. Bala linked you to a previous example I gave using ODBC to an MsAccess database file -- you're request is simply a different DBMS vendor. The same approach should work InterSystems Cache DB by following the concepts in the documentation page linked about.

Note that ODBC is a slow interface as its essentially a wrapper to your client Database. Its not as fast as a full native DBMS driver. Keep that in mind when querying and using your data.


How do I modify the individual links on comments (reply, delete, any others I add in Flags, etc...)?

thanks to your link to the theme_links i managed to solve my problems, so here's how i would solve yours.

the idea is to split the links in two parts, one to print before and the other after the content.

$group = $content['links']['comment']['#links'];
$plain = array();

if( isset($group['comment-like']))
{
    $plain['comment-like'] = $group['comment-like'];
    unset($group['comment-like']);
}
if( isset($group['comment-reply']))
{
    $plain['comment-reply'] = $group['comment-reply'];
    unset($group['comment-reply']);
}

$first = $content['links'];
$first['links']['comment']['#links'] = $group;
$second = $content['links'];
$second['links']['comment']['#links'] = $plain;

//before the print render( $content);
//note: apparently, you can't add a class to the <ul> element from here, so you should manually wrap it and fix your css accordingly
print '<wrapp class="something">'.render($first).'</wrapp>';

//after
print render($second);


Top article image not showing when I share content with Facebook or Google Plus

We need to pass the url for the image derivative based on the style we're using.

So - not this:

[my_site]/sites/default/files/my_image.jpg

Rather, this:

[my_site]/sites/default/files/styles/large/public/field/image/my_image.jpg?itok=kB4r6YaD

This image derivative url is not part of the $node object, so we have a bit of wrangling to do. One way is to enable the php filter and use this as the value for facebookpost:field-facebook-picture:

<?php
  if($node->field_image) {
    if(array_key_exists(0, $node->field_image['und'])) {
      $fid = $node->field_image['und'][0]['fid'];
      $result = db_select('file_managed', 'fm')
        ->fields('fm', array('uri'))
        ->condition('fm.fid', $fid,'=')
        ->execute()
        ->fetchAssoc();
      $path = $result['uri'];
      $style_name = 'your_style_name';
      print (image_style_url($style_name, $path));
    }
  }
?>

I used similar logic in a custom token instead of using php evaluation for the value of facebookpost:field-facebook-picture.


The correct format is [current-user:name].


Drush is an incredibly helpful tool, you are going to enjoy it. There are a lot of other benifits you'll get from installing it as well.

I'm going to assume you are on a Mac.(There are other ways to do this on a Windows machine, but you'll have to look for them.)

Drush installation is independent of your Drupal version. The only variable is which version of Drush you install. This shows that you'll want version 8.x for Drupal 8.
Yes, your Bluehost server already has Linux, Apache, PHP & MySql. The LAMP stack that is referred to in the digital ocean tutorial is one that you install on your home computer. This will allow you to work locally much faster than making changes locally, uploading them to your Bluehost server and seeing if they worked. I'd recommend using homebrew to set it up. Here's a great article to help you out.
Here's some info on installing pear on your Bluehost server.

As for the other questions...

No, you don't need the composer module. (I haven't used it & I've been using drush for years. I'm not dissing the module, I just know it isn't needed.)
Try this go to see how to install composer. This will tell you how to install Composer on both your

You haven't specifically asked about this but I hope you take the time to install LAMP on your home computer. It'll be a hassle but end up in a huge leap in your productivity. BTW You can also use homebrew to install drush. Here's a Drupal article that explains how.

Good luck!


Your DGMap.js script isn't external, you should use file as type parameter instead.

drupal_add_js('sites/all/modules/GoogleMapByDave/DGMap.js', 'file');

or use an absolute path.

drupal_add_js('http://example.com/yourscript.js', 'external');


If theme folder contains no html.tpl.php file, which html.tpl.php would Drupal default to using?

I found it, it's in

mysite/modules/system/html.tpl.php


import local drupal site with database already exist

You can use Backup & Migrate Module for importing and exporting DB's.

  Backup/Restore multiple MySQL databases and code
  Backup of files
  directory is built into this version
  Add a note to backup files
  Smart delete options make it easier to manage backup files  Backup to
  FTP/S3/Email or NodeSquirrel.com  Drush integration  Multiple backup
  schedules  AES encryption for backups


If there are different data that you would like to store from your csv, you should create your own content type, add required fields there.

Then in create your feeds importer, set the required settings(like selecting your content type), set mappings and let feeds do its magic(yep, its an awesome module!)

Fees is a great module where you have to import data into nodes, users or taxonomy.


How to insert a block inside the content?

You render the block in the preprocess function for that template. Each template (with its family of suggestions) has a preprocess function. For instance, if you are rendering page.tpl.php or a suggestion based off that, then the preprocess will be named THEME_preprocess_page (template_preprocess_page in the docs).

Inside the preprocess function you add a new key to the $vars array, and set it to the html output that you want printed. Then, in the template file (ie page.tpl.php) you print that variable.

example:

template.php file

function MYTHEME_preprocess_page(&$vars) {
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  $vars['my_block'] = render($block['content']);
}

page.tpl file:

<?php print $my_block; ?>

You can also just assign the block to a region (below content for instance) and then move it out of there into wherever you want it by using hook_page_alter.

Drupal 7 preprocess tutorial adding variable to template

Using hook_page_alter to move node render items into blocks

Placing the contents of a block in any location

Drupal 7 - How to Print Blocks in templates


Why are all Drupal mails going to spam folder wheter it is reset password mail, account activation e-mail etc.?

This is not a technical sure fire solution. There can't be a sure fire answer either, because spam detection algorithms are different, even if the recipient mail server had same software, per-account activity and a lot of factors can be used to decide whether the email is spam or not.

There are some steps I take for every site before going them live.
The obvious one is to not send spam content in first place, but other than the content itself, there are other ways to convince the recipient you are not spamming.

Setup SPF records for your domain. The spec is easy to understand, and there are tools to generate the record too. You need to make sure you only send emails from the correct IP addresses only.
Install MimeMail module. This is probably overlooked, but Drupal default mail class sends emails using php's mail() function directly. Mimemail does this too, but it adds extra headers and better mime information. All modules using drupal_mail to send emails will be instantly compatible with the module.
Think about going to a meeting with a basic dress vs a complete suit.

Mimemail trick is the most effective one I've tested.


Difference of two Dates in Computed Field

Here is a sample snippet (to be used in Computed Code PHP Block inside of a computed field)

$food_date_value = array_pop(field_get_items($entity_type, $entity, 'field_food_date'));
$food_date = new DateObject($food_date_value['value'], '');
$current_date = new DateObject('now', '', 'm/d/Y');
$entity_field[0]['value'] =$food_date->difference($current_date, 'days');

field_food_date is a date in the Unix Timestamp format (another field in my content type). DateObject can then be used for doing any date calculations.


How to use / configure the Course Requirements module?

The Course Requirements module does not have a lot (any?) docu. But comment nr 3 of issue # 2148985 helps to make it work, i.e.:

Add a node reference field to your Course content type (to references other courses).
Go to admin/config/course/requirements and select that node reference field you just added.
Add courses through the node reference field.

After completing these steps, this is how it should work:

The courses you add in the field should block that course from being enrolled into without completing the referenced courses.
After completing a course it should also tell you what courses required that course for completion.


Using Views would be the most common way to do this. I will show you a Display Suite method though.

Install these modules:

Display Suite (or any model that can give you extra view modes such as Entity view modes

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. A predefined list of layouts (D7
  only) is available for even more drag and drop fun!

View Mode Page

  Create separate pages for different view modes for a given content
  type.

  On the manage display page for a given content type, you can assign
  patterns for view modes so that they will become a page at the given
  path. For instance, if you want to show the teaser at a specific URL,
  you could do node/%/teaser. If you also use Display Suite or other
  modules that allow you to create new view modes, you can use these
  modes to display one or more fields from a node at a separate URL.

Field multiple limit

  This is a simple module that provides settings to limit the number of
  values to display on fields with multiple values.

Token

  Provides additional tokens not supported by core (most notably
  fields), as well as a UI for browsing tokens.

Default View Mode:

On your content type's default view mode activate One Column Display Suite layout and click on the gear next to your multi value field and set it to show the first 5 of the multi value field. Use Display Suite to create a Code Field on entities node, with Field code:

Show all.

Tick Token. Back on the manage display for the default view mode you will now see that field: Show all. Drag it to where you want it displayed

Show all View Mode:

Use Display Suite to create an additional View mode. Go to Manage display for the new View mode and set the 'View mode pages' URL pattern to node/%/all. Make sure you set the multi value field to show all values.


Separate and display only particular parent term from a taxonomy vocabulary

I think this is, what you searching for: Taxonomy Term Reference Tree Widget.

Here is a quote about it (from the module's project page):

  ... provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


How to add help text to tabs in admin/structure/types/manage/{node-type}

The summaries are dynamic so they're controlled by JS. It should be something as simple as this:

(function($) {
  Drupal.behaviors.csmFieldsetSummaries = {
    attach: function (context) {
      $('fieldset.csm-form', context).drupalSetSummary(function (context) {
        // Make a decision about what summary to display based on your tab's current value.
        var summary = $('input.foo', context).is(':checked') ? 'Input checked' : 'Input not checked';

        // Or static strings are fine too.
        summary = 'Static summary';

        return Drupal.t(summary);
      });

      $('fieldset.another-csm-form', context).drupalSetSummary(function (context) {
        // ...
      });
    }
  };
})(jQuery);


I found the solution - had a silly error.
In lightbox2 module configuration page, under Page Specific Lightbox2 Settings, I was telling it to not load on any page.


There's a module called Content locking that covers your use case.

  Block concurrent editing: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing
  so, and notified that the content is already being edited.

You can also adjust when a lock will expire if an edit is abandoned.


Shipping line items not displaying with [commerce-order:line-items]

If you enable the Token module (maybe you already have?), you are given a new view mode on all fieldable entity types called Tokens. You need to enable this in the Custom display settings fieldset on the Manage display page for order types (found under Administration > Store > Configuration > Order settings). Once you've done this, you'll be able to choose any eligible View you want for rendering the line item field's tokens, so if you add another display to the default View and remove that line item type filter, you can use that just for rendering the token.

You can read more w/ screenshots here: https://www.drupal.org/node/1299662


Modules i18n: How to set the default language home page url without alias

Make sure to declare your home page node as a "multilingual varialable". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

I'd be interested to some day hear if this  resolved the issue here.


Separate drupal view filters from the results

I haven't used the Drupal Search API but if you are creating a View with exposed filters, you can have them put in a Block instead of being part of the View.  Then you can put that Block anywhere you want.  To do this, you go into the Advanced Settings of your View:

and in Exposed form in block: select Yes instead of the default No.  Then you can go into the Block UI and place the newly created block wherever you want.

One interesting effect:  If you don't restrict this block to the page of the View in the Block UI, it will show up on all pages, and if your users then select any of the filters in it and hit apply, that will take them to the View page and results.


Where has module-specified HOOK_preprocess_page gone in D8?

This hook has not been removed, there are still preprocess hooks for modules:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_preprocess_HOOK/8.2.x


Custom tokens and/or text filters for consistent link look?

You could implement an input filter, or implement hook_node_view_alter().

Keep in mind that an input filter is not only used for node's body, but also for comments, user's signature, some part of a view, and theoretically with any module that uses check_markup() and that also allows the user to select an input format to use. As consequence of this, input filters should not take assumptions about when it is invoked.

There isn't normally any performance issue for accessing a node's fields; Drupal uses caches to avoid executing queries when not necessary.

If you are talking about the tokens provided from Drupal 7, or from the Token module, you could also implement a token, but you should consider that a token is accessible not only in the context you are expecting it to use it.
You should still need code to replace the token in text, using an input filter (for which the previous notes are still valid), or hook_node_view_alter().

If you need to provide a token that should be accessible in a specific context (e.g. to be replaced in the body of nodes), you could use the code used by Drupal, which (in _user_mail_text()) uses the following code.

  if ($replace) {
    // We do not sanitize the token replacement, since the output of this
    // replacement is intended for an e-mail message, not a web browser.
    return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  }

user_mail_tokens() is the function that provides the custom token that should not be available in other contexts.

function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
  }
}


How do I get a count of comments by querying the database table?

I think you can do it using the following query:

SELECT count(comments.cid), node.nid
FROM node
INNER JOIN comments on node.nid = comments.nid
WHERE node.type='forum'
GROUP BY node.nid


Can Views Bulk Operation be used to re-index specific nodes

I didn't deal with that for a few time but since I found the answer my self I thought about posting that here in the hope that someone finds it useful. I dug into Views Bulk Operations and into the Search API devel, copied and modified some code.

For this to work we need to create a custom module and put in the module the following:

<?php
/**
 * Implements hook_action_info
 */
function MY_MODULE_api_action_info() {
  /**
   * Defines an array of actions to be performed on nodes
   */
  return array(
      'MY_MODULE_api_reindex' => array(
          'type' => 'node',
          'label' => t('Reindex node'),
          'behavior' => array('changes_property'),
          'configurable' => FALSE,
          'vbo_configurable' => FALSE,
          'triggers' => array('any'),
      ),
  );
}

function MY_MODULE_api_reindex(&$node, $context) {
  /**
   * function to implement the action defined above (see the key of the array
   * returned in vbo_search_api_action_info()
   */
  //copied the code from the search_api_devel module
  //load all indexes
  $indexes = search_api_index_load_multiple(FALSE);
  foreach ($indexes as $index) {
      if ($index->enabled) {
        search_api_index_specific_items($index, array($node->nid));
      }
    }
}

There might be a better way to go around this problem. For example the code now loads the index for each visited node, whereas Search API supports indexing an array of nids. So potentially we could gather all nids and then submit to Search API


Use term reference field in node--custom.tpl.php

If taxonomy_term_load() return false then

the supplied argument (tid) is either non-numeric
Or there is no term with this id.

To check if there is any term against this id try

`taxonomy_term_load_multiple(array($tid), array());`

If taxonomy_term_load_multiple() returns empty array then it is clear there is no term with this $tid.


How to call a Rules action settings form via drupal_get_form

You must be using an old version of commerce to get an url like that. It was changed long ago to dmin/commerce/config/payment-methods/...

In hook_menu, the commerce_payment_ui module creates the path, where the rules forms should be located:

// Add the menu items for the various Rules forms.
$controller = new RulesUIController();
$items += $controller->config_menu('admin/commerce/config/payment-methods');

You could alter those if you want to change the url. You should however be aware that this url is also used elsewhere:

/**
 * Builds the payment settings page using the Rules UI overview table filtered
 *   to display payment method rules.
 */
function commerce_payment_ui_admin_page() {
  RulesPluginUI::$basePath = 'admin/commerce/config/payment-methods';

  ...
}

Since most of what Rules does, including creating these settings form is classed based, it wont exactly be easy to create the form. I haven't delved much into the Rules code, but I remember seeing public functions called

form
form_validate
form_submit

I believe these are used to create the form, but how it ends up in the FAPI is beyond me. If all you want is to change the path, you could just use hook_menu_alter and for commerce, overwrite the commerce_payment_ui_admin_page function with your own to create the overview table.


Allow some products to be sold only in bundles (groups) with some other products

As far as I know, there are no supported modules to acheive what you want.

So if you want a sustainable and future proof solution, you should probably code it yourself.

I would go for solution, where I create a custom entity type, Product Validation.

Here are some fields, that I think it should contain:

Product ID (The product it's active on).
Applies above (quantity) (A minimum quantity that must be purchased, before the validation is applyed).
Depending products (Products that be must purchased too).
Min SUM (The minimum sum of all the depending products).

Those are just fields that should probably be there, you can always add more fields like, if only one of depending products must be purchased, or all of them, maybe also support for multiple product ID's to avoid creating duplicates, etc.

Then add a custom validate handler, when the user clicks the place order button on the cart page.

EDIT: To alter the cart form you could use hook_form_alter, and check if (strpos($form_id, 'views_form_commerce_cart_form_default') === 0.
The cart form has a unique ID per order so that's why you want to do like that. Then you can add $form['#validate'][] = 'MY_MODULE_product_validation', where the logic will then be.

Your logic will look similar to this:

$product_validation = $entityTypeManager->getStorage('product_validation')->loadByProperties([
  'product_id' => $product->id(),
]);

if (isset($product_validation)) {
  if ($product_validation->getAppliesAbove() > $product->quantity) {
    $total_quantity = 0;
    foreach ($product_validation->getDependingProducts() as $dep_product) {
      // Check if $dep_product has been added to cart.
      // If yes $total_quantity += $cart->getItem('something')->quantity.
    }
    if ($product_validation->getMinSum() >= $total_quantity) {
      return TRUE;
    }
    return $form_state->setError($form, 'something');
  }
}

OBS: This code is using dummy variables and is intended to help you understand the logic, not as a "ready to implement" solution.

I hope it all makes sense.


Which drupal 6/7 ?
See here http://www.pixelclever.com/custom-drupal-themes-drupal-5-and-drupal-6
and this JQuery menu module.

Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.

Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don’t use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.


How do I properly detect if region is empty?

try to apply filters after render, like this :

{% set has_sidebar_first = page.sidebar_first|render|striptags|trim is not empty %}
{% if has_sidebar_first %}
    {# ... #}
{% endif %}


How to show a date in the correct timezone?

I suspect the problem has to do with some of the nuances of strtotime().

strtotime() can take just about any string, and convert it into a Unix timestamp.  The problem is that when the string doesn't contain an explicit timezone, it will use what is set by date_default_timezone_get().  That should be set from the current user, though (it is set by the account proxy).  However, the string that you are pulling out of $node->field_date->value is implicitly in UTC.  In other words, I think the string is being parsed by strtotime() is being interpreted as in 'America/New_York' and not 'UTC'.

The good news is that you can simplify your situation a lot.  The field item for a date range consists of four parts

'value' is the start date as a string in UTC
'start_date' is a DrupalDateTime object representing 'value'
'end_value' is the end date as a string in UTC
'end_date' is a DrupalDateTime object representing 'end_value'

For a plain date time field they are

'value' is the date as a string in UTC
'date' is a DrupalDateTime object representing 'value'

So, you can work with the DrupalDateTime() object directly.  In addition, that date.formatter service should pull in the proper timezone in use by the user viewing the page by default (in addition to using the user's active language).

I suspect something like this will work

$node = Node::load(2100);
$start_date = $node->field_date->start_date;
$formatted = \Drupal::service('date.formatter')->format(
  $start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s P'
);

Note I added the 'P' format placeholder in there so you can see what what timezone the system thinks is in use.

Make sure you have the proper timezone set up on admin/config/regional/settings, and that your user timezone is what you are expecting.  Also ensure that you have the proper timezone set in your php.ini (it's the date.timezone setting); weird things happen when this isn't set (And off the top of my head, I don't recall if that causes a warning in the installer or on the status report when not set.  I remember the issue, but not whether it got committed).


Not a defintive answer, just some input.

We (the paragraphs maintainers) are working on reaching feature and user experience parity (or be better, of course) with the Field Collection module, specifically for non-typical paragraph scenarios (single paragraph type, single cardinality, default paragrapht type, ..). There are discussions on officially deprecating field collections in favor of Paragraphs, this might or might not happen. So I'd recommend to not use FC, but I'm obviously biased there.

The latest Paragraphs dev version has support for setting a default paragraph type now, which means that it will by default show the form fields for that already, and you don't need to add a type. The add button should only be shown if you allow more than one field, which is the default for paragraph fields but can easily be changed.

Revisions should work fine in IEF as well, if you use an Entity Reference Revisions Field. If not, then you'll have to report a but, but I assume the maintainers are actively working on that as it is a critical element of Commerce 2.x.

One important difference between the two is Paragraphs are by definition a composite of the parent node, that means they have a parent reference and not re-usable, in case that is a requirement. IEF doesn't have that and allows to search and reference existing entities.

The advantage of custom entitiy types (with base classes or traits to re-use base field definitions) is that they're way more efficient, Paragraphs/IEF both result in separate entities that need to be saved, and all the configurable fields need to be stored in separate tables. With custom entity types, you can add all the fields you need as base fields. We're constantly working on requiring less code for custom entities, listings can be done with views with none or very little custom code, widgets work for base fields too, so anything you can do with configurable fields can be done with base fields as well. One major pain point right now is a revision UI, but we're making improvings there as well and entity.module provides some basic user interfaces there as well, diff.module is also working on supporting all entity types.

Yet another option would be to define base fields/configurable fields in code. That is possible as well, but I personally wouldn't really recommend it, there are still some unfinished areas there, especially uninstalling/removing those fields is really hard, as the delete/purge process only works for configurable fields. You could technically also maintain configurable fields with code and sync them between multiple bundles.


How to give confirmation for deletion through link?

Don't bother testing the value of confirm, the user is only given a choice to submit or go back (with cancel link).

function products_delete_confirm_submit($form, &$form_state) {
  $param = $form_state['values']['_product'];
  drupal_set_message(t('Product ' .$param.' will get deleted.'));
  db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
  drupal_set_message(t('usergroup has been deleted.'));
  $form_state['redirect'] = 'mailusers';
}

Also, your access callback is set to TRUE, which bypass all permission checking.

Final answer

It should be products_delete_confirm(&$form_state, $product_code), see the example at https://www.drupal.org/node/751826#creating, you were messing with your form structure.


Watchdog errors with location = http://default/index.php

The first error seems to be due to a failing operation with the Backup & Migrate module. This module is probably configured to make a backup of your database on a scheduled (CRON) interval. As the error message suggests, increasing PHP's max_execution_time setting may help.

The second error you're seeing is due to a missing 'type' column in the file_managed database table. This field is usually added by the Media and/or File Entity modules. You likely updated these modules' code, but didn't run updates. Try running your update.php, or if that fails, disable, uninstall, and re-install the Media and File Entity modules.


How to use Twig expression in content fields and render?

You cannot use Twig code as field value. You have to put that code in a template file. Or you can use Twig code in Views field value rewriting (but not as field value). 2nd is limited to variables of the view that are before to rewritten field. The function can be found in Views UI by clicking on the field name in the "Fields" section.


Problem with custom dropdown default value

Are you providing #default_value when loading form? If yes, you need to make sure that you're providing what is selected by user first. Check example below:

global $user;
// Check if user has set the timezone,
// if yes use that else set to default 'America/Creston'

$timezone = isset($user->timezone) ? $user->timezone : 'America/Creston';
$form['timezone'] = array(
  '#type' => 'select',
  '#title' => 'Select Timezone',
  '#options' => $options,
  '#default_value' => $timezone,
);

As per Form API Reference Documentation, it says #default value is:

  The value of the form element that will be displayed or selected
  initially if the form has not been submitted yet.


composer update drupal/drupal does not work : Nothing to install or update

Finally, i could update with these modifications.

Step 1, optional in case your composer.jsoncontains this. If it is ok, apply step 2

add

"require": {
        ---
        "drupal/core": "~8.5"
    },

remove

"replace": {
    "drupal/core": "^8.4"
},

Step 2

delete this folder :

vendor

delete this file :

composer.lock

run

composer update --with-dependencies


Use spaceless tag. This will not minify the HTML, instead avoids extra whitespace between HTML tags to avoid browser rendering quirks. When cached, can serve better.

In html.html.twig

{% spaceless %}

<!DOCTYPE html>
<html{{ html_attributes }}>
 #rest of the code
</html>

{% endspaceless %}

For compression there is a twig extension

Edit: Use Minify Source HTML module which comes for both D7 and D8.


twig check if image style or view mode exists

You can check image style existence in a preprocess hooks like follows.

$variables['image_style_exists'] = (bool) ImageStyle::load($style_name);

Though it's better to validate user input instead.
Note that configuration entities like image styles or views can be selected through entity reference field which may perform such a validation for you.


Maintenance mode doesn't work on front page without www prefix

Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

(Per this tutorial)


Form API: Show/Hide/Select option based on a previous option

You can solve this problem using AHAH on your Form API. The module AHAH Helper may be very useful for you... take a look there...


How Can I send sms confirmation when user creates a new account in my website?

Rules module will allow you to do something when something happens in the system. You can send email or sms when an account is created. This is a very handy module, you should have it.

In regards to SMS, there are a few options.

SMS Framework module
Messaging module
VoIP Drupal module

In regards to the SMS framework, I don't know how stable is the 7.x development release. You need to make some decisions here.

There are a tons of video/other tutorials on how to use Rules module, I recommend googling it and you will come across several sources. Do try the free videos provided by DruaplizeMe, they are very useful.


How to identify all modules hosted on drupal.org that depend on a given module?

As was mentioned above the solution could be parsing info files of all projects hosted on drupal.org. You can use this small tool to facilitate the process of obtaining the codebase of Drupal contributed projects.

Below is an example of searching dependencies for Quiz module.

drupal-project-loader -c 5 -b 7.x -d d7_modules -y &&
cd d7_modules && ag 'dependencies\[\] = quiz$' -G \.info$ |
sed 's/\/.*//;s/^/https:\/\/www.drupal.org\/project\//' | uniq | sort

The result:

https://www.drupal.org/project/certificate
https://www.drupal.org/project/certify
https://www.drupal.org/project/civicrm_cert_quiz
https://www.drupal.org/project/cloze
https://www.drupal.org/project/course
https://www.drupal.org/project/elms_features
https://www.drupal.org/project/grouping_question
https://www.drupal.org/project/image_target_question
https://www.drupal.org/project/kalvi_core
https://www.drupal.org/project/mark_word
https://www.drupal.org/project/og_quiz
https://www.drupal.org/project/opigno
https://www.drupal.org/project/opigno_pretest_app
https://www.drupal.org/project/opigno_quiz_app
https://www.drupal.org/project/opigno_quiz_import_app
https://www.drupal.org/project/qq_import
https://www.drupal.org/project/quiz
https://www.drupal.org/project/quiz_ddlines
https://www.drupal.org/project/quiz_drag_drop
https://www.drupal.org/project/quiz_evaluation
https://www.drupal.org/project/quizfileupload
https://www.drupal.org/project/quiz_h5p
https://www.drupal.org/project/quiz_progress
https://www.drupal.org/project/quizrubric
https://www.drupal.org/project/quiz_sentence_drop
https://www.drupal.org/project/quiz_share
https://www.drupal.org/project/quiz_userpoints
https://www.drupal.org/project/quiz_voice_answer
https://www.drupal.org/project/quizwebform
https://www.drupal.org/project/simple_mcq
https://www.drupal.org/project/tincanapi


Drupal 7 pager from module fuction not displaying in page.tpl

You just need to add ->extend('PagerDefault');

$query = db_select('mymodule_table', 'uf')->extend('PagerDefault');

I find the examples module really useful.  They have a pager example.

For what its worth I think using the Drupal db API with theming is a perfectly valid way forward that has a lot of strengths: it's efficient, flexible, powerful and you can put it in version control.  Obviously you should use the best thing for the situation.


How to change an image field to a certain fid programatically?

You can do this in the comment tpl file. Add something like this:

$img_array = array(
    'style_name' => 'thumbnail',
    'path' => $user->field_picture['und'][0]['uri'],
    'width' => '',
    'height' => '',
    'alt' => $user->field_picture['und'][0]['alt'],
    'title' => $user->field_picture['und'][0]['title'],
  );

$img = theme('image_style', $img_array);

You can then add <?php print $img; ?> where you want the image to appear.


How to programatically change image style of images gathered by view?

You could try a different approach, via the Views UI, adding the same image field 3 times, and assigning each of these different image styles.

Add a View result counter field, this will let you know the row number.

Then on template/twig file print image field that was assigned x image if counter (this is the twig variable name for View result counter) equals y.


EntityDrupalWrapper->value() causes infinite recursion on user login?

are you sure the user is logged in and you have a full $user object available in your rule?

Maybe you have to call $user = user_load($uid, TRUE); explicity for this 1 case?


Off-site payment method from the terminal

This isn't doable, unfortunately, because it would require a redirection process that is currently only supported by the checkout form. If it's a requirement for a site, I'd pursue a way for administrators to use the checkout form like a normal customer and submit payment being redirected from there instead.


How do I access node body from template.php?

It all depends where exactly you want to access it from.

For example in template_preprocess_node() you have full node object in $variables['node'], including body field ($variables['node']->body).


View display content by value based on user profile field values

You may use the flag module to flag users (it could be an automatic flagging in conjunction with Rules)as regulated, unregulated or both and then filter via views all flagged users. For anonymous users needs some  special handling.


If you have a content type which has a photo filed and you want to show the photos in the form of slider, Than I will suggest to use FlxSlider.

Go to your_seite/admin/structure/types/manage/your_content/display/
Change the photo filed form to flexslider
Click the setting icon to customize the slider options
Click Save

If your want to have some sort of photo album in your site than I will suggest to use Juicebox HTML5 Responsive Image Galleries

This module provides an integration between the popular Juicebox HTML5 responsive gallery library and Drupal. Juicebox is in many ways the successor of Simpleviewer and offers a powerful cross-device solution for image galleries, sliders and more.


Pathauto does not trigger on node_save when programatically creating nodes

We discussed on Drupal.org that not setting the $node->language property causes this issue to happen. Either setting $node->language = LANGUAGE_NONE or $node->language = 'en' should fix this.

Also using $node->path['pathauto'] = TRUE rather than $node->pathauto_perform_alias for Drupal 7.


Click here and check if it was added as a row class.

Else, look under Advanced

If nothing is there, check your theme's templates folder. They probably created a template file (.tpl.php or .html.twig) for the view.

Lastly, if still nothing, check inside your theme's folder for template.php or theme-name.theme


1) Checkmark ☑ expose filters

2) Select Single Filter

3) Select is between

which will result in

Unfortunately there is no way to do it in drop downs like you have it until the better exposed filters module gets ported.

Well you could do it in Drop downs using Group Filter with is between, but you would only be able to do it by year only though.


Drupal commerce update to 1.14 from 1.13 - breaks checkout screen

There is no way for anyone to diagnose the issue with the information given. A blank page typically means a PHP error has interrupted the page request. When you encounter situations like this, look to your PHP / Apache error logs to see what clues is gives you.

I'm not aware of anything in the Commerce 1.14 release that should cause the checkout form to suddenly break, but perhaps it's related to some other contributed module on your site. If you track it down to a core problem that you can reproduce on a clean install of Commerce Kickstart 1.x, feel free to open a bug report in the Drupal Commerce issue queue.


I've run into the inverse problem using Pressflow. From that I have learned:

The js version runs if and only if the has_js cookie is set. If you are able to clear that cookie (and keep it away), you will be able to run batch.
When the cookie is not set, there is a query parameter in the meta refresh tag, namely op=do_nojs (and not op=do as is normal). If it is a batch you are trying to run and one for which you know the batch id, you may be able to force a nojs solution.

Based on that, if you are only having problems with tunning batches yourself, the simple solution is to disable js in your browser before starting the batch operation.


Drupal 8 url after installation using drush site-install

Congratulations on getting this far. You got Drupal and Drush downloaded and were able to configure the database. Those can both be challenging things to do.

Based on your description it seems like do not have a webserver. Drupal.org has some documentation on setting up a webserver and there are a few solutions to that, like setting up apache or nginx.

Since you mentioned you have drush available one of the easiest solutions is to use drush's runserver command. It is documented here

From the project root run the command:

drush runserver

The output of that command will tell you the URL to load into your browser. By default the URL is http://127.0.0.1:8888 which it will tell you Listening on http://127.0.0.1:8888.

Here's a more detailed article from Lullabot on runserver.


How to deactivate keyboard navigation when using the “Views Slideshow: Swiper JS” module

Okay, so I solved this. It’s clear to me that the Views Slideshow: Swiper JS is somehow not passing all the config options it claims to handle to the final Swiper JS instance that gets loaded on the page.

So my solution that—works directly in the view—is to go to the Swiper JS settings “Format > Slideshow > Settings” scroll down and select “Events” and then add the following to the swiper.on('init', function() {} event:

this.params.keyboard.enabled = false;

Apply the settings, save the view and… et voilà! It works and cleanly disable keyboard navigation.