How do I include a jQuery in the body of a content type?

As @Gulok and @Drupalist said it is not good that add your js in content,the simple way to add js with one of below solutions (it is seems you are newbie to drupal I suggest if you want use learn and use drupal  use is correct,I can suggest a solution that you can add js in body(content) but I prefer guide you in correct way ;) )

  The PHP function drupal_add_js() lets you add a JavaScript file,
  setting or inline code to the page and it takes 5 parameters (see the
  api reference).

  The first parameter is always going to be a path to a js file, an
  array, or a piece of JavaScript code. If the second parameter is
  'module' (the default), 'theme', or 'core', then the first parameter
  must be a path and the only difference between these three is the
  order in which the script tag will be placed relative to other
  scripts, i.e. core scripts first, then module scripts and finally
  theme scripts.

  If the second parameter is 'setting', then the first parameter must be
  an array of settings. This is very handy for telling JavaScript about
  the configuration settings for your module, for example, and is
  explained in more detail in the next section.

  The final possibility for the second parameter is "inline" and this
  means you are passing in straight JavaScript code as your first
  parameter, which you want written directly to your page between script
  tags, rather than a call to a file.

  These two are the most important parameters for this function - indeed
  you may never even use the second one if all you ever want to do is
  add a js file for your module - but you can learn about the other
  parameters by reading this function's documentation at api.drupal.org.
  Adding JavaScript from within a module

  So, let's say you have written some jQuery code that targets some of
  the elements that are output by your module or theme. You simply need
  to save your jQuery code as a JavaScript file (i.e. with the .js
  extension) and place it in your module or theme's directory. If it's
  for a module, you then need to make the call to drupal_add_js() as
  above, from wherever the module is about to output content (e.g. in
  hook_block or hook_nodeapi), or if the JS is not acting on content
  output by your own module you can call it from hook_menu or hook_init.
  Note, that putting this file into hook_init means it will run on every
  page request, whether needed or not. Here is how you would ensure the
  file gets added:

  The jquery.js file is included automatically so you don't need to
  worry about adding it.

  To add JS (or CSS) file from form builder function the recommended way
  is to use Form API #attached property as below,

  See Form API reference for more details. Adding JavaScript from within
  a theme

  Adding JavaScript to a Drupal 8 theme With drupal_add_js (Drupal 6 &
  7)

  (drupal_add_js is deprecated in Drupal 8; use '#attached' instead.) If
  you are adding your .js file from within a theme, then you simply need
  to make the call from within template.php, you need to add the second
  parameter this time as 'theme' so that Drupal knows this script should
  be loaded after all core and module scripts are loaded:

  <?php drupal_add_js(drupal_get_path('theme', 'mytheme')   .'/mytheme.js'); ?>

  Using the theme's .info file (Drupal 6 & 7)

  You can add your script path in the .info file of your theme and
  Drupal will include them automatically. name = My theme description =
  Theme developed by me. core = 7.x engine = phptemplate

     scripts[] = mytheme.js Using a preprocess_page function

  To conditionally add js to the theme, you can use a process_page
  function:

 <?php function mytheme_preprocess_page(&$vars, $hook) {   if (true) {
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
     $vars['scripts'] = drupal_get_js(); // necessary in D7?   } } ?>

and according you comment your js will be something like

I try to include a jQuery in the body of a content type, as shown in the image below:

enter image description here

The purpose of this jQuery is to hide a div with id="test", so that the text aaaaaaaaaaaaaaaaaaaa in it is not shown.

The jQuery was added to the content (saved in it), but yet I still can see the aaaaaaaaaaaaaaaaaaaa and my js did not run.

Seems like Drupal JQuery.js file is not loaded, so how can I get it loaded?

(function($) {
$(document).ready(function(){
$('#wrap').hide();
});
})(jQuery);


What I ended up doing was creating a separate page with a generated PayPal button. You can include a hidden field called 'custom' that you can use to pass in your own data so I included the current user's UID. After a successful payment you can get PayPal to send a POST with the details to a URL of your choosing. I set up a custom page with a listener then updated the user account specified by the UID.


Custom tpl.php for custom content types rendered through another tpl.php

You shouldn't be printing it with print_r(), just try print.

$node = node_load($aTab['nid']);
$view = node_view($node, 'full');
print drupal_render($view);


well propably is a theme issue. if you encounter this on all pages check your page.tpl.php and make sure this

  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

is before

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

this is all i can say with the info provided.


Disable Taxonomy Generated Teaser List Pages

Just install the Views module and enable the Taxonomy Term View. This will give the option to set the access permissions to Authenticated or Administer or any role or permission, preventing the page from being viewed by the public or robots.

PS: if you are not using Views, you have not yet discovered Drupal.


Best way to add edit + flag links to a node being displayed inside Colorbox Node?

You could use Views, create a block view.

Under advanced, add relationship of flags of the node and check mark require relationship.

Add flag link and edit link as fields.

Add Contextual filter of nid and select provide default value, then select get ID value from url. (preview will go blank, which is normal here)

Place view block on your node.

  Php filter is fine to use.

This is very risky, see: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?, if you want to use php, create a template file for your node, block, or view.

Therefore, another option is to create a template file for your content type.

node--[type-name].tpl.php and do php code there.

Ex: node--article.tpl.php

In your template file put

  <?php print 'nid . '/edit"> edit '; ?>

  <?php print flag_create_link('FLAGNAME', $node->nid); ?>

<?php print render($content['title']); ?>
<?php print render($content['body']); ?>
<?php print render($content['field_name']); ?>

and so on, you print all the fields you have.

Remember to flush/clear the cache to see changes.


Why recurring order becomes completed immediatelly after payment (no fulfillment status)?

So my question is why it's not changed to "Fulfillment" but to
"Completed" as soon as payment is done?

Because you're setting it to completed, the code you found is just an example.
For your case, it needs to be:
$next_state = $capture ? 'fulfillment' : 'authorization';


How to include the same menu twice in a .tpl file

You can probably use the show() function to un-hide the previously rendered element:

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

    <?php print render($content); ?>
    <?php show($main_menu); ?>
    <?php print render($main_menu); ?>


Is there a number field with + and - feature?

Try the Stepper Field module

  The Stepper Field module is based in a plugin for jQuery UI called jQuery.ui.Spinner and provides a new steps widget that can be added to any Integer field.

Here is the image


Where do pending drush database updates live?

Drupal will look in /modules and /sites/*/modules if the site was installed on top of the default profile. If you're using a distribution or other contrib/custom profile then it'll also look under /profiles/[name-of-profile].

SELECT filename FROM system WHERE name = 'video_embed_field'

will tell you exactly where Drupal is looking for the module you're trying to find.

  Are these database updates stored in a table in the database[?]

I haven't looked at Drush, but as far as core's update.php goes, no. The .install file of each enabled module is checked to see if it has any update functions with a schema greater than the currently installed schema. I'd imagine Drush does the same thing, no real reason for it to do things differently.

If that assumption holds, then you basically couldn't be seeing those updates as options unless the module is somewhere in the file system (or at least a PHP file that will be included in a normal bootstrap containing a function called video_embed_field_update_7123() or similar).

So keep looking, it's likely to be there somewhere!


Any action that makes a call to either cache_clear_all(NULL, $table); on all core cache tables or a call to cache_clear_all(); can be termed as General Cache Wipe

I could list down following based on a quick grep search for these functios.

Cron : Very obvious.
When a vote is submitted on a poll.
Any operation performed on admin/content page like

Node Multiple Delete. (Handled as a special case with confirmation form)
Any other operation like

When node access is rebuilt. (Like change of permissions)
When menu cache is cleared. (Node module clears all the caches [node_menu()])
Node Form Submission. [Creation or Updation]
Node Deletion
Comment Form Submission
Any operation performed on admin/content/comment page
Block administration. Any action performed on admin/structure/block
Create, Delete/Update any custom block.
Any forum form submit.
Any System Theme settings are changed.
When aggregator parses a feed.
Profile fields are edited/updated/deleted or their weights and categories are changed.
When a user account is cancelled.
When taxonomy term/vocabulary is added/deleted/updated.


Block not showing on a matching path (menu item duplicate)

Perhaps on the Contact Us page, the block is trying to display child menu entries for the new level 1 "Contact Us" item, and there are none? The block won't get rendered if there's no content.


adding extra tab to user's profile using hook

Your code works - just remove the first forward-slash from the URL you are passing to hook_menu().

Correct: $items['user/%user/email_user'] = array(
Not correct: $items['/user/%user/email_user'] = array(

Be sure to clean cache after you update this.


updates page shows an error for a mystery module 'standard 8.6.12'

going to mark this as answered so I can close it...

I removed a contrib module that we are no longer using and the mystery module "standard 8.6.12" no longer appears.

I cannot say for certain which module it was - but I am 99.78% certain it was from a contrib module, not from a core one.


Add User Edit and Profile pages to Quicktabs

I create my quicktabs programmatically most of the tines exactly to avoid this kind of problems and expedients.

You need to choose 'callback' for both tabs, and use 'user/x' for profile and 'user/x/edit' for the form.

What x is?

the user uid, but since you need it to change based on the current user, you need to take it from the path the tabs will be displayed on.

assuming the path is

"mysite/candidate/{user uid}/dashboard"

replace x with %2 (or %3).

you don't have the uid in your path?

then create the quicktab programmatically :)


Do not map (update) some fields with migrate in update action

Good news! You are doing this exactly right. By "unsetting" the fields in the source data you are taking the proper approach. This practice is common and the relative snippet of documentation is buried a bit in the Migrate Handbook:

  To use default values for NULL or '' or array() values, be sure to remove the item with unset() in your prepareRow() [or prepare()] function.

From https://www.drupal.org/node/1133448

Good luck with the migration!


I suspect that you haven't implemented hook_entity_info(), which is why entity_get_controller() returns nothing, and you can't call a method of nothing.

The Examples project has an issue in the queue for an entity example. Give it a read. :-)

Hooks have the module name, so if the module is called nutrition, you'd declare nutrition_entity_info().


Alter existing form and add element with an ajax "add more" button

Answering my own question after resolving the issue.
Removing $form_state->setCached(FALSE); fixed the issue.

However, I am not sure why it did or whether this have negative consequences. Hope this helps others.


XHR2 upload using Drupal 7's ajax framework

I think your approach is flawed. You should use as much of Drupal's ajax system as possible, even though is wildly uncomprehensible and weird. Don't create your own Drupal.ajax object. Let Drupal handle that and the events and triggers that come with that.

Then there are only 2 problems left:

Don't create an iframe and a fake form and submit that. Use Ajax.
Don't serialize and preprocess that request. Use only what I'm giving you.

They're combined in jquery.form.js apparently. So all you have to do, is override where ajax.form.ajaxSubmit(ajax.options); is called: Drupal.ajax.prototype.eventResponse.

The result inside my failed-attempt-module.

It's an override of Drupal.ajax.prototype.eventResponse. I've added everything inside if ( 'FormData' in window )

My original plan (as the module name says) was to make all file fields drop containers for HTML5 File drag/drop. My approach was flawed too. I think with this approach, it's not so difficult. Just extend the FormData object at the right time.


Ubercart- free shipping through pay per click

You need to use Commerce Free Shipping module.

  This module provide a solution to add Free shipping rate on top of
  commerce_shipping services.

  This module change the price of the service to 0 and can display a
  message to the user saying the free shipping are applyed or the amount
  left to obtain free shipping.

  You can use this module to have a free shipping rate by:

  Shipping service
  Total amount of the line items in the cart (don't take in account the shipping line items)

How to setup free shipping


Inline add/edit/delete data in views in Drupal 7

I think Editable Fields module should do the trick for you. It lets you edit the fields in both node and views. Checkout the project page image for more details.

Regarding the delete option you may need to do some tweaking. Adding a 'add new meter reading' should not be very difficult. Just get the nodes value from the context and generate the add link.


How to patch a file that is not in a module's git repo?

That gihub repository looks to be outdated, as the last commit was made May 15, 2020
To see a module's repository, go to the projects page and click on on "Browse code repository"

Which will take you to the GitLab repository.

So where is this directory?

Well... that directory doesn't exist. Maybe your composer.json already contains a patch that creates it? OR someone manually added that folder and file, as that folder and file is not officially part of Commerce.


Rule to redirect to registration page after adding new product to cart

Yes, the options is given by default in ubercart. Go to admin->store->configuration->cart
Please check the attached image for more clarification.


Bulk update got slower after conversion of database tables to InnoDB

Thanks for the nice tips. I tried most of the suggested InnoDB tuning tips and it was not enough to remedy my problem.

Here is how I was able to fix my issue. This may be a special case that is isolated to my situation, but I hope that this could help other developers who are in a similar situation.

When I ran node_save() in a loop with 25 different nodes, it took 2 seconds with MyISAM and 13 seconds with InnoDB.

I captured 80 some database queries generated by node_save() in a single loop. Some of them came from running node_load(), which is needed before node_save(). I used devel module's feature of database query info collection. I put the queries side by side. The same queries from InnoDB were slightly faster than MyISAM especially for simple SELECT queries, which took majority portion of all queries.

I identified an INSERT query from InnoDB side that took more than a 0.5 second when total 80 queries took 0.6 second. The query was from notifications module, whose hook implementation was fired every time a node was saved.

I narrowed it down to the table notifications_fields in the query and decided to create an index on the table for the column value. And that made all the difference. After creating an index on value, saving 25 nodes now took only 0.2 seconds (down from 13 seconds), even ten times faster than MyISAM's! (BTW, creating index on MyISAM table also made it run ten times faster than before)

In this case, I have to admit that InnoDB's under performance gave clue to find out that an index was needed. I would not have found out about the index with MyISAM because it was relatively fast enough to hide the situation.

There have been several cases like this that adding indexes improved site performance quite a lot. However, actual application and result from it can differ in different sites. Back to my case with notifications_fields table, adding another index on field column -- hoping to strech performance boost -- ruined the effect and actually made it slow again. So one needs to be careful with adding indexes and understand that one fix on a site may not work the same way on another site.


custom module: drupal_add_js and drupal_add_css do not work after form validation?

I don't use D7, but I believe you should be using #attached and it should fix your issue.


Alter/insert into the links variable in a field_collection

In a custom module you can use hook_field_attach_view_alter(). In this example I'm using the distribution profile eRecruiter so there is a bundle called resume with several field collections and in an entity type profile2. Every time there is a field attached to a field collection this hook is fired recursively but the links are not contained there.

/**
* Implements hook_field_attach_view_alter()
*
* @param mixed $output
* @param mixed $context
*/
function helper_field_attach_view_alter(&$output, $context) {
  if ($output['#entity_type'] == 'profile2' && $output['#bundle'] == 'resume') {
    $f = 'do stuff here';
  }
}

So you understand how the links work here is some of the code used in field_collection.module.

The links are created in a render array. Don't worry about 'links__field_collection_view' too much because it doesn't do anything. When the #theme function is called more familiarly as theme('link__field_collection_view', $variables) it looks first for TEMPLATE_link__field_collection_view(&$variables) or link--field-collection-view.tpl.php however if it doesn't find it, it will use as it does in this case theme_links();

  $links = array(
    '#theme' => 'links__field_collection_view',
  );
  $links['#attributes']['class'][] = 'field-collection-view-links';
  foreach (array('edit', 'delete') as $op) {
    if ($settings[$op] && field_collection_item_access($op == 'edit' ? 'update' : $op, $field_collection)) {
      $links['#links'][$op] = array(
        'title' => $settings[$op],
        'href' => $field_collection->path() . '/' . $op,
        'query' => drupal_get_destination(),
      );
    }
  }

hook_admin_paths() is used to make the links rendered in the dialog window.

function field_collection_admin_paths() {
  if (variable_get('node_admin_theme')) {
    return array(
      'field-collection/*/*/edit' => TRUE,
      'field-collection/*/*/delete' => TRUE,
      'field-collection/*/add/*/*' => TRUE,
    );
  }
}

hook_menu() is set up for the link callback in this case the edit link

  $items[$path . '/%field_collection_item/edit'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('field_collection_item_form', $count),
    'access callback' => 'field_collection_item_access',
    'access arguments' => array('update', $count),
    'title' => 'Edit',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'field_collection.pages.inc',
  );


Add Attachment to Rules Email - Drupal 8

Drupal core does not provide a way to send HTML e-mail or to send e-mail with attachments. Thus, you will have to use a separate module which has this functionality AND which integrates with Rules. One such module is Mime Mail. Mime Mail does have a D8 port, but it's not complete. When it is complete, Rules in D8 is ready and able to use that functionality.


Is there a way to provide a Select All / Check All checkbox for a field that displays multiple checkboxes in Drupal 7?

You can do a form alter. hook_form_alter and attach your js to the form.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'YOURMODULE') . '/YOURMODULE.js',
);

Then add the code as in here


How do I load the node create or edit form?

Copying partially from an answer that I gave here: How to alter $form_state before render a form?

To get an add form, you can have to do something like this:

$values = array('type' => $node_type);

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

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

Edit: Somehow I missed that you said edit. You do exactly the same then, except that you don't create a new $node, you load the one you want to edit and then use that.

As written there, this is based on the entityblock_form module, so if you need this in a block, you can also just use that module.


7 - Dynamically changing links based on environment

I don't think I would try to do this in Drupal. I would setup a small proxy server using Apache/mod_rewrite. You can rewrite your url's based on the source url. There is some good starter information at on the Apache doc site. There is also full on mod_proxy, but I think mod_rewrite would be sufficient for your use case.


I'm afraid I posted to quickly, my apologies.

After re-reading your post, I would advise you to work with an AJAX callback that returns te search results.

First of all you need to create a form api implementation that holds the ajax callback

$form['search']['client'] = array(
'#type' => 'textfield',
'#title' => t('Search Client'),
'#description' => t('Search for an existing client'),
'#autocomplete_path' => 'searchclient/autocomplete',
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Search'),
);

Then you need to make sure that 'searchclient/autocomplete' is registered as a valid menu path (hook_menu) like this for example:

/**
* @return array
* Implements hook_menu().
*/
function your_project_menu() {
$items = array();

$items['searchclient/autocomplete'] = array(
  'title' => t('AutoComp Menu'),
  'page callback' => 'your_project_search_client',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

  return $items;
}

After this you need to create your page callback function that will actually return the content to the page:

function your_project_search_client($string) {

  $matches = array();

  // do what you want here

  drupal_json_output($matches);
  exit;
}

As some extra info:

-> $string is the entered search text in the form element
-> $matches holds the data to be returned to the screen.

More information on ajax callbacks can be found here:

https://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7
https://www.drupal.org/node/2046693


How to add a new CSS class to a Link Badge if the value is 0?

Thanks to @Ramis Wachtler at Stack Overflow, I got the following JQuery code:

if($(".link-badge").text() == "0"){
    $(".link-badge").addClass("link-badge-zero");
}

Possible easier solutions are always welcome.


Taxonomy description for a custom taxonomy view

Edit your taxonomy vocabulary.

Add the field (or fields) that you want. (Hint: The existing field named "Description" doesn't work, so create a new text-area field if that's what you want. I called my replacement field "Definition".)

From the List tab, edit each term's value for the new field.

Create a new view.

Show: Taxonomy terms of type: your_vocabulary, with a page display

Continue & Edit

Configure the view to display only your new field(s).

Use pager: Display a specified number of items | 1 item

Add a Taxonomy Term contextual filter

Edit the existing Taxonomy Term view.

Click on the "add" button in the Header section

Select Global view type header

Select the new view you created above

Check the "Inherit contextual filters" checkbox

Now when you visit the Taxonomy Term view, your new fields view will be included at the top.


How to find the url of a media library image field in a preprocess function?

I wrote a little module I found helpful to get the media entity image values.
custom_helper_services/custom_helper_services.info.yml:
name: 'Custom Helper Services'
type: module
description: 'Provides useful services for working with themes.'
core_version_requirement: ^8 || ^9
package: 'Custom'

custom_helper_services/custom_helper_services.module:
<?php

/**
 * @file
 * Contains custom_helper_services.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function custom_helper_services_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the custom_helper_services module.
    case 'help.page.custom_helper_services':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Provides helpful service functions.') . '
';
      return $output;

    default:
  }
}

custom_helper_services/custom_helper_services.services.yml:
services:
  chs:
    class: Drupal\custom_helper_services\Services\CustomHelperServices
    arguments: ['@entity_type.manager','@current_route_match','@entity.repository']

custom_helper_services/src/Services/CustomHelperServices.php:
<?php

namespace Drupal\custom_helper_services\Services;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;

/**
 * Class CustomHelperServices.
 *
 * Provides helper services to be used in modules and themes.
 */
class CustomHelperServices {

  /**
   * Entity Type Manager.
   *
   * @var Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Route Match Interface.
   *
   * @var Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Entity Repository Interface.
   *
   * @var Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * CustomHelperServices constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity Type Manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
   *   The Route Match Interface.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
   *   The Entity Repository Interface.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, RouteMatchInterface $routeMatch, EntityRepositoryInterface $entityRepository) {
    $this->entityTypeManager = $entityTypeManager;
    $this->routeMatch = $routeMatch;
    $this->entityRepository = $entityRepository;
  }

  /**
   * Build our media style path service.
   */
  public function getMediaFieldImage($mediaField = NULL, $imageStyle = NULL) {

    if ($mediaField && $mediaField->entity) {

      // Get image.
      $mediaImage = $mediaField->entity
        ->get('field_media_image');

      // Get image attributes.
      $alt = $mediaImage->alt;
      $width = $mediaImage->width;
      $height = $mediaImage->height;
      $title = $mediaImage->title;

      // Get image entity.
      $mediaImageEntity = $mediaImage->entity;

      // Get image mime type.
      $mediaImageMimeType = $mediaImageEntity->getMimeType();

      // Get image file URI.
      $mediaImageEntityUri = $mediaImageEntity->getFileUri();

      // Set image URL.
      $url = file_create_url($mediaImageEntityUri);

      // Set image style URL.
      if ($imageStyle && $mediaImageMimeType !== "image/svg+xml") {
        $url = $this->entityTypeManager
          ->getStorage('image_style')
          ->load($imageStyle)
          ->buildUrl($mediaImageEntityUri);
      }

      return [
        'url' => $url,
        'alt' => $alt,
        'width' => $width,
        'height' => $height,
        'mimeType' => $mediaImageMimeType,
        'title' => $title,
      ];
    }

    return NULL;
  }

}

Then in preprocess node, for example, you can call:
$variables['myVariable'] = \Drupal::service('chs')->getMediaFieldImage($node->get("field_name"), "image_style");
// Just need to pass the media field name. The image style is optional.

Then in a Twig template you can access as:
{{ myVariable.url }}
{{ myVariable.alt }}
{{ myVariable.width }}
{{ myVariable.height }}
{{ myVariable.mimeType }}
{{ myVariable.title }}

I've stripped down this code to show just the media entity image get, so let me know if there are issues and I can update if needed.

A shorter version (using preprocess_node()):
use Drupal\image\Entity\ImageStyle;
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->hasField('field_name') && $node->get('field_name')->entity) {
    $imageURI = $node->field_name->entity->getFileUri();
    $variables['myVariable'] = ImageStyle::load('image_style')->buildUrl($imageURI);
  }
}


There is a setting in Webform "Available as block" so, it will be Available as block, you can use this block in all node pages


As of Drupal 7, themes can implement alter hooks, so you can use hook_menu_alter() in template.php.


Wildcard Loader function called multiple times (_load)

There's an issue for this. It looks like you have to implement caching in your loader.

I was curious and tried it out on admin/structure/types/manage/%node_type. I grepped for node_type_load and nothing seemed to be calling it directly, so I put a ddebug_backtrace() in the load function. I got 13 traces when visiting that path! 10 of these came from menu_local_tasks() which loops through the local tasks and calls _menu_translate() which calls _menu_load_objects() for each router item. The other two extra calls came via menu_set_active_trail() which also called _menu_translate(). So I guess it depends on your menu structure how many times a loader might be called. As far as I can tell the object's loaded only to check whether or not it can be (access is denied if it can't). I guess this just reinforces Damien's comment about implementing static caching in your loader.


Can you create a view to display all files within a certain directory?

Only tools I've seen dealing with showing file are more like this...

http://drupal.org/project/elfinder

http://drupal.org/project/webfm

http://drupal.org/project/manager

http://drupal.org/project/filebrowser

You can create a view of all attachments to nodes, but that's not what you want either.


It is possible to set up a menu item with hook_menu that points to an existing path?

You can only use hook_menu() if you're defining new paths, ideally, paths that are provided by the module implementing the hook.

If you want the Delete link to show up as a tab, hook_menu_alter is definitely the way to go, and adjusting the context value is what does the magic - as per Step 2 from marcvangend's post. If you want to change the "access callback" as per your snippet, then you can do that in hook_menu_alter() too, although I'm not sure why you'd want to let anyone delete pages?


How to wrap field out put in custom markup?

Might be misunderstanding but it sounds like you just want a #prefix and #suffix on the base render element:

function bootstrap_modal_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  ...


How to use settings.local.php with Drupal 7?

When u install drupal u need to copy example.settings.php into settings.php, after drupal installation u need to include following code in settings.php:

if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php')) { include DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php'; }


Secret forum visible only to users of a specific role


Paragraphs are entities in and of themselves - it's most straightforward to migrate the paragraphs separately, then populate the reference to the migrated paragraphs within the "parent" node migration.


I don't think there is really a "100% Safe" solution for upgrading your modules. But for the future, the best thing that you can probably do is:

Make sure that you are using a version control system such as CVS, SVN, Git, etc. That way when you update and see that things go south you can always revert your changes.
Always backup the database before running update.php. Again, if things don't work out, you always have a restore point.
It is a good practice to read the release notes of the version that you are upgrading to and to take a peek at the issue queue of the module in question. Most likely another Drupal developer would have tried already to perform the same update that you are trying to perform, and there is an entry in the issue queue indicating what was the problem when updating. Sometimes if there's an entry in the issue queue it will also tell you how to upgrade from one version to another. Sometimes you can upgrade without no problems, sometimes you can't, and other times you have to follow a few manual steps before upgrading.

As for the present tense, since you already attempted the upgrade, I would start by following step #3 above, and if you can't locate a relevant entry in the Views issue queue that points you in the right direction, you're more than welcome to open one.


This is what helped for me.

https://stackoverflow.com/a/2474164/28672

Using the second option to generate the view manually then modifying the array in the result property.

And this is the code I used to sort the results to the argument

 // Sort the view based on the argument now we've generated it.
  $results = $view->result;
  $view_argument_array = explode('+', '1099+1100+1102+1098+1101+1097');
  $new_result_order = array();
  foreach ($view_argument_array as $nid) {
    foreach ($results as $result) {
      if ($result->nid == $nid) {
        $new_result_order[] = $result;
      }
    }
  }
  $view->result = $new_result_order;


Filter referenced item without losing other content

As what I understand your needs its very simple.

You have to set the filter criteria in the views:

Add Content Type A
Add Content Type B
Add Published field twice
Add Date Field and set its criteria as you already set
The field (Entity Reference field in Type B) that reference to Type A and set its operator as Is not empty (NOT NULL)
Now, Open re-arrange the filter criteria fields

 7. You need to Create new filter group under the filter criteria and drag drop your fields in required group like below

I hope this will at least give you an idea how to filter different content types with different field(s).

Thanks


After a lot of digging I just need to change a folder name -.-
Changed from "optional" to "install", after that everything works as expected.
Thanks for your help.


Install Drupal into a different directory than drupal-vm is installed

You can override the default configured webroot directories by altering the local_path property in the vagrant_synced_folders array with a custom config.yml file (copy over default.config.yml if you don't have one).

Per default.config.yml:

# A list of synced folders, with the keys 'local_path', 'destination', and
# a 'type' of [nfs|rsync|smb] (leave empty for slow native shares). See
# http://docs.drupalvm.com/en/latest/extras/syncing-folders/ for more info.
vagrant_synced_folders:
  # The first synced folder will be used for the default Drupal installation, if
  # any of the build_* settings are 'true'. By default the folder is set to
  # the drupal-vm folder.
  - local_path: .
    destination: /var/www/drupalvm
    type: nfs
    create: true


How to show/render 'Add to Cart' button?

There are a couple of things I would try to see what is going on.In the post that you referenced, they said the following code. render($content['field_product']).

Have you tried just rendering the whole content using the following render($content), which for you I think would be render($productw). This should render the whole product including the add to cart button.  I am guessing that if it doesn't show up then, then there is something wrong with how you are getting the content and field_product isn't even available to render.

Also, which display are you affecting when you change your product reference to Add to Cart form?  Your default or your teaser? Are you modifying the right template?


Understanding Recruiter profile in detail

taxonomy_vocabulary_load_multiple(FALSE)

will load all vocabularies. If you wanted a specific one you'd pass in the relevant id instead.


Why does the Google Analytics module restrict uid?

There is nothing specific in the GA documentation that forbids it. There is actually a section in the GA Help which explains how to use user ids: Benefits of using the User ID feature, so using user ids is not forbidden by GA at all.

Why it doesn't work in the GA Drupal module is because of this paragraph, as stated by one of its developers (found here):

  If you upload any data that allows Google to personally identify an individual, your Google Analytics account can be terminated, and you may lose your Google Analytics data.


How are global roles synced with group roles?

Take a look at the roles & permissions page for a group (and also group's documentation). By default groups treats all authenticated non-members as outsiders no matter what their role is, but there is an advanced option to define permissions based on their global drupal roles.


Is it safe and correct to run Drush under the same user account that the webserver runs on?

In general, the answer is "yes", it is safe and correct.  However, the specific answer here depends on (a) your security policy, and (b) what you want to do with Drush.  Some people prefer to make the code files not writable by the web server.  If you had a setup like that, then you would not be able to run drush dl as the webserver user.

The other thing of note here is that any time you run any Drush command, all Drush commandfiles are given the opportunity to alter the command's behavior.  This means that it is generally NOT considered safe to run drush via sudo to root, unless you trust all of the code in your Drupal site to run as the root user.  This is not generally a concern for sudo -u www-data, though, as you are already trusting the code in your Drupal site to run as the web user.


AJAX button - HTML in #value causes problems

Here is the proper way of adding glyphicons to your buttons, you alter the button function and use a custom made one.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['button'])) {
    $theme_registry['button']['function'] = 'mymodule_button';
  }
}

function mymodule_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }
  if (!empty($element['#glyphicon'])) {
    $glyph_name = $element['#glyphicon'];
    return '<button' . drupal_attributes($element['#attributes']) . ' /><span
      class="glyphicon glyphicon-' . $glyph_name . '"></span> '.
      $element['#value'] .'</button>';
  }
  else {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

Then all you have to is add #glyphicon element to the submit and assign it the glyphicon name:

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
    '#glyphicon' => 'envelope', // in your case use "refresh"
  );

Result:


Export node report base on Word and Excel template

You can use the Views Data Export to export in many popular table formats.  XLS, CSV, DOC, TXT and XML.

Some other modules worth mentioning here:

Views Datasource

Service Views

It should go without saying that the modules above will require Views be installed and enabled.


Generate a Barcode from Form Data & Submit Form Data to Database (for Views)

Have taken a look at these modules.  MERCI Barcode, Views Bulk Operations Barcode Select , Barcode

The first two are for Drupal 6 only so they will not work in a Drupal 7 site out of the box. If you save the files without installing them you can read the code and see what they did.  The Third one has a beta for Drupal 7.x, so it can be installed.  Feel free to borrow code to learn how.

As for getting it to work together...we would need specifics to provide answers.  Ask about whatever your stuck on.


Add the cache tags to the cacheable metadata of a cacheable response:

use Drupal\Core\Cache\CacheableResponse;

  $response = new CacheableResponse();
  // ...
  $response->getCacheableMetadata()->addCacheTags(['node:nid', 'node:nid']);


Access to private file only from website, not using direct link

You need to use private filesystem as shown in documentation. Then you can create custom module to implement more advanced rules, like link timeouts et cetera.


Well if I am getting you right, for this issue you should do this;
Create a new view, and in filters option select type "toys" and again select type "areas", this will give you 2 content types into one view.

For exposed filters, in the filter criteria, select both the fields, "series_taxonomy" and "area_name" and select them as exposed filter.

Hope this helps.


How can I get the URL to the public files directory?

$my_path = file_create_url("public://");

Will definately work, however it's not coming from a service. Let me investigate more on this!

Okey I found it! This is how file_create_url works:

And this is the corresponding line specific to "public://" resolving (if you are sure you are trying to resolve a "public://..." uri):

  if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

Which means you will have to use StreamWrapperManager service, and after calling the getViaUri, you will able to get the external url. So this is service based solution!


How to resolve the SSL error with local copy of site on Dev Desktop?

DevDestop now supports this.
https://docs.acquia.com/dev-desktop2/sites

Acquia Dev Desktop now provides simulated HTTPS support using a self-signed SSL certificate, which supports local testing and development of websites that rely on SSL. Learn more.

Just download a new version of DevDesktop. I'm currently on Version 2, Control panel rev: 032976b and have it working with sites that use SSL.


PDO datetime exception when saving a Computed Field (but no datetime in my query)

In the end, something in the BOA or Entity update affected fetchField(). I resolved it by explicitly setting the index like so: fetchField(0).

I added a comment to api.drupal.org to hopefully help the next person who has the problem.

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/DatabaseStatementBase%3A%3AfetchField/7


How to change data type from varchar to text?

You are missing recreating the index.
Also you can use your schema changes:

$schema = drupal_get_schema_unprocessed('my_module', 'simplenews_subscriber');
db_change_field('simplenews_subscriber', 'mail', 'mail', $schema['simplenews_subscriber']['fields']['mail']);

Another thing you can do is test out altering the table manually just so you can see what errors are popping up.


Cannot instantiate interface DrupalStreamWrapperInterface

The error is because you are trying to create an object of a PHP Interface, which is not allowed in PHP. You can only create objects from a PHP Class.

To solve your issue, something like this might work:

$wrapper = file_stream_wrapper_get_instance_by_uri($img_path);
if (is_object($wrapper)) {
  $file_path = $wrapper->realpath();
}


Error using Drupal Feeds to upload a comment in a text field

I was running into this same issue myself where half of my records were getting cut off when I uploaded them via the Feeds Importer. I found an answer that was posted on a Drupal forum that indicates that the problem is not with Feeds, but with the file itself.

It appears that by default Excel exports your CSV file into ANSI format, which creates issues when there are dates embedded within one of your fields.  By using Notepad++ and converting the file into UTF-8 it works. Here is the link which gives more details.

https://www.drupal.org/node/2502761

NOTE: It also appears that if the file is encoded in UTF-8 BOM, then the CSV file can still be read by Drupal and Excel. Otherwise Excel treats it as a fixed length record.


How to get the contents created by a User?

$currentUser = \Drupal::currentUser();
$query = \Drupal::entityQuery('node');
$query->condition('uid', $currentUser->id());
$author_nids=$query->execute();


How do I reinstall the Forum module in Drupal 7?

To uninstall a module, you follow these steps:

Deselect the checkbox shown for the module in admin/modules, and click on the "Save configuration" button at the bottom of the page
Select the "Uninstall" tab (admin/modules/uninstall), and in that page select the checkbox shown close to the name of the module you want to uninstall ("Forum")
Click on the "Uninstall" button
In the next page, click again on "Uninstall"

When you execute the first two steps, you are only disabling the module, which is not yet uninstalled. It is when you execute the last two steps that you uninstall the module.

To re-install it, you need to:

Return to the page listing all the modules (admin/modules)
Select the checkbox shown for the module you want to install ("Forum")
Click on the "Save configuration" button at the bottom of the page

Uninstalling a module should already clear the cache, but to be sure you can manually clear the cache before to re-install the module.
Once the module is uninstalled, installing it back will let Drupal create the database tables used by the module again. The same tables are deleted from Drupal when the module is uninstalled.

I noticed a little issue that happens when you uninstall and re-install the Forum module: The default taxonomy term used by the module is created again all the times you re-install the module, and it seems it is not removed when the module is uninstalled. This is the result of uninstalling and re-installing the module more than once; each time the taxonomy term is created, even if it was already present.

Actually, it is not even required to uninstall, and re-install the module; it is enough you disable, and then re-enable the module, as the code that creates the missing field is not contained in forum_install(), but in forum_enable(), which the function executed when the module is enabled.

I was going to suggest a different way to resolve this issue, and which consisted in manually creating the missing field, but I noticed it doesn't work. The problem is that the module that allows to create a field through the user interface always add "field_" at the beginning of the field names for the fields you create, but the field created from the Forum module doesn't have that prefix; the result is that some database tables and a field present in a table don't have the name the module is expecting, and the module throws errors.


How to create a fieldset in a node form, that expands with ajax

You might need to add this module.  https://www.drupal.org/project/field_group
Add those fields on the form to a field group, and set the group to start out "Collapsed".


Duplicating Database For Local Development

It's important to understand the differences between the data of your site and the structure. You probably don't need all the data (new nodes, user information...) updated every day in your development site, What you need is to upload the new structural changes to your live site once you reach a stable point in your development.

I've been using a combination of git + features to develop my sites and keep them in sync between develop and live enviroments. With Features you can upload the structural changes to your live site without overwriting the database. When you reach a stable point in your development site you prepare a feature with the changes (content type, image style, views... whatever), save it to code and upload to your live site with the source control program.

Then only sometimes, when the content difference really is important I download the database to my local site, usually with drush.


You cannot find any custom fields because fields created using the field API are not stored in the node table, but in a different table. In code, you should use the EntityFieldQuery class.

  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_event_date', 'value', '2016-07-29 16:25:00')
    ->fieldOrderBy('field_event_date', 'value', 'ASC')
                    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));


CSS

I'm going to assume you are using the default markup that the Collapse Text module generates, which is fieldsets. I'm being intentionally verbose in the CSS rules below so you can see the html elements along with the classes I mean to target, just in case your markup is different. You will probably not need so much specificity.

To insert bullets before each title, you can use the following CSS in your theme:

fieldset.collapse-text-fieldset legend span a.fieldset-title {
    display: list-item;
    list-style-position: inside;
}

html.js fieldset.collapse-text-fieldset legend span.fieldset-legend {
  background: none; /* Removes the arrows */
  padding-left: 0; /* Depends on your theme */
}

Outcome

Explanation

Collapse Text wraps each collapsible chunk of text in a fieldset and adds a few wrapper classes like collapse-text-fieldset. I suggest specifying one of the wrapper classes before targeting anything inside the collapsible fieldsets to avoid selecting all of the fieldsets on the page or on the site depending on where in the theme you're adding the CSS.

Your theme may have different indentation or padding applied to fieldset elements. In my test case there was 15px of padding-left on all fieldset legends as part of the base styles of my theme, and I wanted to remove that in order to avoid unnecessary space.


Listing Inventory items without being purchasable items

You can probably do this with just Drupal core and the Views module if you don't need any e-commerce functionality. It would probably go something like this on a basic level:

Add a new vocabulary called 'Categories' and add your terms to it (engines, pumps, etc.).
Add a new content type called 'Inventory Item'.
Add a term reference field to the 'Inventory Item' content type linking to the 'Categories' vocabulary you just created.
Add whatever other custom fields you need to the content type (price, stock, etc).
Create a view that lists all content of the 'Inventory Item' type.
(optional) Create any other views that you may need to filter the content by whatever criteria is applicable.
Start adding content.
(optional) Grab the Taxonomy Menu module so you can easily create menus that break your inventory items down by category.

The order of those steps is somewhat interchangeable.

If you're not familiar with views there's good documentation out there.


what function do i use to print out a menu? the menu was created in the admin

You can use menu_tree_all_data function.

E.g.

$tree = menu_tree_all_data('machine-name-of-menu');
//menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));

For more info go through the function documentation.

menu_tree_add_active_path will be found here. It will be used when you want to add active trail on menu.


How do I utilize Drupal commerce to sell large files stored on Amazon S3

You really want to use the Drupal License and License Billing modules to sell access to Commerce Files.

It might take a little custom code (a few simple objects and a few hooks) to make sure your amazon S3 links are getting licensed correctly to the right user.

In terms of your two requests:

The ability to choose buckets within the field when creating a product.
link to an existing .zip file already stored on S3

Yeah, it looks like s3 file system module is the way to go for S3 API ... they even have a migrate module and a proxy module that could make a simple file on your website, load to an s3 of your choice and still be linked to your local.

If you installed the S3 module mentioned above, you could:

Use hook_form_alter() to modify the file field
Use hook_form_alter() to add pre-empt the normal submit handler
Use your new submit handler to save the file to your preferred bucket.


Yes, drupal 7 does have a node table. The reason why your database does not might be either because you are looking at the wrong database or perhaps because your configuration are using a database prefix. Look in your sites/default/settings.php file and check if you are using a prefix. For example:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => 'd7_',
);

or

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => array(
    'node' => 'd7_',
  )
);

The first example would prefix all tables in the database with d7_, while the second would only change the name of the node table.


You can use Contextual filters on Drupal 8 to pass the current entity as the filter. Have a look at:
https://valuebound.com/resources/blog/how-to-use-contextual-filter-in-drupal-8

and https://www.youtube.com/watch?v=FUlj6-Rb7Ds for more details.


How can I use the field_ui_table element in a custom module?

Looking at theme_field_ui_table(), the function that renders the field_ui_table element, and field_ui_display_overview_form(), a form builder that uses that form element, I can say that:

Neither #options nor #rows is used from the rendering function
Leaving out those two element attributes, the code you shown contains just the declaration of the table; it still needs to define the elements to render in the table, which the render function expects to be a list of fields.

The code adding the fields to be listed as rows of the table is quite complex.

  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $display = $instance['display'][$view_mode];
    $table[$name] = array(
      '#attributes' => array(
        'class' => array(
          'draggable',
          'tabledrag-leaf',
        ),
      ),
      '#row_type' => 'field',
      '#region_callback' => 'field_ui_display_overview_row_region',
      '#js_settings' => array(
        'rowHandler' => 'field',
        'defaultFormatter' => $field_types[$field['type']]['default_formatter'],
      ),
      'human_name' => array(
        '#markup' => check_plain($instance['label']),
      ),
      'weight' => array(
        '#type' => 'textfield',
        '#title' => t('Weight for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#default_value' => $display['weight'],
        '#size' => 3,
        '#attributes' => array(
          'class' => array(
            'field-weight',
          ),
        ),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
          '#title' => t('Label display for @title', array(
            '@title' => $instance['label'],
          )),
          '#title_display' => 'invisible',
          '#options' => $table['#parent_options'],
          '#empty_value' => '',
          '#attributes' => array(
            'class' => array(
              'field-parent',
            ),
          ),
          '#parents' => array(
            'fields',
            $name,
            'parent',
          ),
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $name,
          '#attributes' => array(
            'class' => array(
              'field-name',
            ),
          ),
        ),
      ),
      'label' => array(
        '#type' => 'select',
        '#title' => t('Label display for @title', array(
          '@title' => $instance['label'],
        )),
        '#title_display' => 'invisible',
        '#options' => $field_label_options,
        '#default_value' => $display['label'],
      ),
    );

    // ...

  }

Yes, it is possible to use that form element, using the correct data. Since it has been written for a very specific purpose, it's easier to write code for a custom form element, if the task is not showing a table with the same degree of complexity. If the code is then used for a single form, it's even easier to create a custom table in a form.


Just use the Group module, and create a content type like "Connected Users". And then create a "group" for each user (using something like the user's name as its label), of group type "Connected Users".

Tune the permissions which come with the Group module (which are different from standard Drupal permissions!) to fit your needs.

Possibly you also want to use all sorts of integrations with modules such as the Rules module or the Views module (the Group module is entirely entity based, so those kind of integrations or virtually unlimited).

Voilà ...

PS: This answer applies for either Drupal 7, or Drupal 8.


Fatal error: Call to a member function advanced_render() on a non-object

I think you may have copied that code somewhat from a Drupal 6 version? The only problem is that the pattern for theme function signatures has changed in Drupal 7; only the $vars argument is passed in now, which is an array of named variables for the function:

function myTheme_views_view_field($vars) {
  $view = $vars['view'];
  $field = $vars['field'];
  $row = $vars['row'];

  // ...
}


Would PHPLint's advice be beneficial to our community?

In theory, there sure are benefits. There are however some issues with doing it, as you partially found out yourself already.

There will be like a million false warnings, might just be as hard to find the real issues as when simply reading the code.
Drupal has a quite a few custom coding standards. For example, we're currently not using type declarations in docblocks except for @return $class.

I don't know how configurable PHPLint is, maybe there are a few checks that would make sense to run on our code.

For coding style issues, it might make more sense to use http://drupal.org/project/drupalcs


How do I add a dynamic Facebook like button to every node of a certain content type

Inside a template_preprocess_node() I have done:

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['full_url'] = url('node/' . $node->nid, array('absolute' => TRUE));
}

Then in my node.tpl.php, I have

<?php // http://developers.facebook.com/docs/reference/plugins/like/ ?>

<div class="fb-like" data-href="<?php print $full_url; ?>" data-send="true"
  data-layout="button_count" data-width="450" data-show-faces="false">

In my html.tpl.php, I will hardcode the JS include so that it is right after the body (so I am not at the mercy of render trees, preprocess, etc:

This is from a pretty specific use case on a recent site.  I am not 100% sure if I tested this with multiple nodes on a single page, as the site I did this on doesn't have pages like that.


how to remove anonymous user role from list of profile members

Add a filter for user: UID and set to "not equal to" and enter 0 for the value.


Twig template suggestions for user default, compact, and user account view modes

You can do this by creating a theme suggestion alter hook in your theme.

/**
 * Implements hook_theme_suggestions_user_alter().
 *
 *   An array of alternate, more specific names for template files or theme
 *   functions.
 */
function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

Note, $vars['elements']['#view_mode']; was derived from using kint($vars) under this function to see the view mode array in user.

You can add this code to your theme's .theme file and then clear cache. Once you clear cache, you will then see the new theme suggestions appear within Twig debug.

Note, in my case, I am in "full view mode so that's why user--full.html.twig shows up. If you are view the user in compact mode, then a suggestion of user--compact.html.twig will show up.


Setting a variable as a class (using set classes) in a region template

It seems the way to do this was to create a theme hook for all preface regions and then it can have its own template. So first I create an alter preprocess function in my theme's .theme file.

function MYTHEME_theme_suggestions_region_alter(&$suggestions, $vars, $hook) {
  // Print the $vars.
  kint($vars);

  // Define a var for the #region.
  $preface = $vars['elements']['#region'];

  // Now check for any of the three preface regions and create a theme hook.
  if ($preface == 'preface_first' || $preface == 'preface_second' || $preface == 'preface_third') {
    $suggestions[] = 'region' .  '__' . 'preface';
  }
}

Next, voila, when I look at Twig debug, I see a suggestion for my new theme hook.

   * region--preface.html.twig >> **** This is the new template from the alter
   * region--preface-second.html.twig
   x region.html.twig

Now I can create a common template for all three preface regions with region--preface.html.twig.

Then in the new template, I print the classes like so:

 {%
set classes = [
'region',
'region-preface',
'region-' ~ region|clean_class
]
%}

This gives me exactly what I set out to do and prints this HTML:

<div class="region region-preface region-preface-second">

Now I can use .region-preface for common theming / HTML for any of the three the preface regions.


Programmatically creating a custom block

I didn't find a way to display the view and restrict for certain roles.

But I've managed to solve the problem in another way.

I created a script in Admin > Structure > Block > My_Block > Configure > Visibility PHP:

<?php
$match = TRUE;
$heh = \Drupal::currentUser()->getAccount()->getRoles(TRUE);
$hide_from_roles = array('administrator', 'sefii', 'membership');
 if (count(array_intersect($heh, $hide_from_roles)) > 0) {
    $match = FALSE;
}
return $match;
?>


yes you can do this by using some of the contributed modules example is shown down
https://www.drupal.org/node/522240

https://www.drupal.org/node/1117234

http://www.appnovation.com/blog/proximity-search-using-views-drupal

read this this will help you to find out


Create a MySQL view table on one database but fill with results from another database

Since that view is only a SELECT on that table, try using a FEDERATED table instead.

I never had the chance to use it so far, but it should go like this:

CREATE TABLE myshop_migrate ( exactly like myshop table )
ENGINE=FEDERATED
DEFAULT CHARSET=same of myshop
CONNECTION='mysql://user@host:9306/myshop_migrated/stock_commerce';

where user and host are those of the remote server.

create it from phpmyadmin or mysql workbench, just to have additional options and hints that drupal can't give you.


Programatically assigning multiple user role ?

If you look at User::addRole it says

  User::addRole($rid)

  string $rid: The role ID to add.

Therefore, this cannot be an array. Thus, you must do this separate

$user->addRole('lecturer');
$user->addRole('program coodinator');
$user->save();

If you look at class User, there is no such thing as "addRoles" or any method that allows multiple way of doing it with an array.


Overriding views-view-grouping.tpl.php when grouping by only one field

I've had the same issue. At first I though it was connected to the current theme I was using, but after testing with a few different themes I discovered that not to be the case. I still do not understand that behavior.

As a workaround I've used views-view-unformatted--YOURVIEWMACHINENAME.tpl.php template where you can give a wrapper to a group in a single-grouped view. Here's what I had in the template:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
    <?php
        //open group wrapper
        print '
';
    ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>
<?php if (!empty($title)): ?>
    <?php
  // close group wrapper
    print '
';
    ?>
<?php endif; ?>

You can even assign a custom class to each group by taking a certain field from $view object and transforming its value into a class name.

Of course, this method will only work for a single-grouped view. If the view will be grouped by more than one field, only the most inner group will be wrapped. Hope this helps.


Grant users of role the ability to edit users that have specific role


Drupal 8 uses PDO, so I think mysqli is not supported.

From the documentation:

  Drupal's database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon PHP's PDO (PHP Data Objects) database API, and inherits much of its syntax and semantics.


Organic Groups - Include nodes as part if it on group creation

You can use Rules to generate the nodes upon creation of the group.  If you haven't worked with Rules it is an incredibly powerful module and is well worth the time investment to learn its intricacies.


Field filter in Views, filter by TID, not name

@no-sssweat' answer is what you want as long as views can figure out the right tid from the url.  In cases where it can't but you know how to, you can do an argument replacement in a custom module.  Here is some code I have that is doing that:

/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    $views_to_process = array(
        'view_name1' => array(
            'display_name1',
            'display_name2',
            'display_name3',
        ),
        'view_name2' => array(
            'display_name1',
        )
    );
    if (!in_array($view->name, array_keys($views_to_process))) { return; }
    if (!in_array($view->current_display, $views_to_process[$view->name])) { return; }
    if (!empty($args[0]) && !_MYMODULE_isInteger($args[0])) {
        $tid = _MYMODULE_get_tid_for_top_level_term($args[0], 'area');
        if ($tid) {
            $args[0] = $tid;
        }
    }

}

/**
 * Helper function to determine whether a value is an integer or not.
 *
 * Sourced from http://php.net/manual/en/function.is-int.php#82857
 */
function _MYMODULE_isInteger($input){
    return(ctype_digit(strval($input)));
}

The `$views_to_process is a tree of views and displays that this should be applied to and the first two ifs just ignore this hook if the display isn't in $views_to_process.  I then check to make sure there is an argument of some kind in place and that it isn't already an integer (helper function included for that), and then it loads a tid based on the current argument.  It then replaces that argument with the tid.  If you replaced _MYMODULE_get_tid_for_top_level_term with your helper function for loading up the tid, you can then use the tid as a contextual filter value.  I hope that helps!

note: I currently have a question open on that very view, and while I don't think this solution has anything to do with the issue I'm having, there is a chance.


How to display specific exposed filters of a view in a block

It's very simple.

Create a new view as a block using the Add button on top of your view admin page (Add > Block).

In your new view Exposed Form section, click on "Exposed form in a block" and press yes. In this way a block of your exposed filters is created in your Blocks admin page (admin/structure/block).

Using the blocks admin page enable your block and place it to the region of your liking.

Doing the above steps, you will get one exposed filter group on top of your view and one exposed filters block wherever you like in your site.


create a menu based on the parent of a drupal book

I figured out my issue, turns out my theme_menu_link function was hiding the book menu block. Once I realised this I placed the block alongside my main menu on the block pages, and used my theme_menu_link to style it.


Restrict access to edit page for specific user

Looks like you're looking for Edit own user account permission.

This module add 'edit own user account' permission.
The goal of this module to prevent changes in user account information in the demo sites.

Or to do it in code:
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
    $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($user) {
  if ($user->uid == 267 || $user->uid == 268) {
    return FALSE;
  }
  else {
     return TRUE;
  }
}


EntityMalformedException: Missing bundle property on entity of type node in modal

EntityMalformedException: Missing bundle property on entity of type node

This means that at some point in code when the node entity should be handled, it is unclear what type (bundle) that is. Now when you look at node_form() you see that it expects a node object as a parameter. If that's not given the node add form doesn't know what fields and properties to render because the node type can't be identified. Looking further into node_add(), which is the function normally called to create a new node of a specific type, I think you could go along the following lines (completely untested):

global $user;
ctools_include('modal');
ctools_include('ajax');
$node = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'page',
  'language' => LANGUAGE_NONE,
);
$form_state = array(
  'ajax' => TRUE,
  'build_info' => array(
    'args' => array($node),
  ),
);
module_load_include('inc', 'node', 'node.pages');
$output = ctools_modal_form_wrapper('page_node_form', $form_state);


Drupal Commerce, behaviour when you disable order status

I dig in a bit and run some custom code.

$order = commerce_order_load($order_id);
$order_status = 'payment_received';
commerce_order_status_update($order, $order_status);

and changed status. So even if status is disabled, it still is changed. Only way is to remove the status, unset it in

hook_commerce_order_state_info for whole parent state
or
hook_commerce_order_status_info
for particular status.

What happens then is if you try to change status to the one that is not there, status will be undefined.


I am not sure what your code looks like, but my suggestion is to use custom handler if  the core is not working. I used custom handler in almost all my projects if I get any issue in core handler. Example is:

/**
 * A handler to display dates as just the time if today, otherwise as time and date.
 *
 * @ingroup views_field_handlers
 */
class views_handler_cusom_field_date extends views_handler_field_date {

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $form['date_format']['#options']['example_custom'] = t('My custom format');
  }

  function render($values) {
    $format = $this->options['date_format'];
    $value = $values->{$this->field_alias};
    // check for our custom format
    if ($format == 'example_custom') {
      // check to see whether value is whithin today range
      $timezone = new DateTimeZone("Australia/Melbourne");
      $date = new DateTime();
      $date->setTimezone($timezone);
      $today = strtotime($date->format('Y-m-d 00:00:00'));
      if ($value >= $today) {
        // this value is still within today
        return format_date($value, 'custom', 'g:i A');
      }
      else {
        // this value is older than today
        return format_date($value, 'custom', 'j M Y g:i A');
      }
    }
    // otherwise render the date using the normal date handler
    else {
      return parent::render($values);
    }
  }

}

And then call this custom handler in your date field

'date' => array(
           'title' => t('Date'),

           'field' => array(
              'handler'=> 'views_handler_cusom_field_date'
              'click sortable' => TRUE,
           ),


The 'edit' page probably isn't working because you've mis-spelled page callback (it's currently spelt page callbacks).


Nevermind, this worked for me:

$node->get('field_office_hours')->getValue();


Can I render a region of my drupal site on a non-drupal site?

You can try Web Widgets module to embed.

  Create dynamic snippets of your Drupal site that users can copy and
  paste to their websites.

  Supported widget styles: iframe, inline, UWA or Google Gadgets.
  Build a view and make a widget from it.
  Embed any other web site content in a widget with a simple widget API.

also look in to Embed widgets module.


Node object doesn't exist when not logged in

Maybe you should check the anonymous user permisions
www.yourwebsite.com/admin/people/permissions/anonymous


I found that in order to get the values I had to use getValue() instead of ->value like so:

$tags = $node->get('field_tags')->getValue();


Call multiple node forms using multiform_get_form()

Use your own 'page callback', and in this callback call module_load_include('inc', 'node', 'node.pages'); which is required for node forms


You need more in your hook_menu() like this:

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

  $items['something/%id_here'] = array(
    'title' => 'Some title',
    'type' => MENU_NORMAL_ITEM,
    // This is the function that will return your page content.
    'page callback' => 'something_custom_page',
    // This will pass the $data variable you returned from your loader function
    // into your page callback (not the ID in the URL).
    'page arguments' => array(1),
  );

  return $items;
}

Then your load function needs to actually return what it has loaded, like this:

function id_here_load($arg) {
  // Do some checks o make sure no one can pass in bad data via the url.
  // This is an example you need to check based on your data.
  if (is_numeric($arg)) {
    $data = get my custom data from an external xml feed based on $arg; //this works nicelly - I get an array with the data I need.
    // If you get back valid data.
    // Again you need to make this relevant to your data.
    if ($data) {
      // Return the data.
      return $data;
    }
  }
  // If for any reason you didn't end up getting data return FALSE.
  // This will cause access denied for this page because of an invalid ID or something.
  return FALSE;
}

Then you need to implement your page callback function like this:

function something_custom_page($data = array()) {
  // Do something with the $data to create the page and return
  // either a string of HTML or a drupal render array.
  // Returning a render array is the preferred option.
}

See Render Arrays in Drupal 7 form more info on render arrays.


How can I get all the taxonomy term objects from the database regardless of vocabulary?

You can use the entity_load() function. The second argument, $ids, is defined as such:

  An array of entity IDs, or FALSE to load all entities.

So you can get all taxonomy terms in the database with this simple call:

$all_terms = entity_load('taxonomy_term', FALSE);


Checking if personal contact form exists

This is taken from contact.module:

function _contact_personal_tab_access($account) {
  global $user;

***snip***

  // If the requested user has disabled their contact form, or this preference
  // has not yet been saved, do not allow users to contact them.
  if (empty($account->data['contact'])) {
    return FALSE;
  }

***snip***

  return user_access('access user contact forms');
}

You should be able to see in the user object whether or not they have they are allowing people to contact them. This will also be empty if they don't have a contact form.


How do I write NULL values to the database using drupal_write_record?

does this patch suite your needs? http://drupal.org/node/227677#comment-4302522


Looks like it should be

{{ stream.node_title[0][0]['#context'].output }}

You can get the other two with

{{ stream.node_title[0][1]['#context'].output }}
{{ stream.node_title[0][2]['#context'].output }}

But obviously this would be hard coded. To make all of this dynamic, you can loop.

{% for title in stream.node_title[0] %}
    {{ title['#context'].output }}
{% endfor %}


How can I make a mobile app that is basically a mobile browser to access my live Drupal site?

There is no module(convenient) to build all apps in Drupal, You have to build your own or if you have a mobile site then you can do it without Drupal help, see my article for android app. There are so  many builders like iBuildApp, Appypie, Como, and so many.


Display a block when a view doesn't return any result

You can call your block inside "No results behavior", using a "Global: Text area" and the "PHP" Text format.
But you won't be able to display it where you want, it will have to be at the same place as the view.


Exposed view filter is not rendered properly

You could check if it is the top level (maybe by checking if it doesn't have a - at the start), and then add the attribute disabled (disabled="disabled")

You could also use this module: drupal.org/project/term_reference_tree. It has on option to only allow selection of the lowest term in the hierarchy. I used it on a site recently and it worked well.


Access a template variable from another template (or theme hook)

You can't access easily variables from other templates. But you can use the entity objects to access field values.

For a nested paragraph you find the parent paragraph in element['#object']:

field--paragraph.html.twig

{{ element['#object'].field_my_field.value }}


Admin to Create User type Foo that can then Create User type Bar

@cwiggo Drupal doesn't really have a concept of a user 'type', just roles that a user can participate in, which I presume you know. You can of course layer 'types' on top of the provided structures using additional fields and tables. You've obviously looked at some of the candidates for helping with this, but have you considered Organic Groups, which might be closer?

As for using projects before stable release: my best suggestion is to dive in and help get a project over the line, perhaps by contacting the module maintainers and offering to help directly. There are however a lot of sites based on 'dev' modules; the maintainers just have to evaluate the code, the issue queue, and the overall risks/benefits and make a decision.


How to style answers from the Answers module to make them look as in the demo site?

First you should enable vote_up_down Field module too, so you can add it to your preferred content-type (e.g answers), while adding it, in settings it asks which kind of widget to use; set it as default, then it will be like in your picture, without any need of altering the used CSS styles. If you still dont get your desired look, it must be the CSS styles that are overwritten. Inspect the element, and look for it.


To add Joins to your views using the Views UI you will need to open the Advanced settings and visit Relationships. (See graphic)

Assuming the user is the author ($node->uid) of the donation's and subscription's payment types you should be able to use the "Content: Author" field to accomplish this join.

This should allow you to build the second table from your question.  To see results displayed in a similar format to your first table you will need to use aggregation.  'Use Aggregation' can be found under the Advanced menu.

Once use aggregation is enabled you will see a new link below your fields called "Aggregation settings."

Select SUM on the field you want to display the totals for and you should see something similar to your first table.

Lastly, while you are getting aquanted with the Views module I recommend turning on the "Show the SQL query" feature in Views settings.  This can be found at admin/structure/views/settings

This will show you the SQL views is generating which can be useful while debugging or learning the Views UI.


Filter Entity reference based on attribute

The best way I found offering a very high amount of flexibility is to combine the two following components:

The Dynamic Dependent Fields (DDF) module takes in charge the relation between the other fields composing your form and your Entity Reference field.

Concretely, it will add a new mode for the entity selection, "Views: Filter by an entity reference view with dynamic argument", which allows you to dynamically pass the value of one or several other fields of your edit form as contextual filters to a view.

The magic here is that the values proposed by your Entity Reference is dynamically updated upon modification of the controller fields content (JavaScript).

The only limitations I encountered with this module is that it does not support autocomplete fields as the controlee Entity Reference fields, drop-down lists must be used instead. Moreover, DDF does not take into account programmatically set default values for the controller fields, however I submitted a patch solving this.
A patch for Entity Reference (currently in RTBC status) adds the possibility to use tokens now as contextual filter for the views and complement very well the above mentioned DDF module.

For instance, this patch allows very easily to exclude the current entity from the Entity Reference available choices.

Associating the two modules let your Entity Reference fields available values to be generated by a View taking into account both tokens and other fields values. Hard to get more flexibility !


To have a single access callback handle a dynamic number of roles which varies per menu link, try something like this in hook_menu()...

// hook_menu()
$items['foo'] = array(
  /* ... */
  'access callback' => 'MODULENAME_user_has_role',
  'access arguments' =>  array('éditeur taxonomie', 'administrator'),
);
$items['bar'] = array(
  /* ... */
  'access callback' => 'MODULENAME_user_has_role',
  'access arguments' =>  array('some other role'),
);

Then your access callback implementation:

function MODULENAME_user_has_role() {
  global $user;
  $roles = func_get_args();
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

That should do it.

Some alternatives

Remove the global $user and access arguments from hook_menu().

Then change your access callback function implementation to this:

function MODULENAME_user_has_role() {
  global $user;
  $roles = array('éditeur taxonomie', 'administrator');
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

Since hook_menu() is invoked only when the menu router is being rebuilt (e.g. a cache clear, typically done by an admin or drush), global $user is not usually very useful from within that function. Instead, an access callback function is invoked at a more appropriate time (i.e. when the page is being viewed, or a menu link is about to be shown [or not] in a menu), at this point it is much easier to make a decision about the current user's context.

To make the access callback more generic, and be able to handle multiple menu link paths, I'll typically use a switch/case on an arg() to further curate the context:

switch (arg(3)) {
  case 'taxonomie':
    // do stuff...
    break;
}


I got it working for MySQL with the extra option:

$> drush sql-dump --extra="--routines"

References:

Drush command: https://drushcommands.com/drush-8x/sql/sql-dump/
MySQL dump options: https://dev.mysql.com/doc/refman/5.5/en/mysqldump-stored-programs.html


translate the page title in search template file

Drupal 8 has extensive multi-lingual support and French is one of the supported languages.

As administrator, turn on the language module at Administration -> Extend

Then go to Administration -> Configuration -> Regional and Language -> Languages, click on Add Language and select French. If you want it to be the default language set it as the default and Save Configuration. (This can cause issues if the site is already live!)

The User Interface Translation module (also in core) can be used to import additional translations and to allow you to translate strings manually as needed.


This is untested but you could override the comment_count variable in a template_preprocess_node.

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  // Not sure if you wanted to limit to teasers but here goes.
  if ($variables['view_mode'] == 'teaser') {
    // Get the node object.
    $node = $variables['elements']['#node'];
    // Fetch the language the user is browsing the site in.
    global $language;

    // Query against the database all comments for the node in language the user
    // is browsing the site in.
    $result = db_select('comment', 'c')
      ->fields('c', array('cid', 'language', 'nid'))
      ->condition('language', $language->language, '=')
      ->condition('nid', $node->nid, '=')
      ->execute();
    $comment_count = $result->rowCount();

    // Now we override the comment count from the comment module with our result.
    $variables['comment_count'] = $comment_count;
  }
}

Observe that Views for example fetches $node->comment_count which is set in a node_load by the comment module.

So if you are using Views to display the comment count will still be wrong. One idea could be to add your own hook_node_load and populate $node->comment_count. This needs to be done after the comment module has run it's hook_node_load.

But if you are displaying nodes using the teaser view mode the code above (maybe with some modifications) should work :)

Edit
On second hand it might make more sense to setup a new variable called something like comment_count_active_language instead of overriding comment_count. In theory the comment_count is correct for the node. You are more asking for another count.

Change the example above but setup a new variable.

$variables['comment_count_active_language'] = $comment_count;

Then print that in node.tpl.php instead of $comment_count.


How to rsync files between two remotes which share the same host?

Normally you can't use two remotes for rsync, but because these two instances are on the same host you may use drush dd to return the filesystem path and use it as a source.

In example (syncing webroot):

$ drush -vy @remote.test rsync `drush dd @remote.dev` @self

or syncing just files folder:

$ drush -vy @remote.test rsync `drush dd @remote.dev:%files` @self:%files

This will work if you're using the same credentials for both.


Drush do not autocomplete files and directory names

The problem is caused by the Drush version (5.10.0) that is the one available in Linux Mint repositories.

Once I disabled that version and installed the most recent one following the instructions in http://docs.drush.org/en/master/install/ it started working.


Options set in dynamic multiple select field with ajax are not preserved

You can refer the following example for creating Dependent select list

function multiselect_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    $options_first = multiselect_first_dropdown_options();
    $value_dropdown_first = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);

    $form['dropdown_first'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => 'First Dropdown',
        '#options' => $options_first,
        '#default_value' => $value_dropdown_first,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'multiselect_school_ajax_callback',
            'wrapper' => 'dropdown_second_replace',
        ),
    );
    $form['wrapper'] = array(
        '#prefix'  => '
',
        '#suffix'  => '
',
    );
    if(!empty($form_state['values']['dropdown_first'])){
        // Code here or call function for  fetching value second and third dropdown
    }
    $form ['wrapper']['dropdown_second'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => 'Second Dropdown',
        '#prefix' => '
',
        '#suffix' => '
',
        '#options' => multiselect_second_dropdown_options($value_dropdown_first),
        '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',

        '#ajax' => array(
            'event' => 'change',
            'callback' => 'multiselect_class_ajax_callback',
            'wrapper' => 'dropdown_assignment_replace',
        ),
    );
    $form['wrapper']['dropdown_assignment'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#title' => 'Second Dropdown',
        '#prefix' => '
',
        '#suffix' => '
',
        '#options' => multiselect_second_dropdown_options($value_dropdown_first),
        '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
    );
    return $form;
}

The basic idea about above example is that use wrapper as a div which will have your second and third dropdown so on change of first drop down form state will be set so it will go into if condition than that will give you the value for the secoond and third drop down


Only allow specific roles to upload specific extension files

I have a quick solution for this using hook_form_alter.

So in your hook_form_alter you can check the user role and alter the validators key for that field. In my case the field was called field_material

global $user;
$valid_role = 'animator';

if(in_array($valid, $user->roles)) {
    //Change the extension in the validators key of that upload field
    $form['field_material']['und'][0]['#upload_validators']['file_validate_extensions'][0]  = 'mp4 mp3';
}

I am sure there are better solutions but this is quickest one so far for me to get going.


Weird node edit form behavior with feeds imported nodes

Ok,I found the problem. Seems like feeds does not support languages. So in order to make it work, you need to manually update the language of the field in both the data and the revision table for the node you imported using feeds. Once both table are done, the data appears in the edit form.


EntityFieldQuery doesn't work correctly in hook_cron

I have also encountered this kind of issue that running EntityFieldQuery does not work sometimes in the cron job.

It turns out that EntityFieldQuery will run access check.

Cron job is run as anonymous user role and it cannot access to order_status node.

To work around this issue you can add tag DANGEROUS_ACCESS_CHECK_OPT_OUT to bypass node access.

Here is the example:

$query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', array('order_status'))
    ->propertyCondition('status', 1);
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();


In your function cptc_test_field_widget_form(), change
$element['widget_test'] to $element['field_test']. and make sure your hook_field_is_empty() has the following line of code:

return empty($item['field_test']);


Thumbnail generation with nginx reverse proxy

that is similar to me, i added this line in my nginx vhost config,

location ~* /sites/default/files/styles/ {
    if (!-e $request_filename) {
    rewrite  ^/(.*)$  /index.php?q=$1  last;
    break;
    }
}

you need to reload to make the image display, hope someone can improve my answer


How do I display inline content with the Colorbox Module?

No PHP, this is done with HTML and JavaScript

CSS style the inline-content you want to display with "display: none;"
for colorbox: in "configuration", "Media", "Colorbox" --> advanced settings,
activate "Enable Colorbox inline"
add this as the html code for opening the colorbox webform link: <a class="colorbox-inline" href="?width=310&amp;height=460&amp;inline=true#name-of-your-inline-content">
If this is not working try some additionally jQuery-Magic: $('#name-of-your-inline-content').colorbox();


Couple options come to mind,

if you don't want to code then you can use Node Clone module and have 1 unpublished template node, and everytime you want to create a new one just clone the template node.

Also without installing any modules, you can use the Default value in the field setting of the content type

The other way is a bit more tricky, you have to create a custom module and use hook_form_alter to set the default values of the fields for your specific content type.


Is it possible to display a Boolean field in a block using views?

Would a button do?

To do this you have to create a custom module, or add to an existing custom module.

First define your form. All you need is a submit button, and the value can be any label you want on the button.

function modulename_onlinevisibility_form( $form, &$form_state) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Change my on-line visibility'),
  )
}

Then you need a submit handler for the form:

function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $account = user_load($user->uid);
  $account->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($account->field_optout[LANGUAGE_NONE][0]['value'])
      && ($account->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  user_save($account);
}

This will switch the value of the boolean field turning it off if on and visa versa, for the logged in user. (Profile fields may not be included in the $user variable, so a full user object is loaded using user_load.)

Then in your view, add a footer using the Global: PHP type, and add the code:

<?php
print render(drupal_get_form('modulename_onlinevisibility_form'));
?>

This will place a button at the bottom of your view which will toggle the user's on-line visibility.

EDIT.

If you are using the Profile2 module, then the code for the submit handler should be changed to:

function modulename_onlinevisibility_form_submit(&$form_state) {
  global $user;
  $profile_type = 'main'; // substitute the machine name of the profile if you are not using the default
  $profile = profile2_load_by_user( $user, $profile_type);

  $profile->field_optout[LANGUAGE_NONE][0]['value'] =
    (isset($profile->field_optout[LANGUAGE_NONE][0]['value'])
      && ($profile->field_optout[LANGUAGE_NONE][0]['value'] == 1))
      ? 0 : 1;
  profile2_save($profile);
}

Profile2 profiles are not loaded by user_load.


I can offer next thing, you can create a taxonomyvocabulary  with months, and to unpublish nodes, you can do next thing:

Query to db to find nodes with taxonomy term inside(for example January)
Load node with node_load
Set the $node->status = 0
and save the node with node_save

This will unpublish all nodes with that month. About associated nodes - can say for sure, how they accosiated with a node?
Probably you will need to write your own module.


Drupal module upgrade via Composer not being recognized

Do you have more than 1 copy of twig_tweak.info.yml located anywhere under Drupal root? Composer will install the module in <drupalroot>/modules/contrib. Installation through the UI will put modules in <drupalroot>/modules.
Did you originally install Twig Tweak with composer? If you originally installed the module manually/through the UI and then did a composer require, you will have two copies of the module. That won't work. You have to ensure you have one and only one copy of the module's code on your site.
The cleanest way to fix this is to uninstall the module from the UI, then remove both versions of the module code - remove both the <drupalroot>/modules/contrib version and the <drupalroot>/modules version. Then you can re-install the module using composer and re-enable it.


Can I have both Language and Country path prefixes?

you can either use pathauto patterns or pathologic which is still -dev .. to adapt your paths.


After going through all the configurations, I found out that skipping review order step was causing the problem.Now its working fine.

Tks
-Vil


How to let admin upload background image for view page and webform page?

This module can do it for you Background Images.


Remove time filter in a date exposed filter in a view

Here you can implement this functionality by choosing "Is Between" in exposed filters. It works only with date.
Because at time of node creation, it's asking for date and time both in "Authored On" section.
If still you want to implement, you will have to use any trick by using jquery and hiddem fields in background


How to create table view with progress bar?

You either need

A custom views field
A themed/templated existing field.

A good option in D7 for progress bars is jQuery UI progressbar ( API docs here ), as it's shipped with core.

You can add the required JS with

drupal_add_library('system', 'ui.progressbar');