Set field_id for views "Global: Custom text" field I have a view with several 'Global: Custom text' fields. These are actually just serving as place-holders, and I'd like to create a field template file for each, that essentially places some custom html/php when it encounters these fields in a view.

Almost everything is in place and working... except, I notice that Drupal automatically gives the id of 'nothing', 'nothing_1' etc to its global custom text fields.  So, if I have more than one of these global text fields and would like to create a separate field template for each, I'm presented with a problem.

I'd have to name my template files views-views-field-nothing.tpl.php etc.  This is undesirable, because I want to reuse these field templates throughout my site.  I shouldn't have to worry about ordering these global fields just so in my views, so that the one I expect to be nothing is 1st and gets that id and the one that I expect to be nothing_1 or nothing_2 gets that id...

Has anyone run into this issue before?  Any ideas whether I can set my own field-ids for global custom text fields in views, so they don't all have those generated id's?   Is there a module that does this out there?  My searching hasn't found anything yet.

Thanks for any guidance!

p.s.  The reason I'm doing this is because I'm trying to put some html in my view (like <fieldset>) that is getting stripped from the views fields, so I need to do it in a template file.

Well, sometimes the only way to solve a hard problem is to write your own module (or, as in my case, just collaborate with someone who's already writing such a module).

I'm now using the newly-launched Views fieldsets module to achieve what I was trying to do!


How do I override /theme/custom twig in my module to render input fields? I have a module that is building a form. I want to theme the form using twig within my module so it does not interfere with my theme/custom twigs.

My buildForm function is:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

I have set the theme for the form as custom_form and it works fine using this in my .module file:

function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_form' => array(
      'render element' => 'form',
    ),
    'input' => array(
      'template' => 'input',
      'render element' => 'element',
    ),
  );
}

However the input fields are still being rendered using input.html.twig file in my /theme/custom theme folder.

I have created copied the twig template file using the same name and placed it in my custom_module folder however Drupal is still using my theme input.html.twig file.

How do I override this twig and use the input.html.twig file in my custom_module templates folder?

Thanks

Found the answer after some intensive searching and looking at Drupal From API: Create a twig file for the theme, I called it custom-input.html.twig and place it in your custom_module templates folder. Then you tell Drupal about it using hook_theme() function:

function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_input' => array(
      'render element' => 'element',
    ),
  );
}

Lastly, in the buildForm function you say what theme will render the element like below:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
    '#theme' => 'custom_input'
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

This will tell Drupal to render the form input elements using the custom twig file you created.


Fail to enable booking time slot in D7 I am newbie to Drupal. I am trying to install booking timeslot module in D7. I've installed 7.x-1.x-dev version. However, I fail to enable the module.

The description for the booking time slots as below:

  Provides features for Booking Time Slots
  Requires: Booking Timeslots (disabled), Addressfield (missing), Calendar (enabled), Views (enabled), Chaos tools (enabled), Date API (enabled), Date Views (enabled), Date (enabled), Entity (missing), Entityreference (missing), Features (missing), Hierarchical_select (missing), Hs_taxonomy (missing), Hs_taxonomy_views (missing), List (enabled), Field (enabled), Field SQL storage (enabled), Options (enabled), Number (enabled), Opening_hours (missing), Taxonomy (enabled), Text (enabled), Workflow (missing)

Can anyone help to tell me what to do so that I can enable it?

The modules that in that list are followed by "(missing)" are the modules that are not present in the Drupal installation, and that are required from the module you are trying to install. Just install them, and you will be able to install the Booking Time Slots module.

The trick is understanding which modules you need. Since the modules are not found on the server, what the module page shows is not the module name, but the short name of the module capitalized.

The list of the modules that site needs is the following:

Entity API
Entity reference
Features
Hierarchical Select
Opening hours

As you see, the module pages says that the Opening_hours module is missing, but the module name is Opening hours, while opening_hours is the short name of the module, the same used in the URL for the project page. Join https://drupal.org/project with opening_hours, and you get the complete URL of the project page for the module you are looking for: https://drupal.org/project/opening_hours.

The list of modules is shorter because there are modules that are sub-modules of modules already listed as requirements.

The Opening hours module then depends from the following modules:

Date Popup (part of the Date module)
Tipsy


What module can create a gateway or doorway popup AD page before viewing content for Drupal 7? I'm looking for a module that can create gateway or doorway pages like on many publication sites where you have to view an AD first before letting you view the article.

The Splashify module should do exactly what you need. You can specify a list of the pages you want to redirect to an ad (you can use the wildcared (*) too) and a list of different pages to use for the ads, and they're choosen either random or in order. You'll have to create the pages for the ads though. How they get from the ad page to the content they requested may require a little PHP/javascript, I'm not sure.

http://drupal.org/project/splashify


Is comment fields data store in render array? Is render array contain key-value entries that is generated by node module only? or comments fields also included?

The render array for a node contains also the content of the comments, which is added by comment_node_view(), an implementation of hook_node_view(). That hook is invoked from node_build_content(), which is called from node_view().

The Devel module shows the following output for a node render array.

In Drupal 8, node_view() is a thin wrapper for entity_view(), which renders the node using entity_render_controller().


How to show Comments (created with entity form) only to the Admin user and logged in? I'm cool fresh drupal :)

I'm trying to filter views in a content type entityform for the user logged in and admin. In practice this form through the admin and user login should communicate.

problem: On page dein results I see only the one who wrote the admin, but the user responses.

Then I node (private area) with filtered content to the user, so each user sees the content added by the administrator for each user.

I would like each user to comment on the content that the administrator has reserved for each user.

Now I tried with modules or with the comments of core drupal views of seeps into single user comments and the admin.

example:
There are three users, User "A" User "B", User "C",
Each of these users comments posted content dall'aministratore reserved for them. The administrator shall have commmenti User "A".

The same node (private area) would like to display the comments and views with only the user "A" and the responses made administrator user "A". And so also for users B, C, D, F etc. ...

I hope to be as clear as possible. :)

Where am I wrong?
help me. :)

Sorry for my bad english

You might try updating PERMISSIONS.  By default, EntityForms only allows administrator to view, edit, or delete.  If you want a user to be able to view their own EntityForm submissions, you have to update the permission for this.  You can find it under PEOPLE->PERMISSIONS->EntityForms->View own entityform submissions-> [check] AUTHENTICATED USER.

Good Luck!

Chrisjan


How to programmatically truncate table in Drupal8 I'm wondering how to programmatically truncate a table in drupal8.

Like:

db_truncate('some_table');

Is this possible?

Sure, the function still exists: https://api.drupal.org/api/drupal/core%21includes%21database.inc/function/db_truncate/8.5.x.

It's deprecated, though, with the advice:

  Instead, get a database connection injected into your service from the container and call truncate() on it. For example, $injected_database->truncate($table, $options);

If you're not in a context where injection is possible, get it from \Drupal:

\Drupal::database()->truncate('foo')->execute();


How to translate views footer content? I am building a multilingual site using Drupal 7. I have used Views to generate a page, and in that page I have added a link in the view footer. The custom code that I use in my views footer is as below.

<?php To blog archive

My problem is that I am using i18n module to translate the contents. In the translate interface I get the full above code, and as a result I lose my footer in views. Is there any way by which I can translate the "To blog archive" instead of the full code?

Try changing your footer to the following:

<?php
$link = l(t('To blog archive'), 'blog-archive');

print $link;
?>

References:

l();

t();


Large amount of entity revision cleaning leads to connection abortion I am trying to remove revisions from each entity type which has the revision feature via drush command.
The amount of entities are quite a lot: around 10K nodes, 2k paragraphs.

On localhost everything is fine.
But in the cloud the drush_print($log) successfully runs and the following error appears:

 [warning] PDO::beginTransaction(): MySQL server has gone away Connection.php:1165
 [warning] PDO::beginTransaction(): Error reading result set's header Connection.php:1165

In Connection.php line 1165:

  SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

The two environments are close to identical. Any suggestions where could I start to investigate?

It turned out what the real issue was. I didn't mention (thought it's not important) that this was actually a Drush command pointing to another multi site.

The actions took "too long" on the other site and by the time it returned with success, the default Mysql connection was timed out and couldn't write to the database anymore. (even tho the corresponding Mysql timeout settings were way higher than the actual amount of time that was spent on the other site)

We solved with with

$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes);
if (!is_resource($process)) {
  throw new \InvalidArgumentException("Could not execute `{$command}`.");
}
while (($status = proc_get_status($process)) && ($status['running'])) {
  $this->entityStorage->getQuery()->count()->execute();
  sleep(5);
}
proc_close($process);


D8 Migration: Can 'Default Bundle in Destination Plugin be dynamic? My goal is to take an existing D6 content type ('mini') and migrate it into one of two specific D8 content types based on its current D6 URL Alias (either 'course' or 'page') and where this alias falls in the hierarchy.

I've have successfully written a simple source plugin that adds the alias into RowSource.

How do I control the destination plugin so I can migrate into the appropriate bundle - either 'page' or 'course'?  Is there any property of $row that can be adjusted to do so?

Or is this process more involved?

I know that nodes use the 'entity:node' destination plug-in, but how can I extend this per above? It's unclear to me what exact class the destination plug 'entity:node' represents

Any insight would be much appreciated.

Thanks!

In your config, use a row instead of the default value plugin.

Instead of this:

process:
  type:
    plugin: default_value
    default_value: course
  title: title
  etc.

use this:

process:
  type: target_bundle
  title: title
  etc.

Then you can set the target_bundle dynamically in your source class's prepareRow function.

$row->setSourceProperty('target_bundle', $target_bundle);


Make webform submissions non-editable? I have created a web site with a bunch of Webforms used to collect data from surveyors.  My client is interested in having the ability to make individual submissions non-editable by the surveyor while not removing the ability for surveyors to edit their own submissions generally.  In other words, she wants the surveyors to be able to edit their submissions at her direction, but once she considers the submission complete, she wants to lock it down and prevent further editing, partly to prevent confusion if the surveyor perhaps has two or three different webforms they are working on.

Do you know any way to do this?  Thanks!

Checkout the "Content Access" module:
https://www.drupal.org/project/content_access

Once your client wants to "Lock down" the webform, she can do so within the Role Based and Per Content Node access control settings.

Hope this helps.
-Wrench


Create Related Terms Block Showing Terms on Taxonomy Term Page Hi i have been hunting high and low for years to create this and i still havent found an answer. I have seen folks looking for similar but these questions usually went unanswered as if the answer is still unknown.

Im using views 2 and drupal 6. I am using the 'related terms' bit of when i edit a term. I would like to show the related terms to a term when viewing a taxonomy term page. I dont want to show nodes just terms.

I have created a term view and have played about with the Taxonomy: Related terms argument and Taxonomy: Related terms relationship but to no avail.

It sounds like quite a simple thing for drupal and views but for some reason there doesnt seem to be a definate answer to this. all help appreciated. thaks

First off, I wanted to let you know that this is not necessarily intuitive, and there's very hacked methods of doing this. Another thing that I want to mention is that I did this in Drupal 7 with Views 3. However, one of the things that I think is most different is the UI. So text descriptions should be able to guide you. :)

The way that I went about doing this is as follows:

In Views, I created a block which is to display the content type of the related items (mine was recipes). I added the fields which I wanted to appear, which were just pictures and titles. Then in Contextual Filters (I think D6/Views2 calls this arguments), I added two.

The first is "Content: Nid" and I configured it as follows:
When filter value is not available => Provide default value => Type: Content ID from URL. Under "more" (not sure what V2 calls it), there's an option called "exclude", which if selected, the numbers entered for the filter will be excluded rather than limiting the view. This is great because it essentially says, "Return me the list of everything of this content type EXCEPT this one that I'm on."

The second filter is "Content: Has taxonomy term ID". This one was a bit trivial because I want to provide relationships on multiple vocabularies of taxonomy terms. So it's configured as follows: When the filter value is NOT available => Provide Default Value => Taxonomy term ID from URL => Load default filter from node page => Limit terms by vocabulary => Selected my vocabularies => Multiple-value handling -> filter to items that share any term.

When the filter value IS available or a default is provided => Specify validation criteria => Validator = Taxonomy term, with my previous chosen vocabularies selected again => Filter value type => Term IDs separated by , o + . Under "more", I checked "allow multiple filter values to work together."

This was the way that I was able to get the related content. I specified the amount of results that I wanted in the pager.

Hope that this helps!


Hiding link from anonymous users How can I hide a particular link in the main menu from anonymous users without making the whole menu invisible?

You don't so much configure the visibility of links directly, but rather you configure the permissions of specific content types, and any link to content of a particular type will either be visible or invisible depending on the permissions of the content the link points to.

You can configure the permissions on any given piece of content by going into the Permissions section in Administration and finding the content type you want to restrict permissions on, and configure those permissions (check boxes for view, create, edit, etc..) based on role appropriately.

If you need to configure access to specific nodes/content, then you might have a look at Content Access.


Determine conditions for Rules when changing field value I've a Rule with below specification

Events:
After updating an existing user account

Conditions:
???

Actions
Create a Message

But I don't know how can I set a condition on field in rule condition part that return true when the field changed,any body know how can I add condition on specified field that return true when the field changed?

You need to create the rule for Before saving content rather than After saving content.

Before saving content has both the original node values and the new updated values which allows you to compare the values.

After saving content only has the updated values, so you won't be able to see what the old values are.


how can i add classes to the content I'm trying to add class to the content, however its not adding anything

    function themename_preprocess_page(&$vars) {
      $is_sidebar_first_or_second= (empty($vars['page']['sidebar_first'])) || (empty($vars['page']['sidebar_second']));
      $is_sidebar_first_and_second= (empty($vars['page']['sidebar_first'])) && (empty($vars['page']['sidebar_second']));
      if ($is_sidebar_first_or_second) {
        $vars['page']['content']['#theme_wrappers'][0] .= ' one-sidebar';
      }

      if ($is_sidebar_first_and_second) {
        $vars['page']['content']['#region'] .= ' two-sidebar';
      }

    }

can anyone help me on this?

Have you tried this code ?
I have taken it from here

// Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }


How can I use the "Taxonomy display" view on the Panels taxonomy override page? I'm trying to change the weight of Page Manager module to enable the taxonomy term template in Panels. This is the error I'm getting:

Page manager module is unable to enable taxonomy/term/%taxonomy_term because some other module already has overridden with views_page.

I tried to change the weight directly from phpmyadmin but the weight field in page_manager_handler table is empty. I also tried the util module but it is not adding the required 'module weight' column in the module listing. Also it clashes with Module Filter module causing drupal to go crazy with a lot of errors.

Any suggestions?

In this case, you don't need to adjust the module weight-- you need to remove the override on the taxonomy term pages.

Are you already overriding the taxonomy term display in Views?  If so, just disable that view and the error should go away.

EDIT: If you still want to use the taxonomy view in Panels, you should edit the view as follows (I do this on one of my sites):

Open the edit screen for the Taxonomy display view.
Click page.
Where it says clone page, click the triangle and select disable page.
Click Add.
Choose Content pane.
Add the content pane.
Click Argument input.
For the first argument, choose From panel argument and First.
For the second argument, choose From panel argument and First. (identical to the settings for the first)
Go to your panel and add this content pane instead of the page (it will appear under View panes).

Why do you have to do this?  Because otherwise Views and Panels will fight each other over who controls the page.  By using a content pane, you avoid assigning a URL path in Views, allowing Panels to override the path successfully.


What hook for installing a large list of field options? If a custom module installs a dropdown-style field, using a large internal list of options (about 200 items), should this list be populated in hook_install or hook_init for greatest efficiency?
Yes, I know, with such an extensive list, I should provide an ajax-driven widget for ease of use, but at this stage of development and my skills this is a side issue :)

I would probably use the List field predefined options module.


How do I populate fields in content type not in feed when importing? I have a content type that contains a couple of required fields that do not have a mapping counterpart in the csv feed.  When I import the csv feed, the process fails because of the required fields.  What plugin can I use in a custom module to 'finish' the import by providing the values for the other fields?  Is this even possible?

You can use the Feeds Tamper plugin "Set value or default value".

Install the modules Tamper and Feeds Tamper.
Go to the mapping page.
Select a target that you want to set a default value for.
On the source selector that appears, select "New CSV source". Type in a source name that does not appear in your CSV file.
Repeat step 2 and 3 for every field you want to set a default value for and save the mappings.
Go to the 'Tamper' page.
For each target you want to set a default value for, click on "Add plugin". From the selector that appears, select "Set value or default value".
A field called "Value" appears. Fill in the default value and click "Submit".


How to hide Profile2 entity fron user view? I have a few profile2 types. Profile2 entity is always rendered on standard user view page.

How can I hide this entity? I know I can hide all fields in Manage Display tab, but I wondering if there is a way quicker way.

At admin/people/permissions you can configure what user roles are allowed access to the Profile 2 profiles on a per-profile-type basis. So if you're alright with letting admin users see the profiles, you can hide them for everyone else with the permission controls.


Form element validation #element_validate not working I am porting this contrib module to D8 and need some help.

The module is shipped with a custom node type. Certain elements options in the node_form will be populated dynamically. Also other modules needs to able to provide options for these fields.

hook_form_FORM_ID_alter calls the wrapper class MyModuleManager that performs several helper duties. All is going well except that I can not get the custom element_validation to work.

Upon form validation a warning is generated

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'FilebrowserManager' not found in Drupal\Core\Form\FormValidator->doValidateForm() (line 282 of core/lib/Drupal/Core/Form/FormValidator.php).

together with the fatal error:

Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /var/www/drupal8/core/lib/Drupal/Core/Field/WidgetBase.php on line 376 and defined in Drupal\Core\Field\WidgetBase->massageFormValues() (line 511 of core/lib/Drupal/Core/Field/WidgetBase.php).

The fatal error occurs exactly when validating $form['my_field']

class MyModuleManager implements MyModuleManagerInterface {
  use StringTranslationTrait;

  public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
    ...

    return $form;
  }

  public function addFormDefaultOptions(array $form, FormStateInterface $form_state) {

    // Replace MyModule_hook by Events
    // ...
    // Events returns dynamic $options

    $form['my_field']['widget']['#options'] = $options;
    $form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

    return $form;
  }

  public function myModuleValidateTrue() {
    return;
  }

}

As the warning tells it can not find the callback in FormValidator I suspect the problem might be the way I wrapped my code in this class. Being new to OOP I would appreciate all help.

It's probably this line:

$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

Which should be this, without parentheses in the method name:

$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue'));

See PHP: Callbacks / Callables for the full story.


Programmatically get input format in field template We change some output in our field.tpl-files for body fields, depending on the input format that was used on the node (which itself depends on the user being able to modify it).

Now this worked by drilling down to $element['#object']->body["und"][0]["format"] but that's hardly best practice as illustrated by helpful articles.

But – what is the correct way to get a reliable, language-agnostic variable like $ouptut['format']?

Thanks for any infos on that!

I would suggest you to create separate template based on field's text format.
Here is the way:

Create a TEMPLATE_preprocess_field function in template.php file of your theme.
Copy and paste a file named "field.tpl.php" and rename it to "field--[your-field-name]--[its-text-format].tpl.php.

The function is :

function MYTHEME_preprocess_field($variables) {
  switch ($variables['element']['#field_name']) {

case 'body':
  $element = $variables['element'];
  $entity_type = $element['#entity_type'];
  $field_name = $element['#field_name'];
  $language = $element['#language'];
  $entity = $element['#object'];
  $values = field_get_items($entity_type, $entity, $field_name, $language);
  $item = array_shift($values);
  $format = $item['format'];
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $format;
  break;
      }
    }


Server connect time significantly increased over the time I run my web site on D7 with enabled Cache pages for anonymous users option Cache blocksis off. It works pretty fast for non registered users but I started to observe significant difference for registered users (they can create content and do other things) over 2 months. Server connect time has grown. What can be a reason for that and how can I fix it?

You can use block cashing for users
you can check this link for more details https://www.drupal.org/node/326504
Check your MySQL server memory.


Instr() function on drupal I need a funtionality for search tags from a textarea (drupal form), I make it from sql, then, mysql have this function:
https://dev.mysql.com/doc/refman/5.0/en/string-functions.html
I believe that oracle/pql does have same function.

select * from cms_tags ct
 where instr('Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry', ct.name);

How can I use that query in drupal way? using db_select() or something else.

A plain db_query() might be easier for this particular query, but if you want to use db_select() you can make use of the SelectQuery::where() method:

$string = 'Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry';

$query = db_select('cms_tags', 'ct')
  ->fields('ct')
  ->where('INSTR(:string, ct.name)', array(':string' => $string));


How do I share views on multisite in drupal 8 Is it possible to have a multisite set up in drupal 8 and create view on Site A and have that appear on Site B?  I cant find anything in drupal documentation for sharing views.  I can share users, content, and taxonomy, but nothing else.

Multisite sharing works by using the same prefix for certain tables. It's dark magic, especially in 8.x, with the automatically created entity and field tables.

Since all config is stored in the same table, that's not possible.

You could write a custom config storage controller that stores certain config in a shared table, but that seems like a very crazy idea to me.

Configuration can be exported/imported and probably doesn't change that often. There will also be modules like features and others that will make re-using configuration easier.

I would also strongly recommend to consider other options to share your content. I can't imagine that this works reliably in 8.x.


Show custom query page based on user logged in I want to make a customized query page based on the user who is logged in. The query page is a node made in custom made content type "query"(this content type has no additional fields than which are created in a new default content type)

I have a <p id = my_para> tag in my node. I call an external query.js script in my node which uses xmlHTTPRequest to call an external query.php. This php connects with mysql and does a query like

select * from my_table where user = "logged-in-user";

and returns the query result using json_encode back to query.js. The query.js parses json and displays it on my node using document.getElementById("my_para").innerHTML = my_parsed_json_variable

So I some how want to get the logged in user details(there can be many logged in users to mysite at the same time) so that each user can see a custom page through these scripts.

How can I get the user details in my external query.php ?
I tried using these in my query.php

global $user;
$name = $user->name;
$id = $user->uid;

But it gives

  Trying to get property of non-object in
  C:\xampp\htdocs\mywebsite\sites\all\themes\danland\query.php

If your page is being created via code, then you can check the role of the user via code and not display the filters you want.

Otherwise, you may want to create different query pages for different roles and enable the right page for the right role using a module that restricts access such as the 'node access' module.


custom field - How to get saved term selected for entity_autocomplete I've looked all over, and for my level of understanding, I can't figure out how to get the stored value of an entity autocomplete field targeting taxonomy term type. I thought I could do something similar to what I have for select field, but it breaks the page. This is for a custom field...

    $element['description_term'] = array(
      '#type' => 'entity_autocomplete',
      '#target_type' => 'taxonomy_term',
      '#selection_settings' => [
        'target_bundles' => [
          'descriptors'
        ],
      ],
      '#title' => t('descriptor'),
      'default_value' => previously-entered-value,
      // this didn't work... '#default_value' => isset($items[$delta]->descriptor) ? $items[$delta]->descriptor : NULL,
      '#required' => FALSE,
  );

with some help above from Ajay Reddy, I was able to finally get to something that worked... Here's what did it:

  '#default_value' =>
  \Drupal\taxonomy\Entity\Term::load($items[$delta]->description_term),


How do I pass an organic groups GID to a view in a pane? I have a drupal 7 site using Organic Groups, for each group I have list pages - so for instance if i have the group mygroup I have a page which lists all posts - (www.mysite.com/groups/mygroup/posts). This page has a groups audiance field (og_group_ref) which has the correct gid..

I have the list page set up with panes one of which is a view showing all posts with the contextual filter set to GID.

The view works on its own if I pass in the GID of the group I want, however, I cannot get this to cooperate with the list page, probably something to do with the pane, or panels, or a relationship I need to add to the view?

I've tried inserting the view into the pane as a content pane and as a block, but I'm having no joy...

What do I need to do to get this to work?

I have since found this post:

How do you display a pane in an organic group?

this seems to be the answer to what I'm looking to do, however, the settings shown in that post are not available to me. Maybe because panels/views/og have been updated and the settings are a little different now? Either way I still don't have this working. Does anyone have any pointers?

Solved it like this:

Create a "Content pane" view mode of your view, and set "Argument input: Input on pane config".
Create a contextual filter in your view that expects a group ID value.
Enable the "Tokens" display mode for content type with the og_group_ref field. According to here:

Go to "Structure → Content Types → [your content type] → Manage Display".
Click "Custom Display Settings" below the field list, enable the "Token" option and save.
Go to the new "Token" display mode in the horizontal tabs on the top.
For yourog_group_ref field, set "Format: Entity id" and save.

In the Panels configuration of your list, insert your View pane.
In the View pane config form, there will be a single input field expecting a gid value and saying "You may use keywords for substitutions." below. Enter %node:og_group_ref.

How I think it works: Panels allows CTools context keywords when supplying arguments to panels. These context keywords are automatically available for all fields (%node:nid works out of the box) and all defined tokens (examples). But for fields, they evaluate to the formatted field value, such as your group's name. We could change this behavior by defining a token of the same name, and choosing a formatter that outputs the raw value (the number) when that token is evaluated.

References:

This Drupal SO question, providing the basic technique.


Expose a filter to turn a different filter on or off I have a view of items that have a due date, and I want to be able to expose a boolean filter "Is overdue by more than 30 days"

I can create a filter on this due date as a relative date filter "<= today -30 days"; however this filter is always active on the view.

The best I've been able to come up with is to add a new boolean field on my content type "date_filter" that is always null, and in the view create a new exposed filter "is not null" (i.e, when active, will always be false).
Then add this filter to a new OR filter group with the above relative date filter. This works, as when the filter is "off" it returns true and overrides the relative date filter. When on, only the rows that fit the date filter are returned.

However, is there a way to do this without adding dummy fields? Ideally a module I can use to do this. I'd prefer not to have to write a hook just for this filter.

There is a module for that; you can use Views Dependent Filters which allows the presence of exposed filters on a view to being controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.


Programmatically set the block visibility I set Configuration type to Block and selected my custom block to export the configuration from development/configuration/single/export. I got the following block visibility configuration.
visibility:
  _menu_position:
    id: _menu_position
    _menu_position:
      'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186': 'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186'
      'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87': 'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87'

For this, I have used the following function.
function placeBlock(EntityInterface $entity) {

    $config = \Drupal::configFactory();
    $settings = [
        'plugin' => '_block_module_block', // Set the plugin id
        'region' => 'header', // Set region to header
        'id' => $entity->id() . '-_bm_autoheader', // Use the page id and the module name for machine name
        'theme' => $config->get('system.theme')->get('default'),
        'label' => $entity->label(), // Use the page label
        'visibility' => [],
        'weight' => 0,
        'label_display' => 0, // disable label
        'page_id' => $entity->id(), // Reference page
    ];
    $values = [];
    foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
        $values[$key] = $settings[$key];
        // Remove extra values that do not belong in the settings array.
        unset($settings[$key]);
    }

    foreach ($values['visibility'] as $id => $visibility) {
         $values['visibility'][$id]['id'] = $id;
    }

    $values['settings'] = $settings;
    $block = Block::create($values);
    $block->save();
}

In my case, $visibility gets a NULL value.
langcode: de
status: true
dependencies:
  module:
    - _block_module
  theme:
    - _drupal_theme
id: 57148-_bm_autoheader
theme: _drupal_theme
region: header
weight: 0
provider: null
plugin: _block_module_block
settings:
  id: _block_module_block
  label: 'Header Contact'
  provider: _block_module
  label_display: '0'
  page_id: '57148'
visibility: {  }

I need help to understand the block visibility setting. How does it work in Drupal 8? How can I programmatically set it?
Thanks in advance.

I have found the solution, set the visibility configuration by the following function using $menuLinkItem->uuid().

  function setVisibilityConfig($instance_id, array $configuration)

$block->setVisibilityConfig('_menu_position', array('id' => '_menu_position',
        '_menu_position'=> [
              'main:menu_link_content:'.$menuLinkItem->uuid() => 'main:menu_link_content:'.$menuLinkItem->uuid()
            ],
        'negate' => null,
        )
    );

Thanks, @SumitMadan for helping out to understand the visibility concept.


Creating a News Blog in Drupal Can anybody help me with this, any help is appreciated.

I want to create a news blog where any anonymous user can put the news post, but for posting news article,
the user must provide their valid email, the verification mail should be sent to that user. News should only be posted after only the email is verified.

This has been discussed at Use email to validate post, not unlike craigslist.

A module that is still in alpha is also available:

https://drupal.org/project/anonymous_publishing

The module is not widely used, thus not extensively tested. It might be safer to write your own rules as discussed in the first link.


How to provide theme override for stylesheet conditionally included by a module I have a module that conditionally includes a stylesheets using #attached on a render array it outputs. (By conditionally I'm meaning that sometimes the module adds the attached css, sometimes not; I'm not referring to conditional stylesheets as in "is it IE9".)

The render array the module outputs includes the following:

$output['#attached'] = array(
  'css' => array(
    'tiles-styles.css' => array(
      'data' => drupal_get_path('module', 'mymodule') . '/css/tiles-styles.css',
      'type' => 'file',
    ),
  ),
);

In my theme, I have css under a css/ directory. I want to override both these, but only when they are required.

It seems that by adding

css[tiles-styles.css][data] = 'tiles-styles.css'

to my theme.info file I can get my file included, and it overrides the
module-provided one. However, doing this also includes this stylesheet on
every page load, which is unnecessary.

Is there a way to override the stylesheet but only if the stylesheet was included in the first place?

You can do this by implementing hook_css_alter as follows:

/**
 * Implements hook_css_alter().
 */
function mytheme_css_alter(&$css) {
  if (isset($css['tiles-styles.css'])) {
    $css['tiles-styles.css']['data'] = drupal_get_path('theme', 'mytheme')
                                       . '/css/tiles-styles.css';
  }
}


How to put multiple entity fields inline as sub fields? Not sure how to explain this so will add an image.

I want a field to have 2 values, one is the type of data, the other is how many, needs to be on the same line.

For example for a website, I need the client to be able to select the photo type, and then how many of them.

I'm using entity form, but a solution for webform also might work, although I prefer entity forms.

Have you considered Paragraphs? It allows you to 1) create predefined sets of fields and 2) allows you to add fields that allow you to add those predefined fields. You have the option to restrict the paragraph selection as well as the number you can add.

A closely identical module is Field Collection although their project page suggests moving to Paragraphs instead.

It's not the two dropdowns you're looking for, but allows you to select a type and add as many as you want.


How to programmatically delete a display from a view? I am trying to programmatically delete an existing view’s display (at the same time as deleting a node) but I am not able to find the good implementation.

HOOK_node_delete(Drupal\Core\Entity\EntityInterface $node) {
//[…]
$view = Views::getView("VIEW_MACHINE_NAME");
$display_name = "block_1";
$views_display = $view->storage->getDisplay($display_name);
//[…]

I can access to the view’s display using the view entity (storage) but as the display has protected access I can’t delete it.

Any help?

DisplayPluginCollection has a remove() method:

$view->displayHandlers->remove($display_id);

But this doesn't work and I couldn't find any code which is trying to actually remove the display from configuration.

So you would have to do this yourself in the view entity (storage):

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$displays = $storage->get('display');
unset($displays[$display_id]);
$storage->set('display', $displays);
$storage->save();

The problem is this will not run the remove code of the display. For a block display this doesn't matter, but if you delete a page display you might consider running the remove method mentioned above before deleting the display from storage. This will delete the menu links from the page.


Share one back office (database) over three drupal websites I'm wondering if there is a way to have one back office for three drupal websites with different domaine names, so I can share users over the three websites, I think I'm gonna have one database for all my drupal websites, but I'm not sure how I can achieve this using drupal.

Teeyo,

You can do this with the domains module that can be found here:
https://www.drupal.org/project/domain

The installation instructions can be found here:
https://www.drupal.org/node/477372

Don't forget to edit your settings.php file ;-)

I used the module myself a couple of times, so if you need any assistance, just let me know :-)


Why is the jquery_update module not supporting the latest jQuery version? The recommended jquery_update module only supports 1.10. Why recent jQuery security version 3.4.1 not updated?
https://jquery.com/download/

So is it recommended to make my Drupal site to update with latest jQuery version for security reasons?

When I try to make the module to support latest jquery version, I am facing issues with other jQuery UI files. What are the additional UI files need to be addressed to work with latest jQuery version?

Thanks,

You'll want to use the latest dev version of jQuery update, 7.x-3.x-dev to get the latest version of jQuery, or at least jQuery 3.1.  See this drupal issue for more insight.

You can see in the 7.x-3.x dev branch, it has jQuery 3.1.

Note, there is also a patch for jQuery 3.2, 3.3, and 3.4 against the 7.x-2.7 branch.


Template suggestions not recognized I have just introduced my custom template suggestions in MYTHEME_preprocess_node, based on a certain field's value. Won't work somehow.

The content type is project. In my template folder I have already a file named node--project.tpl.php, and my suggestions append additional two: node--project--pcgame.tpl.php and node--project--movie.tpl.php. They are visible when I dpm() the variables, but are not found/applied to the node, even when I remove node--project.tpl.php.

Cache cleared.

Any clue as per what could be the cause?

The code I'm using:

function MYTHEME_preprocess_node($variables){
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = (int) $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project__pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project__movie';
      }
      dpm($variables['theme_hook_suggestions']);
      }
   }
}

You try this code.

 function youthemename_preprocess_node(&$variables) {
 $node = $variables['node'];
    if($node->type == 'project'){
      // Determine project type based on a term field.
      $project_type = $node->field_genre['und'][0]['tid'];

      switch($project_type){
        case 4:
          $variables['theme_hook_suggestions'][] = 'node__project_pcgame';
          break;
        default:
          $variables['theme_hook_suggestions'][] = 'node__project_movie';
      }
    }
}

You file name should be node--project_pcgame.tpl.php and node--project_movie.tpl.php.
Clear performance cache, it should call hook_theme_registry_alter(&$theme_registry).


Is there a module that can "lazy load" content, not just images? Utilizing the JAIL module I can lazy load images. Is there any module that lets me do this for content as well (i.e. only load portions of the page that are in the current viewport)?

You can try out infinite scroll. It (lazy)loads the content as you scroll through the page.


Handling shared content without multisite? Are there any good solutions out there for this? We have a couple of sites that share content (news, events, etc.) and they are not part of a multisite and we don't plan to make them a multisite. We need people to be able to edit them on each different site.

You could have a look at the Feeds module. You should set up one site as master (where news and events are entered) and use the Views module to publish an RSS feed of the content you want to share. Now on the other sites, you install the Feeds module and configure it to pull in the RSS feed and import the content from the master site.

Downsides to this approach:

There will be a delay between the publishing on the master site and the import on the other sites.
This especially works well when all content is entered on site. If you need content to be entered on all sites, things quickly get more complex.
Once the content is distributed from the master site to the other sites, it can be edited on all sites, but the changes will not be synchronized across all sites.


Is it possible to modify help text on a vocabulary page? I am using a custom way of managing relations between terms in a particular vocabulary so I want to disable (or at least hide) the built-in functionality allowing terms to be placed in a hierarchy.

I have managed this to some extent with CSS (managed by the module that also does the custom relations). I have removed the "Relations" section from the taxonomy term edit form and I have removed the handles from the vocabulary list so that you cannot move the terms around and place them in a hierarchy that way. But I cannot see how to get rid of, or alter, the help text which says "You can reorganize the terms in Topic using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.".

The problem is that there are no containers around this to identify which vocabulary is being adminstered, or indeed that it is on a taxonomy vocabulary list page at all. I have read the Drupal 8 docs on attaching libraries and they all say that targeting pages by URL is deprecated.

I suspect hook_form_alter would not work either as it is outside of the form tags.

Is there any way to do this?

When creating a vocabulary you have the option of turning on/off the ability to arrange terms in a hierarchy. If you choose "Single Hierarchy" for example then the help text will change to read: "VOCAB contains terms grouped under parent terms. You can reorganize the terms in VOCAB using their drag-and-drop handles."

See http://cgit.drupalcode.org/drupal/tree/core/modules/taxonomy/taxonomy.module#n78

... Otherwise you can create a custom module that implements hook_help and check for $route_name = entity.taxonomy_vocabulary.overview_form. As long as your module's hook_help fires after taxonomy_help() your's should win. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook_module_implements_alter/8.4.x to control whose module wins when implementing a hook


How to print external html output in form_submit I have written a form that accepts user's input and based upon the input queries an external site and extracts the html of the result page from the external site. Is there a way to print html inside the form submit so that the results would appear on my drupal site. Following is my form_submit. (Drupal 7 is the version that I am working with)

   function tripal_search_form_submit($form, &$form_state) {
    //debug($form_state);
    switch ($form_state['triggering_element']['#name']) {
     case 'submit':
     $string=$form_state['input']['string'];
     $organism=$form_state['input']['dropdown'];
     $some_var = file_get_contents("http://legumeinfo.org/gb2/gbrowse/$organism/?q=$string");
     print $some_var //This is were I need help
     break;
     case 'reset':
     $form['items']['name'] = array(
     '#type' => 'markup',
     '#value' => '<input class="form-button" value="Reset" type="reset">',
     '#weight' => 2000,
    );
   break;
  }
}

You might try using the drupal api function drupal_set_message()

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_message/7

so in your case:

drupal_set_message($some_var); // will display the rendered html as a status message


How do I get the number of nodes using terms from a vocabulary on the same line together the link to the term page? I created a view of taxonomy terms, and then followed these steps to add the number of nodes using each term listed in the resulting view.

As Format, I selected HTML List showing Fields
As relationship, I added Content using field_blog_category, where field_blog_category is the field I added to a content type I created
I checked Use aggregration
I added ID (listed under the Content category) as new field
I set Aggregration type to Count for the new field (by clicking on Aggregration settings for that field)

It works as expected, except the fields are not in the same line.

I checked the settings for both the fields, but I could not find a way to make them appear on the same line; even changing the settings for Rewrite results didn't help me.

Is it possible to have those two fields on the same line, without using Table as Format?

Yes. By default, a HTML List View displays fields wrapped in a couple of DIVs, a block-level element. Hence, it displays each field on a new line. To disable this, use the Style Settings > Customize field and label wrapper HTML checkbox for each field to use an element that isn't a block-level element (e.g. SPAN).


Drupal Rules: How do I check if node is updated via edit form or via VBO? I'm trying to build a reaction rule that fires on the event After updating existing content, but with the condition to only run after the node has been manually updated using the node edit form, not as part of a Views Bulk Operation action that updates nodes.
My issue is I can't find a condition that achieves this.

Does anybody have an idea? Thanks for thinking along :-)

This answer is slightly experimental as I have done something similar but not precisely the same. You may need to do further work, but here's the outline which will require a custom module that uses Entity API. What it does is create a custom node property which says where it was updated from:

Implement hook_node_submit() to check which form the node update has been submitted from and if it's a node_edit, add a custom member item to the node object, eg $node->is_node_edit = TRUE;
Implement hook_entity_property_info_alter() to add a custom property to the node entity type corresponding to the custom member as above.
Implement the getter callback you declared in that hook to be something like:

function mymodule_node_update_from_edit($data, array $options, $name, $type, $info) {
 $node = $data;
 return (boolean)@$node->is_node_edit;
}

You can then check the value of the property in a Rules condition.


Commerce kickstart select country and don't show product I use commerce kickstat and I have some products on my site. I want to disable add to cart button when user is not form some country.. for example.. USA.. if user is from USA he can see add to cart.. other not

Your best bet is to add a hook_form_alter and modify the commerce add to cart form to remove the button and/or change it up to your liking:

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'cart_add_to_cart') === 0) {
    if (/* Insert your logic here */) {
      unset($form['submit']);
      $form['submit'] = array('#markup' => '
Not available in your country
');
    }
  }
}


htaccess style login for drupal I want a separate login for my site for Drupal. One to simply access the page, the same functionality that an .htaccess login would provide.

Except I want it to be styled as a separate html page, not as the default module popup htaccess does.

Is there a Drupal module for this or do I need a simple PHP script outside Drupal.

The Secure Site module could be the best choice:

  This module allows you to authenticate users with a browser-based
  password (HTTP Auth). You can restrict access to the site by role and
  choose to secure restricted pages or the entire site. This means the
  site will be inaccessible to search engines and other crawlers, but
  you can still allow access to certain users.

You can change the settings to use a page instead the popup. It's also possible to theme the login page - see the information here.


How to "close" from view standard taxonomy page I made several taxonomy dictionaries and all of them have terms. I use terms for Views generations. But standart drupal functionalaty lets end-user to enter as URL: "site/dictionary name/term name" and get list of materials which were marked by this term.
How I can "close" this page? I do not want end-user to see my materials by this hack.

Luckily there is module for that: Disable Term Node Listings

By default, on taxonomy term pages, Drupal will display a list of nodes (teaser build mode) that are tagged with that term. Disable Term Node Listing allows you to selectively disable node listings on taxonomy term pages by vocabulary.
Disable term listings for a particular vocabulary by going to the edit page [/structure/taxonomy/[vocab_machine_name_here]/edit].


Alter views contextual filter field I have two content types, Brand and Sector. Brand have a sector field which is an Entity reference field.

I have views that display the list of Brands and it has a sector contextual filter which displayed as an input field where you have to input a node ID.

I was trying to make it a dropdown with sector titles for a user friendly experience but wasn't able to achieve this in views. So I decided to alter the views form but it seems like that it's not working the same as in D7.

What's the right way to alter the views field or is there a way to render a field as dropdown using views?

OK, I managed to achieve this by implementing hook_form_FORM_ID_alter() in my mytheme.theme file.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form['#id'] == 'my-views-exposed-form-id') {
    $query = db_select('node_field_data', 'n')
      ->fields('n', array('nid', 'title'))
      ->condition('type', 'sector')
      ->condition('status', 1)
      ->orderBy('title', 'ASC');
    $options = $query->execute()->fetchAllKeyed();

    // $form['sector'] is a type text, changing it to select.
    $form['sector'] = array(
      '#type' => 'select',
      '#options' => array('' => t('Filter by Sector')->render()) + $options
    );
  }
}

Hope it will help someone.


Create link to node on view I want to add a 'like' button to a table. I get as far as the like button appearing on the page, but I can't figure out how to build the link into that spot.

The problem is, the only way to do that (that i've found so far) is to make a full html field on the content item and place the code for the iframe in there. I can't figure out how to make that a link to the node itself.

I tried using the view to add a field Global text, but I can't get an iframe to load from there. If I could do it there then I could use replacement patterns to build the proper link.

If it helps unmuddle it to remove some context: I want to create a table of nodes that pass a filter. I want that to be a table of iframes loading the node the table row represents.

Is this table generated from Views?

If so, you should be able to just add a node link, rewrite it to output ONLY the URL, hide it, then use that field as a rewrite pattern in your facebook button's output, so the like button is applying to the URL of the node itself.


Apply CSS and Javascript affect to images Updated

I am trying to add CSS and Javascript hover affect to some images in drupal 7 .. something like in this tutorial.

http://callmenick.com/2014/03/06/image-overlay-hover-effects-with-css3-t ...
Hover on some touch devices is sticky like iphone .. in this example it gives the user a (X) which close the sticky hover when it is touched

i have jQuery Update already installed ... and when i applied the code like in this tutorial in custom CSS and Javascript files .. its not working ... i really do not know what am i doing wrong or if i have to install another library to drupal or what am i missing to add to drupal ... even when i try to test it here http://codepen.io/anon/pen/onsyH ... still not working ..

any help will be appreciated

I have done a CSS only alternative for you.

http://jsfiddle.net/bk5h7/

EDIT: In answer to the JS not working in Drupal, you may need to wrap any document ready JS in behaviour tabs, and/or declare jQuery.

This will also help if you use it in a view that uses AJAX. Putting it in a behaviour instead of document ready, means the JS will load again even on every AJAX request.

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

        // Put your jQuery Code Here

  }
};
})(jQuery);

EDIT 2: The demo uses jQuery 1.9.1, whereas Drupal 7 is shipped with 1.4.4. Maybe try using the jQuery Update module to update your version.

EDIT 3: What are you using to load the Modernizr.js script? That touch function you are talking about relies on device detection using Modernizr.js.

Copy the modernizr.js file to your themes JS folder, and in your themes template.php file, try adding...

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/js/modernizr.js');


Send different email response based on form options? I need to set up a Request Download form in which users choose which software they want from a drop-down. Is there any way to make it, so they are sent a unique email for each software? If not, is there a way to just show different responses on form submit?

I experienced the same problem a while ago. I wrote a blog post on it (link below) if you need more information. Basically you can change the email that gets sent based on the input of the form by creating your own webform-mail-[node-id].tpl.php. Within this template you can change the content based on submission data in the $submission variable.

<?php
  if ($submission->data[1]['value'][0] == 'General Application'){
    print 'Thank you for submitting your resumé and covering letter'."\n\n";
  } else {
    print 'Thank you for submitting your resumé and covering letter for the position of '.$submission->data[1]['value'][0]'."\n\n";
  }
 ?>

http://bouncingorange.com/blog/201204/custom-email-templates-webform


How to get all node ids from same content type I am using Drupal 8 and I want to create related content, but the problem is that I can't figure it out, how I can get all node IDs(except current one) for a specific content type.

This is a basic query that returns last 10 changed nodes (published) of type 'article'. Modify for your needs.

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'article')
  ->range(0, 10)
  ->sort('changed', 'DESC');
$nids = $query->execute();


Assign a role upon registration I'd like to assign a specific role when a new user registers on my site using the regular registration form, beyond that of just "authenticated user".

How can I do this?

This is easily accomplished using the Rules module and setting up the "event" and "action" to behave the way you want it to behave.

I set it up so that "after saving a new user" I "added a user role" of the type that I wanted to have. That should do the trick.


How to control from a module the block visibility of a block implemented by another module? The default options in the administrative page for block visibility (e.g. admin/build/block/configure/block/3) are not enough for my needs.

For security reasons, I do not wish to use the PHP option (Show if the following PHP code returns TRUE (PHP-mode, experts only).).  I plan to turn off all PHP configuration throughout the site.

The only route that remains available is to create a module that will control the visibility of certain blocks on specific pages.  I am an experienced module developer but I do not know how to implement this specific thing.

What API exist that I could use? Apparently it's possible in Drupal 7. What alternatives do exist in Drupal 6?

Edit:
I actually easily found the answer to my original question. Now, I want to be able to control from my module the visibility of a block implemented by another module. My specific use case is thus: core's aggregator.module  create feed blocks, but I want each feed block to be displayed on pages of certain types authored by specific users who are associated with specific feeds. I could re-implement the whole aggregator_block() or... I could let the aggregator.module do its job and simply control the visibility of the block that it produces. Is it possible?

You can call the aggregator's (or an other module's) block routines by doing something like this in your module...

$foo=module_invoke('aggregator', 'block', 'view', 'BLOCK_DELTA');
$content.=$foo['content'];

...with the resulting $content containing the html of the block in question.

So, it would be fairly trivial to include something like the above in your custom module's block view hook instead of copying all of the aggregator module's code into your module.

More information on module_invoke() here.

Just an FYI:  Using the visibility key set to PHP in hook_block() actually requires the <?php ... ?> brackets with the whole shabang being passed through eval() so IMHO I don't think it is all that much safer than using the Block UI's PHP option.


Email notifications for disqus comments on a node I setup a blog in drupal and used the disqus module to integrate it with the disqus commenting system.  The drupal commenting system isn't used.  When someone posts a disqus comment on the node, I'd like drupal to email the node author a notification of the comment.  Disqus' system is setup to notify a primary administrative account when a new comment is posted but not the node author, as that information lies within Drupal. How do I go about this?

This feature is not supported out of the box. There are a few solutions:

Use http://drupal.org/node/1117622 to fire a callback to Drupal to notify the author.
Sync disqus with the Drupal comment system. The module supports it, but I haven't tested.


Changing Drupal's default email notification on password reset I need to change the text the user gets in the email with the one time login url. How can I do that?
By the way, say I want to generate a login url from my module, is that possible?
I'm using drupal 6

Pop to http://www.mysite.com/admin/user/settings, you can edit the subject and body for the email under the "Password Recovery Email" fieldset.

To do this programatically you can call _user_mail_notify() with the password_reset op parameter:

_user_mail_notify('password_reset', $account);

You can generate a one-time login link using the user_pass_reset_url() function:

$url = user_pass_reset_url($account);


JavaScript asynchronous loader Which module (not library) works best in Drupal 7 (they support corresponding libraries), labjs or headjs? Which is one better written, tested, and with less bugs?

Both LABjs and HeadJS are recent modules, actively developed by professional Drupal developers, both are offering versions for Drupal6 and 7 and both have less than 100 installations (see statistics).

Also both are aware of each other modules and collaborate together, see

Because they are so recent modules and you can't know how well they will be supported later in the future, I would  base my decision on which JS library fits your needs. Probably I would trust more on LABjs, that is much more tested and used (twitter, vimeo, etc are using it), plus it's a library focused in JavaScript loading, nothing else.

HeadJs library in the other hand also is offering other features: detecting CSS3 features, detecting screen resolution, etc something that can be good or not, depending what you are looking for. And also HeadJS is better integrated in the Drupal ecosystem: integration with Boost, CDN, Advagg modules.

If you are interested in this topic, I would recommend you a must read blog post from the author of LabJS to get a inside view of the technology under these JavaScript loaders (LABjs, HeadJS, ControlJS from Steve Souders, etc )


Table Pager Rendered in an Ajax Callback Shows White Page I have the callback function below that renders a table with a pager. Every page of the table is 20 rows. Below is the code:

function myid_print_all_submitted_id_callback($form, &$form_state){
    $table_html = '';
    $rows = array();

    // Build the sortable table header.
    $header = array(
        'idnumber' => array('data' => t('ID Number'), 'field' => 'idnumber'),
        'student' => array('data' => t('Student'), 'field' => 'student'),
        'status' => array('data' => t('Lacking ID Information | Status'), 'field' => 'status'),
    );

    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query
        ->fields('t1', array('idnumber','student','status'))
        ->condition('t1.studid', 1 ,'=')
        ->extend('TableSort')->extend('PagerDefault')->limit(20)
        ->execute();

    foreach($result as $record){
        $rows[] = array(
            'idnumber' => $record->idnumber,
            'student' => $record->student,
            'status' => $record->status,
        );
    }

    $table_html = theme('table', array('header' => $header, 'rows' => $rows)) . theme("pager");

    //Build the table
    $form['table'] = array(
        '#type' => 'item',
        '#markup' => $table_html,
        '#empty' => t('Table has no row!'),
        '#prefix' => '
',
        '#suffix' => '
',
    );
    return $form['table'];

}

It looks like the image below:

When I click the next page it shows a blank page:

Where did I go wrong? It was redirected to http://19.46.1.13/myid/system/ajax?page=1, when it must be redirected to http://19.46.1.13/myid/user/1/myid_print?page=2.

I was guessing it is because the table pager was not loaded yet because it was rendered by a callback function. Any suggestions/solutions on how to solve it?

This sounds like a known bug in core:

Pager, tablesort links in a form point to system/ajax when reloaded via AJAX
https://www.drupal.org/node/1181370

Someone has offered up a "quick fix" in comment #22:

  As a quick fix I overrode theme_pager_link() to set the url of my AJAX-loaded pager to the page url instead of $_GET['q'] (which was system/ajax).

[Edit...]

I haven't tested this, but give it a try:

In your callback function, save the current path in a session variable:

$_SESSION['page_path'] = current_path();

Copy and paste this function into your *.module file:

/**
 * Implements hook_theme_registry_alter().
 */
function YOUR_MODULE_NAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['pager_link']['theme path'] = drupal_get_path('module', 'YOUR_MODULE_NAME');
  $theme_registry['pager_link']['function'] = 'YOUR_MODULE_NAME_pager_link';
}

Copy the theme_pager_link() function into your *.module file.
Rename the function YOUR_MODULE_NAME_pager_link.
In the function, replace the following line:

$attributes['href'] = url($_GET['q'], array('query' => $query));

with:

if (isset($_SESSION['page_path'])) {
  $attributes['href'] = url($_SESSION['page_path'], array('query' => $query));
}
else {
  $attributes['href'] = url($_GET['q'], array('query' => $query));
}

Clear the caches.


Block showing Parent Taxonomy Term of current Node Ok my taxonomy is setup like this:

Holiday Cards
Trees
Bears
Religious

So the goal is to display a node belonging to 'Trees' but in that node I need to have a block that shows the Parent Item of 'Holiday Cards' (along with the description of 'Holiday Cards'.

I have attempted to use views to accomplish this but I keep hitting a wall.  Can someone please walk me through, step-by-step, what I am missing in order to accomplish this seemingly simple task?

I think this is impossible with the Views module.

To achieve the goal, you can create a block with a relation to the "Holiday Cards" term. Under Filter criteria select Taxonomy term: Name (= Holiday Cards).

To display the block only with the content related to another taxonomy term, you can consider to use the Context module.

Instal the module and turn it on.
Go to /admin/structure/context/add and create your new context
Under "Conditions" choose your taxonomy term "Trees"
Under "Reactions" choose "Blocks"
Select your block created in views and place it in appropriate region
Save the context

That's it! Your block with relation to "Holiday Cards" will be displayed only with content which is related to "Trees."


How to change user field value after node form is submitted? I currently have a user field called field_reputation with a default integer value of 0 (if a user registeres).

The idea is that this field increases when certain actions are executed. For example, when a user publishes a new article, field_reputation should be its current value + 10.

I am trying to achieve this using a form hook:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'node_article_form') ) ) {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_increase_reputation';
        }
      }
}

And then this function is called:

function _increase_reputation(array &$form, FormStateInterface $form_state) {
  // Do something here
}

However I can't seem to figure out what code should be written in this function.

As @Clive says, form submit handler is a bit too late. Do it in hook_node_presave or hook_entity_presave. If you do it in hook_node_presave:

Check the node type first: if ($node->bundle() === 'article')
Get the current user:
$user = User::load(\Drupal::currentUser()->id());
Then set the field value: $value = (int) $user->get('field_reputation')->getString() + 10; $user->set('field_reputation', $value); (I'm not 100% sure on this code, but I'm sure there are better ways to do it when you have more than 5 minutes :D. Feels dirty to use getString() and then type-cast it into int)
Save the user entity with $user->save();

If you use hook_entity_presave then you just need to check for the entity type additionally: $entity->getEntityType->Id() === 'node'


Need help or idea on how to setup a Drupal site on a given scenario I need ideas/help on how to setup a drupal website with following given scenario. I just come up with the scenario this is not real but if I get the answers then I think I can apply on real poject.

I have two content-type Movies & Celebrities.

Movies content type will list all the movies information like...
"Movie story overview", "movie review" and "movie cast"

Similarly I have Celebrities content type which will Celeb information like
Movies acted, Bio, awards etc.

Now what I want...

First Objective:

When I add a new celebrities node to site, how can I create/add multiple pages automatically
Example: I added a new celebrity named “kate winslet” by using “Add Content”->Celebrities content type. Now when I save it there should be 4 urls created in one go.

a.   Domain.com/celebrity/kate-winslet
   b.   Domain.com/celebrity/kate-winslet /movies-acted
   c.   Domain.com/celebrity/kate-winslet /bio
   d.   Domain.com/celebrity/kate-winslet /awards

Similarly while adding a Movies content type it should generate multiple pages like

a.   Domain.com/movies/titanic/overview
b.  Domain.com/movies/titanic/cast
c. And more like this.

Note: I don’t want to create pages manually. Only one main landing page for each type should be created manually and rest of the pages should be added itself.

Now...

Second Objective:

On the “domain.com/movies/titanic/cast” page, how can I have functionality to look-up all the celebrities page titles & url and link both, a movie with its casts or an actor/actress with movies.

Example: I added a new movie “titanic”, now the movies content type may have a custom filed (CCK) named as “movie cast” where I will be adding actor/actress full name like “kate winslet”, “leonardo dicaprio” etc.

Now what I want is these names should be link to their corresponding celebrity pages like

a.  “kate winslet” shoule be linked to Domain.com/celebrity/kate-winslet

b.  And “leonardo dicaprio” should be linked to Domain.com/celebrity/ Leonardo-dicaprio

Any idea or help is highly appreciated.

For the second objective instead of adding the actors to the movie, since you already are going to add movie appearances to each actor, make those movies taxonomy terms.  Then when you want to make a cast page for a movie, just display all of the actors that have that taxonomy term (the movie name) associated with it.


Customize the HTML of a link field from a custom theme I've a Link field named field_home_link, attached to a Content Type named Home, and I'm trying to customize how it is rendered as HTML from inside a custom theme.

Instead of the default generated HTML:

Link text

I need to render this HTML, adding custom CSS classes on it:

  Link text

But I would like to have most flexibility as possible on the rendered HTML, not only adding classes. For example I might need to add other attributes on the tag  or maybe also change the tag  with something else.

Would be enough having access to the link's properties (url and text) and arrange them in some custom HTML code.

How can I do this?

I tried to create a template for the link field:

field--field-home-link.html.twig

but inside this template I don't know how to access link's elements (url and text) and I'm stuck with this:

{% for item in items %}

  {{ item.content }}
{% endfor %}

Is there no way to do something like this?:

{% for item in items %}

    {{ item.content.text }}

{% endfor %}

Try this:

{% for item in items %}
  <a href="{{ item.content['#url'] }}" class="btn-circle btn-circle--blue js-open-modal">
    {{ item.content.text }}
  </a>
{% endfor %}

Found it in a video from 2015, where MortenDK is showing off
It's about 25 min. in

DrupalCon Los Angeles 2015: Drupal 8 Theming with Love


Serving the CSS and JavaScript files of the Bootstrap theme locally I have installed bootstrap theme on drupal 8 and instead of using CDN provider, I'd like to load my bootstrap files locally for offline intranet usage.

Does anyone knows where should I put my bootstrap css & js files to in order to achieve this? Are there any instructions I can follow to achieve this?

Thanks

You need Bootstrap Library module.

Quote:

  Download Boostrap files on /libraries/bootstrap (you`ll have to
  create "libraries" folder in Dr8 install directory).
  Then go to
  example.com/admin/config/development/bootstrap_library
  -configure on which pages you want to load the libraries (by default everything but admin/*).
  Configure on which themes you want to load the libraries.
  Drink some champagne coffee.


Form API + Module: Nested default value variable_get doesnt behave the same as unnested variable_get Heres the example code:

function mymodule_form($form, &$form_state){
    $form['nest'] = array(
        '#type' => 'fieldset',
        '#title' => t('Nested settings'),
        '#tree' => TRUE,
    );

    $form['nest']['nested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Nested Example Item'),
        '#default_value' => variable_get('nested_example_item', 'example value 1'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Nested Example Item'),
    );

    $form['unnested_example_item'] = array(
        '#type' => 'textfield',
        '#title' => t('Unnested Example Item'),
        '#default_value' => variable_get('unnested_example_item', 'example value 2'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description' => t('Unnested Example Item'),
    );

    return system_settings_form($form);    }

Now what happens when i change both values and submit the form is the following:

The unnested field behaves like expected - it reflects the changes.
The nested field item, does not show this behaviour, does not reflect the changes

I am confused, should I treat the nested variable_get differently?

I'm pretty sure system_settings_form() only looks for variables defined at the root of the $form_state['values'] array.

Since you have '#tree' => TRUE on your fieldset element this will not be the case. If you remove the '#tree' => TRUE' line, the value of your nested element will be saved in a variable called 'unnested_example_item' as you expect.


How to load a node based on its title? I only know the title of a node, and I want to load the node using node_load().

How do I do that?

In Drupal 7, the parameters for node_load() has been changed. To get the nodes that match some conditions, you should use the EntityFieldQuery class.

$query = new EntityFieldQuery();

 $entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'your_node_type')
  ->propertyCondition('title', 'your node title')
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();

  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }


How to get node IDs from drupal.org? In Drupal, we can get argument values using arg() function. drupal.org uses path alias. For example https://www.drupal.org/project/elysia_cron is actually https://www.drupal.org/node/274365, the node with ID equal to 274365.

How can I get the node ID of a project page from drupal.org?

As already mentioned in the comments, you could parse the HTML from the web page and extract the node ID from a class value.

But that's very messy, and it'll break if Drupal.org changes its markup for node pages.

A more robust approach would be to use the API, and consume the project's update feed. That feed contains the raw URL of the project node, from which you can get the ID.

I'll leave the PHP implementation to you, but the steps are as simple as:

Load a DOMDocument up with the contents of https://updates.drupal.org/release-history/MODULENAME/all.
From the root node, select the first <release_link> element and extract its value.
Extract the nid from that URL.

I realise that method also relies on the XML not being changed, but I think that's less likely to change than the markup on the HTML version.


how to update a field schema I am trying to add a field (middle name) into the field_schema of the contrib addressfield module (I initially didn't want to hack it, but was unsucessful in adding a field in from my custom module.). The module has the following hook_field_schema()

function addressfield_field_schema() {
  $columns = array(
    'country' => array(
      'description' => 'Two letter ISO country code of this address.',
      'type' => 'varchar',
      'length' => 2,
      'not null' => FALSE,
      'default' => '',
    ),
    'administrative_area' => array(
      'description' => 'The administrative area of this address. (i.e. State/Province)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_administrative_area' => array(
      'description' => 'The sub administrative area of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'locality' => array(
      'description' => 'The locality of this address. (i.e. City)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'dependent_locality' => array(
      'description' => 'The dependent locality of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'postal_code' => array(
      'description' => 'The postal code of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'thoroughfare' => array(
      'description' => 'The thoroughfare of this address. (i.e. Street address)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'premise' => array(
      'description' => 'The premise of this address. (i.e. Apartment / Suite number)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_premise' => array(
      'description' => 'The sub_premise of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'organisation_name' => array(
      'description' => 'Contents of a primary OrganisationName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'name_line' => array(
      'description' => 'Contents of a primary NameLine element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'first_name' => array(
      'description' => 'Contents of the FirstName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'data' => array(
      'description' => 'Additional data for this address.',
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
      'serialize' => TRUE,
    ),
  );

  return array(
    'columns' => $columns,
    // TODO Add indexes.
  );
}

I found this post online for doing a field_schema update https://drupal.org/node/150215, but I don't know what the field name or table name is, its not listed in the file.
How can I do this?
My ultimate goal is to make a standalone plugin file to be used by addressfield, but I needed to update the schema first.

The field will be named whatever you named it when you added it. If you can't remember, go to the "Manage fields" UI page for the relevant entity type/bundle and you'll be able to find it there.

The table names will be based on that field name; if the field is called field_my_field then the two database tables are:

field_data_field_my_field
field_revision_field_my_field


How to implement responsive social sharing button with counters? I'm looking to implement some social sharing buttons on my website.

Requirements are

responsive
counters

I like the looks of the Ridiculously Responsive Social Share Buttons module, but they don't have counters.

Any ideas about how to implement this in a Drupal, maybe using some jQuery library?

Try any one of this following

1) Social Share Counter

  This module is clearly inspired by the share buttons used by Mashable.

  This module gives the share counts for only Facebook,Twitter and more
  which has some excellent features in more elegant manner. If you have
  a website, then you definitely need this module.

2) Social Share statistics

  This module is developed to track the share statistics of social media
  clicks. So when a registered drupal user shares any content to social
  media, this module saves the uid, nid and the share count for
  FB/twitter/GPlus in the database for the record.

  There is a 'Shares' tab on the user profile page where the user can
  get the list of content shared on different social networks (facebook,
  twitter).

  This module only tracks shares that are made using the share buttons
  that the module provides. If you share the nodes with some other
  mechanism (say directly copy paste the link to Facebook, Twitter, etc.
  or use some other module), those actions / shares do not count.


Entity form in ctools modal I'm trying to add an entity form in Ctools popup. I'm using this module https://www.drupal.org/sandbox/andreymaximov/2058521 . My entity form path is like this eform/submit/quote

module docs say use this as link

modal_forms/%ctools_js/eform/submit/%entityform_empty

I'm really lost how to put my quote entity form here according to that link.

I recommend trying to use Ctools Automodal module. It's really easy to use just look at the project page:

  Provides automatic modal support for any hook_menu() paths that have
  'modal' => TRUE defined. This makes it easy to add optional modal
  support in any contrib module and helps reduce the burden on module
  developers to support modals.

  Example Usage

<?php
function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE, // This line is where the magic happens.
  );
}
?>


Setting the default value of an entity form radio button using hook_form_FORMID_alter I have written a custom Drupal 7 module which needs to set the value of a radio button of an entityform based on a value queried from the database.
I have tested hook and it is working as i am able to set a text field with in the form using:

$form['field_sem_submitter_id']['und'][0]['value']['#value'] = $user->uid;

I have tried, to no avail, to set the radio using the following and various other suggestions:

$form['field_sem_pledge_currency']['und'][0]['value']['#value'] = '2';
$form['field_sem_pledge_currency']['und'][0]['value']['#value'] = 'currency_bitcoin';
v$form['field_sem_pledge_currency']['#default_value'] = 'currency_bitcoin';

I have searched and tried numerous other suggestions on the web with no success.
Any suggestions greatly appreciated.

Can u please try below code:

$form['field_sem_pledge_currency']['und'][0]['#default_value']['value'] = 'currency_bitcoin';


Define available default colors for Color Field programatically I use the Color Field as a field in a custom module from where I create the content type programatically.

By default the available colors are defined at this hook:
color_field_field_settings_form

in the color_field module.

I need to modify the list of available colors and I wanted to do at the field creation time.

At my _slider_installed_instances function I have:

EDIT: Added the settings section with no results.

        'slider_background' => array(
                'field_name' => 'slider_background',
                'type' => 'color_field_rgb',
                'label' => $t('Slider background color'),
                'widget' => array(
                        'type' => 'color_field_default_widget',
                ),
                'settings' => array(
                        'default_colors' => array(
                                'default_value' => '#AC725E,#D06B64',
                        ),
                ),
                'display' => array(
                        'default' => array(
                                'label' => $t('Slider background color'),
                                'type' => 'text'
                        )
                ),

        ),

and I wonder how to define the settings for default colors so the list will be the one defined by me at my module.

I'll appreciate any hint.

Thanks in advance.

Finally to achieve I move to implement in my custom module the hook hook_field_info_alter and update at this hook the $info[field]['settings']['default_colors'] list of hex color values.

I couldn't find the solution I was looking for.


Module to cache URLs commonly request by bots? Open the logs of a dozen Drupal sites and you will see some patterns for non-Drupal packages in the http requests that received a 404 response.  Requests like /postnuke/article.php, /exchange/logon.asp, /awstats.pl, /wp-content/, /mailman/, /phpBB/page_header.php, etc, etc.

Nearly 100% of these are bots scanning for exploits.  I know there are several modules to block these requests based on IP, http header, or some other key piece of data.

I've been mulling over the idea of writing a module that approaches this differently.

Instead of trying to block the request, just cache the response.  For sites using a reverse-proxy layer cache like Varnish, set the max-age for a ridiculously long time (1 year).  The module would simply generate menu entries for common packages that a Drupal site is very unlikely to have installed.  I would include the option to exclude a specific package so if you really did want to run Drupal and phpBB in the same web root, you could... but may require you to install https://www.drupal.org/project/bad_judgement to do that :)

I realize that this type of configuration can also be done at the .htaccess level, but maintaining that for all of the packages bots are trying to exploit is beyond the skill set of many people.

Does something like this already exist?

Am I missing some obvious reason this wouldn't work.  It seems like this would improve performance of a site by simply never letting a 2nd request hit the php/mysql level for another year (or until you cleared the Varnish cache)?

You can alter the fast404 code inside of setting.php to handle this. It will handle *.asp & *.pl; changing the regex so it handles paths like

/postnuke/article.php
/wp-content/
/mailman/
/phpBB/page_header.php

Can be done by replacing this

$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

with this

$conf['404_fast_paths'] = '/^(postnuke|wp-content|mailman|phpBB)|\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

All i did was add ^(postnuke|wp-content|mailman|phpBB)| to the start of the string, right after the first /. This means that if any path starts with any of these strings we'll skip booting drupal and 404 right here taking very little server resources.

To enable fast404

  Go to the sites/default directory. Open up to the setting.php file.
  Around line 500 uncomment this drupal_fast_404(); by removing #

Source: https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.g385c64257_0178

If you have dblog enabled you can run this query to find what paths are the worst offenders

SELECT
  COUNT(*) AS count,
  watchdog.*
FROM watchdog AS watchdog
WHERE type = 'page not found'
AND message NOT LIKE 'sites/all/%'
AND message NOT LIKE 'sites/default/%'
AND message NOT LIKE '%/styles/%'
GROUP BY message
ORDER BY
  count DESC,
  wid ASC


D7 Services node view mode I am using the services module. When I call domain.com/json/node/3 is it possible to ask for a specific view mode of the node ?

Something like this ?

domain.com/json/node/teaser/3

Thanks!

Nope, Drupal Services just return the node object by default. Looking at the end points in node_resource.inc, it would seem it would not be hard to build thou.


including javascript via theme.info doesn't work. I'm trying to include a simple javascript into my theme using the theme.info

It works like a charm on my home-setup but when I try to load in on a real page it doesn't include the .js-files (not even an empty <script>-Tag is displayed in the source).

The Code:

...
engine = phptemplate
stylesheets[all][] = css/bjqs.css
stylesheets[all][] = css/style.css
scripts[] = js/bjqs-1.3.js
scripts[] = 'js/jquery-latest.min.js'
features[] = main_menu
regions[slider] = Slider
...

The CSS-Files get included on both projects without any problem.

Do you have aggregation on in configuration > development > performance?

If so, this causes the problem. Clear all caches, and the problem should be solved.


Using custom .tpl.php for fieldable panel pane view mode I'm having a difficult time getting a view mode on an FPP to use my custom .tpl.php file.

Here is hook_preprocess:

function mymod_preprocess(&$variables, $hook) {
  $element = $variables['elements'];
  if ($element['#entity_type'] == 'fieldable_panels_pane') {
    $entity_type = $element['#entity_type'];
    $bundle = $element['#bundle'];
    $view_mode = $element['#view_mode'];
    $variables['theme_hook_suggestions'][] = "{$entity_type}__{$bundle}__{$view_mode}";
    $variables['theme_hook_suggestions'][] = "fieldable-panels-pane-banner-banner-full-bleed";
    kpr($variables);
  }
}

The relevant output of the kpr() (the theme_hook_suggestions part of it:

array(3) {
    [0]=> string(29) "fieldable_panels_pane__banner"
    [1]=> string(48) "fieldable_panels_pane__banner__banner_full_bleed"
    [2]=> string(46) "fieldable-panels-pane-banner-banner-full-bleed" }

I hard-coded that last one thinking that it might just be a mishap in the naming conventions.  I've tried every combination of dashes and underscores that I can think of; theme_devel isn't suggesting any of the ones in theme_hook_suggestions, the only ones it recommends are: panels-pane--fieldable-panels-pane--fpid-4.tpl.php < panels-pane--fieldable-panels-pane.tpl.php

I have the templates in /sites/all/modules/custom/mymod/templates with the module file in /sites/all/modules/custom/mymod/mymod.module.

Thanks for any direction!

Two dashes for tpls. Your file should be named fieldable-panels-pane--banner--banner-full-bleed.tpl.php


How do I use the photoswipe script? I want to use photoswipe script on my site to preview images. I downloaded the script, copied two JS files code-photoswipe-1.0.11.min.js and simple-inheritance.min.js. Include them in a file theme.info:

scripts[] = js/code-photoswipe-1.0.11.min.js
scripts[] = js/simple-inheritance.min.js

Next, I overwrite template with image field:

            <?php print $output; ?>

HTML generate this code:

But nothing your working. What's wrong?
FireBug displays two errors:

Uncaught ReferenceError: SimpleClass is not defined       code-photoswipe-1.0.11.min.js:28
Uncaught TypeError: undefined is not a function                                       8:62

The order of includes should be reversed (as you did). There is also accompanying css file and the following initialization js code (see examples src http://github.com/downloads/dimsemenov/PhotoSwipe/code-photoswipe.v1.0.11.zip).

<script type="text/javascript">

        // Set up PhotoSwipe with all anchor tags in the Gallery container
        document.addEventListener('DOMContentLoaded', function(){

            Code.photoSwipe('a', '#Gallery');

        }, false);
</script>


How can I assign a View Page on a Domain? On my Drupal 7, I assign Views Block by using Domain Access and Domain Context on a node(a node that already assigned to a domain). How can I assign a Views Page with Domain Access? The Views Page "Path" does not have the domain option, which I only can assign to the default domain. Anyone know how?

Domain Views

This module should provide that integration. It is supposed to link the domain access module and views together.


Auto remove uber cart product attributes's option Module:
https://www.drupal.org/project/ubercart

Scenario:
Product A: (has three options)
- blue (Expire in May) (It has node to describe more about this option)
- green (Expire in May) (It has node to describe more about this option)
- red (Expire in June) (It has node to describe more about this option)

Currently I use Scheduler module to auto remove the node once its expire, but unable to remove product attributes's option. As a result, I use rule to send me email once node had been remove.

Question: Can I use rule to remove product attribute's option or is there any other solution?

Many Thanks.

Try to use Commerce Product Attributes module. I haven't use this module. But I hope you will get that you want.

  This module provides some enhancements to the Drupal Commerce
  attribute handling.

  The improvement contains:

  Attribute field for line item
  Edit option for attributes

Or

Try this Refer Link also if you will not getting any solution from above module.

Or

You can do this by adding below code to Ubercart Attribute module.

contributions/ubercart/uc_attribute/uc_attribute.module, line 831

uc_attribute_option_delete

function uc_attribute_option_delete($oid) {
  // Delete the class attribute options.
  uc_attribute_subject_option_delete($oid, 'class');

  // Delete the product attribute options (and the adjustments!).
  uc_attribute_subject_option_delete($oid, 'product');

  // Delete base attributes and their options.
  db_delete('uc_attribute_options')
    ->condition('oid', $oid)
    ->execute();

  return SAVED_DELETED;
}