can needs-data be an array in drupal hook_token_info? Can the function hook_token_info() have an array for needs-data ?

hook_token_info()  {
 $type = array(
                'name' => t('ABC Settings'),
                'description' => t('Tokens related to ABC admin settings.'),
                'needs-data' => array('abc_user','abc_trans' ,'abc_trans_sub' ,'abc_gist_email_for_report_download','abc_gist_email',
                                      'abc_st_email' ,'abc_send_fax'),
                );}

There is no type limit on needs-data. It all depends on how do you want to call token_replace(). On the other hand, it might be wise to use 'node' approach - when you provide node, you provide also user object of node's author, even if it is never provided or mentioned in needs-data explicitly.


How can I have a page title different from the name of its menu link? I have the following implementation of hook_menu in a custom module:

/**
 * Implements hook_menu().
 */
function employee_list_menu() {
    $items['employee-list'] = array(
        'title' => 'Employee list',
        'page callback' => 'employee_list_render',
        'access arguments' => array('view employee list'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

I also have a custom menu in which a menu item link is 'Staff' and the path is 'employee-list'. When I click on the 'Staff' link the page opens and the page title is 'Staff', but I want it to be 'Employee list'. How can I fix this?

Thanks

You can set the page title with drupal_set_title() in your page callback.


how to get rid of descriptions that are linked to input types? I've got a question about the descriptions that are linked to input type options.
How do I get rid of it?

I've inherited a site that, for some reason, when I mouse over the options they start twitching as the text adjusts and tries to move to the second line. As a result is a pain to make the PHP selection.
I've seen other drupal sites that have the option without the description, but when I went to "Site configuration > Input formats" I didn't see any way to remove those descripts.

any suggestions or links to documentation would be welcome!

The Better Formats module is your friend here, you can use it to remove all or part of the format descriptions/options:

  Better formats is a module to add more flexibility to Drupal's core input format system.

  ...

  Set the default format per role.
  Set the default format per content type.
  Control allowed formats per content type.
  Hide format tips.
  Hide more format tips link.
  Hide format selection for nodes, comments, and blocks seperately, forcing the default to be used.

  ...

(emphasis mine)


Add active-trail class to menu I am working on a drupal 8 project. I am building menus from drupal. My menu would be like the following structure:

-parent

--child 1

--child 2

--child 3

when i go to a page which is child 3, and the menu will also appear on that page. i would like to set active class on both child 3 and also parent. Is there any way to do so? Thanks.

That happens automatically, at least by default for themes inheriting from Classy. See https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21navigation%21menu.html.twig/8:

  {%
    set classes = [
      'menu-item',
      item.is_expanded ? 'menu-item--expanded',
      item.is_collapsed ? 'menu-item--collapsed',
      item.in_active_trail ? 'menu-item--active-trail',
    ]
  %}
  <li{{ item.attributes.addClass(classes) }}>

So, make sure you are inheriting from Classy (recommended) or duplicate some of this logic in your theme.


Undefined index: und I have created a custom profile field called "field_protection". I am using the following code to reference that field but am getting error:

Notice: Undefined index: und

$is_protected = 0;
   $is_protected  = (int)$act->field_protection['und']['0']['value'];
    if ($is_protected == 1) {
      form_set_error('from', t("Protected !!!"));
      return;
    }

I like to use EntityAPI module for working with fields. You don't need to worry about some key exists or not. here is an example:

$entityWrapper = entity_metadata_wrapper('ENTITY_TYPE (eg. node, user..)', ENTITY_KEY_OR_ENTITY);

$protectionFieldValue = $entityWrapper->field_protection->value();

if (null != $protectionFieldValue /* put your condition */) {
  form_set_error('from', t("Protected !!!"));
  return;
}

or here is a way without an EntityAPI:

if (isset($act->field_protection['und']) && ($is_protected  = (int)$act->field_protection['und']['0']['value'])) {
    if ($is_protected == 1) {
      form_set_error('from', t("Protected !!!"));
      return;
    }
}


Is it possible to detect access to table on site db table and redirect the db query to a db shared by multiple websites? I'm working on a project where I use a database that is common to all sites and another that is specific to each. Is there a way to detect access to a specific table on a contrib module (maybe using a hook) and redirect the queries to a table on the db of the shared site?

The contrib module in question is Oauth2.0 server and the table in question is the one where clients are stored, namely oauth2_server_client .

You don't need to intercept all the query done for a database table. It is enough you change the settings for the database in the settings.php file.

Suppose that the default database definition is the following one.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

If you change it as follow, you change the database used for that particular table.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => array(
    'oauth2_server_client' => 'otherdatabase.',
  ),
  'collation' => 'utf8_general_ci',
);

In this way, you are telling Drupal that for the oauth2_server_client table, the otherdatabase database needs to be used. That database needs to be accessible from the same database user (username, in my example).

Generally speaking, you can alter the query done from a module if:

The query is a dynamic query
The module added a tag to that query, such as in the following code

$query = db_select('node', 'n')
  ->addTag('node_access');

In that case, you could implement hook_query_alter() or hook_query_TAG_alter().

In your case, since you want to change the database table used for all the queries to that table, I would change the database definition in the settings.php file.


Updating a term reference programatically I've written a module that - among other things - automatically categorizes uploaded files based on their file extension. The idea is simple: the module programatically sets up a taxonomy and automatically adds new terms to it whenever it stumbles upon a new file extension (i.e. pdf, .doc, .jpg etc.).

I cannot get it to work, however. The taxonomy terms are succesfully added to the taxonomy and I can go and investigate them in the admin interface, but the term reference between the node and the term is never saved to the database. I use $node->computed_file_extension[$node->language][0] = $term->tidto save the reference and I'm pretty sure that I've done this with sucess in the past.

I'm actually a bit confused about using 'und' or $node-language. I suppose $node->langugage is the more universal of the two, but it seems it does not always work - in this case I've tried both without success.

When I inspect my node object I can see that the reference is on the node object, but there are no records added to the table taxonomy_index in the DB when node_save() is triggered.

I'm triggering this function on either node update, node insert or node delete and only if changes have been made to the field where I store the uploaded file (i.e. a file has been added or removed).

function _uvp_fields_update_field_file_extension($node) {

// Load the vocabulary called 'file extensions'.
  $vocabulary = taxonomy_vocabulary_machine_name_load('file_extensions');

  if (!empty($vocabulary)) {
    if (!empty($node->field_file['und'][0]['fid'])) {
      $file = file_load($node->field_file['und'][0]['fid']);

// Split the filename and grab the last part to get the file extension.
      $extension = array_pop(explode('.', $file->filename));

      $term = current(taxonomy_get_term_by_name($extension));

// If there is not already a taxonomy term with the given extension, create it.
      if (empty($term)) {

// Build taxonomy term object.
        $term = (object) array(
          'vid'  => $vocabulary->vid,
          'name' => $extension,
        );

// Save the taxonomy term.
        taxonomy_term_save($term);
      }

// Add taxonomy term reference.
      $node->computed_file_extension[$node->language][0] = $term->tid;
//$node->computed_file_extension['und'][0] = $term->tid;

    }
    else {

// If the file has been removed, remove the tag.
      unset($node->computed_file_extension['und'][0]);
    }

// Save the node.
    node_save($node);

    return TRUE;

  }
  else {

    watchdog('uvp_fields', 'The vocabulary "file_extensions" does not exists.');

    return FALSE;
  }
}

You're one level off; this:

$node->computed_file_extension[$node->language][0] = $term->tid;

Needs to be this:

$node->computed_file_extension[$node->language][0]['tid'] = $term->tid;

Without specifying the field column (tid in this case), Drupal doesn't know which DB field the data should be stored in.


How to correct url path I am using a key to connect with it's node nid but when I click on Next it gives path /node/node/256 instead of node/256. Here is my code:

$key = array_search($nid , $nids);
print $key;
$next = ($key + '1');
$previous = ($key - 1);
$total=count($nids);
$next_link =    "Next";
$previous_link = "Previous";

$nids is an array. How to handle this situation?

Use l() to construct URLs in Drupal.
$next_link = l('Next', 'node/' . $nids[$next]);
$previous_link = l('Previous', 'node/' . $nids[$previous]);


Having duplicate entry error with Panelizer module I installed the Panelizer module and enabled it for a specific content type. When trying to add new content, I get a duplicate entry error as follows :

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'node-196-197-page_manager' for key 'PRIMARY': INSERT
  INTO {panelizer_entity} (entity_type, entity_id, revision_id,
  no_blocks, css_id, pipeline, did, view_mode, css_class, title_element,
  link_to_entity) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 196
  [:db_insert_placeholder_2] => 197 [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => standard
  [:db_insert_placeholder_6] => 0 [:db_insert_placeholder_7] =>
  page_manager [:db_insert_placeholder_8] => [:db_insert_placeholder_9]
  => H2 [:db_insert_placeholder_10] => 1 ) in drupal_write_record() (line 6888 of
  /Library/WebServer/Documents/www/jkl/includes/common.inc).

Any insight?

Looks like a known bug:  unable to edit nodes with default panelizer state.

Try the patches in the above issue.  Looks like it might be useful to chip in there with your issue also!


Redirect after login from custom login block I have added the login form to a page using drupal_get_form.
Now, I would like to redirect the users back to that page after login.
Note: I don't want to redirect users that logged in somewhere else (e.g. user/login), and I also don't want to use a contib module for that.

B.T.W
Maybe if I'll Ajaxify the login form it will have the same effect?

I'll appericiate any help and/or examples.

Thanks!

You have to add form_alter and add custom #submit handler to user_login form if current_path() is correct for you and set $form_state['redirect'] there.

Check this post Redirect to a custom page after a node has been added or edited.

Also it can be achieved via custom rule, if you don't want to write any custom code.


Date argument as view filter I'm using Drupal 6.

I have a custom view that needs to be filtered by an argument passed by the user.

The argument is a simple date, and I need my query to be filtered like the following:

WHERE created >= %argument&

Where %argument% is the user argument passed within the URL.

The thing is, I manage to filter it, but only as equals, like this:

WHERE created = %argument&

Is there any way I can make it filter as greater or equal to?

I've found that Drupal 6 views dont support such feature.

The solution was to implement the module_views_query_substitutions hook and alter the query manually:

function module_views_query_substitutions($view)
{
    $view->query->where[0]['clauses'][3] =
        str_replace('=', '>=', $view->query->where[0]['clauses'][3]);
}


Should I save temporary data in $form_state or in my form class? As far as I can see, there are two ways of storing temporary data when working with complex forms in Drupal 8.

$form_state->set('key', 'value'). The value ends up in $form_state['storage']['value'], and I can use it other places because it is passed around from function to function.
Make a non-static property inside class MyForm extends FormBase. The value is also accessible everywhere I need it, since all of the form functions are in one class.

After browsing through a lot of core EntityForm code today, it seems that both are used! Is any of the above necessarily "better" or more in line with "The Drupal Way"?

Related question: It seems that there is a 1:1 mapping between an instance of MyForm and the $form_state variable. Why then, is $form_state not implemented as a non-static class property? Then it wouldn't be necessary to pass it from function to function. The same can be asked of the $form variable.

While the storage in $form_state can be cached, the class property can't. So if you build a multistep form you would need to use the first option.

And a validate or submit function is not necessarily in the same class or in no class at all if it is defined in a hook. This also answers the related question.


Apache solr search integration at live site I have a Drupal site configured to use the Apache Solr module for searching.  I developed it using a local server on my machine.   This works fine once everything is indexed.

I need to make this live, but I have shared hosting, which doesn't support Tomcat.

What can I do in this situation?  Does the Apache Solr module support running the webserver and Solr server on different hosts?

You can't run a solr instance on a regular hosting service; the most of them give you a database server and Apache Server.

However, you can use a Free or Paid solutions like OpenSolr, for example.
Once you have this configured, you just need to copy and paste the Solr URL into your Drupal Solr configuration.


How do I resolve this conflict between two Feature modules? I have two content types with various menus, views, menus, etc. which I have packaged as two Feature custom modules.  The two content types both use a taxonomy and use several of the same fields in the database.  When I load these Feature modules in a new site, they show conflicts with each other over these common fields and vocabulary and I am not certain what would be the best way to resolve the conflict.

Although the Feature modules are intended to work together, they do not need to both be present on the same site. Each may also work with other different features as well.  They both use the taxonomy and fields for views filtering etc so it makes sense that they each include these components in their Feature definition.  Should I:

Remove the fields and taxonomy from one of the modules, and declare a dependency to the other?  This is not desirable since each can work without the other.
Make two versions of the features, one for independent use, and one for collaborating.
Define the fields and taxonomy as a separate feature?
Ignore the conflict and enable the modules?  (If I do, will they both share the field?)
Another solution?

I have not yet tested this, but will disabling or uninstalling one of the two Features modules remove the fields from the database even though the other module requires it?

Create a third Feature defining the components(*) used by the other two independent Features.

In the other two Features, remove the components which are now claimed by the third Feature, and instead, list the third Feature as a dependency.

(*) In Features for Drupal 7, however, this functionality isn't yet committed — see http://drupal.org/node/1064472, and help review the proposed code there. — This patch has been committed to Features 7.x-2.x.


Shipping price for different countries using Commerce Kickstart I'm using commerce_kickstart distribution.

I need to set different prices for shipping products to different countries.
Ex: France -> 10€, Spain -> 15€...

I guess I have to create a rule at: admin/commerce/config/shipping/calculation-rules but I don't know to create a condition to check over the selected Country in the Shipping Information filled by the buyer.

I think I saw a video about this at http://vimeo.com/31586256 but i can't find it though.

An easy solution is to create multiple flat rate shipping methods. As each of them is create as a rule, you can add different conditions to them, being the value of the contry in the shipping address.

Commerce shipping with then only present the user for the flat rate shipping that has the correct contry, and the price you setup will then be applied.


Planning for migration to version 7 I am just taking on responsibility for a Drupal 6.2 site. It has some custom modules and some quite poorly organised code which I am working with developers to improve alongside developing new features to the site. And being fairly new to Drupal I am just getting my head around how it all hangs together.

One of the things I want to assess is when we should be planning to migrate to Version 7.

Is it a reasonable assumption that, as a commercial website, we should upgrade to version 7 as support for 6 drops away over the next year or so?
Is it possible to develop and refactor on version 6 in such a way to make that migration as painless as possible when we get to it?
Is there anything else I should consider as I plan the development roadmap over the next 12 months?

Should you upgrade?

All contrib modules will slowly shift major version. If you don't follow suit, you risk needing to re-invent the wheel more often than otherwise necessary. Most module maintainers have since long ago shifted focus to D7. A few have even begun maintaining their D8 version.

D6 will become unsupported, and have no more security updates after D8 is released.

How do we make it painless?

I don't think there's an answer that can be applied across all sites, but here are some general guidelines.

Features needs to be "released" (warning, lots of reading), and then upgraded by their providing module, and finally re-added to their respective features.
Use the Migrate module to easily test getting content over.
If possible, run both versions at the same time. Hide the fact as well as you can, possibly using a reverse proxy. This is non-trivial to accomplish, but ensures that when you move your last piece of functionality from D6 to D7, parts of your D7 site has been live for a long while already, and you know that it's stable. As one quick example of a relatively general measure one can take to ease this, Entity API can allow you to redefine where an entity reads/writes its data.
Often Contrib-space will solve a common problem that Core later decides to incorporate. Switching to these techniques for problem solving everywhere it's relevant will allow you to "partly" upgrade a current DX site to DX + 1, making the gap during the complete upgrade much smaller.
Two examples of this are below, but this list could probably be much longer:

Use Panels and Page manager instead of modules like Context and Spaces. The Pm+P approach to site building is the foundation of a huge re-write of core for D8.
Use Guzzle instead of Http Client. Guzzle is the official http-client for Drupal 8.

Anything else?

Nothing that comes to mind at the moment.


Can Crumbs be used with Panels? I'm building a site with Panels (and Panels Everywhere, with a custom theme based on Precision) and trying to customize the breadcrumbs for particular nodes based on their content type.

The Crumbs module looks like it does what I need, and I've been able to make it work perfectly on a test site in Garland, but as soon as I switch to using Panels, the Crumbs breadcrumbs aren't being used.

Specifically, it looks like the "Breadcrumb" Page Element Content provided by ctools doesn't use the Crumbs breadcrumb trail. Somehow crumbs_preprocess_page is being completely suppressed.

Can these two modules be made to work together? I don't see any open issues for Crumbs, or any comments on the troubleshooting page at http://drupal.org/node/1008658, so I have to think that someone has made this work.

(Drupal 7.18, Panels 1.2, CTools 3.3, and Crumbs 1.8)

Crumbs provides a "Breadcrumb (Crumbs)" block that you should be able to use.


How do I send a privatemsg to all users that have flagged a node using Rules? I am using the Privatemsg module, Flag module and Rules module.

I wonder if using Rules I could send a private message to all the people who have flagged a specific node when a new comment is posted.

Thus, the flag would act like a subscription for new comments notification.

Create a new rule triggered on After saving a new comment`.
No conditions necessary; set them up only if you require something specific.
Actions:

Fetch users who have flagged a node
Loop through those users (argument will be populated automatically)
Under that loop create a new action "Send a message". This will require you to have "Privatemsg Rules Integrations" module enabled.


Removing specific HTTP response header I am trying to remove specific HTTP response header from my site.
The header looks like this:

Link: <https://example.com>; rel="canonical",<https://example.com>; rel="shortlink"

So far I have tried this simple code in my theme_html_head_alter:

header_remove("Link");

But that does not remove the header. Is there some specific Drupal way to deal with this, or am I using this code in wrong function? Or am I completely wrong with this?

Thank you in advance

You can remove it using hook_html_head_alter like the following:

/**
 * Implements hook_html_head_alter().
 */
function myTheme_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $head_element) {
    if (strpos($key, 'drupal_add_html_head_link:shortlink') === 0) {
      unset($head_elements[$key]);
    }
  }
}

PS : the above code remove links with rel="shortlink" if you want to remove links with rel="canonical" just add another if and change shortlink by canonical.


How to read JSON from external URL and display in a block? I want to load some JSON data from an external URL and display it in a block.

How do I go about that?

For the most basic solution, you would need to:

Create a custom module;
Implement hook_block_info and hook_block_view to define your block (see block_example.module for examples);
When generating the block content, use drupal_http_request to retrieve the json data from your URL and process the return value as needed.

A more complex version of your custom module could for instance involve implementing hook_block_configure to make the URL configurable from the UI, using theme functions to generate the HTML output, and caching/storage of the return value.

A completely different approach, which may or may not be appropiate in your case, would be to use the Feeds module to retrieve the JSON and store the data as nodes, and use the Views module to generate a block listing those nodes.


Cache context drupal don't work I changed services.yml file (i use dynamic cache):

renderer.config:
required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'cookies:Drupal.visitor.Country']

And sey the cookie properly with an event:

$events[KernelEvents::REQUEST][] = ['checkCountry', 30];
...
 user_cookie_save(['Country' => $country]);

I checked and the cookie is saved correctly.
But the cache does not work...

Anonymous page cache does not respect cache contexts, I'm guessing that is your problem.

To get that working, you need to switch out the PageCache service in a custom module with a ServiceProvider and override the getCacheId() method.


What is the simplest way to flush cache at a predetermined date and time? For site a) I would like to set up a schedule "page and else"cache clear every day at midnight.
For site b) I would like to set up a schedule full cache clear every Wednesday day at midnight.

I am using the modules Varnish and Expire (Cache Expiration) to clear node caches when events occur (added deleted node etc).

As far as I can tell Rules does not provide Time/Date as an event which can be used as a trigger.

I am looking to do this internally in Drupal rather than on the servers cron.
Is there a simple way to achieve this?

May be How can I schedule a rule to always be run at a specific hour of the day? can be useful , but using cron, build a module and in it's hook_cron function check for the current time, if it is your specific time use the cache_clear_all function and it's parameters to clear the page and else cache. just make sure that the cron is ran on Wednesday day at midnight. it's periodic run time should come to 24:59.

you can also check the clear drupal cache - php script for more options of clearing the cache statement.


403 forbidden error loading "sites" files I had an installation of Drupal 7.24 and I was doing a new install with 7.26. Everything went well until the end, when I tried to login. When I try to login or submit any form the page just refreshes back to where I was.

I inspected element to see what was going on and noticed a bunch of files from site/default/... were returning 403 forbidden. I chmod-ed all the files in sites/default to 777 to try it out and it still did the same thing.

What part of Drupal could this problem reside in?

EDIT:
deleted cookie,
fore refreshed,
tried in incognito.

Have you checked out if you have set the public &/or private file permission on configuration page > Media > File System.
Also do check permission of what ever form your are trying to submit.


Can I make a search that shows all results, regardless the user's permissions? We have a knowledge base with very strict user access permissions. We want users to be able to see all pages in search results, even the ones that they can't access. We want users to be able to see if the content they are interested exists and ask for permission.

You can build this in views. Build your view as you normally would, use an exposed search, then under advanced > query settings > check off "Disable SQL rewriting". This will disable node_access checks as well as other modules that implement hook_query_alter().


How can I add a way to jump months using the calendar module I have a calendar being shown by month. How can I add an exposed filter or dropdown so users can jump ahead to any month and year?

Add Below code for your calendar. Click This link for example

$(function () {
  $("#datepicker").datepicker({
    changeMonth: true,
    changeYear: true
 });
});


How to disallow spam in tag field We are a a job site where we allow visitors to post Jobs / Events through various forms. However it looks like that spammers are using this process to put spam in tag fields. This has resulted into tag cloud being spammers paradise.

How can I restrict that?

If you add something like

reCAPTCHA

to your form, that should stop the spammers in their tracks.

If the form is auto-populated by a bot, it should prevent adding spam content in any of the form fields as they won't be able to submit the form without passing the challenge.


How do I add a custom image in a block (unique for every page)? I have a block at the top of my site used for an image slider on the home page (using Nivo Slider), and I need to allow the users to add a custom image to fill that block space for any pages created (aside from home page).  This image will be different per page.  How can I do this?

I'm running Drupal 6

Figured it out.  See this link for the answer.


How should a custom configuration entity define a dependency on other configuration? In a custom module I am defining a defaults Configuration entity that references a role.
I would like to define a dependency on the role. This is my first attempt.
public function calculateDependencies() {
  $this->dependencies = parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this; // Also tried return $this->dependencies;
}

The Drupal documentation on dependencies references the Block configuration class that looks very similar:
  public function calculateDependencies() {
    parent::calculateDependencies();
    $this->addDependency('theme', $this->theme);
    return $this;
  }

However I am seeing an error shown below when trying to save the entity.The backtrace indicates it is coming from the attempt to add a dependency on the user module. I chose to add that dependency by taking an example from system.action.user_add_role_action.administrator.

PHP Error:  Cannot use object of type Drupal/my_module/Entity/MyAccessDefaults as array in /app/web/core/lib/Drupal/Core/Entity/DependencyTrait.php on line 32

For example I am trying to test with this code:
$values = [
  'id' => 'administrator', 'label' => 'Administrator role grants',
  'grant_type' => 'role', 'role_id' => "administrator",
  'grants' => ['grant_view' => 1]
];
$default_admin_config = \Drupal::entityTypeManager()->getStorage('my_entity')->create($values);
$default_admin_config->save();

ConfigEntityInterface::calculateDependencies returns $this, so this line:
$this->dependencies = parent::calculateDependencies();

Is causing problems (replacing the dependencies array with the instance of the current class, which is presumably a MyAccessDefaults).
Looking at the code, and other core classes which implement ConfigEntityInterface, your code should be:
public function calculateDependencies() {
  parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this;
}


Add author's name to view Is there some simple way I can add the author's name as a field to be displayed in my view?

In view add a relationship Content: Author

Then choose User: Name under fields,

this will display author name


Taxonomy term as node css class Kind of similar to my previous question, but apparently doesn't work the same way: is there an easy way to use a taxonomy term or a token as node css class to theme different pages?

Edit you node-type.tpl.php for this.

<?php
    foreach($node->taxonomy as $term){
            $term_classes[] = $term->name;
    }
?>

And print those classes in your node content wrapper.

<div class="content <?php print implode(' ', $term_classes); ?>">
    <?php print $content ?>
</div>


Custom line item fields in Create an Order page I have successfully added the custom line item fields in the cart through Views and modified the new total using a hook, but how do I do the same thing in Create an Order page (admin/commerce/orders/add)?

The custom line item field was added in
admin/commerce/config/line-items/product/fields
I'm using inline
entity form and I can see the custom field, but the custom field is
not visible in line items table.

Sounds like you just need to alter the commerce_line_item_table View. Edit this view and add your fields so that they show up when it is embedded when the line item reference field formatter is used.

You'll want to take some extra steps, however, to save your customizations since that view is provided by the module. I would clone that view and update your field formatter's to use that view (it's customizable from the display options!)

Or, implement hook_views_default_views_alter and completely override the view with your own export.

EDIT: Some info on the line item manager widget

In order to get fields to show up in the line item manager widget table, you're going to need to override the widget's theme function. See commerce_line_item_field_widget_form and theme_commerce_line_item_manager.

Essentially you may need to invoke hook_field_widget_form_alter to added your field's value, and then override theme_commerce_line_item_manager to place it properly.

Snippet of a theme override that could be used, to add length

// Add each line item to the table.
foreach (element_children($form['line_items']) as $line_item_id) {
  $row = array(
    drupal_render($form['line_items'][$line_item_id]['remove']),
    drupal_render($form['line_items'][$line_item_id]['title']),
    drupal_render($form['line_items'][$line_item_id]['length']),
    drupal_render($form['line_items'][$line_item_id]['line_item_label']),
    drupal_render($form['line_items'][$line_item_id]['commerce_unit_price']),
    drupal_render($form['line_items'][$line_item_id]['quantity']),
    drupal_render($form['line_items'][$line_item_id]['commerce_total']),
  );

  $rows[] = $row;
}


How to group this view? I have a view that pulls data from the Speaker content type, as well as from related sessions (Session content type contains an entity reference to the Speaker, so to get that "reverse lookup" I'm using the "A bridge to the Content entity that is referencing Content via field_speaker" relationship type to get the Content: Title from the session nodes.)

This all works, but I can't get the view to display the way I want when a speaker has more than one session. I've tried grouping by speaker name (Content: Title on the speaker node) and get this:

What I want is this:

Here's the basic view setup:

Can this be done just in the Views UI, or do I need to start fiddling with templates?

Not sure but try grouping with all the fields that are common between this 2 like the job title should also be in group so that it will be display only once


Custom error messages on search result page i have a drupal 6 multi language site with languages English and Arabic. In Arabic version i want Arabic error messages on search page. How can i do this?.

please check this, their is a procedure for translating words using Locale module


How can I include Google Structured Data via a module? Looking through Google's suggestions of search optimisation for a site that I control, I would like to add their "Structured Data" JSON to various pages on the site. Their suggestion is to include the data in custom script tags:

<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Organization",
  "url": "http://website.com",
  "logo": "http://website.com/logo.png",
  "contactPoint": [{
    "@type": "ContactPoint",
    "telephone": "+44 1234 567890",
    "contactType": "customer service"
  }]
}
</script>

What I can't work out is how to include this data "the Drupal way". I tried adding it as a library (thinking I'd later use DrupalSettings to customise the contents) but that includes it as a standard "type=javascript". How do I add it to the page header with the correct script type?

Google ref: https://developers.google.com/search/docs/data-types/corporate-contact

(answers giving a module that does this already are also welcome!)

There is a Drupal 8 module works tandem with the Metatag module: Schema.org Metatag

From the module description:

  This project extends Drupal's Metatag module to display structured data as JSON LD in the head of web pages. Read more about Schema.org, JSON LD, and how this module works in an article on Lullabot.com, Create SEO Juice From JSON LD Structured Data in Drupal.


Entityform: email submitted form to someone who is not admin? How do I get the Entityform module to email the contents of a submitted form to user@example.com. The owner of this email address is not the admin. Thanks

go to admin/config/workflow/entity_rules/entityform_submission and clone "Entityform Notification Email Submitter" or "Entityform Notification Email Admin", edit accordingly. If that does not works, please add a custom rule (admin/config/workflow/rules):

event: After saving a new entityform submission
Condition: Entity has field: [entityform], Field: token of your field
Action: send email, use the token for your email field or any email you want.


Colorbox Node and template files? I have a node being pulled into a modal with overlay using Colorbox Node but it's pulling in more markup and pieces of the page than I really want.

After trying to pick through some user threads on drupal.org, the only solutions I saw suggested were ones that only work for Drupal 6 and/or break when page caching is enabled.

Is there a robust way to template the output of nodes in modals in Drupal 7?

Colorbox Node creates a new display mode for each content type - that's where you can change the fields shown.

Structure -> Content Types -> 'manage display' on the content typ ein question - in the top right, select the 'Colorbox' display mode and adjust what shows and doesn't show as needed.


Programmatic user registration not forcing user to activate account I'm manually creating a user and then sending a notification email as follows:

$new_user = array(
  'name' => $username,
  'pass' => $password,
  'mail' => $email,
  'status' => 1,
  'init' => $email,
);

$account = user_save(drupal_anonymous_user(), $new_user);
 _user_mail_notify('register_no_approval_required', $account);

However, the user is able to login right away. How can I enforce account activation? I have it enabled in the admin panel

You can use the LoginToboggan Prevent preauth module is available for Drupal 6 and 7.
And it realy does all the stuff. We can have "Email account activation without admin approval and also a user set password".

Code:

    $new_user = array(
      'name' => $username,
      'pass' => $password,
      'mail' => $email,
      'status' => 1,
      'init' => $email,
      'roles' => array(logintoboggan_validating_id() => TRUE)
    );
   $account = user_save(NULL, $new_user);
   // Send mail with account confirmation
   _user_mail_notify('register_no_approval_required', $account);

P.S. Don't forgot to uncheck 'Immediate login' option.


No available translations found I've gone ahead and installed Localization Update, Localization Client, Language Switcher Dropdown, and the Language Icons modules. I've also enabled the Locale and Content Translation modules.

I've added two languages to my site (Finnish and French). According to the Translate Interface (Configuration --> Translate Interface), all of my modules are up to date for translations. However, the Drupal Core (7.24 it says, even though I haven't updated to 7.24 yet, still on 7.23), says "No available translations found" for both Finnish and French.

Just wondering if anyone has any idea on how to fix this? I haven't tried manually downloading and installing the .po files yet, as that's not really a solution for me, as I will be unable to do this manually for all of our clients.

Just wanted to add that I've tried this now on a few different setups and I still get the same thing happening on each one. I also tried one machine from a fresh install using 7.24, and still get the problem.

I figured out the reason it wasn't working. It's a conflict with the Update Manager module. If that module is installed, Localization Update looks for the newest possible version as returned by that module, instead of looking for the installed version on the system. Because of this, it was looking for 7.24, which doesn't have any translations attached to it as of yet.


Load and submit user profile form I want to programmatically load the user profile form for a specific user and submit it ( in order to trigger hook_form_submit() in another module ).  So far I have :

module_load_include('inc', 'user', 'user.pages');
$account = user_load($uid);
$form = drupal_get_form('user_profile_form', $account);

but how do I submit the form ?

Thanks

If oyu want to get and submit a form programatically you must use the function drupal_form_submit

  Retrieves, populates, and processes a form.

  This function allows you to supply values for form elements and submit
  a form for processing. Compare to drupal_get_form(), which also builds
  and processes a form, but does not allow you to supply values.

Check this function's documentation page and its comments for some examples.


How work BigPipe cache around block views? I have 2 blocks with swiper.js around.

This 2 blocks are from the views module.

I need to print them in the theme like i want so, i load them into the preprocess_page.

$block1 = \Drupal\block\Entity\Block::load('views_block__test_1');
$variables['block1'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block1);

And the second :

$block2 = \Drupal\block\Entity\Block::load('views_block__test_2');
$variables['block2'] = \Drupal::entityTypeManager()
                    ->getViewBuilder('block')
                    ->view($block2);

They have exactly the same configuration in views and block config.

But for block 1 swipper work, not for the block2 every time i load the page.

If i look at the source i got this for the second block :

For the block 1 i got the HTML render.

I don't know why the second block is cached by big-pipe and not the first block.

But my js on the ready state work every time on the first block, and depend if i clear the cache but it's not everytime, work on the second block the first time i load the page.

The callback (in the bigpipe attributes) call something at the bottom of the page after the js include.

That why my second block doesn't work ? it's not clear.

What's happen ?

I don't know why the second block is cached by big-pipe and not the
  first block.

This depends on the auto placeholder conditions defined in services.yml and the cache metadata of the block:

auto_placeholder_conditions:
  # Max-age at or below which caching is not considered worthwhile.
  #
  # Disable by setting to -1.
  #
  # @default 0
  max-age: 0
  # Cache contexts with a high cardinality.
  #
  # Disable by setting to [].
  #
  # @default ['session', 'user']
  contexts: ['session', 'user']
  # Tags with a high invalidation frequency.
  #
  # Disable by setting to [].
  #
  # @default []
  tags: []

As mentioned in the comments, when the module BigPipe is enabled you need to use Drupal.behaviors for your javascript, see:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


Prevent caching of URL redirect to file We have complaints that are related to caching. A Global redirect URL points to a  PDF file on the server. People claim they get an old version even after an FTP update.

Using Apache 2.4 D7 and Global Redirect module.  URL is in a block (example.com/newsletter) which redirects to sites/files/upload/newsletter.pdf

I don't even know if this is client side or server side caching, but I want to make sure that caching expires daily.

Possible approaches:

Use drupal file system to manage this as a field
change the redirect type (gloabal redirect supports a few: like 301, 304,307,etc)
Add something to the a href tag ?

I'm guessing you mean the Redirect module, not the Global Redirect module.

One thing to clarify: Are you trying to change the actual destination of the redirect (by initially having example.com/newsletter redirect to sites/files/upload/newsletter.pdf one day, then the next day having it redirect to sites/files/upload/newsletter-2.pdf)?  Or (as I think you're saying) are you actually overwriting newsletter.pdf on the server so that it's a different file?

I'll assume you're doing the latter.  If so, then the type of redirect doesn't matter.  You're facing caching on the browser side and you need to change your mod_expires settings.  Assuming you're allowing htaccess files to influence your apache configuration, you can put the following in the mod_expires section of your .htaccess file in the root of your site:

ExpiresByType application/pdf A86400

That would make browsers cache PDF files for a day (86,400 seconds).  An alternative, equivalent syntax is:

ExpiresByType application/pdf "access plus 1 day"

You can adjust that parameter however you like.  See documentation here.


Activate an existing menu item through code I need to activate an existing menu item through a hook when I'm on a certain page.  To give some context, I have a primary navigation bar which is visible on all pages, and when I'm on a user profile page I want to activate the People menu item.  The path to people is /people.  Any help is appreciated.

Cheers.

I would recommend using the Context module. You can setup rules for when a menu item is active such as content type or menu path which will save you from writing related code.

This might make it easier to understand as well for someone inheriting your site.


Nexus theme tb mega menu showing below slideshow I am using the Nexus theme however when using tb mega menu it shows below the slideshow. I know it has something to do with the z-index but where and how do I change this?

You need to find out the class of tb mega menu and add

{
    position: absolute;
    z-index: 2;
}

Note: z-index max display on top.


Flexslider only showing to logged in users My flexslider is only showing to logged in users. I'm using a view in a block and I've checked that the block is showing for all user roles.
The View "Access" permissions are set to anyone that can view published content. Changing the Access value to "none" didn't seem to make any difference. The admin user still sees it, but anonymous users don't... Any suggestions ?

I was having the same problem with Flexslider.

After checking all the permissions issues, I remembered that the content for my slides was "unpublished". I switched it to "Published" and, VOILA! It worked.

It's a common practice to have the slides "unpublished", so I don't know why this makes a difference, but it did.


How to theme one specific Views 3 exposed filter form template and HTML? I know of two ways to theme views exposed filter forms in Views 3:

Copy the file views-exposed-form.tpl.php in sites/all/modules/views/theme to your theme folder and edit the HTML directly
Use hook_form_alter in your template file, for example:

.

   function yourtheme_form_alter(&$form, $form_state, $form_id) {
     switch ($form_id)  {
       case 'views_exposed_form':
         # do things to the array
       break;
     }
   }

My problem is, I have different exposed filters on different views, and these approaches both hit all exposed filters equally. There's also nothing about exposed filters templates in the Theme Information on the views edit page.

How can I target these to one specific exposed filter on one specific view?

Views 3 with Better Exposed Filters (BEF) module, Drupal 7.

For the .tpl file

Views recognises files with names of the form views-exposed-form--view_id--display_id.tpl.php. You can also use less strict filenames of the form views-exposed-form--view_id.tpl.php or views-exposed-form--display_id.tpl.php.

While it's not addressed directly there, you can look up and copy-paste what these values should be by going to the view edit page, then Advanced > Theme > Information, then taking a suffix from an option under Display Output at the top.

For example, this is a view with machine name products, and I'm targeting its page display:

So the filename is views-exposed-form--products--page.tpl.php.

Other prefixes in the Display Output section can be used too, for example views-exposed-form--products.tpl.php would target all displays from the "products" view, including blocks or panel panes, while views-exposed-form--page.tpl.php would target all views pages.

For template.php

You can put a condition on the form's HTML id, which is generated along similar lines, like this:

   function yourtheme_form_alter(&$form, $form_state, $form_id) {
     switch ($form_id)  {
       case 'views_exposed_form':
         if($form['#id'] == 'views-exposed-form-viewid-displayid'){
             # do things to the array
         }
       break;
     }
   }

Or potentially even switch($form['#id']){} - but the original is written assuming you already have other uses of this hook based on $form_id for other forms.

Continuing with my previous example, it'd be views-exposed-form-products-page.

Note that this might need a different string if you've overwritten the form ID output anywhere, and there doesn't seem to be any way to target all displays short of something crude like if(strpos($form['#id'], 'views-exposed-form-products') !== false){  }


Does Drupal 8 entities have any events I can listen to? I know we can use hook_entity_update() hook to do something when an entity is updated. But is there an event to listen for node updates/deletes, or other entities such for that matter?

You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity.

Here is the order of hooks and other events that happen during an entity save:

Entity::preSave() is called on entity objects, and FieldItemListInterface::preSave() on field objects.
hook_ENTITY_TYPE_presave()
hook_entity_presave()
Entity is saved to storage.
Entity::postSave() is called on the entity object.
hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
hook_entity_insert() (new) or hook_entity_update() (update)


Is it possible or/and how to restrict access to the block on th certain page using route name? I am trying to restrict access to the block to be accessible only on the route:entity.user.canonical route.

Is it possible to define that on the block edit form?

There is no UI for it, but you can either write your own condition plugin to do that or implement hook_block_access() like this:

function yourmodule_user_block_access(BlockInterface $block, $operation, AccountInterface $account) {

  $hidden_blocks = ['yourtheme_block_id'];
  $hidden_routes = ['entity.user.canonical'];

  if ($operation == 'view' && in_array($block->id(), $hidden_blocks) && in_array(\Drupal::routeMatch()->getRouteName(), $hidden_routes)) {
    return AccessResult::forbidden();
  }
}


How to get a list of modules implementing hooks? Is it possible to get a list of defined hooks for debugging purposes?

I have implemented mymodule_datalayer_meta() for datalayer's hook_datalayer_meta(). However, as far as I can tell, it's not firing. I'd like to look up a list of hooks that modules implement so I can see if my module is actually implementing it or not.

You are looking for the module_implements function

  Determines which modules are implementing a hook.

Use this function in the devel/php form, for example.

dpm(module_implements('THE_HOOK'));

This way you can see easily if your module implements 'THE_HOOK'.


How to auto unpublish a node after edit and later published by admin? I need to unpublish my node after edit. For this I created a rule. It's doing the unpublish of my node after editing. But after this I am not able to again publish this node.

I also need to fire a mail to admin after update.

Here's how you can do this:

Create a rule on node update event.
Add Condition where user role is not "Administrator/Moderator". (This will make sure that the content doesn't get unpublish when admin is updating it.)
If required, Add condition where content is of type "Article".
Add Action "Unpublish content" under node section and save.
Add another action "Send Mail" under System. Add required details to send email and save.

Above steps will unpublish content and notify site admin using email. After which site admin can navigate to "Admin => Content", review the content and approve. If you need to provide a custom/different UI, you can create a list using views and VBO module and allow site admin to Approve Content.


Views Autocomplete search multiple values I'm trying to have a search filter that searches on 2 values and works with autocomplete list.
This is what I've done:

Installed the module Views filters populate.
added two filters "CNK" and "Naam" (both not exposed) and added them to a OR filter group. I used the operator "Contains any word" for both fields.
Created a filter "Global: populate filters", added the two fields into this and exposed it.

My filter criteria looks like this:

But I don't have the option for autocomplete. How can I do this the best way?

You can use Views autocomplete filter module to have auto-complete feature on views exposed filters.

  It works for node titles or cck text fields.

  The autocomplete results are actually the view results, so they are
  view related.

Check out this Demo video.


How to print alt or title field image in custom block programmatically? I want to print alt or title field image file in custom module Drupal 8. I load file entity use Drupal\file\Entity\File; I checked core/modules/file/src/Entity/File.phpall public function but not get any function which return title or alt text.

$graph_data = Paragraph::load($graph['target_id']);
$output .= '
';
$output .= '
';
foreach ($graph_data->field_slider_image as $item) {
 $title_img =    "Need image title here";
if ($item->entity) {
$slide_uri = $item->entity->getFileUri();
$url = ImageStyle::load('orignal')->buildUrl($slide_uri);
$output .= '

'.$title_img.'

';
}
}

Please anyone give idea ?

Thankyou

You can load the node and then fetch the paragraph targetid . Later you can load paragraph targetid and then get all attributes of the image.

use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;

$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);
$image_alt = $paragraph->my_image_field->alt;
$image_title= $paragraph->my_image_field->title;


Does Commerce Physical Convert Imperial to Metric? Developing a commerce for an international audience and would like to be able to show the sizes (dimenstions of the pieces) in both SI and Imperial. I was approaching this by simply having to Height and Width fields for both SI and Imperial, but wondered if this was the best approach. At least right now, I don't have to figure the dimensions into my pricing logic so I wanted to know if Commerce Physical had conversion capabilities that might let me clean up my layout a little bit? I can forsee using their logic as the site develops, but for now it's unnecessary. So, does Commerce Physical convert units? and or does anyone have advice on approaching this?
Thanks!

Commerce Physical invokes physical_dimensions_convert which is part of the Physical module. This provides a means to converting data between Metric and Imperial.

physical_dimensions_convert is on line 771 of Physical module - http://drupalcode.org/project/physical.git/blob/refs/heads/7.x-1.x:/physical.module#l771


Drupal 7 and PageSpeed The Apache module PageSpeed provides various optimizations for HTML, JavaScript and such, which is great.

However, some of its features are redundant with Drupal's own aggregation and optimization methods. So has anyone tested which filters would be useful for a typical Drupal 7 website and which would be useless due to Drupal already providing support for it?

This is the PageSpeed section from my .htaccess:

<IfModule pagespeed_module>
    ModPagespeed on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters rewrite_css
</IfModule>

Whilst there is a little overlap with the js and css compression, I'm not seeing any negative results. I've set Drupal 7 to aggregate and compress CSS and JS.

The site isn't particularly high traffic though.


Is there a module to translate blocks and pages with language modules? I am working on drupal 7, and I want to translate each Block/Pages/Node to multiple language.

Is there any module available that will provide facility language tabs to enter language specific content and save?

[<English>]  [Spanish]
|---------------------------------|
| Lorem Ipsum                     |
|                                 |
|---------------------------------|

<Save Content>

I have tried following modules:

Internationalization.
Locale (core module).

It only works on Plain/Text format to translate, I need module which allows me to support all Format to translate content in Block/Page/Node, etc.

Block languages submodule of i18n
Submodule i18n_block, included in the i18n module, could be what you're looking for ... or at least address part of your question.
Some more details about it:

This module provides support for multilingual blocks.
You can set up a language for a block or define it as translatable:

Blocks with a language will be displayed only in pages with that language.
Translatable blocks can be translated using the localization interface.

Bean module
Consider looking at the BEAN module also. It offers all sorts of enhancements as compared to the (old fashioned) blocks. And possibly you may want to combine it with modules such as Entity Translation to achieve your goal.
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of the BEAN module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
Managing translations
To actually "manage translations", there are a few typical modules like these (quotes from their project pages, with some bold markup added here):

Translation Management Tool (RC-version for D7).

... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

This module seems already well ported to Drupal 8 also, so much that it is already recommended as a successor of the Translation Overview module (which is about translations of  nodes), which also refers to the Translation Table module (which is about translations of taxonomy terms and menu items).

Translation Management  (No version for D7, only for D6).

... provides complete workflow management for multilingual Drupal sites.
Content managers can manage all translations from one central page. The module shows which contents need translation and notifies translators about what they need to do.
... The module introduces a new Translator role. This role allows translating between specific language pairs. Translators have individual job queues, showing documents that were sent to them for translation.
... Translators can translate everything without having to learn Drupal administration. Node contents, menus, taxonomy, CCK, blocks and strings are all translated from the same interface.

Note: even though there is no D7 version (yet), there are quite a few D7 related issues (and there is a GIT branch for D7 also). And there is the Drupal-Translation.com website with tons of interesting documentation.
Interface translations
The translation of the interface is about the translation of various text strings used throughout the site, like labels used on buttons such as submit, or on tabs such as view or edit. They are the same on all sites (no matter what actual content is contained in a site).
To manage these kinds of translations, there is the Localization update module.
More translation modules
Translations in Drupal is fun, here are a few more to finish:

Language Icons.
Variable.
Title.
Entity.


Create alphabetical pager I want to list all the posts with alphabetical headings like this site:

How can I do this with drupal 7 using views?

Have you looked at the "Glossary" view?  It is a sample view included with the views module that lists all site content by letter in a manner similar to the link you listed.

The "Glossary" view is disabled by default, but you can enable it on the views admin page (admin/structure/views).

The settings for sorting the posts in the "Glossary" view can be found on the views edit screen under Advanced-> Contextual Filters-> Content: Title.  If you click Content: Title, under "More" you will find the option to use upper or lower case when sorting the view.


Editable field in view to display editable form only I'm using the Editable Views module to create a view in which the user can edit the values of numerous fields.

Currently picking an editable table formatter and adding an editable field results in showing the current value of the field above and an editable form below it.

I would like to show only the form with the current value editable, is it possible?

If its possible with another module, please feel free to suggest.

I was informed lately that another module fits better my requirements so instead of Editable Views, I had to use editablefields module.

Editable Fields provides you with an editable formatter which allows you to display the field as an editable form only.

Unfortunately it appears to be only on alpha2 for Drupal 7, but seems ok for my expectations.


How to correctly install PHPMailer + Messaging on Drupal 6 I have a Drupal 6 site where I would like to use PHPMailer to send notifications about newly created nodes and such.
When I install PHPMailer 6.x-3.1, it needs Libraries and that phpmailer be placed under sites/libraries.
As I want different notifications for each content type, I installed
Notifications 6.x-4.0-beta7 and Messaging 6.x-4.0-beta8.
What confuses me, is that I have two different places where PHPMailer can be configured, and they can have different settings: http://mysite.com/admin/messaging/settings/method/phpmailer and http://mysite.com/admin/settings/phpmailer.
Can anyone confirm my setup?

BTW: I had some trouble finding out that existing subscriptions had to be replaced with new (or edited in database) to move from notifications to notifications_content. Might be a help for others.

I have chosen to not use the messaging_phpmailer module and only rely on the PHPMailer module. It works now, but notification/messaging is a mess on Drupal (at least with the beta-versions I'm running). Users email addresses are copied from table users to table notifications(.destination) and table messaging_destination(.address), and sometimes it is not. Maybe it happened during update, but I had to manually update the two via SQL updates, before notification works,. Until I did, the log was filling up with PHPMailer errors 'Invalid Address'.
What's worse, when a user changes his e-mail, the subscriptions copies are not updated, so notifications are still send to the first email address.
You have to tell your users to unsubscribe before changing email, and then subscribe again...

Kind regards
The Roadrunner


Filter and display all commerce product sales by date in a block? In my Commerce Order settings I have created a custom select list field with the following Allowed values.
Allowed values list

1|01/03/2013
2|02/03/2013
3|03/03/2013
4|04/03/2013
5|05/03/2013

Currently I can choose a date from a select list and that filters all sold products and gives me the result for that date.
I am able to separately filter all products sold for each date using views but
is there a way I can list the results of each date separately in a block?
Is this possible or do I have to add the field for each date and set the operator Is equal to the date for each date in my select list?
I would like the output to be something like this.
Event Date Sales

01/03/2013 Total: 210
02/03/2013 Total: 150
03/03/2013 Total: 621
04/03/2013 Total: 500
05/03/2013 Total: 142

You need to do some advanced Views building to make this happen, so if you've never used Views aggregation (formerly I think it was called "group by"), then I'd recommend looking into video tutorials on the topic.

Basically, if you start with a View of Orders and turn on aggregation (under advanced settings), then you can add two fields to the View:

Your custom date select field using "Group results together" as the aggregation type.
The Order ID using "Count" as the aggregation type.

Fiddle with it from there to get it to look like you want, probably using an unsorted list display format with the fields set the show up on the same line.

Here's a quick working export of a View that groups orders by user and shows the number of orders per each user (courtesy of joshmiller): http://pastebin.com/j7NTrkp9


HTML Purifier filter I installed HTML purifier because the default input format is filtered HTML and my users need to be able to add inline styles to the elements in their nodes. I'm trying to get it to work, but it is not very intuitive and there doesn't seem to be much documentation out there.

Can someone please suggest a tutorial or tell me how I can add the style attribute as well as width and height?

What wysiwyg editor are you using? In my end I'm using TinyMCE and I have a related task as yours. What I did was I created a plugin to insert a class on a selected texts. Doing this will provide a convenient way to your users to add styles.

Note: you can use hook_wysywyg_plugin() for this.

Hope this help!


How to load .css file only on your custom 404 Not Found page? Following this guide I created a custom page--404.tpl.php page for my custom 404 Not found page. We put this in template.php:

function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
 }
}

Now I need to load CSS only when that page is loaded. This here only shows how to load it in either node or front page, but not custom 404 page.

This does not work:

    $header = drupal_get_http_header("status");
    if($header == "404 Not Found") {
      $vars['theme_hook_suggestions'][] = 'page__404';
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/bootstrap.css");
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/custom-style.css");
    }

}

As mentioned by @Yogesh, you should use drupal_add_css. Your code cannot work because you have missing slash. Please use below code.

function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/bootstrap.css");
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/custom-style.css");
 }
}


How to count date difference excluding weekend and holidays in Computed Field How to count date difference excluding weekend and holidays?

I should count the number of days between two dates but the weekends and holidays must be excluded from the counting. I used Computed Field.

$start_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_from'));

$end_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_to'));

$start_date = new DateObject($start_date_value['value'], '');

$end_date = new DateObject($end_date_value['value'], '');

$entity_field[0]['value'] =$start_date->difference($end_date, 'days');

Here is my working code for counting the days.

why would you try something like this,

create a variable array that contain all the Hollidays

$currentyear=the current year;
$holiday['01-01-'.$currentyear,other holiday,other holiday];

$result=$start_date->difference($end_date, 'days');
for(ctr=0;ctr=sizeof(holiday);ctr++;)
{
    if(holiday[ctr]>=start_date && holiday[ctr]<=end_date)
    temp++;

}
$result -= temp;


Keep something in cache even after flushing the cache from the Drupal back-end (not drush) I have a particular use case where we use a cache warmer to keep a custom resource in cache (/api/the-url/xxx). The cache warming is done with a bash script that is added to the crontab and runs at night.

For this particular use case I want /api/the-url/xxx to stay in cache even if admins flush the cache in the Drupal back-end.

For now I wrote 2 queries:

One query that moves all the /api/the-url/xxx from cached_data to cached_data_temp on flush cache.

/**
 * Copies xxx cache from "cache_data" to "cache_data_temp".
 * @param $cid
 */
public function copyCacheDataToTempDataCache($cid) {
    $select = $this->connection->select('cache_data', 'c');
    $select->fields('c');
    $select->condition('cid', $cid . '%', 'LIKE');
    $query = $this->connection->insert('cache_data_temp')->from($select);
    $query->execute();
}

One query to move all the /api/the-url/xxx from the cached_data_temp after the flush cache.

/**
 * Copies xxx cache from "cache_data_temp" to "cache_data".
 */
public function copyTempCacheToCacheData() {
    // Select query to fetch all rows.
    $select = $this->connection->select('cache_data_temp', 'c');
    $select->fields('c');
    // Insert rows into "cache_data".
    $query = $this->connection->insert('cache_data')->from($select);
    $query->execute();
    // Empty table.
    $this->connection->truncate('cache_data_temp')->execute();
 }

I've implemented hook_cache_flush which implements the following:

/**
 * Implements hook_cache_flush.
 */
function MY_MODULE_cache_flush() {
    // Before cache is cleared, get all CID's that start with route:api/the-url/%
    // And store it in "cache_data_temp" table.
    $manager = Drupal::service('xxx.manager');
    $manager->copyCacheDataToTempDataCache('route:api/the-url/');
}

And to rebuild the cache:

/**
 * Implements hook_rebuild.
 */
function MY_MODULE_rebuild() {
    // On info rebuild, put back all data stored in "cache_data_temp" in cache_data.
    $manager = Drupal::service('xxx.manager');
    $manager->copyTempCacheToCacheData();
}

Technically everything works fine. The data is kept in cache_data on flush (after moving it to the temp table) but it seems the cache is invalidated. What am I missing here?

For this use case, you might need to consider another storage instead of cache.

warmer -> cache

warmer -> storage -> cache

storage could be either key value or entity or any other storage you prefer.Check here if you are not sure which one to pick.

This way, your warmed data always persistent in the system and can be purged only by warmer (crontab).

When cache clear happen, you can always fallback to storage.


Hook Advance Search Form I want to hook the Drupal advance search form for add more filter criteria,

I want to add the below criteria
1) Search By Post Date
2) Search Between Post Date
3) Search by last day, last 7 days

I applied the hook Mymodule_search_form_alter(&$form, $form_state) {} to add the fields,

Please You suggest me Guys that how can i alter the search query, i am looking for this by last 2 days, but nothing found

This is the link that i got only

https://stackoverflow.com/questions/8575289/extending-drupal-7-search

But that not works,

Any suggestions Please...!!

To alter the query itself, try hook_search_api_query_alter (for search api) or hook_search_execute for the core search


Static image management module for Drupal 7 I want to display a couple of static images on my Drupal 7 site. I could store them in a specific directory I could create in my theme directory (for example).

However, I was wondering whether there was a module to load such images and let Drupal deal with these. I know it is possible to create image fields, but this is (IMHO) overkill compared to a specific directory solution.

Does such module exist? I can't find any. Thanks.

If you're just using static images as part of of your theme, you are indeed correct in your suggestion that using an image field is overkill. I'd even go so far as to say it's entirely incorrect to use image fields for static theme content: fields aren't very portable and add way too much overhead to something that'll likely be a part of every page on the site.

Instead, handling static images is built directly into Drupal's core API and theming layer (so, no need for a separate module). What you'll to do is reference the images in your theme using preprocess functions and the Drupal API.

Let's assume you have a logo (logo.png) in the images/ directory of your theme, and you want to display that logo on every page. In the page.tpl.php template file of your theme, you could do something like this:

But that's pretty brittle: what if the theme moves to another directory? What you want to do instead is create a variable such that you could do something like this:

<?php print $logo; ?>

To do that, you create a preprocess function to create a variable for use in your templates. In your theme's template.php file, create the following function (if it doesn't already exist):

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
}

Then, get the path to the logo using drupal_get_path():

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';
}

Finally, render the path to the logo as an image using theme_image():

// Replace MYTHEME with your theme's short name
function MYTHEME_preprocess_page(&$variables) {
  $theme_path = drupal_get_path('theme', 'MYTHEME');

  $logo_path = $theme_path . '/images/logo.png';

  // Prepare the information needed to theme an image
  // @see theme_image()
  $image = array(
    'path' => $logo_path,
    'alt' => t('My Site'), // t() makes a string translatable
    'attributes' => array(
      'class' => array('logo', 'nav-home'),
    ),
  );
  $variables['logo'] = theme('image', $image);
}

Now, $logo is available for use anywhere in your theme's page.tpl.php. Do the same process (get the path to the image, then assign the themed image to a variable) for any other static images you want to use as part of your theme.


TB Megamenu 3rd level does not expand I'm using TB Megamenu on a D8 site. With a bit of tweaking all working fine.. However, when I try to have a third level of links I can't get this to show expanded. In the menu itself the level 2 item and all level 3 items have 'show as expanded' ticked on, to no avail.

In the TB toolbox it shows correct, I can have the level2 item function as header (group set to 'yes') and have the feel 3 links in one or more columns under level 2. But on the site I get a toggle arrow, and no leave three links. And clicking level 2 does not show the level 3 items underneath (I think they're rendered on the right, outside my 100% width submenu).

Structure wanted:
level 1 link | level 1 link | etc
level 2 nolink (group yes) | normal level 2 items
level 3 items always expanded as group | level 3 items

(when looking at mobile the level 3 does appear under there level 2, but again not expanded, only unfolding when clicking the level 2 item..)

I have a suspicion I could change the one of the twigs (tb-megamenu-submenu.html.twig? tb-megamenu-subnav.html.twig?) but don't know how..

All help massively appreciated!

TB Mega Menu is a pretty awesome module, but we've been using it for a few years and occasionally run into issues where the rendered menu doesn't appear to reflect the menu's structure. It gets "stuck." Here are a few things that have worked for us, in various combinations:

Clear your site's cache.
Rebuild your site's menus (use devel for this).
For the items that aren't showing, create a new parent menu item and move the child items to under the new parent and delete the old parent menu item.

From our troubleshooting, we've determined that TB sometimes seems to "lose track" of the menu and basically all of these efforts are intended to get TB to re-sync.

Hope it helps!


Is Drupal 8 with PostgreSQL supported? Is the new Drupal 8 supported/certified by the Drupal community to run on PostgreSQL?

This is the top hit,

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

I don't really know what that means here in the Open Source part as the majority of support is MySQL (or so it appears).

it works and its even blazing fast.

tested on

drupal core 8.3.7
postgresql 9.6.3
amp stack - XAMPP

drupal case to follow on postgres drupal integration
https://www.drupal.org/node/2564307


What is required for a view menu item to show up as a link in the admin page? I'm creating several views that are to be used as reports. Since they all have a common topic, I'm grouping the views under a sub-path of admin/reports (e.g. admin/reports/data/needs_correction and admin/reports/data/status).

With most admin sections in Drupal, there's usually a landing page that lists all of the sub-content for the section. So, to provide that, I've implemented hook_menu() in the feature that contains the exported report views, as follows:

/**
 * Implements hook_menu().
 */
function MY_menu() {
  $items = array();

  $items['admin/reports/data'] = array(
    'title'             => 'Data reports',
    'description'       => 'Various reports on the status of data in the system.',
    'position'          => 'left',
    'page callback'     => 'system_admin_menu_block_page',
    'access arguments'  => array('access administration pages'),
    'file'              => 'system.admin.inc',
    'file path'         => drupal_get_path('module', 'system'),
  );

  return $items;
}

The only problem is that, after a cache clear, when I navigate to admin/reports/data, all I get is the message "You do not have any administrative items."

In addition to the report views needing to have "Page" displays with URLs nested under admin/reports/data, I also had to make sure the following settings were enabled under "Page: Menu item entry" settings within the Views:

Type: Normal menu entry
Menu: Management

Without both of these settings, the menu links will not show up under the new custom reports page.


How to enable user registration, but don't allow any of those users to login? I want to use the user registration page to collect user data and use its email verification checking to filter out fake users. But the thing is I don't want these users to be able to login to the site. How can this be done in Drupal 7?

Note: So no login at all. I just want to use the registration system to send them an email to verify their account.

You could use Rules

Event: After saving a new account

Action: Block a user >> data selector: account


Remove colons from Drupal form fields/labels How can I remove the : from appearing after every label in forms made with the Drupal Form API?

Create your own implementation of theme_form_element().
The offending semicolon is in $t('!title: !required', ...), and would need to be removed in both locations.

Not the easiest thing to change, but at least it's possible without hacking core!


Modifying destination directory for imagefield file migrating D6->D7 I'm working on a D6->D7 site migration, and I'm having problems trying to figure out how to do a couple things with the migration of some of the files. An added wrinkle in this migration is that I'm moving the storage of the files from the local server to Amazon S3 using the S3FS module (which is really slick, BTW). The source D6 blog content type has two image fields - field_mainphoto and field_thumbailphoto. I would like to combine these fields into one multi-value image field in the blog content type in the D7 site titled field_images. The file storage locations for the two fields are main_photos/[site-date-yyyy]/[site-date-month] and thumbnail_photos/[site-date-yyyy]/[site-date-month].  The new field_images will have a storage location of images/[site-date-yyyy]/[site-date-month]. Therefore, what I need to do is twofold:

Change the destination directory from main_photos/ and thumbnail_photos/ to images/.
Combine the data from these two image fields into one image field.

In the interest of asking one question per post, this one is limited to the first one. I've been looking through all of the documentation, and the shortest and easiest way would be to implement an override of the prepare() method, and modify $entity->destination_dir.  The only thing I don't like is that it's modifying a string. Do I need to go as far as overriding MigrateDestinationFile or MigrateFileUri, or is there a simpler way to do this?

Thanks.

To avoid future situations like this, here is what I came up with:

  public function prepare($entity, stdClass $row) {
    // Change the destination directory for the field_mainphoto and
    // field_thumbmailphoto files to be /images.
    foreach (array('main_photos', 'thumbnail_photos', 'video_thumbnails') as $dir) {
      if (substr($entity->destination_file, 1, strlen($dir)) == $dir) {
        $entity->destination_file = str_replace($dir,'images', $entity->destination_file);
      }
    }
  }


Page redirect in rule after VBO new custom operation is is not redirecting I need to page redirect after the VBO operation.

The page redirects is inside a rule component that I have created for a new operation in VBO.
This is the my new operation in my VBO:

I have marked force redirect. And it doesn't work too.
I tested installing rules debug, to see if rules was executed, and it shows as executed, but it doesn't redirect to cart.
What could I check on this issue?

The debug is showing, skipping page redirect during the batching process, see it please.

How could I add a rule for page redirect, just after the batch process of my VBO operation? This could works.

Note: Not very relevant but

Here is the export of the rule:

{
 "rules_vbo_add_to_cart" :

"LABEL" : "A\u00f1adir las fotos seleccionadas al carrito",
"PLUGIN" : "action set",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_cart", "rules" ],
"ACCESS_EXPOSED" : "1",
"USES VARIABLES" : { "commerce_product" : { "label" : "Commerce product", "type" : "commerce_product" } },
"ACTION SET" : [
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : [ "commerce-product:sku" ],
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  },
  { "redirect" : { "url" : "\/cart" } }
]

}

}

There could be a possibility that some other redirect rule is overriding you page redirect to cart Rule. So please check if in case any other rule is getting triggered or not. If yes, then set priority of page redirect to cart rule's high.

For checking if any other rule is overriding the "Page redirect to Cart"  rule we can actually use
watchdog('Backtrack message','<pre>'.print_r(debug_backtrack(),true).'</pre>');
It will give show everything what all code running at the time the rule triggers.
You are absolutely correct sir, just need to set the weight of Page Redirect to Cart rule lower than other rule. It will set the priority higher.


Resume Parsing to Profile2 I'm looking for a module, integration or solution for parsing a resume on the profile fields.

Big companies like Monster.com and Indeed.com can provide you the ability to upload a resume and fill out all the fields of registration for you. One of my clients ask me for this feature on the website and I have no idea where to start.

Base of what I read online there are two module for parsing Parsing Api and Feeds extensible parsers but they do not exactly what I'm looking for.

I'm using the Recruiter Distribution and Profile2.

My goal is to be able to upload a resume and that resume will complete their resume (Profile fields) for them.

For this you have three options

a) either use third party resume services. I recommend best one RChilli . We implemented them for various client.s

b) Or you can build your own algorithm for Resume Parsing.

c) 3rd one if you are getting fixed format of resumes then write own  using drupal parsing api.

Let me know if I can be of further help.


Hide "Your name" field in comment form from everyone except admin What I want to achieve is to hide the "Your name" field in comment form from all anonymous and authenticated users but visible to users with the admin role.

I was able to use CSS to hide the field, but it also hides from admin.

Please is there a way to selectively hide the field to anonymous and authenticated users but not to administrators?

function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  global $user;

  if ($user->uid != 1) {
    unset($form['author']['name']);
  }

}

Another way is, if your theme has a comment.tpl.php file, putting a condition to restrict authenticated and anonymous user.

<?php print $author; ?>

To limit this to a particular content type, you can create a separate comment template file for that content type.


Remove user entities on module uninstall I am using the following code to delete all the nodes and clean up on uninstall of my custom module. How can I do the same thing for my user entity?

    function wl_project_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(
    ':type' => 'wl_project'
  ));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }
  node_delete_multiple($nids);
  foreach (array_keys(_wl_project_fields()) as $field) {
    field_delete_field($field);
  }
  node_type_delete('project');
  // Purge all field information
  // http://api.drupal.org/api/function/field_purge_batch/7
  field_purge_batch(1000);
}

You can load all user uid's and call user_delete


Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this? I have a panel overriding the node/add form of a custom content-type in one pane and a view listing some nodes including 2 exposed filters to reduce the results of that list in another pane.

Both, the form and the view show up as i want, but if i use the exposed filters the node gets submitted instead of filtering the view.

How can i prevent this? Is there some way to do this step by step?

Drupal 7, latest dev-versions of Views and Panels.

Thanks in advance!

I have the same problem, what i have dug up so far is that the "form" html tag goes missing when the view exposed filter form is rendered within a node form. I am still trying to fix the issue as i haven't figured out why. I will update you if i get any further on this.


How do I insert a   tag inside the   tag on my main menu I have asked exactly this question on Stack Overflow, but it makes more sense to ask it here.

I'm trying to make the text between my tag not display by wrapping it in a and then styling that.

I've added the following function to my template.php file, but I cannot see any difference on the front end; the span just does not appear. (I have cleared my cache.)

Am I using the right function? What am I doing wrong?

function my_theme_link($variables) {
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Rather than building the anchor tag, and passing the result of url() to check_plain(), you should call l(), which builds the tag for you.
Remember to set $options['html'] to TRUE (where $options is the last parameter passed to l()), when the string you pass as first argument to l() contains HTML tags; by default the function assumes $options['html'] is FALSE.


Export nodes from Drupal 4? I am looking into updating a Drupal 4 site. The Node Export module does not seem to have a release suitable for Drupal 4. Can anyone recommend an alternative module or procedure?

The site is running Drupal 4.6.3.

I'm assuming you're on a shared server. Here are some options.

Option 1 - Downgrade PHP.
Although it might not be the safest choice, as both the PHP and Drupal is probably no longer supported, you can do the following.

Some hosts allow to specify a different PHP version in php.ini.
Rent a cheap VPS, which will allow you to set the PHP version.
Some shared hosts specialize with older PHP versions, make a switch.

Option 2 - Use backup and migrate modules.
There are a number of backup and migrate drupal modules which will make the migrating process easier. This would be a safer choice, but the downside, is that you'll loose your theme and you might have to upgrade to ->5, ->6 and only then to ->7. Here are a few modules to look at

Backup and Migrate
Backup

Option 3 - Start from scratch, import in bulk.
It's both safe and probably the best choice. Set up a new site and a theme. Export the data from the old site, using feeds, or other Drupal modules and import it into the new site using modules like Migrate.

I would advise to upgrade to D7, since the support for D6, not alone D5, will be dropped soon.


Is it possible to record user agent information on node creation? I have a custom content type, Picture, which has only a single required image field.  Since this field is required, I thought that it should be impossible for users to save a node without uploading a file, but every once in awhile there is a node created that has no file uploaded.

Users have permission to create nodes of type Picture but not to edit them.

To try to troubleshoot this problem, I would like to record the user agent information (browser, etc.) of users when they create nodes of this content type.  Is there a "standard" way to go about this?

I'm on Drupal 7 if it matters.

I would probably use a combination of hook_node_insert and watchdog (to keep UA info off of nodes and because it is really a logging exercise).

Example (this is totally untested and off the top of my head):

function MYMODULE_node_insert($node){
  if ($node->type == 'MY_NODE_TYPE') {
    // Check for the empty value however you want here.
    // e.g. Field API, EntityMetaDataWrapper, or whatever
    if (!isset($node->field_MY_IMAGE_FIELD[$node->language][0])) {
      $user_agent = $_SERVER['HTTP_USER_AGENT'];
      $account = $_GLOBALS['user'];
      $message = t('Empty image field created by !uid using !user_agent',
        array('!uid' => $account->uid, '!user_agent' => $user_agent));
      watchdog('MYMODULE', $message, WATCHDOG_NORMAL);
    }
  }
}


Quick question: horizontal align taxonomy @ node/add? When adding a node (node/add/article), all the fields are showing up. With module "field group" i can alter the vertical presentation to an editor. In fact, the editor sees (for example) taxonomy-choices as:
Taxonomy
[] Tag 1
[] Tag 2
[] Tag 3
[] Tag 4
[] Tag 5

[] Option 1
[] Option 2
[] Option 3
[] Option 4
[] Option 5

[]Choise a
[]Choise b
[]Choise c
[]Choise d
[]Choise e

But how can i present it horizontal, like

Taxonomy-choices (here radiobuttons

+-----------+---------------+--------------+| [] Tag 1  | [] Option 1 | []Choise a || [] Tag 2  | [] Option 2 | []Choise b || [] Tag 3  | [] Option 3 | []Choise c || [] Tag 4  | [] Option 4 | []Choise d || [] Tag 5  | [] Option 5 | []Choise e |+-----------+---------------+---------------+

You would do that with pure CSS. In your example you would assign a float:left to your fieldgroups.


Prevent form fields changes I have custom field on theme settings. I get default_value for that field from .info file and that's OK. I change the value of that field and submit the form and get a changed value but I do not want it. I want, after submitting form the value of that field will be changed but in that field the value will be showing the default_value from .info file. How could I do that.

If I've understood right you should implement next steps to achieve your goal:

Take a look at drupal_parse_info_file() function to get a value from .info file.
Alter your form and set appropriate value to #default_value property whithin your field.


Feeds: use custom field as unique field for mapping I am using D7, Feeds, XPath Parser.
For mapping, I need to use a custom field as the unique field. I am retreiving data from booking.com and the unique value their is the hotel id, so i need to save this hotel id from the user as well as retrieve data from booking.com bsed on this unique field and map to my contents based on this unique field.

In the documentation of feeds i found this -
Use field other than nid as unique node field in feeds for 7.x-2.x

It says you need to apply a patch from this comment - http://drupal.org/node/661606#comment-5921904

This patch applies to a file called field.inc in the mappers folder of feeds. However this file is not even present there.
The patch also applies to another file, however running the patch gives errors.

Is field.inc actually present in feeds/mappers?
Am I making some mistake in applying the patch?
Is there any other way of achieving  - custom field as unique field for mapping?

Any help on this would be greatly appreciated. Thank you.

This tutorial works for me:

How to configure unique fields in Drupal feeds importer ?

See also the official documentation, which states that you can either use the Field Validation module, or write a custom solution implementing hook_feeds_processor_targets_alter().


Programmatically subscribing all users to Mailchimp list with module I've installed the Mailchimp plugin and added a field to my user profile called field_mailchimp_test and I'm attempting to subscribe all current Drupal users to this list programmatically (since it seems this feature was taken out of the 7.3 branch for whatever reason).

I attempted this code:

function module_mailchimp_subscribe() {
  $users = entity_load('user');
  foreach ($users as $key => $user) {
    if ($user->uid != 1 && !empty($user->mail)) {
      $edit = array(
        'field_mailchimp_test' => array(
          'und' => array(
            0 => array(
              'value' => true
              )
            )
          )
        );
      var_dump(user_save($user, $edit)); exit;
    }
  }
}

Which returns a user object with the field_mailchimp_test field set to true, which I would think would subscribe them, but when checking the users page and/or var_dumping the user object, the field is no longer set to true.

So my question is either what is wrong with my code that it's not subscribing users, or what is a different (easier/more sensical) way of doing this?

I'm pretty sure the MailChimp module doesn't actually store user subscriptions in the Drupal database, it picks up data from the MailChimp API when required.

What worked for me was to export all my Drupal users and import them into MailChimp through their website.  This is fine for a once-off, and you should be able to handle new and updated users directly through the module.


User Login block missing It vanishes suddenly without any notifications today. I am using Drupal 7 with "Mix and Match" theme. I used to working this morning.

Website shows no error at all.

I have tried the following to get it back:

Find the block table in the database and tried to modify the visibility of the user, login of current theme entry - not working
At admin->structure->blocks, under the current theme. The "User login" is already under sidebar first. I tried remove it and add back, changing the weight - not working
In the other themes the user login block does not show up either, including the default theme Bartik.
Repeat the above steps with a drush cc all command. Not working.

What else could I try to get it back?

Anyway, I found the problem. It was the permission setting. I should set it to "no restriction" rather than restrict to every tick-able role (because guest is not there to tick)


Link doesn't appear in configuration I'm a Drupal 8 newbie writing my first module. I have a functioning yet basic module to learn from. What I'm working on now is for it to get a value from a configuration page. If I go directly to the URL for the custom config page it works. What I'm having trouble with is getting a link to my custom config page to display on the main config page. I've been through every tutorial I can find on this topic and I just can't figure out why it's not working. I hope you all can help. Here's my yml files.

itemrequest.info.yml

name: Item Request
type: module
description: Allow the public to request items for the District to purchase.
package: YCFLD
core: 8.x
configure: itemrequest.settings

itemrequest.routing.yml

itemrequest.itemrequest:
  path: '/itemrequest'
  defaults:
    _controller: '\Drupal\itemrequest\Controller\ItemrequestController::itemrequestpage'
    _title: 'Request an Item'
  requirements:
    _permission: 'access content'
itemrequest.settings:
  path: '/admin/config/itemrequest/settings'
  defaults:
    _form: '\Drupal\itemrequest\Form\ItemrequestForm'
    _title: 'Item Request'
  requirements:
    _permission: 'access administration pages'
  options:
    _admin_route: TRUE

itemrequest.links.menu.yml

itemrequest.settings:
  title: 'Item Request Form'
  description: 'Settings for Item Request form"
  route_name: itemrequest.settings
  parent: system.admin_config

Do see anything wrong in the .yml files? Is there anything I can do to troubleshoot this?

system.admin_config is the top-level page at /admin/config. Normally you would not put your configuration link there - you would instead put it into one of the blocks that appear on that page. For example, the "People" block would be user.admin_link, so if you want your config under "People" use user.admin_link as your parent. Or if you want to put your configuration link under the "Development" block use system.admin_config_development as your parent.

If you want to create your own top-level block then you need to do things a little differently - see the core user module and how it defines user.admin_link in user.links.menu.yml and user.routing.yml - this shows how a new block is created on the config page. You can then put your configuration link in that new block.