How do I redirect a Read More link to another URL in Showcase Image? When creating a showcase image for my homepage, I would like to redirect the Read More link to another page in the site, instead of the default link back to the image.  Is it possible?

Or do I just have to remove the Read More link and insert a URL link inside the slide text?

You can use the path-redirect module to forward the URL in the "read-more" link to any other internal or external URL.  If you forward internally, you need to use the "node/123" system URL and delete the alias for the node you are forwarding from, before you setup the redirect.

If you point at the read more link you'll see its node or alias in the lower left hand corner of your browser.


How to display content in views with large 4-layer taxonomy term tree filter? To describe my problem more accurately I'll give a simple example of my situation:
I have a categorized content. There are 10 different categories like clothes, cars, lamps etc. Each of them have more child terms(clothes:white,red,black) Each of those has more childs(white: size1, size2 etc). If i put everything under one vocabulary, the term Filter in views gives a very long list of every single term in that vocabulary. That's kind of crappy.

A thing like this would probably solve my problems: http://drupal.org/project/hierarchical_select

However, it's still not available for views. So how do i go about this?

I saw sites with same category trees using just top layer of vocabulary for views filter, and other terms putting as menus above whole content view. For example if Clothes is selected in filter, you see all the relevant content plus menu of White, Red and Black and so on. Maybe it's not exactly the way they do it but i'm trying to figure out what's the best way to solve this.

You can filter by parent term in views; that way you don't have to list every term in the vocabulary.  Also, learn what a contextual filter is and how to use it.  Here's a series of free screencasts on learning how to use Views.


Cleanest way to write EntityCondition on field from widget The widget is nodehierarchy_menu_links - it has a structure embedded in the node like:

[0]
-> [module]
-> [menu_name]
...
-> [pnid]

It has more than one value as per the widget system. I have a partial entity query, but want to filter on [pnid] i.e. show me all the nodes owned by uid and belonging to a particular parent. Is there an elegant to filter on these sub-items using the basic EntityFieldQuery?

I was trying to find a way to filter on complex parts of the node - ie widget items that were attached as properties.

I didn't find a way. Resolved with just SelectQuery. I manually did the join instead of using node semantics and related node hooks. It would be nice to have findNodeByPnid... - and I can't see a way to build a condition without having to go another layer down into the node and working out how it is built.

Lots of our code has various forms of 'find where parent is' and 'show me the parent of this node' - subtly different enough to make it hard to generalise. Therefore, the code is broken up into parts.

1 initiate query

Always adding tag.

$query_key = 'associatenode_' . implode('', $node_types);
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'))
      ->condition('n.type', $node_types, 'IN')
      ->orderBy('title', 'ASC')
      ->addTag($query_key);

2 Add join

Either calling join function directly or by tag. Further mangle query later.

function hottopicsresearch_query_associatenode_hot_topic_research_alter(QueryAlterableInterface $query) {

Calls

function hottopicsresearch_research_for_topic_query_join($parent_nid, QueryAlterableInterface $query) {
  // Find our menu links
  $query->leftJoin('nodehierarchy_menu_links', 'nh', 'n.nid = nh.nid');

  // Find associated menus. This is used to find the parent menus.
  $query->leftJoin('menu_links', 'menu', 'nh.mlid = menu.mlid');

  // Now find the parent menu
  $query->leftJoin('nodehierarchy_menu_links', 'nh_parent', 'menu.plid = nh_parent.mlid');

  // Grab the actual parent nodes
  $query->leftJoin('node', 'node_parent', 'nh_parent.nid = node_parent.nid');

  // Filter out anything that is not our parent
  $query->condition('nh_parent.nid', $parent_nid, '=');
}


Why are hooks (except hook_help) not working? <?php
function webformta_init() {
    dsm('hello world');
}

does absolutely nothing.

<?php
   dsm('hello world');

sets an alert message with the text "hello world".

I've tried wrapping this in several hooks. Hook_load, hook_node_load, you name it.

But somehow, oddly, hook_help seems to be working.

function webformta_help($path, $arg) {
  switch ($path) {
    case "admin/help#webformta":
      return '<p>'.  t("Grades quizzes like a TA. Works with Webform.") .'</p>';
      break;
  }
}

creates a nice little help link in the module list and outputs the text and everything.

What did I screw up?

You need to clear the cache after adding new hooks.


Printing a block in node.tpl.php Would appreciate it if someone could let me know how to print a block in node.tpl.php. I basically have a block created through a view and I haven't set a region for that block as I would like to do is display this block in a specific position in all my node pages.

This is what I did in my theme's template file:

function mytheme_preprocess_node(&$vars) {
  $vars['my_block'] = mytheme_block_render('views', 'myblock-block_1');
}

function mytheme_block_render($module, $block_id) {
  $block = block_load($module, $block_id);
  $block_content = _block_render_blocks(array($block));
  $build = _block_get_renderable_array($block_content);
  $block_rendered = drupal_render($build);
  return $block_rendered;
}

And in my node.tpl.php file, I just do:

<?php print $my_block; ?>

However, this is giving me a memory limit exhausted error.  I can get it to work perfectly if I render the block in mytheme_preprocess_page function and print it in page.tpl.php, but I need to print this in node.tpl.php.  I tried the following as well:

function mytheme_block_render($module, $block_id) {
  $block = module_invoke('views', 'block_view', 'myblock-block_1');
  return render($block);
}

That is giving me the same memory exhausted error.  Is it too later to render a block in the node preprocess function?  Why can I render it in the page preprocess function but not in node?  Is there some other preprocess function that we can render it in and then have access to it in node.tpl.php?

I think module_invoke() is correct and you can simply call that in your tpl file. However,

use

print $block['subject'];

print $block['content'];

instead of

print render($block);

Also

D6 and earlier:

$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];

D7:

$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

Refer

http://drupal.org/node/359021
http://drupal.org/node/26502

for more some more help.


Display menu items of unpublished nodes to users without "Administer Content" permission I have a content editor who is building out a section. All the nodes are yet unpublished. The problem is unpublished nodes are not displayed in a menu. While this is correct behavior with a user viewing a site, the editing experience is lacking in that way. How can I build a representation of a menu of unpublished items?

I ended up using a module called Menu view unpublished which is a ...

Small module that allows users to view menu links to unpublished nodes.
The menu system from Drupal core hides menu links that link to nodes
that are unpublished. This modules provides a permission that undoes
this behavior, but only if the user has access to view the
(unpublished) node.


Frontpage grid - Rowsize to big Following configuration: Drupal 7.31 / Theme: Tb Corpal (based on nucleus 7.x-1.5)

I am using views to configurate what is shown on the frontpage. Format is "Grid".

Please have a look at the page: www.reatch.ch

You will notice, that the first three teasers are shown right below the slideshow. Then there is a huge vertical gap to the fourth teaser. After the fourth teaser there is another huge vertical gap to the footer.

I am not sure why this happens. Did not find an option in views which enabled to change that... Please let me know what other information you need to answer this!

Looks like the system is tossing in an unusual min-height value for each div.  Can you locate this in your code:  div class="grid-inner col-inner clearfix" style="min-height: 2694px;"
You might have to work your CSS to get it all formatted properly.  If you remove that min-height variable, it formats correctly (in FireFox)


How do I change page callback for a particular menu? There is already a menu defined in core module. I need to alter the page callback of this menu in another module. Similar to using hook_menu_alter() in Drupal 7, but since there is no hook_menu_alter() in Drupal 8, how do I define another page callback?

In Drupal 8 You don't have hook_menu and the are changed to "Routers" now.

Drupal 8 has a new menu system, there is no hook_menu and no hook_menu_alter anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at YOURMODULE/src/Routing/CLASSNAME.php that extends RouteSubscriberBase:

/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a YOURMODULE.services.yml file in the root of your modules directory:

services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

To get a better insight to the new menu system I would recommend the following articles:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
What Happened to Hook_Menu in Drupal 8?
Edit:  the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.


Run feeds importer crons one after another I have two feeds importers. I wanted to run the 2nd importer when the first is finished.

I have written a cronapi hook for those two importers.

/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi($op, $job = NULL) {
  $items = array(
    'cron_one' => array(
      'description' => 'import feeds one',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_one',
    ),
    'cron_2' => array(
      'description' => 'Import feeds two',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_two',
    ),
  );

  return $items;
}

In the hook_enable I am executing the first importer

function mymodule_enable() {
  mymodule_import_feeds_one();
}

function mymodule_import_feeds_one() {
  $src = feeds_source('import_feeds_one');
  $src->save();
  // Set the directory path.
  $source = 'directory-path';
  $config = array('FeedsFileFetcher' => array('source' => $source));
  $src->addConfig($config);
  $src->save();
  try {
    $src->import();
    $src->schedule();
  }
  catch (Exception $e) {
    return FALSE;
  }
  // Prevent notices from being thrown.
  $src->state(FEEDS_FETCH);
  $src->state(FEEDS_PROCESS);
  $src->state(FEEDS_PROCESS_CLEAR);

  return FALSE;
}

In hook_feeds_after_import

/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  if ($source->id == 'import_feeds_one') {

    mymodule_import_feeds_two();
  }
}

The problem is, when I enable the module, it schedules both importers on next cron run.

I want to schedule only the first one and when the first one is completed then schedule the 2nd one.

How can I do that?

Your approach is already heading in the good direction. If you don't want to schedule the import of both importers, then you should only schedule the first one in mymodule_cronapi().

Then, in mymodule_feeds_after_import(), you'll schedule the next one by calling startImport() on the second source object (or by doing something similar as you did in mymodule_import_feeds_one()). If you configure your importer to import in the background, then startImport() will result into the source being imported during cron. If your import task is large, it may be divided in multiple chunks (depends on the implementation of the parser) so PHP wouldn't exceed the maximum runtime. In this case the import may take multiple cron runs to complete.

/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi($op, $job = NULL) {
  $items = array(
    'cron_one' => array(
      'description' => 'import feeds one',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_one',
    ),
  );

  return $items;
}

/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  if ($source->id == 'import_feeds_one') {

    feeds_source('import_feeds_two')->existing()->startImport();
  }
}

I'm not sure why you want to start an import in mymodule_enable(). This code is only called once, when enabling your custom module (unless you disable the module and enable it again).


How to access session in twig? I wondering how to access to session in twig ?

In my Controller I have this part of code :

   $tempstore = \Drupal::service('user.private_tempstore')->get('mdm_user');
   $tempstore->set('num_donateur', $num_donateur);

I tried to display the session in my twig template :

  {% set mdm_session = app.session.get('mdm_user') %}
  {{ dump(mdm_session) }}

But nothing is displayed. Even session is inaccessible.

  {{ dump(session) }}

Any help would be appreciated.

Try this:

{% set varname = app.session.get('varname') %}

This is the session value {{varname}}


How to change order currency in cart/checkout page? I want to change the price of the order in the cart/checkout page.
Let's say I have a product ABC with $100(USD) and I added that in cart. But after adding I want to change the currency to EUR and proceed with the checkout process.
I tried to change the currency and amount in order like below:

$order = commerce_order_load(1234);
$amount = 100;
$order->commerce_order_total['und'][0]['amount'] = round($amount,2);
$order->commerce_order_total['und'][0]['currency_code'] = 'EUR';
$order->commerce_order_total['und'][0]['data']['components'][0]['price']['amount'] = round($amount,2);
$order->commerce_order_total['und'][0]['data']['components'][0]['price']['currency_code'] = 'EUR';
commerce_order_save($order);

But when I refresh the checkout or visit cart page, it's still in USD.
So I need help in changing the currency of order based on user input in cart/checkout page or based on the field (currency) which admin has created for every product.

You cannot directly manipulate the order total like this, as it gets recalculated based on its line items' prices each cart refresh. (That happens on every pageload in checkout and however you've configured it for other routes.)

You should look into the Commerce Multicurrency module instead or else configure your pricing rules / otherwise hook into product sell price calculation to change the currency on the order items (and shipping if present). If those are all the same target currency, the order total will use it, too.


Move only jQuery UI Tabs load in footer in Drupal 7 I need jQuery UI Tabs to load after Token renders values. I see the simple method being to move jQuery UI Tabs script to the page footer. Please show me how to do this.

Try using the following code.

drupal_add_js(drupal_get_path('theme', 'youthemename').'/js/jquery.easing.1.3.js', array('type' => 'file', 'scope' => 'footer'));


How do I attach JS and CSS on Slick Views I would like to attach a CSS file and a JS library on Slick Views module from a custom module. Is there a hook function for Slick Views or any solution?

Picking up from @leymannx (and copy/pasting from the linked answer) here's a more spelled-out solution:

You could use the template_preprocess_views_view() hook to do this:

function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'my_slick_view') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}


PHP code in mail body - Rules In the Rules module, is it possible to write php code in mail body?
There is no input format beneath body text area.

If you are willing to use PHP, I suggest you create your own rule, using hook_action_info().

You have a good example in the Examples module.


How to tell if a field has renderable content before printing HTML around it? I have a half dozen reference fields on a content type that sits at the bottom of a page under a heading of "Related" and some markup structure. I was checking if node.field_name is not empty, ... in twig before entering and printing "Related" and then each individual field, but in cases where the referenced entities are unpublished, this results in just "Related" and nothing else.

How can I figure out ahead of time if the field I am about to render has actual accessible content to show the user? is content.field_name|render|striptags|trim still the only way?

Related

      {% if node.field_topics is not empty  %}
        {{ content.field_topics }}
      {% endif %}

      {% if node.field_programs is not empty  %}
        {{ content.field_programs }}
      {% endif %}

      {% if node.field_working_groups is not empty  %}
        {{ content.field_working_groups }}
      {% endif %}

      {% if node.field_projects is not empty  %}
        {{ content.field_projects }}
      {% endif %}

      {% if node.field_papers is not empty  %}
        {{ content.field_papers }}
      {% endif %}

      {% if node.field_datasets is not empty  %}
        {{ content.field_datasets }}
      {% endif %}

Edit: updating with Hudri suggestion, it still prints the h2 of Related:

{% set display_related = false %}

{% if not (node.field_programs.isEmpty == true) and content.field_programs is defined %}
  {% set display_related = true %}
{% endif %}

{% if display_related %}

...

The answers so far are only valid for non reference fields. A reference field is different, because the referenced entities can have different access results than the parent entity. The rendered field can be empty although the field in the node object is not. As explained in How do I hide an empty field if my custom field formatter removes all items? there are two unambiguous empty conditions for the output of the field formatter in {{ content.field_name }}:

Check the first field delta, which always starts with 0:

{% set display_related = content.field_name.0 is defined %}

or check whether the field formatter could find any renderable children and has added the field wrapper:

{% set display_related = content.field_name['#theme'] is defined %}

For a reference field it is important to render content.field_name even if the result is negative, because it contains the cacheable metadata of the access checks. When for example a referenced node is published, the parent node needs to be invalidated and rerendered.

So checking content.field_name|render|striptags|trim is not so bad at all, because this check renders the field content and if the result is negative you don't have to render the field again, because the metadata bubbled up already.

Field Groups

For halve a dozen fields you could use Field Groups. Place all reference fields in a group "Related" and display the header in the field group template. If the field group template doesn't hide automatically you can check with striptags as before. You get the entire rendered result of all fields in the variable children.

Although I would prefer to check the specific content you expect to be inside of the field group and so ignore labels or other things that may be added later. The already rendered field group content is in a markup object and you need to render it again in twig, so you can check it casted as a string. For example whether it contains a linked node:

field-group-html-element.html.twig:

{% set display_related = '<a href' in children|render %}


How to put links into description text? In my field's description, I want to link to more documentation. If I do it like this:

$form['field_name'] = array (
  '#description' => t('Here are some words about') . ' ' . t('stuff') . ' ' . t('and things and whatnot'),
);

It works. It looks like this:

  Here are some words about stuff and things and
  whatnot.

If I do it the proper way, like this:

$form['field_name'] = array (
  '#description' => t('Here are some words about @stuff and things and whatnot', array('@stuff' => l('stuff', 'blah')),
);

Then the HTML is generated and then output into my description as raw text, like so:

  Here are some words about stuff and things and
  whatnot.

Why is the "correct" way not working?

Firstly, here are some of the ways NOT to pass links to the t() function:

// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => ''. t('the Drupal Handbooks') .''));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at the Drupal Handbooks.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

And these are the accepted ways to pass that type of arg:

// Do this instead.
$external_link = t('Look at Drupal documentation at the Drupal Handbooks.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to the Administer screen in the main menu.', array('@administer-page' => url('admin')));

This all comes from Dynamic or static links and HTML in translatable strings, which contains justifications for that reasoning.


Hide the header of a view block when there is no content On a page, a views block should show some text on top of the view when the block doesn't hide and there is content to show:
Title •
.
Now, when there is no content in the block, this text should be hidden.
I've tried to do this with putting the header in the view as 'unfiltered text' in 'header' and then setting the view to hide when there's no content. This doesn't work or could it be that I'm doing something wrong?

Update, I got it to work, and think the following is happening:
It is possible to just put this text in the header of the view as 'unfiltered text' in 'header' and it will hide when there are no results.
However, when the view is based on a taxonomy relationship as it was with mine, and 'require this relationship' is not set, there will always be a result, so the header will show eventhough those results are filtered away.

Well I think you are asking how to hide a block view completely when it is inserted as a global: view area in the header of another view.

  For the parent view:

When inserting the block view into the header of another view, make sure you leave the box unchecked that says: Display even if view has no result

  For the block view that is being inserted check these 3 things:

1:
If you are displaying fields in the block view, you want first make sure you are hiding any empty fields under Show: Fields | Settings

2:
Then you want make sure you you have the Hide block if the view output is empty: set to yes under the advanced tab in the block view.

3:
You also want to add a contextual filter for the block view that defines the context you want. Then set the WHEN THE FILTER VALUE IS NOT AVAILABLE setting to hide view. (For the image below, my context needed was taxonomy term ID.)

Hope this helps!


Breadcrumbs/menu for dynamic pages Im breaking my head around getting the breadcrumbs set properly on views page.

my views' page address is "teachers/%" where % is a term-id.

I have a content type called 'program' with a field taxonomy term reference field "field_department"

I want to set my breadcrumb for the page  'teachers/%' to be the breadcrumbs of the program associated with % + the program itself.

my site is using also menu_breadcrumb which gives the rule for my program breadcrumbs.

I want the the breadcrumb of 'teachers/7' will behave as if it is the menu child of node/22.

I tried both hook altering the breadcrumbs or adding the pages to the menu dynamically but I dont manage.

Can this be done? and how?

Views breadcrumbs can be tricky. You can create a module and a class that implements BreadcrumbBuilderInterface and do:

class MyBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * The AdminContext service.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * The AliasManager service.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    AdminContext $admin_context,
    AliasManagerInterface $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->adminContext = $admin_context;
    $this->aliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) : bool {
    if ($this->adminContext->isAdminRoute()) {
      return FALSE;
    }

    // Using route_match, check if the current route is a view and which view id
    // and return true or false
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $breadcrumb = new Breadcrumb();

    // create your breadcrumbs...

    return $breadcrumb;
  }

}


Exposed filter value into the session and cookie? I want users visit my site regularly. And I need to store their settings to session (cookie). These settings are: Views Exposed Filter on the FrontPage (like to hide materials from the black list users).

So I have the FrontPage View and Taxonomy Term View. These views have exposed filter.

Once visitor selected values in this filter they should to store during he browsing the site and more when he visit site again.

I do not want to use JavaScript. I want to store cookie with php and to get it with php.

And I want drupal cache all pages for all possible filter values.

Please, have I to write a new Drupal CMS or where have I to get the answer?

There is a setting in the "Configure filter criterion" form.

Test this one. I guess it will write a cookie for the user.


How to create a select drop down that opens a URL? I have a select drop down. When the user selects a value from the drop down, the user will then click on a button and based on what the user has selected it will open a url in a new tab. While this is quite simple in JavaScript I am struggling how to figure this out in drupal.

So far I have created a custom module which has a select form and the submit button. From here I am stuck as to how to write if user has selected value a open google.com etc. any suggestions or pointers would be greatly appreciated.

You can do this by using $form_state->setResponse() together with TrustedRedirectResponse.

Create the dropdown, like this:

$form['select'] = [
  '#type' = 'select',
  '#title' => t('Select'),
  '#options' = [
    'https://google.com' => t('Google'),
    // More links...
  ]
];

To open the link in a new tab, you can add this to your form:

$form['#attributes' => ['target' => '_blank']];

Then create the submit handler, like this:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setResponse(new TrustedRedirectResponse($form_state->getValue('select'), 302));
  // You can change the response code from 302 to whatever you need
}


Does disabling a module erase its settings? This is kind of a basic question that I can't find the answer to in the Googles. In the process of debugging, I know disabling modules is a good start but I'd like to be able to go back and turn them on without losing any pre-configured settings.

"Disabling" a module means to disable its user interface aspects only.

This means:

All code of disabled modules remains to be loaded.
Services of disabled modules remain to be functional.
Routes, plugins, info hooks, etc. remain to be available.
Access to all data items that support any notion of access is denied for all users.

hook_enable(), hook_disable(), hook_modules_enabled(), hook_modules_disabled() are removed, without replacement.


Get raw and relative path of a file uri I have a file with an uri and I want to get its raw and relative path.

Uri: public://videos/Test Video.mp4
Path: /sites/default/files/videos/Test Video.mp4

I found already a way to do this:

$file_uri = $file->getFileUri();
// public://videos/Test Video.mp4

$absolute_url = file_create_url($file_uri);
// https://www.example.com/sites/default/files/videos/Test%20Video.mp4

$relative_url = file_url_transform_relative($absolute_url);
// /sites/default/files/videos/Test%20Video.mp4

$relative_raw_url = rawurldecode($relative_url);
// /sites/default/files/videos/Test Video.mp4

Is this the Drupal-way? Or is there a better solution for doing this?

I had to do this recently and found this solution using Drupal 9.1.
$file = File::load($fid);

$relative_file_url = $file->createFileUrl(TRUE);
$absolute_file_url = $file->createFileUrl(FALSE);

I found the createFileUrl() function in web/core/modules/file/src/Entity/File.php.  Maybe this would be considered "the way?"


How do I use Hook_update_N to update an FieldConfigStorage? function some_config_update_8101(){

if ( !FieldConfig::load('image_byline') ){
    $config_path = drupal_get_path('module', 'some_config') . '/config/install/field.field.node.main_image.field_image_byline.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('field.field.node.main_image.field_image_byline')->setData($data)->save(TRUE);
    $message .= "FieldConfig installed for module some_config.\n";
  }
  else {
    $message .= "It didn't work!\n";
  }

     if( !FieldConfigStorage::load('image_byline') ){
        $config_path = drupal_get_path('module', 'some_config') . '/config/install/field.storage.node.field_image_byline.yml';
        $data = Yaml::parse($config_path);
        \Drupal::configFactory()->getEditable('field.storage.node.field_image_byline')->setData($data)->save(TRUE);
        $message .= "FieldConfigStorage installed for module some_config.\n";
     }
     else{
       $message .= "That didn't work either!\n";
    }

Above is the code I am attempting to use to update a content type with a new field on my site.  When I run the dbup command I get "PHP Fatal error:  Using $this when not in object context in EntityStoageBase.php.

How is my code affecting the context of EntityStorageBase, if I have not changed code in that file?

FieldConfigStorage::load() isn't static, so you can't use it statically.

Get an instance of FieldConfigStorage instead, and use that

if ($storage->load('image_byline')) {
  // ...
}


How to add recurring to all product by default monthly? I am using ubercart and uc_recurring module and Drupal6.  I wanted to add monthly payments to all products by default.  How can i do this ?

I added a rule to add the data to the DB  using php code while creating new product

$data = array(
  'pfid' => ' ',
  'nid' => $node->nid,
  'fid' => 'recurring',
  'description'=>'When this product is purchased, add a fee for the same amount as the product selling price charged first after 0 days and every 1 months after that 99 times.',
);
drupal_write_record('uc_product_features', $data);

$q = "SELECT pfid FROM {uc_product_features} WHERE fid= '%s' AND nid = %d";
$result = db_query($q, 'recurring', $node->nid);
$num = db_result($result);

$data2 = array(
  'pfid' => $num,
  'model' => ' pro',
  'fee_amount' => ' ',
  'initial_charge'=>'0 days',
 'regular_interval'=>'1 months',
  'number_intervals'=>100,
);
drupal_write_record('uc_recurring_product', $data2);

Still recurring is not working? When i go to the path /node/*/edit/features and simply submit the form without updating any fields it works?

Am I missing anything?

Finally its solved by changing the code in rules

<?php
    //Recurring
    $data = array(
   'pfid' => ' ',
   'nid' => $node->nid,
   'fid' => 'recurring',
   'description'=>'When this product is purchased, add a fee for the same amount as the product selling price charged first after 0 days and every 1 months after that 99 times.',
     );
   drupal_write_record('uc_product_features', $data);

   $q = "SELECT pfid FROM {uc_product_features} WHERE fid= '%s' AND nid = %d";
   $result = db_query($q, 'recurring', $node->nid);
   $num = db_result($result);

  // Build the recurring fee's product object.
   $product->pfid = $num; //pfid
   $product->model = '';
   $product->fee_amount = 0.000;
   $product->initial_charge = '0 days';
   $product->regular_interval = '1 months';
   // If number intervals is negative, it means that it's unlimited intervals.
   $product->number_intervals = 100;
   $product->nid = $node->nid;

   uc_recurring_product_feature_save($product);
 ?>

I am not sure whether its a proper way..


How do I add an access condition to a menu item? How can I add new conditions on top of existing conditions that determine whether a menu item is visible? These conditions should not be limited to permissions settings.

As an example use case (not necessarily the reason for this question): Suppose I have a content type of which users are only allowed to create one node. I have a menu item for adding that type of content. But if the user has already created a node of that content type, I want to hide the menu item. My first thought is to run a query to check for the existence of a node created by the current user that is of the specific content type. If one exists, hide the menu item.

I would think this type of functionality should go into hook_menu_alter() and add the required logic there. But I'm not sure how to do that without bypassing the existing checks, like checking if the user has permissions to create that type of content. Would I have to include that logic within my own condition? Or can I add to the existing access logic without overwriting it?

Edit: Some people seem focused on answering "how do I limit a user to creating one node of a content type". That is not the question here. The question is how to I add custom access conditions to a menu item.

What you need to do is to add your callback via hook_menu_alter(), and then inside your callback you simply do your logic then return the data via the original callback.

To be certain that you don't overwrite any other hook_menu_alter() changes, you should pass the previous callback to your callback via the access argument.

This is all theoretical, but the code should go something like this:

MYMODULE_menu_alter(&$items) {
  $items['menu']['access arguments'] = array_merge(array($items['menu']['access callback']), $item['menu']['access arguments']);
  $items['menu']['access callback'] = 'MYMODULE_access_callback';
}

MYMODULE_access_callback() {
  $args = func_get_args();

  // Do Stuff.
  if ($something == FALSE) {
    return FALSE;
  }

  $function = array_shift($args);
  return call_user_func_array($function, $args);
}


How to recover from a borked cache? The following steps lead to a situation where drush cc all would fail.

Build a site, with fields and stuff. Especially one or some fields for the user entity.
Install an alternative cache plugin, e.g. mongodb.
Change the site configuration. E.g. remove one of the fields on user entity.
Disable the alternative cache plugin, switch back to database cache.

Now the database cache contains really old data (or this is how I imagine it), still referencing fields that have long been deleted.

On drush cc all, drush first wants to bootstrap Drupal. Doing this, it also tries to load a user account for login. This lets it use cached data for user fields.

I get a crash with mysql exception from field_sql_storage_field_storage_load(), because it tries to load non-existing fields.

I suppose this is just one example for a site being broked due to really old cache data, after switching the cache plugin.

How can one recover from this situation?

For me the following hack worked:

Edit includes/cache.inc. Let function cache_get() return FALSE.
Run drush cc all.
Revert the hack in includes/cache.inc.

I am not saying this is the best solution. But it did work for me, on a dev system. I am not sure I would recommend this on a production system.

Here is the hack:

 function cache_get($cid, $bin = 'cache') {
+  return FALSE;
+  # return _cache_get_object($bin)->get($cid);
-  return _cache_get_object($bin)->get($cid);
 }


FB connect in Drupal6 I am working in drupal-6 trying to do facebook connect button.

I installed fboauth module sucessfully. now i also  got fb connect button and also able to connect successfully. now first time i allow application for this. it works successfully.  Now
When i logout from website as well as from Fb. then try to connect fb coonect it goes to app page after login. i want it directly goes to my website. when i logged in ..

Any body have idea?

Got the Problem. FB changes their structure of application. Not a bug


How can I let users create new drafts for *existing* content? We have two roles of user: Admins and Content Creators (basically Authenticated with a few more permissions to create content). We'd like to have Content Creators be able to create new drafts from existing content and let the Admins approve to publish.

While this approach sounds straight forward, I've hit a number of road blocks and have tried multiple approaches:

Workbench Moderation: I've failed to install this to any working degree. Each time an admin approves a piece of content it's permanently unpublished. I describe the issue better here. If an Admin tries to publish their own content it falls into an endless cycle where WB sees the item as published but Drupal reports otherwise. Others seem to have similar problems.
Draft: Looked promising but there is no D7 release
Save Draft: Works nicely on new content, but doesn't offer to create a new draft of an existing item.

Other things we consider:

Workflow: I'm hopeful but there is a lot of configuration to set up for such a seemingly simple work flow. Also it appears a bit overwhelming. I hoped Workbench to be a simplified version of this.

We see that this feature is built into D8. Infact, this very ticket explains what we're trying to do:

  Ideally, I should be able to assign an arbitrary state to any revision. I could have a published revision, a revision pending approval, and a draft revision beyond that.

Is there a way to make this happen in Drupal 7?

We use the Workflow module and have found it to be pretty stable, and we use it exactly as you have described, to allow a content person to edit content, then for an admin to approve it.

Configuring the workflow module is a bit complicated, but it is worth doing as it will provide you the functionality you need. Generally it has the following steps:

Install the workflow module.
Configure the workflows:

Create a new workflow.
Make some states.
Assign the workflow to a content type (the tutorial below calls it a node).

Set the permissions for each type of user to use each state of the workflow.

Creating a Workflow for Drupal Users contains a good tutorial.


Attach dynamic inline css to Is it possible to add inline CSS to into the <head> section of a Drupal 8 page? My expected result should look like this:

<head>
<style>
.my-custom-class {
  background-color: red;
}
</style>
</head>

I've tried to add it to hook_preprocess_HOOK() but it will not show up.

function my_module_preprocess_html(&$variables) {
  $variables['html']['#attached']['css'][] = array(
    'type' => 'inline',
    'every_page' => TRUE,
    'data' => '.my-custom-class { background: ' . $dynamic_color . '; }',
  );
}

I've tried a few other things but it did not work either. Whats the right way to do this?

After doing some more research i've found an answer to my problem. The main reason for not finding a solution was, they don't want you to do this in Drupal 8.

From their documentation:

https://www.drupal.org/developing/api/8/assets#dynamic-css-js

  If the dynamic CSS/JS is built for each request, then you enter the truly advanced territory. This is hard, and for a good reason: per-request dynamic assets have to be built on every single request and therefore slow Drupal down. We want to make it hard to make Drupal slow down, so this is why we don't offer a nice API for this — since we don't want you to do it.

This makes sense and there is a short description how to get it to work anyway but its lacking of an example. This is what i've done to get it to work:

function my_module_page_attachments_alter(array &$page) {
  $background_color = '#000';
  $page['#attached']['html_head'][] = [
    [
      '#tag' => 'style',
      '#value' => '.my-custom-class { background: ' . $background_color . '; }',
    ],
    'my-custom-module'
  ];
}


Rules Conditions being evaluated after schedule time elapsed? Backstory:  I have a content type that will send an email after a period of time if a boolean is true.  From the creation of a node to the time the email will be sent, the boolean could change at any time.

My Problem:  I would like a clean way to have the conditions of a rules (see if the boolean is true) to be evaluated before going about executing an action set.  Through my testing, I cant get the Rule to be properly check the boolean when a node is both created and updated.

Optimally, I would like the conditions to be evaluated after the elapsed time of the Rules scheduler rather than upon initially after being created or updated.

Clarification Edit:  Make a Rule that will execute sending an email after a given set of time that is set by the user upon node creation.  The single condition of sending the email is if a boolean is true.  The boolean could be modified on node creation or through a node update.  So the Rule can not be activated based on one of those.  No Sssweat was able to show me how to move an evaluation from a standard Rule to the component allowing it to only be evaluated when the standard Rule scheduled the component.  So the Rule is set up to be triggered on node creation with only a given time frame field as its condition.  Depending on which time frame field was selected, the Rules Scheduler will start.  During this period the boolean to be evaluated could be shifted from true to false many times.  So only be the end of the scheduled time should the boolean even become relevant.  The component side of the rules looks at the boolean to see if it should send the email or not.  If true > send email. If false > do nothing.

Some more clarifications:

The user has a field to choose the time frame for resolving the node.
If a node is updated, the countdown should not be reset.  One email should be evaluated to be sent at the end of the given time frame.
If the boolean has been changed to false, the email should not be sent and no further action is needed.

Give this a try

Create a New Component

1) Add Compotent of Rule.

2) For Data Type: select Node. Name, Label and Machine name use whatever you want.

3) Add condition of Content is of type

For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of test you put test
Select your content type

4) Click on Add and select Data Comparison and select your boolean field.

Example: When creating the component, if you gave the Node Data Type a machine name of test and your boolean field is named hello. For your boolean field you need use test:field-hello as your data selector.

5) Add action of Send Mail.

Now Create a new Rule

1) For action use after content is created

2) Leave the condition empty (no need for condition here)

3) for Action add the scheduled component evaluation and select the component you just created.

use node as your data selector

  I believe this will evaluate your rule component only when the schedule time hits.


Add mail to user register with user_external_login_register I'm creating a module that should add an external authentication server, and I'm using user_external_login_register function.

The problem is that the user created with this functions does not have a "mail" attribute, and also if I try to user_load it, the mail attribute is not present.
Why?

Is there a way to add it or I've to create user in the ordinary way, by code?

I could add it on hook_user_insert, but the mail address is a response from a web services, called before the hook.

The function user_save is called in user_external_login_register, so you could just use hook_user_insert to add the info you need.


How to remove certain meta tags? How can I remove these tags from my pages in Drupal 7?

<link rel="shortlink" href=" .... " />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<link rel="canonical" href="...." />

Update: I have the code for template.php, which removes the generator and canonical tags.

function program_html_head_alter(&$head_elements) {
  unset($head_elements['system_meta_generator']);
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
      unset($head_elements[$key]);
    }
  }
}

Can anybody add something to remove the short link tag?

This is displayed in html.tpl.php in the variable $head. $head is added to the variables in template_process_html by using drupal_get_html_head(). In that function, you can see that hook_html_head_alter() is called.

There can you remove these.

However, note that these links can be important for SEO, to avoid that a search engine thinks that you have duplicate content on your site, if for example a node is available through node/nid and the alias.


How do I override an endpoint provided by a module in a feature? I am using the Services module and Drupalgap, which provides a service endpoint by default.  I want to make changes to the available services on the drupalgap endpoint, and I manage configuration on my site using Features, so I want to override the endpoint provided by Drupalgap.

However, if I check the box in the Features UI, it doesn't add the drupalgap endpoint because it's already "owned" by the Drupalgap module.

I dug into the code and the Drupalgap endpoint is provided by drupalgap_default_services_endpoint().  I tried adding the exported service configuration in mymodule_drupalgap_default_services_endpoint() and clearing the cache but it doesn't look like this gets picked up.

So, how can I override a service endpoint in a module's code with my own code for that endpoint?  If there's no way to do it, I guess I can cut and paste the exported, updated code over the endpoint in the Drupalgap module, but that seems like the wrong approach.

I found a smooth way to do this without overriding anything.

Create a new services endpoint by cloning the Drupalgap endpoint.
Add the new endpoint to a feature to keep it in code.
In Drupalgap's settings.js, change the endpoint to the new custom endpoint. The relevant line is:

// Default Services Endpoint Path

Drupal.settings.endpoint = 'drupalgap';


Drupal commerce - what page/function should i call after an off site payment I'm creating a module to integrate 'xpay - carta sì' payments inside Drupal commerce.
I don't have any documentation on xpay apart for the module developed for ubercart.
Anyway i managed to code the part where the payment method is added and i succesfully dealt with going from my site to the bank page sending the correct data. I'm stuck with where to go after the payment is completed.
When i send the data to the bank i set some url to call according to the outcome of the transaction

'RESULT_URL' => $site_url.'/cart/xpay/complete',
'NOTIFICATION_URL' => $site_url.'/cart/xpay/server',
'ERROR_URL' => $site_url.'/cart/xpay/error',
'ANNULMENT_URL' => $site_url.'/cart/xpay/error',

I've defined those menu_callbacks, but i'm not sure that Drupal Commerce works like this, maybe i should do something totally different like returning to $site_url.'/checkout/%order_id/payment'

Has anybody of you tackled something similar?

i used those two

// Return to the previous page when payment is canceled
'cancel_return' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

// Return to the payment redirect page for processing successful payments
'return' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

but also have an IPN. (your NOTIFICATION_URL)

don't forget to create a commerce transaction with the feedback from the carrier !

maybe have a look at another module, like postfinance (by me),
or paypal (by Ryan - the commerce god ;))


how to use a relative path with form API image_button? I'm building a module in D6 that renders a form to a custom template (also within the mod).
I need to use an image for the submit button, but I'm having trouble with the path to the image.

$form['submit'] = array(
'#type' => 'image_button',
'#src'  => 'sites/all/modules/custom/mymodule/images/show-my-score-button.png',
'#value' => t('Show My Score'),
'#submit' => array('mymodule_submit'),
'#redirect' => '',

);

This is the code I have in place, and it is functional. However I can't use the path as it's shown since I don't know where my module will end up.

How can I make the image show in my module while using an image path that is relative to my module?
I'd love to have something like "/images/show-my-score-button.png" but it doesn't work.

You need to define an absolute path, a relative path won't work. But you can use the drupal_get_path() method to retrieve the path to your module, so you don't have to worry about where it will end up in the filesystem.

For example:

$image_path = drupal_get_path('module', 'mymodule') . '/images/show-my-score-button.png';


Find which views are using Views PHP I have a project that is using Views PHP, and I'd like to figure out which views are using PHP from this module. This will help me determine if I can easily remove the dependency on the module.

Is there a query or something else I can use to figure out what views are using this module?

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

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

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

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


form alter user login drupal 6 I have added this:

    function ahml_form_alter(&$form, $form_state, $form_id) {
      if ($form_id == 'user_login') {
        $form['my_field'] = array(
        '#type' => 'link',
        '#title' => t('Example link'),
        '#href' => 'login'
      );
    }

into a custom module and instead of a link in the output I have two text boxes: one reads
"example link title", the other "example link url".

Do I have this wrong of is there just something else in the system causing this to happen?

I recommend you to write the function as follow:

function ahml_form_alter(&$form, $form_state, $form_id) {
  //for register page
  if ($form_id == 'user_register') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Login page', 'user/login'),
    );
  }
  //for login page
  if ($form_id == 'user_login') {
    $form['my_field'] = array(
      '#type' => 'markup',
      '#value' => l('Register link', 'user/register'),
    );
  }
}

For additional details, check Drupal 6 Form API Reference


More than one path alias per node I have a ticketing system where the path aliases are set like ticket/[node ID], e.g. http://example.com/ticket/1234.

I would like to create multiple path aliases for the same node, and be able to access it also as discussion/[node ID], e.g. http://example.com/discussion/1234.

I will be using different node templates basing on the path.

Is there any way to set multiple path aliases for the same node?

You can set multiple path aliases for one node, this is no problem. If you can't do it with Pathauto, then it's possible with custom code when saving the node.

But in your case it might be more efficient to set up different routes for /ticket/{node} and /discussion/{node}. You can either set a fixed route parameter or use a custom node controller to set a marker, that you can use in theme name suggestion to choose the custom template.

Another solution would be to set up a View with a contextual filter for the node and two displays with different paths. Choose for each a different view mode to get different templates. Technically it's almost the same, but you need no custom module, because Views sets up the routes for you.


Automatically load pending draft I'm using drupal 8 and webform module (multistep). In the webform submission settings, i enabled submit several drafts which adds the 'save' button for saving the progress.
When the user logs out and logs in later on, a messsage to 'load pending draft' appears. In my settings, each user is allowed one submission. Is there a way to automatically load pending drafts without clicking on the link in the said message?

Appreciate any help given, thanks

There is. When a user's saves draft a token gets generated. You need to get their token value.

$webform_submission = \Drupal\webform\Entity\WebformSubmission\WebformSubmission::load($sid);
$token = $webform_submission->getToken();

Then, you need to generate a URL like this

$draft_url = '/form/webform-name?token=' . $token

and on login redirect them to that url.


Views field cache tags does not invalidate the views cache I've implemented CacheableDependencyInterface on my ViewsField plugin.

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return ['arbitrary_tag'];
  }

I can see the tag on the HEADER and the View configuration object.

However, when that tag is invalidated, the View is not updated.

I've also tried using adding cache tags to the render method:

return [
  '#markup' => $message,
  '#cache' => [
    'tags' => ['my_list'],
  ],
];

Both to the Views field, but also tried directly on the View element using hook_views_pre_view

While debugging, I've made sure to try invalidate that specific tag:

Cache::invalidateTags(['my_list']);

While debugging further it seems like that the ResultRow values are still cached after clearing the tag.

Although there are Views plugins which use CacheableDependencyInterface, I'm not sure it is the right way for a field plugin, because a field renders content and a cache tag of rendered content belongs in the render array.

This was discussed in this issue for block plugins. Don't know if this here or in the other issues for blocks is a core issues, because you can see in both core modules the effort to collect plugin cacheable metadata, or Drupal assumes, that all render arrays fulfill the requirements outlined in the docs:

  "It is of the utmost importance that you inform the Render API of the
  cacheability of a render array"

Anyways, an easy fix is to put the cache tag in the rendered output of the field.


How do I check the content type of a file using hook_file_presave I wrote a module to strip Exif data from uploaded file.

function modulename_file_presave(Drupal\file\FileInterface $file) {
if ($file->getMimeType() == 'image/jpeg') {
  $filepath = \Drupal::service('file_system')->realpath($file->getFileUri());
  $path = $file->getFileUri();
  $img = new Imagick($path);
  $img->stripImage();
  $img->writeImage($filepath);
  $img->clear;
}

it works to all files, but I want to restrict this module to work in only specific content type.
How can I get the content type in my module?
Thank you.

The file itself has no reference to the parent node (it can be referenced by multiple entities). But you can get the node type you are adding or the node you are editing when you upload the file from the route:

function modulename_file_presave(\Drupal\file\FileInterface $file) {
  if ($file->getMimeType() == 'image/jpeg') {
    switch (\Drupal::routeMatch()->getRouteName()) {
      case 'node.add':
        $content_type = \Drupal::routeMatch()->getRawParameter('node_type');
        break;

      case 'entity.node.edit_form':
        $node = \Drupal::routeMatch()->getParameter('node');
        $content_type = $node->getType();
        break;

      default:
        $content_type = NULL;
    }
  }
}


In a custom module, get return of hook for making it available in other hook I had some similar questions here, but would like ultimately to know best practices and possibilities for this case.

I have my custom module, in which I use two contrib modules hooks. As I understood, hooks are self-invoked (looking from my module point of view), and as soon as I am declaring it, they get executed.

That said, how I can get return of an hook function ?

I am trying to make $foo1 available in other hook and vice versa for $hook2. I would like to avoid oop solutions if possible.

Example:

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  //$foo2 here somehow ?
  $foo1 = 1;
  return $foo1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  //$foo1 here somehow ?
  $foo2 = 1;
  return $foo2;
}

Yes, if you implement a hook provided by a contrib module, it is invoked by that module function.
You can declare those two variables in global scope so that they can be accessible each other in the functions.

<?php
// mymodule.module
global $foo1;
global $foo2;

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  global $foo2;
  //$foo2 here
  $foo1 = 1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  global $foo1;
  //$foo1 here
  $foo2 = 1;
}

If you don't want to use global scope for your variables, you can save and retrieve them alternatively in your Drupal database using variable_set() and variable_get().

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  $foo2 = variable_get('foo2');
  $foo1 = 1;
  variable_set('foo1', $foo1);
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  $foo1 = variable_get('foo1');
  $foo2 = 1;
  variable_set('foo2', $foo2);
}

Note that, for both approaches, you don't need to return each of them as long as you don't have any other purpose.


Remove components from a feature using Drush Using Features UI to manage a big feature components is a tedious task.

Therefore in order to add a new component I use

drush fe myfeature views_view:myview1

Now how I remove the uneeded component myview2?

From the UI this operation is illustrated as below, I want to remove the conflicted community_content with clone_of_community_content:

The view:

Remove the component by deleting the corresponding line in your feature's .info file. Then run:

$ drush fu <feature_name>

In your case:

Open the file /sites/all/<features_folder>/myfeature/myfeature.info.
Delete the following line.

features[views_view][] = myview2
Save the file.
Run $ drush fu myfeature in your site's folder.


Get single field valure from node object I have loaded a node object in my module, I want to get the single value entered for a specific field (a text field).

I can access it directly with $node->field_position['und'][0]['safe_value'].

Is there a better way to do this? I have looked at field_get_items and field_view_value but I dont want a renderable array or an array at all. Isn't there a way to just return the string value? Having

$items = field_get_items('node', $node, 'field_position');
$position = $items[0][safe_value];

just seems like additional code that doesnt make it any simpler

Entity API

Documentation says: The Entity API provides wrapper classes you may use to make dealing with the values of an entities properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.
https://drupal.org/node/1021556

    // Create wrapper around the node.
    $wrapper = entity_metadata_wrapper('node', $node);

    // We can do it also using only $nid.
    $wrapper = entity_metadata_wrapper('node', $nid);

    // Get the value of field_name of the node.
    $wrapper->field_name->value();

    // Get the value of field_name of the nodes author's profile.
    $wrapper->author->profile->field_name->value();
    $wrapper->author->profile->field_name->set('New name');


Clearing Acquia Varnish Cache when any content gets updated I have a drupal 7 site on acquia and everytime one of my editor makes  changes to content, I have to manually clear the varnish cache for him. Is there a way to fire this clear cache everytime he saves a content? Also clear cache doesnt work, as I have to goto the acquia admin panel and click on clear varnish cache. What are some work arounds to this?

I actually have the Acquia purge button, is this what is used to clear the varnish cache? But it seems like that is failing:

Not sure if this module would work for you, https://www.drupal.org/project/acquia_flush_varnish

Another module that you could check, https://www.drupal.org/project/acquia_purge

If neither one works, you can leverage Acquia's API.

Here's some info on Varnish from Acquia, https://docs.acquia.com/cloud/performance/varnish
Here they talk about the endpoint, https://docs.acquia.com/cloud/performance/varnish/purging#api

  DELETE /sites/:site/envs/:env/domains/:domain/cache

An example from them,

  curl -s -u user:pass -X DELETE \
  https://example.com/v1/sites/site/envs/prod/domains/example.com/cache.json

A example that only resets a specific page is listed here, https://docs.acquia.com/cloud/performance/varnish/manually-purge

  # Replace 'sitename' below with the appropriate value.
  curl -X PURGE -H "X-Acquia-Purge:sitename" -H "Accept-Encoding: gzip" http://example.com/path/to/page

A module that executes that when saving nodes, or a particular content type, should be easy.


Pulling in a title from multiple content types Currently I have 3 content types: Program, Chapter, Item. The program content type has a node reference field to contain multiple chapters and the chapters content type has a node reference to contain multiple items.

I now have a view that lists some items, but I also want to pull in the program title that is referencing that item.

For example:

Program = Fruit
Chapter = Pear
Item = Cutting a Pear

I want to list the title of "Cutting a pear" and also the program "fruit" title.

In my view for my items I tried creating a relationship to tie in the "program", but the only relationship that I can use is the "Chapter" because I guess its directly related to the item. The program is not tied to it in any way.

Any ideas how I can pull in the program title information when its not directly related to the item?

I would put this as a comment, but I'm new so I can't comment on things yet, but what you could do is add the relationship of the chapter, then add a field using that relationship that shows the node reference that the chapter has to the program. As long as you're using that relationship, it should show the proper program.


Show if a user is online, idle, or offline on their account page? I want to display the status of the user on the account page. I added the following code in the theme I am using. It works, but users are never displayed offline.
Why? What is wrong in the code?
user.html.twig

  {% if status == 'Online' %}
     Online
  {% elseif status == 'Absent' %}
     Absent
  {% else %}
     Offline
  {% endif %}

bootstrap_subtheme_front_office.theme
<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

use Drupal\Core\Database\Database;

/**
 * Implements hook_entity_presave().
 */
function bootstrap_subtheme_front_office_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'Offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

I guess the problem lies here, for starters:

//- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'Offline';
  }

The if ($user->getLastLoginTime()) { will be TRUE always, after the user has logged in once. This will prevent the else from ever being hit, thus, 'Offline' never gets set.

I don't know what the difference is for you in terms of time between "Absent" or "Offline", but it sounds like you'd want to figure another calculation here to know what to set status to.

This can be simplified to:

function bootstrap_subtheme_front_office_preprocess_user(&$variables) {
  // get user object
 $user = $variables['elements']['#user'];

 $last = $user->getLastAccessedTime();
 $now = \Drupal::time()->getRequestTime();

 switch ($last) {
   case ($last > ($now - 900)) :
     $variables['status'] = 'Online';
     break;
   case (($last < ($now - 900)) && $last > ($now - 1800)) :
     $variables['status'] = 'Absent';
     break;
   default:
     $variables['status'] = 'Offline';
     break;
 }
}

Then break down smaller functions to evaulate the time against how many minutes ago they were active... use it in the switch above.

getLastAccessedTime() does:

  The timestamp when the account last accessed the site.

  A value of 0 means the user has never accessed the site.

So you don’t need a db_select.


Apply view contextual filter only if user role is not administrator I have a view that filter a list of taxonomies based on the taxonomies associated to the logged in user. This works fine.
Now, I need to create an exception only for users with role "administrator" that must see the complete list of taxonomies, without any filter applied.
I know how to check the logged user role in views, but I can't figure out how to avoid the contextual filter for the specific case.

IMPORTANT NOTE: sorry guys, I forgot to mention that the view will filter the taxonomies list in admin content-type form and not for the front-end pages.

Not entirely an answer to the question, more a workaround, but you could do it as follows.

Make sure to create a second page. It has to be identical to the original one (including the path), so you can clone it from the edit view name/description dropdown button. Then make sure to remove the contextual filter from this display only, and limit the access to users with the administrator role. Finally make sure this views page is listed before the other one (reorder displays in the edit view name/description dropdown button).

This works because views attempts to load the path, if there is no access for the first display, views attempts to load the second display.
So all users that have no administrator role will see the second display, while the admins will get the first display without contextual filter.


Drupal 7 Views Question - How to pass 2 arguments Using Drupal 7, Views 3.

I am attempting to pass a node reference  "department" as first argument via contextual filter.  The department has a number of employees, where I would then want a Views glossary to view by employee name by clicking on a letter.  That is:

Department is Finance, the Views glossary will allow them to choose all employees with last name start with 'A'.  the url will be:

organization/Finance/department/A/staff-listing or in views path, would be
organization/%/department/%/staff-listing

I have cloned the glossary view and am able to get the department with employee listing.  However when I click on the glossary letter, the url is changed to organization/A/department/%/staff-listing INSTEAD OF organization/Finance/department/A/staff-listing

When I manually enter the URL ../Finance/department/A/staff-listing , I am getting the right results.  However, when I click on the letter from the glossary, it goes to the first argument.

I appreciate any advice or thoughts on this.

I think I know the answer.

I suppose the path to your view without any arguments is "organization".

So first you need to add the contextual filter "department" to the "attachment"-display too. This filter needs to be in first position.

Then:

When filter value is not available > check "Provide default value" > type= Raw value from url> Path component= "2" > save this filter.

Next:

Still inside "attachment"-display open up contextual filter "Content: Title" and change Display a summary > Base path to "organization/%/department/%/staff-listing".

Hope this helps


How can I use the web service with one or none arguments? I have a web service with the Services module that works perfectly, with an URL like myweb.com\api\my_conent\124 I obtain the information of my_content that has the 124 id.

Now with the URL myweb.com\api\my_content I want to obtain all the contents of my_content, but it doesn't return anything, a blank page. I have the 'optional' => TRUE, for the arguments.

How can I use the web service with one or none arguments?

Do you have an 'index' operation?
Take a look at the services.services.api.php file in services module, docs folder.

In the node resource, you have several different 'operations' ( retrieve, create, update & index, .. ).
Here's the snippet you should look at:

$node_resource = array(
    'node' => array(
      'operations' => array(
        ..
        'index' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/node_resource'),
          'callback' => '_node_resource_index',
          ..
        ),
      ),
    ),
  );
  return $node_resource;

GET request to endpoint + resource will trigger 'index'. Read more about it here https://drupal.org/node/783254


How do I export a site without it's Node data? I have a site with very high volumes of data (1000+ nodes per day * 3+ years and growing each day). When we need to create a development snapshot of this database it takes FOREVER to import it.

I know this is a long shot, but is there a way to export this database without our node data? Specifically which tables can we excise?

I know as we add more and more custom modules, more and more things will break when we do something like this. But let's say we are just using Drupal 6 core modules with CCK. Would it be possible then? If not, what would we break by doing this and could breaking it be fixed?

Could you just export the db in a typical fashion?  Via PHPmyadmin or command line?

Also, Backup and Migrate lets you choose to export table structure without data.


Check content type of node in preprocess hook I have a series of variables I want to make available on twig templates for specific content templates.

In MYTHEME.theme I have:

function MYTHEME_preprocess_node(&$variables) {

  if (isset($variables['node'])) {

    $mycustomblock = \Drupal::service('plugin.manager.block')
      ->createInstance('myblock', []);

    $variables['mycustomblock'] = $mycustomblock->build();

    $headertext = \Drupal::service('plugin.manager.block')
      ->createInstance('headertext',
        [
          'text-align-submit'  => 'right',
          'uppercase-submit'   => TRUE,
          'header_size'        => 'h4',
          'header-size-submit' => 'h4',
          'grid-size-submit'   => 6,
          'header-title'       => 'This is a test',
        ]
      );

    $variables['headertext'] = $headertext->build();
  }
}

This allows me to use {{ headertext }} and {{ mycustomblock }} in content type templates like node--contenttype1.html.twig and node--contenttype2.html.twig. But I'd rather not build the 'headertext' and 'mycustomblock' variables for every single node type when I only need each one for one content type. It'd be nice to have a switch or if statement that checks which content type it is before generating a variable with a block.

Is there a way that I can check the content type of the node?

I've tried

$type = $variables['node']->type;

But that did not work.

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't make much difference.

public function getType() {
  return $this->bundle();
}

The only difference is that bundle() is defined for every entity, since the concept of bundle is common for all the entities, while content type is the property Drupal used for nodes before changing them in one of the entities Drupal core modules implement; using bundle() makes easier to adapt the code for other entity types, but I don't think it is the case for the code you are using.


Is EntityFieldQuery really this inefficient? I am an admitted newbie to the Entity API, but am trying to cure that.  I'm working on a site that uses a number of content types with various fields attached to them; nothing fancy.  So, when I want to retrieve a set of entries, I have been, in my ignorance, calling directly down into the database and doing something like this:

$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n', array('nid'));
$query->condition('n.type', 'my_content_type');

$query->leftJoin('field_data_field_user_role', 'role', 'n.nid = role.entity_id');
$query->condition('role.field_user_role_value', $some_value);

$query->leftJoin('field_data_field_withdrawn_time', 'wt', 'n.nid = wt.entity_id');
$query->condition('wt.field_withdrawn_time_value', 0);

$query->orderBy('n.created', 'desc');

$query->limit(10);

$result = $the_questions->execute()->fetchCol();

(yes, I could probably collapse a bunch of these lines into a single $the_questions-> statement; pls ignore that for now.)

Trying to rewrite this with EntityFieldQuery, I come up with:

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->fieldCondition('field_user_role', 'value', $some_value)
  ->fieldCondition('field_withdrawn_time', 'value', 0)
  ->propertyOrderBy('created', 'desc')
  ->pager(10);

$result = $query->execute();

if (isset($result['node'])) {
    $result_nids = array_keys($result['node']);
}
else {
    $result_nids = array();
}

which gives me the desired results and is surely much prettier.

So, now I'm wondering about performance.  As a start, I throw each of those bits of code into a stupid for() loop, capturing time() before and after execution.  I run each version 100 times over a not-very-big database, and get something like this:

Direct version: 110 msec
EFQ version: 4943 msec

Obviously I get different results when I re-run the test, but the results are consistently in the same ballpark.

Yikes. Am I doing something wrong here, or is this just the cost of using EFQ?  I have not done any special database tuning with respect to the content types; they're just what comes from defining the content types in the usual, form-based way.  Any thoughts?  The EFQ code is definitely cleaner, but I really don't think I can afford a 40x performance hit.

The EntityFieldQuery class is as efficient as its requirements allow it to be. It needs to be compatible with any field storage classes, even with those that use a NoSQL engine to store the field data, such as the one that uses MongoDB. For that reason, EntityFieldQuery cannot directly query the database, because the current field storage backend might not use an SQL database at all.

Even in the case the field storage uses a SQL engine to store its data, the equivalent of $query->leftJoin('field_data_field_user_role', 'role', 'n.nid = role.entity_id'); $query->condition('role.field_user_role_value', $some_value); for the EntityFieldQuery class requires:

Code to build the database table name from the field name
Code to build the condition to use to join the table containing the field data with the table containing the entity data
Code to build the name of the database row containing the field data

The difference is immediately visible: In one case you are using three litteral strings, while in the other case there is code that (in the simplest of the cases) is concatenating strings.

As per your comment about code that checks if the user has the permission to access the fields, you can bypass that using the following line to the code using the EntityFieldQuery class.

$query->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

This works if you are using Drupal 7.15, or higher; for earlier versions, you should use the following code.

$account = user_load(1);
$query->addMetaData('account', $account);

As usual, you should not bypass the access permission if the code could show to the user information to which the user should not have access. This is similar to what is done from Drupal when an unpublished node is only shown to the users who have the permission to see unpublished nodes. If the code's purpose is, for example, selecting some entities that are successively deleted (e.g. during cron tasks), then by-passing the access control doesn't make any harm, and it is the only way to proceed.


couldn't load site name in html template <?php print $site_name; ?>

Why I couldn't perform the above code in 'html.tpl.php'. This works find in page template. Please suggest how to load this in html template

There's no $site_name variable added to html.tpl.php, but you can add it yourself quite easily with a preprocess hook:

function MYTHEME_preprocess_html(&$vars) {
  $vars['site_name'] = variable_get('site_name', 'Default');
}


Select all nodes that reference the current node I'm new to Drupal and am wondering if anyone could provide direction on this.

Basically I have 2 content types - one called 'clinics' and one called 'clinic groups'. Each 'clinic' has a node-reference to a 'clinic group' node. What I'm trying to achieve is basically, if I'm on the 'clinic group' page - I'd like to pull back all the nodes 'clinics' under it, that reference it.

Is this possible in views?

Thanks everyone.

You could do this using views.Create a view where under

Fields you select your group as Node, Under that choose Title.

For Filters select Node Type, Operator: Is one of and select Clinic content type.

Under Arguments select your group as Content. Under that choose Clinic_group (the node reference field).

You can add additional parameters to your view like Number of items to display, more fields like Node: Body and maybe a filter that Node: Published, select yes.

To see a preview, under live preview give the arguments as node number and click Preview.

Hope this helps!


Displaying custom module content in a popup from other page I have a custom module which displays listings and info about realties. How can I display realty's images in a popup from other page?
In example I have info about realty on realty/566 and it's images can be viewed realtyimages/566

You may want to use the Lightbox2 module.
It will display it in the same window but look like a pop-up in page, like in Facebook.


Apply the timezone offset to my date field I use the Date Module. My contenttype event dates are stored like

field_date['de'][0]['value'] = 2011-12-09T10:40:00 (String, 19 characters )
field_date['de'][0]['value2'] 2011-12-09T13:10:00 (String, 19 characters )
field_date['de'][0]['timezone'] Europe/Berlin (String, 13 characters )
field_date['de'][0]['timezone_db'] UTC (String, 3 characters )
field_date['de'][0]['date_type'] (String, 4 characters ) date | (Callback) date();

How to apply my timezones to the values? When I edit the date on my field_date and also when my dates are displayed, everything is fine. But I have to work with the raw DB values and need to apply the timezone. Doing it by hand with php +1h should work, but then it's summertime again....

This took me a hot minute to figure out...
Use the format_date function, but be sure to specify how the date is stored in the db - usually UTC, and then offset by your date field's stored timezone - usually your drual admin specified default timezone.

foreach ($node->field_date['und'] as $date) {
  $unixdate = strtotime($date['value'].' '.$date['timezone_db']);
  print format_date($unixdate,'medium','',$date['timezone']);
}


Create a new facet block from Taxonomy terms Hi I am using recruiter distribution, I have creates a new taxonomy named as trades, having few terms, Now I want to create a facet block from these taxonomy terms, could anyone please suggest me any tutorial for doing this. I already have few default facet blocks provided by recruiter distribution. I could not find any proper tutorial regarding creation of facet from taxonomy terms.

Thanks

Here is a tutorial for creating facet blocks :Faceted search using search api tutorial

To add a taxonomy term as a facet just check the fields tab to find your term field and enable it and after enabling it you have to re-index and now your facet can be rendered as a block !!!


Using drupal_add_js with google maps I want to pass down an array to my javascript. So that i could create markers on google map.

By doing this:

drupal_add_js('https://maps.googleapis.com/maps/api/js?key=AIzaSyDcl28Qcn9GTi02rRtQaLgVS4GWZbGcQ8E', 'external');
$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');
drupal_add_js('sites/all/modules/GoogleMapByDave/DGMap.js','external');

The javascript that is DGMap.js dosnt seem to work.

Here is the js in the DGMap.js:

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

  //var locations = Drupal.settings.myModule.locations;

 function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var locations = [
                    ['Mājas',56.956344, 24.197409],
                    ['Domina',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

     }

      google.maps.event.addDomListener(window, 'load', initialize);

   }
   }
)(jQuery);

But if I add it through the module as an inline it works! But I dont know if i can use the variables there?

drupal_add_js('jQuery(document).ready(function () { function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById(\'map-canvas\'),
        mapOptions);

    var locations = Drupal.settings.myModule.locations;

    var locations = [
                    [\'Mājas\',56.956344, 24.197409],
                    [\'Domina\',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][\'locationLat\'], locations[i][\'locationLng\']);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][\'locationTitle\']
      });
    };

  }

  google.maps.event.addDomListener(window, \'load\', initialize); });','inline');

EDIT//////////////////////

I got further in this. Adding script like this:

$path = drupal_get_path('module', 'GoogleMapByDave');
drupal_add_js($path . '/DGMap.js', array('weight' => 1));

And the script:

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

var mapOptions = {
    center: { lat: 56.9714744, lng: 24.1291624},
    zoom: 9
};

var locations = Drupal.settings.GoogleMapByDave.locations;
alert(locations);

var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

var locations = [
                ['Mājas',56.956344, 24.197409],
                ['Domina',56.966058, 24.162004]
                ];

for (var i = 0; i < locations.length; i++) {

  var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

  var marker = new google.maps.Marker({
      position: loc,
      map: map,
      title: locations[i][0]
      });
  };
}
};

Now the script is runned. But the problem now is that how can i get settings? I get unidentified from "locaitons" var.

Btw i changed the $settings['GoogleMapByDave']['location'] part.

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

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

or use an absolute path.

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


Keep locations in drupal I have created a form where customers select two fields for a transportation. From origin to destination. My list of geographical locations could be close to 5,000 records. What is the best way to keep this location in the database? Taxonomy or store as a list for selection on each field?

Any recommendation is more than welcome. I'd need to store something like this:

El Salvador SVCSC   Cara Sucia  Cara Sucia, SV  SVCSC|Cara Sucia, SV

El Salvador SVCNG   Chalatenango    Chalatenango, SV    SVCNG|Chalatenango, SV

An important point is that I need users to select this with autocomplete like any airline website does (Kayak, Hipmunk, etc).

You should create a content type Locations

and add the following as form fields
1.cities
2.states(Provinces)
3.countries

Use two modules

Entity Reference

Use a field entity reference in your custom form for origin and destination with content type locations
Tokens  3. Auto nodetitle
By installing the tokens and auto node title you can set the title for locations as per your needs
like [field:cities]|[field:province]|[field:country] in the edit link of content type locations

the title u set for the content type will be used in the origin and destination field . You can set your field as autocomplete as well as follows:

function module_name_menu() {
  $items['location/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('access location autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function module_name_form() {
  $form = array();

  $form['origin'] = array(
    '#title' => t('origin'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

  $form['destination'] = array(
    '#title' => t('destination'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

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

  return $form;
}

function _module_name_autocomplete($string) {
  $matches = array();

  $query = db_select('locations', 'loc');
     ->fields('loc', array('title'))
    ->condition('c.title', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->title] = check_plain($row->title);
  }

  // return for JS
  drupal_json_output($matches);
}


Arguments in url break other view on same page Whenever I go to a url that has parameters in for example www.sitename.com?page=1

It breaks another view that uses contextual filter and looks like this

Why is this happening?

Turns out. If you have a view page with a pager and another view block with a pager on the same page, they conflict.


Adding an image to a media bundle's field I am trying to add create a piece of new media with the following code. When visiting the media overview screen the media item is listed along with a thumbnail however when you edit the media item the file is not attached, although the file exists in the files area?

use Drupal\Core\Language\Language;
use Drupal\media_entity\Entity\Media;

$data =     file_get_contents("https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
$file = file_save_data($data, 'public://plane.jpg',  FILE_EXISTS_RENAME);

$image_media = Media::create([
  'bundle' => 'image',
  'uid' => '1',
  'langcode' => Language::LANGCODE_DEFAULT,
  'status' => Media::PUBLISHED,
  'field_image' => [
    'target_id' => $file->id() ,
    'alt' => t('this is the alt text'),
    'title' => t('this is an image'),
  ],
]);
$image_media->save();

Unless you have a default language setup, Language::LANGCODE_DEFAULT will resolve to x-default.

Either:

Set a default language
Set the property manually, e.g, 'en' rather than Language::LANGCODE_DEFAULT
Remove the line entirely


How to programmatically add default values to existing nodes of a specific content type On a Drupal 7 site, I have a content type that is populated with existing nodes. Later, I added a new boolean field (that is required). The existing nodes now have a blank value for this field.

How do I programmatically populate these nodes with a default value?

You may use module Views Bulk Operation. Then create views page like table and field title, your field, add field Content: Bulk operations (Bulk operations) with settings VIEWS BULK OPERATIONS -> SELECTED OPERATIONS Execute arbitrary PHP script (views_bulk_operations_script_action). Save, Open the page, select one node, choose Execute arbitrary PHP script

enter next code and execute:

//change entity title or what you want to do
$entity -> title = $entity->title . ' test';

//save entity
entity_save('node', $entity);


How to remove the "No front page content has been created yet." message from the front page? I only want blocks on the homepage. Because I don't have any nodes, and I want to keep the homepage as /node I am getting a "No front page content has been created yet." message on my page.

How do I get around this?

Who would have guessed? There's a module for that. Check out the Empty Front Page module. With only 10 lines of code, it must be one of the simplest modules out there.


Keep file download list of each authenticated users I have a content type "Application" and each "Application" content has a downloadable file.

I'd like to keep the downloaded file list, actually node list, & count for each authenticated users.

Is there any ready-made module provided for this feature ?
Or
How can I achieve it by programming ?

The Download Count module may be useful. The module page says

  The download_count module tracks downloads of private files attached
  to nodes via the core upload or contributed filefield modules for d6
  and private core file fields for d7.

But it has only development version for D7.


Fatal error: Call to a member function raw() on a non-object in I am getting this error

  Fatal error: Call to a member function raw() on a non-object in one of my custom modules.

Following is my function:

function _gocoop_services_get_app_instance($wrapper)
{
  $instance_id = $wrapper->field_seller->field_application_instance->raw();
  if (!$instance_id)
  {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'application_instance')
        ->entityCondition('bundle', 'application_instance')
        ->fieldCondition('field_internal', 'value', 1);
    $result = $query->execute();
    if ($result['application_instance'])
    {
      $instance_id = reset(array_keys($result['application_instance']));
    }
  }
  return $instance_id;
}

Have used the above function at couple of places like shown below:

$wrapper = entity_metadata_wrapper('commerce_product', $entity);
$instance_id = _gocoop_services_get_app_instance($wrapper);

Can anyone help me whats wrong as this has occurred all of a sudden.

You could try something like this instead, checking if the field value is set first and catching the exception.

function _gocoop_services_get_app_instance($wrapper) {
  $instance_id = FALSE;
  try {
    // Check if wrapper field set first
    if (isset($wrapper->field_seller) && isset($wrapper->field_seller->field_application_instance)) {
      $instance_id = $wrapper->field_seller->field_application_instance->raw();
    }
    if (!$instance_id) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'application_instance')
          ->entityCondition('bundle', 'application_instance')
          ->fieldCondition('field_internal', 'value', 1);
      $result = $query->execute();
      if ($result['application_instance']) {
        $instance_id = reset(array_keys($result['application_instance']));
      }
    }
  } catch (EntityMetadataWrapperException $e) {
    watchdog_exception('gocoop', $e);
  }
  return $instance_id;
}

You might also want to use a static cache for $instance_id, but that would need to vary based on your $wrapper id value.


CSS not applying in drupal 8 site I have upgraded my site from 8.1.3 to 8.4 after that, while i load any pages. CSS is not been applied

View source:

while inspecting in browser

Cases tried: Placed an image file in the (core/themes/seven) folder and I can successfully access it from the browser.

I have followed this and disabled the css/js aggregation. Css were applied.