The following code, let's login any user programmatically.

Not exactly; it sets the current global user object to an instance of a user, but it doesn't log the account in or touch the session. Many things that happen in that request that rely on the global user object will behave the same as if the account was logged in, but it won't be, and they won't have a session tied to the account (not yet anyway).

Cookies are added at the end of the request, in drupal_session_commit:

if (!drupal_session_started()) {
  drupal_session_start();
  if ($is_https && variable_get('https', FALSE)) {
    $insecure_session_name = substr(session_name(), 1);
    $params = session_get_cookie_params();
    $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
    setcookie($insecure_session_name, $_COOKIE[$insecure_session_name], $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
  }
}

As a by-product of the way Drupal initialises sessions (lazily in an exit hook), if the call to $user = user_load(<any_uid>); happens before the first session has been initialised, the session will be initialised for that user and they will appear "logged in" for their next request, even if the user_load line doesn't execute.

But, hook_user_login won't have been invoked, the last login column in the user table won't be updated, and so on. It's not a full-on "login", just initialising the session for a particular user.

Incidentally, if you call $user = user_load(<any_uid>); when a session already exists for another user, the session for the next request will still be for that other user. It won't be overridden with a session for <any_uid>.


template file for content header of a view

As far I understood you want to  modify title of your views page.
This title is the title of entire page.
You can modify this title using drupal_set_title('Your Title');

If you want to modify this title you can load current title first by drupal_get_title() and then set new title.


The main purpose of the access content system is to have control of what every user can see and avoid every possible security issue. This is the desired behavior and almost every module or general ApI uses it, so you won't find default solutions for this.

I've been in the same situation and the only solution I found was to create a custom modules and, in my case, query directly to the menu table to get all the elements I want, and check the permissions myself to either display a link, or simply a title of the content when the user don't have permissions to see it.


Exclude entities currently referenced on a node with entity browser

You are listing entities as your base type, but you want to filter based on the current node.
You need to introduce the information about the nodes that already reference (all) entities, and also what the current node is.
You do that by using the "backwards" Relationship, the one that goes from Entities back to the nodes that reference them. This Relatinship will be named something like Content using field_entity_reference and its Description will be Relate each Content with a field_entity_reference set to the content.
It will not be named "Content referenced from field_entity_reference", that one is the "forward" Relationship.
You can Require this Relationship because you want the results that do have a reference from a node.
Then add the Contextual filter Content: ID, make it use the Relationship, and configure
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Your CT
Configure the other options as needed, but in the end:
More
Exclude
So we found all nodes that reference entities in our results, and used the Contextual filter to exclude the results related to the current node.


Backup an enterprise application server and restore

I am not sure what you're exactly asking for.

Do you want to do this automatically on a regular basis, or just as a cold/manual standby? We are very happy with Drive Snapshot for full Windows Server backups.
If you're looking for hot failover solution you have to work with redundant machines on all levels (Load Balancer, Web Server, DB Server, File Server). Be prepared to spend some weeks of work (or about 1000 Euros/month) to get this working.
About Drupal 6 itself: You have to backup the DB and the files. For the files the backup & migrate module is very handy. You could combine drush and rsync, but on Windows you will face some problems. Cygwin could solve some of them.


Make canonical URL in document HEAD absolute

True, for nodes you can't use hook_page_attachments_alter. You have to use hook_ENTITY_TYPE_view_alter!

And very likely you also find all of them in the end in hook_preprocess_html.

Here's how I got it working:

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (isset($build['#attached']['html_head_link'])) {
    foreach ($build['#attached']['html_head_link'] as $key => $head) {
      if ((isset($head[0]['rel']) ? $head[0]['rel'] : FALSE) == 'canonical') {

        $url = \Drupal\Core\Url::fromRoute('<current>', [], ['absolute' => 'true'])
          ->toString();

        $build['#attached']['html_head_link'][$key][0]['href'] = $url;
      }
    }
  };
}

Source: How to remove specific meta-tag from header section of page?

Alternatively you can use Metatag. All you have to do is to set the [node:url:absolute] token into the Canonical URL form field in the Advanced section of the Metatag configuration for all Content.

And only then, all of sudden, they become available to be preprocessed in hook_page_attachments_alter. There I removed their trailing slash which gets added by default.

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME/MYMODULE_page_attachments_alter(array &$attachments) {

  // Remove trailing slash from canonicals.
  foreach ($attachments['#attached']['html_head'] as $key => $head) {

    if ((isset($head[1]) ? $head[1] : FALSE) == 'canonical_url') {

      $href = isset($head[0]['#attributes']['href']) ? $head[0]['#attributes']['href'] : FALSE;

      if ($href) {
        $attachments['#attached']['html_head'][$key][0]['#attributes']['href'] = rtrim($href, '/');
      }
    }
  }
}


How to declare core requirements in composer.json?

On further experimentation, it appears that it is unnecessary to add this to the composer.json file. It is enough to add drupal:system (>=8.3) to the info.yml requirements. This seems to be automatically interpreted by the drupal.org package repository.

Even when the composer.json file does not specify any dependencies, composer show drupal/MODULE will show that it requires ^8.3, and it will be impossible to install the composer package on an 8.2 site.


Preprocessed var not being passed to twig template

You're correct in thinking that trying to access your var from within the macro is the issue. See Twig's macro documentation.

But as with PHP functions, macros don’t have access to the current template variables.

You can pass your variable into the macro.
{{ menus.menu_links(items, attributes, 0, menu_name, tollfree_number) }}

Then you have two options, you can update the macro definition to add an extra parameter for your custom var.
{% macro menu_links(items, attributes, 0, menu_name, toll_free) %}
  {# etc.. #}
  {{ toll_free }}
{% endmacro %}

Or you can use the special varargs variable without updating the macro definition.

If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.

Pass the var to the macro the same way, then access it like:
{% macro menu_links(items, attributes, 0, menu_name) %}
  {# varargs[0] has the first extra arg, varargs[1] has the second, etc #}
  {{ varargs[0] }}
{% endmacro %}

Using the special _context and varargs vars:
{{ menus.menu_links(items, attributes, 0, menu_name, _context) }}

{% macro menu_links(items, attributes, 0, menu_name) %}
  {{ varargs[0].tollfree_number }}
{% endmacro %}


Easy way to create blocks programmatically?

For Drupal 7:

Use hook_block_info and hook_block_view hooks in your custom module. hook_block_info defines the block. It will show up in admin > structure > blocks. *hook_block_view* displays the content. See examples below from the Drupal API.

Example of hook_block_info, where two blocks are defined (titled Syndicate and Recent content):

    <?php
function hook_block_info() {
  // This example comes from node.module.
  $blocks['syndicate'] = array(
    'info' => t('Syndicate'),
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['recent'] = array(
    'info' => t('Recent content'),
    // DRUPAL_CACHE_PER_ROLE will be assumed.
  );

  return $blocks;
}
?>

Example of hook_block_view:

<?php
function hook_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {
    case 'syndicate':
      $block['subject'] = t('Syndicate');
      $block['content'] = array(
        '#theme' => 'feed_icon',
        '#url' => 'rss.xml',
        '#title' => t('Syndicate'),
      );
      break;

    case 'recent':
      if (user_access('access content')) {
        $block['subject'] = t('Recent content');
        if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
          $block['content'] = array(
            '#theme' => 'node_recent_block',
            '#nodes' => $nodes,
          );
        }
        else {
          $block['content'] = t('No content available.');
        }
      }
      break;
  }
  return $block;
}
?>

Refer to the Blocks API page on Drupal.org for full list of hooks. Drupal 6 is a little different. There is no hook_block_view hook; instead use hook_block to declare blocks.


Can't install modules in Drupal 8 Ubuntu - Should I change owner?

go to the folder where you installed Drupal 8. Ex:

cd /var/www/drupal

In you case, it looks like it's:

cd /var/www/html/benia

then

sudo chown www-data -R modules

Now try installing again.

To prevent other conflict, I would www-data all of your Drupal

cd /var/www/html/

sudo chown www-data -R benia


If I understood correctly, your view is not returning any results because of it's filter (field_sold = yes), if so, then no field are going to be shown in the view, so if you rewrite a field 'No results behavior' it won't show, simply because your view is not returning any row.

What you are looking for is the 'No results behavior' that's in the advanced tabs in the view. That's what is going to show when your view returns no results at all.

Just add Custom text field and put whatever you want there.


How do you make a module integrate with the Rules module?

The best documentation you will find is in http://drupalcode.org/project/rules.git/blob/refs/tags/7.x-2.1:/rules.api.php. You will also find this file in the code you downloaded from drupal.org.

You also would probably learn something from looking at other modules that implement rules similar to how you would like it in metatags and seeing how they implement the above hooks.

Then it is up to you do decide what functionality from metatags you want to expose to rules using those hooks.


Show tables doesn't work like that. I doesn't know anything about prefixes, it lists all tables in the database.

The schema API has an API method to list tables, which is DB agnostic and respects the prefix.


Views: count and filter by entity field value

Going of memory here, this might be wrong:

Add contextual filter of node id (nid) (so the player nid goes here)

Add a RELANTIONSHIP of Strikers Referencing Entity and checkmark the box that says, "force relantionship" or something along those lines.


Show help text above input and below title of a cck field

you could use template_preprocess_field ( preprocess for theme_field ) to adjust the position of field description/help text.

Cheers


What part of the Feeds api knows if there is a difference between old and new data?

I am modifying the code in hook_feeds_before_update and writing the code like this :

if ($item){
    $node = node_load($item);
    $changed=false;

      if ($entity['ITEM'] != $node->field_item[LANGUAGE_NONE][0]['value']){
         if (trim($entity['ITEM'])=="UNKNOWN"){
             $entity['ITEM'] = $node->field_item[LANGUAGE_NONE][0]['value'];

         }

      }

AND then I flag it with a rule :

{ "rules_flag_when_updated_by_feed" : {
"LABEL" : "Flag when updated by feed",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "flag", "feeds" ],
"ON" : { "feeds_import_csv_importer" : [] },
"DO" : [
  { "flag_flagnode" : {
      "flag" : "flag_asset_for_review",
      "node" : [ "node" ],
      "flagging_user" : [ "site:current-user" ],
      "permission_check" : "1"
    }
  }
]

}
}


Changing a Profile type Machine Name broke the Admin/People search

I think this is a bug in Profile2 module.
I recreated your issue on a test installation and the same results happened.
After I inspected the database itself I found that the machine name was not changed in the table profile but correctly changed in profile_type table.
What you could try is to manually change the machine name in the profile table and see what happens then.
Also, it might be helpful to post your issue in Profile2 issue tracker, maybe they can fix this for other users.

Good luck.


try

Perinote&trade; <?php print render($content['field_mast']); ?>

or this one

Perinote&trade; <?php print render($content['field_mast']->value); ?>

I recommend you to download and install devel module and write

<?php kpr ($content);?>

to see what $content contains. you can also call this function in hook_preprocess_page as well.


You also need to set the language of the fields.

$node->language = 'en';
$field_langcode = field_language('node', $node, 'body');
$node->body[$field_langcode][0]['value']   = $body_text;
$node->body[$field_langcode][0]['summary'] = text_summary($body_text);
$node->body[$field_langcode][0]['format']  = filter_default_format();

See this comment (https://drupal.org/comment/5464106#comment-5464106) for more info.


Why does the zen theme load javascript in the head element?

Some contrib modules only work correctly if jQuery and other scripts are in <head>.

Check out the Magic module or the AdvAgg module, which gives you greater control over how CSS and JS files are handled in your theme.


How to create a button that sets a node value

There is a Field Button module that creates and renders a button.  You can then write a rule that is triggered by button clicks.  This works great if you only need one or two buttons on a page.  However, this module has trouble figuring out which node the button belongs to (and therefor may not be a good option for lists of nodes & buttons rendered by views.)

Another option is the Rules Link module.  This module does roughly the same thing.  It  is not as pretty, but it has better rule integration.


Is there a way to position my Article title in Drupal 8 teaser?

You either need to do it in node templates or you can try out Display Suite, but I'm not sure about the exact state of it in Drupal 8.

Update: Didn't see that you also mean the byline. That one is easy, that's a setting on the node type form whether it should be shown or not.


This is caused by a hiccup in the node menu rebuild after installing a new module. If you run into this issue, its likely due to one of three problems, which you can address in the following order:

Clear full cache, forcing the content menu to rebuild
Go to the menu options under /admin/structure/menu/manage/navigation and look for your add content menu items and make sure they are disabled
If these two fail, then there is probably an error in your build that is preventing the menu from rebuilding correctly - check in your error logs for any issue there and address.


Batch operation for consuming data from API via drupal_http_request

Hi You're probably best off using the feeds module to import from feeds it can do them as one off imports imports or periodic batch jobs and create nodes from the feeds automatically. Even though they're beta/alpha they're well used and actively developed.


I could achieve this by implementing hook_form_alter on add to cart form (in a custom module) and setting combine like this :

$form_state->set(['settings', 'combine'], FALSE);


Where is the field exclude checkbox in Content type > Manage display in Drupal 7

Clicking and dragging the 4-arrow handle, you can move the field (which one you want to exclude) under "Hidden" (In Drupal 8 this is now called "Disabled".) in admin/structure/types/manage/{content type name}/display.


How do I create linked nodes without user intervention?

A solution that doesn't go deep into the code is to use the Prepopulate module.
It enables you to prepopulate form fields through the link to the form page:

http://www.example.com/node/add/recipe?edit[field_entity_reference][widget][0][target_id]=123

You'll probably want to construct the links automatically, it can be done with Views. You create a Block Display that contructs the link using the Food information it's been placed on, through a contextual filter. When the Block is placed on Food pages the link leads to new recipe form that has the food where you just left from already filled in.
You can find more info about how to construct the link with the help of Views in this answer: Add Prepopulate links to Node pages part of the answer.


How can I create a view that shows image file fields which do not have any data?

One way of going about this is using Views PHP. Add your file path as a field and exclude it from display. Add a Global: PHP filter with return file_exists($row->uri); as your filter code. This should return TRUE for files that do exist, and will remove those from the results, showing only files in your database that do not exist. Your current filter criteria are only checking the file_managed table in the database and are not going to be aware if the file exists.


I guess you should use hook_init as it's the first hook called right after Drupal setup sessions.


How to enforce a one-to-one relationship

I think you will need to use an entity reference view to enforce your restriction. In the settings for your reference type you can select Default or Views: Filter by an entity reference view

You will need to create your View first, instead of adding a Page or Block you need to add Entity Reference but this isn't available as part of the Views Wizard.

Part of the filter criteria will be to hide books which have already been assigned to a student. Hope this helps you get to your solution


How do I automatically do an SQL insert when creating a new node?

You've to create your own module and after use a hook_node_insert you'll receive a $node object with all informations you need.


Drush missing the "provision" and "Hostmaster" commands

Have had similar issues with this in the past,

How many instances of drush is there on your server? In my case I had a drush 3.3 version in /usr/share/drush and the aegir 4.4 version (with provision and hostmaster commands) in /var/aegir/.drush

In order to get drush to work, I had to alter the path for the aegir user to include /var/aegir/.drush first

You can always tell which version of drush you are using by running the command

which drush


Why are comments not a node content type?

To answer this, I first had to understand one thing: Entities are not nodes.

Entity Types are special groupings of fields.

Node is an entity type, which requires some fields, such as 'Title', 'Author' and 'Publish Date'.

Content Types are instances of Node which further define more fields. So a 'blog post' content type can have 'Hook', 'Introduction', 'Summary' and 'Related posts' fields, in addition to 'Title', 'Author' and 'Publish Date'.

Node is an entity type specialized for content. A comment is not designed to be a node because it is too different from a typical content. It's not necessary to have a 'Title', 'Author' or 'Publish Date' field in a comment. Because it is so different, it is created as another Entity type instead.

For more details, see this article on Drupal.


So it turned out to be a jquery version problem.

Here is how I sort it out.

I have installed the jQuery Update module with version 1.10 selected and I had to change it to version jQuery Version 1.7 and all the gotchas faded away.

I hope this help to anyone else!

(Module jquery_update)


Reverse proxy causes issue with CSS links and HTTPS

Do you have any css/js aggregation module installed. If so delete the caches under sites directory. You can even try uninstalling the module to debug if that is causing the issue.
Clear Drupal caches
Ensure you do not have global $base_url hard coded to http.


How to enable Administration menu Toolbar style for editor profile?

You just need to grant a few permissions to the editor role to achieve this. Navigate to http://mysite.com/admin/people/permissions and tick the checkboxes next to the following permissions for the editor role:

Use the administration toolbar
Access the administrative overlay
Use the administration pages and help
View the administration theme

Only the pages that an editor user usually has access to will be shown as links in the toolbar.


entityQuery array instead of orConditionGroup()

I don't know how it was working before, but the solution seems to be to place the explicit 'IN' in the query as such:

$results = \Drupal::entityQuery('node')
  ->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_first.target_id', $anArrayOfNids, 'IN')
  ->condition('field_seciond.target_id', array($anotherNid))
  ->execute();

Or, if I was to just convert this to the more complicated, yet more robust method:

$results = \Drupal::entityQuery('node');
$group = $query->orConditionGroup();
foreach($anArrayOfNids as $nid) {
  $group->condition(field_first.target_id, array($nid));
}
$query->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_seciond.target_id', array($anotherNid))
  ->condition($group)
  ->execute();


How to set automatically meta tag from node content?

Log into your Drupal 6 backend and go to sitename.com/admin/content/types

Edit content type you wish to set auto generation of meta tags.

In this example I am editing Basic Page so I hit edit and ended up at

sitename.com/admin/content/node-type/page

Select "Meta tags settings" and on that page you can set various meta tag generation options.

One you probably want to set is:

Generate meta tag content when the meta tag content is empty
(default)

AND

Generate meta tags content from the node teaser (default)

Both of these are default so they should be working out of the box.


CSS3pie - styles not being picked up in IE. How to reference the path?

The PIE Drupal module should add the behaviour where necessary, you don't do that yourself. This would defeat the point of the Drupal module, and in using the Drupal module you don't need to specify the path yourself. (Though your current path there is incorrect, but I'm not sure on the correct way right now.)

css3pie can seem very touchy, there is a long list of known issues, some of which could be causing your problem. Also ensure that your files directory is writable, and that there are no errors on your sites status page. File permission problems can prevent the css3pie module from creating it's stylesheet. Each setting in the themes .info file should also be on a new line.


How to link to a users profile in a view

By default, user profiles are at user/UID, where UID is the numeric user ID.  (This is true unless you are using a module like Pathauto to customize the profile URLs.)

So, one way to do this is to:

Add the numeric user ID field to your view.  Make sure to check exclude from display so it won't actually be shown in the view.
Reorder the fields in the view so that the user ID field comes before the field for which you want to rewrite results.
The value of the user ID field will now be available as a token in "Rewrite results."  So, you can use the token to create a link to the user profile like this: user/[uid] (the actual token may be slightly different).


How to add an 'operations' link to a custom route?

What drupal core version are you using?

Link templates have been changed to links instead of route names a few months ago. See Node and other example entity types.

Another requirement is that link template names and route names need to match.

However, your primary problem is that link templates about the entity or at least entity type that you have, and that's not the case for your example.

Using link templates for operations is convenient when possible but in no way required. It can be any Url object. So your last attempt is actually close, you're just not using the right API yet (and yes, there are definitely way too many ways to generate links/URL's).

Try this:

\Drupal\Core\Url::fromRoute('entity.bloom_stem.add_form', ['bloom_stem_type' => $entity->id()])

Then use that for 'url'.


Module to list menu_router / path debug info?

I'm not sure there's a module specifically for that, if anything I think it would come under the domain of Devel as you mentioned in the comments. I haven't seen anything like that in Devel before though.

Getting the router item for the current path itself is very easy:

$item = menu_get_item();
$callback = $item['page callback'];
// etc...

You could just wrap that in a hook_init() and dpm() it out for a quick solution, or maybe build a patch up for Devel.


Firstly, it seems that the new server does not allow clean urls or it needs some configuration. Check the documentation on Drupal.org: Step 6: Configure clean URLs

Then, clean all caches and run cron. You will then see all image paths as /new/sites/sites/default/files/...

That's because the new site is set on folder ROOT/new or am I wrong? So there is no error, you have to set the domain to look at this subfolder.

If you don't have permissions to do this in your hosting or there are no options like Add-On domains you can follow the discussion at Drupal installed in subdirectory but made to appear in root according to your hosting enviiroment.


There can be multiple reasons why your styles are not applied to the page elements:

CSS aggregation is enabled. Disable aggregation and see if your custom CSS works. If it doesn't, you probably forgot to include the file in your theme - move to the next option.
CSS stylesheet is not added to the theme via THEMENAME.info file or other methods. Placement of the CSS file in your theme's css folder does not make it load while Drupal pages are loading.
wrong selector used
styles are overridden by a selector with higher specificity  ...etc.

To add CSS stylesheet to the Drupal theme, add the following to the current theme's .info file and clear cache:

stylesheets[all][] = css/local.css

You can also add CSS files to your theme via drupal_add_css function that you can use in hook_preprocess_page().

Hope this helps.


drupal_add_js() won't work with footer scope

Make sure you're printing $page_bottom in html.tpl.php.

In Drupal 6, it looked like this:

<?php print $closure; ?>

In Drupal 7, you now want all 3 of the $page_top, $page, and $page_bottom variables which correlate to the header, content, and footer scopes. Here's a sample (and simple) html.tpl.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<body>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>


Theming info on each views is located under 3-rd col - Advanced on the view. Last row say "Theme:Information". Click on Information. According to your needs select template name, and create file in your current theme. Then click on "Style output" for example if you choose this kind of filename, and get code for the file (copy/paste) in above created file. Type dpm($variables); after opened php tag (install devel module ofcource) This will output available data for this template. After creating file, go agayn on theme Info and click Rescan template files. Your new file will be bolded. If not, there is something wrong - start again this process.
There is too many name suggestions - get the last (longest) for your type.

Example:
If we have views "Latest content" with all default options, for example we can create a file views-view-unformatted--latest-content--page.tpl.php in the theme folder. Code must be (with our dpm()):

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */

dpm($variables);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

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

<?php endforeach; ?>

Also we may create separate view mode for node and use them in this views. This way we may theming node views in separate file according to node view. We can get entity_view_mode module for this from DO. This is not alternative to above views theming, but as addition.

There is too many variants how to theming views - this depends what we set on the current views.


Avoid duplicate entries when programmatically adding field values

array_unique could solve your problem here, perhaps employing a similar solution to the one proposed in https://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array


Here the solution, if somebody is interested:

create new section in your theme, call it e.g. bottom-section and use this preprocess hook to move the content of the bottom pane to bottom-section section

function theme_preprocess_panels_pane(&$variables) {
  if ($variables['pane']->panel == 'bottom') {
    // Move to a region
    drupal_add_region_content('bottom-section', $variables['content']['#markup']);
    // Delete the pane from the panel
    $variables = array();
  }
}


What is good way to hide update.php file?

You can add the following line:

RewriteRule ^update.php$ - [R=404,NC,L]

to your .htaccess file so the web server returns a 404 rather than bootstrapping Drupal to show access denied.


How do I print a username of current profile?

It depends on how you build the profile page (which modules you use), but usually you will get the user info on profile templates by accessing $account, while $user is the logged in user.

So, in short, $account->name should be what you are after. Again, this depends on how you create the profile page. For a profile page built with Views, this would not help, but you could add the name in the View itself.


Database::setActiveConnection not working as expected?

Database::setActiveConnection() doesn't influence those objects that already have a \Drupal\Core\Database\Connection object, which means that the following code will not use the preview connection for altering the database table.

use \Drupal\Core\Database\Database;

$schema = Database::getConnection()->schema();
$old_key = Database::setActiveConnection('preview');
$schema->addField($table, $field, $spec, $keys_new);
Database::setActiveConnection($old_key);

When you call \Drupal::logger(), you get a DbLog object that was already initialised before Database::setActiveConnection('preview') is executed, which means it will use the old connection.

To be able to use the new connection for logging, you should try creating a custom logger that uses the connection you want, without you setting the connection before calling its methods.

As side note, Database::setActiveConnection() returns the old key; it's easy to restore it: Just call again Database::setActiveConnection() passing the value returned from the previous call, as I did with the code I shown.


Access webform select list key from within rules

I used a work-a-round for this by using the translate option in Drupal.

I've set up the key as a value and translated the key to the value that I wanted.

This was used for a custom field, but it worked fine for me.


Custom error message + hide generic message

you can use the theme_status_messages function to do search and suppress certain messages.

The String Overrides module lets you do global text replacements which should work in your case.


Query params should be passed to the function in a keyed array:

$query = array(
  'nid' => 123,
  'foo' => 'bar',
);
$params = array('query' => $query);

print l(t('Modifier'), 'node/' . $entity->nid . '/edit', $params);


How to add jquery lower version for a particular drupal page?

Add your condition to remove jquery 1.10 :

function THEME_js_alter(&$javascript) {
if ($your_condition) {
    $path = drupal_get_path('module', 'jquery_update') . '/replace/jquery/1.10/jquery.min.js';
    unset($javascript[$path]);
    drupal_add_js('path/to/jquery1.8');
}


Relation Between Drupal Commerce Line items and Products

It sounds like you are confused.

Short answer:
Line items has a reference to a product.

Explaination
Line items are only used when you add something to your order (cart), they have a relationship between the order and the product and hold data like price quantity, but can hold additional data, like the address (in case of subscriptions), which a unique each time you buy something.

If you have product attributes like size or weight, you probably want to store this on the product, since a products with different sizes and weight should be different products (A S size t-shirt is not the same as a L sized t-shirt).

So it really sounds like you are doing this the wrong way.


First of all: thanks for mentioning the Views Rules module. I didn't know it, but I'm sure it will be handy in the future.

It seems that you're not quite familiar with the Views module. While creating or editing your View, you should click the "add" button at the top, right underneath "Displays". When you select "Rules", a new display is added and there appears a little button with the text "Rules" in it. (I've already added one in the picture underneath.)

Afterwards, configure the Rules' settings by clicking "edit the field info" and choose the desired data types.

Finally, select the View you would like to use in your Rule. In my case, the View is called "Test".


Does hook_install() get called before or after configuration yml files are loaded?

When Drupal install a module, first it installs the default configuration of the module, then it invokes its hook_install(). This is evident from ModuleInstaller::install(), which contains the following code.

  // Install default configuration of the module.
  $config_installer = \Drupal::service('config.installer');
  if ($sync_status) {
    $config_installer
    ->setSyncing(TRUE)
      ->setSourceStorage($source_storage);
  }
  \Drupal::service('config.installer')->installDefaultConfig('module', $module);

  // If the module has no current updates, but has some that were
  // previously removed, set the version to the value of
  // hook_update_last_removed().
  if ($last_removed = $this->moduleHandler->invoke($module, 'update_last_removed')) {
    $version = max($version, $last_removed);
  }
  drupal_set_installed_schema_version($module, $version);

  // Ensure that all post_update functions are registered already.
  /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
  $post_update_registry = \Drupal::service('update.post_update_registry');
  $post_update_registry->registerInvokedUpdates($post_update_registry->getModuleUpdateFunctions($module));

  // Record the fact that it was installed.
  $modules_installed[] = $module;

  // Drupal's stream wrappers needs to be re-registered in case a
  // module-provided stream wrapper is used later in the same request. In
  // particular, this happens when installing Drupal via Drush, as the
  // 'translations' stream wrapper is provided by Interface Translation
  // module and is later used to import translations.
  \Drupal::service('stream_wrapper_manager')->register();

  // Update the theme registry to include it.
  drupal_theme_rebuild();

  // Modules can alter theme info, so refresh theme data.
  // @todo ThemeHandler cannot be injected into ModuleHandler, since that
  //   causes a circular service dependency.
  // @see https://www.drupal.org/node/2208429
  \Drupal::service('theme_handler')->refreshInfo();

  // In order to make uninstalling transactional if anything uses routes.
  \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
  \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));

  // Allow the module to perform install tasks.
  $this->moduleHandler->invoke($module, 'install');

The first lines I quoted are for installing the default configuration, while the last one is for invoking hook_install().


Change Exposed Filter from Dropdown to List

Go to BEF settings in the view....

Find your exposed filter, and choose the display type. (list)


title_prefix override to h1 instead of h2

Potential solutions that didn't work:

http://drupal.org/project/panel_variant_page_title
Changing panels-pane-tpl.php h2 to h1 as this changes all panels not the 1 page panel that needs to be h1.

Eventual solution:

Turning off Page panel titles and just hardcoded h1 tag into body field. Not ideal but there really is no working solution apparently.


Token Not Working On Auto Node Title and Auto Entity Title

This won't work indeed... It has to do with the way Drupal saves nodes. It starts with the title, and then reads and writes the rest of the fields.

The quick and dirty way is to use the rules module, and on node creation or edit, save the node again. I have been using this technique and can confirm it works.


module_invoke() is essentially using three functions: function_get_args(), function_exists() and call_user_func_array(). As it doesn't invoke any database API function, it doesn't influence the performance a lot.
Using module_invoke() allows to write code that is compatible with future versions of the module or Drupal. There is a feature report on drupal.org which asks to use a different schema for the hook names; if that would be implemented (it could happen in Drupal 8), then the code that invokes directly the hooks should be changed.

In specific cases, where (for example) you are invoking the same hook implemented by the same module many times in row, it is possible to change the code to do something similar to:

verify the module implements the hook you need, once, at the beginning
call the hook directly when you need the value returned by the hook

This should be done if the module is really invoking the same hook implemented from the same module many times in row (which doesn't exclude the hook is being invoked in a loop).

To notice that module_invoke() cannot be used when one of the parameters needs to be passed by reference. There are specific functions that invoke hook implementations in that cases (e.g. comment_invoke_comment(), but those functions invoke the hook implemented by all the modules.


Add to Custom Entity Content on Node add/update

You can do like this

Suppose your entity name is my_entity.

<?php
use Drupal\my_module\Entity\my_entity;

function my_module_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
            $form['actions'][$action]['#submit'][] = 'my_module_node_form_submit';
        }
    }
}

function my_module_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $node = $form_state->getFormObject()->getEntity();

    $url = $node->field_website->uri;
    $name = $node->field_com->value;

    // Now to check
    //Generate my_entity entity.
    $entity = my_entity::create(
               [
                 'label' => 'token',
                 'id' => $node->id(),
                 'status' => true,
                 'name'=> $url,
                  "url" => $name,
                  "created" => time()
               ]
         );
    $entity->save();
}

To update enity:

$entity = my_entity::load('content entity id');
$entity->set("name", 'name value');
$entity->set("url", 'url value');
$entity->save();


This is odd, but it's probably not rules-centric.  It looks like the system itself is in a funky state.  Have you had any other problems with white screens?  Do your mysql logs show any errors (I have seen similar problems when the max_allowed_packet size was too small, for example, or when the mysql server ran out of disk space.)


If your theme code depends on certain content types being there, then that tells me that you are actually building a module plus a theme, and not just a standalone theme.

One way to do this is to use the Features module to export your content types and other settings. Then you probably want to move some of your theme functions into the module code, so that other themers can more easily build on top of what you've created.


Print just the value of Views field inside of views-view-fields template

I guess you want to create a row header which contains some value from other fields. If it is your case, I will suggest you this solution.

Use fields in format

Add field Global: custom text

Then you can use the token, which is the value of field, with your custom HTML structure.

Please note that custom text field must be placed after the field you want to use. In my case, it is title. You need to exclude it from display, otherwise, there will be 2 titles.


How to use an omega template with hook_theme

I solved this using this question as a basis to work from https://stackoverflow.com/questions/4100485/register-your-theme-functions-in-drupal.

The template (.tpl.php file) goes in the omega template directory. You then use a hook_theme function to define the theme with the template key in the array pointing to the name of your template file.

The theme is then called with theme(your-theme-name)

Here's my working example for my module called vis:

function vis_menu() {

  $items['images'] = array(
    'title' => 'Images',
    'page callback' => 'image_page',
    'access callback' => TRUE,
  );
  return $items;
}

function image_page() {
  return theme('images');
}

function vis_theme() {
  return array(
    'images' => array(
      'variables' => array(),
      'template' => 'vis',
    ),
  );
}


Prefill content type form field with alter hook

You need to implement either hook_form_alter() or hook_form_FORM_ID_alter() (there's no hook_alter() which is what your code is implementing at the moment).

The second is probably preferable as it targets the form you're interested in:

function prefilllink_form_job_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $form["field_apply"][LANGUAGE_NONE][0]["value"]["#default_value"] = $user->mail;
}


How can I allow HTML links in translated strings?

the problem is the absence of the quotes. I try to insert this traslation on a drupal site and it work!

Some explanations here. You can find a more information
 on the help page.
Note: after changing this
  value,you may have to clear the cache
  for this setting to take effect.

It also work with "


How to display only some terms of a specific vocabulary in Views

This can be achieve through View,

Create a view based on the Taxonomy (Strucutre->view->View settings)
Choose Page or Block View.
Select the desire fields in the field section
Add the taxonomy vocabulary ( categories) and Add term in Filter criteria, and select the Drop down, select the select the hirarchy.

Then it will show the term what you want to filter, select the b,d,e terms over there

And then, b,d and e terms only will be shown in View.


Rule to create a Node from a Webform Submission

Below is something I learned about using webform data in Rules, which may help you to get this to work ... (assuming this question is about D7).

You have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So try to use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform).
the 2nd attempt explains what to do in case of Webform.

Note: if your target field is a multi value field, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "Add item to a list".


How do I fetch a vote given on a node and programmatically apply this vote to the author of the node?

I undesrtand that your question is about a 'code' solution, this one is not but it works, you'll need rules conditional module, and voting rules module , it adds an action: 'a node has been rated', then fecth node-author-by-id, make shure both have the same field (user-bundle and contentype), set user-author-rating-field-value with your node-rating-field-value, or import rule, please edit your field-rating machine name and dependencies as needed. i hope it helps.

    { "rules_set_node_five_star_rate_to_node_author" : {
    "LABEL" : "set node five-star rate to node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "RATING_MODULE_MACHINE_NAME" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_YOUR_FIVE_STAR_FIELD" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "node:author:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched_author_by_id" : "author_by_id" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_has_field" : {
                "entity" : [ "entity-fetched-author-by-id" ],
                "field" : "field_YOUR_FIVE_STAR_FIELD"
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "entity-fetched-author-by-id:field_YOUR_FIVE_STAR_FIELD" ],
                  "value" : [ "node:field_YOUR_FIVE_STAR_FIELD" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


How to display the form submission results in a custom page?

Display Webform Submission Data using Views is a bit challenging. As an alternative to installing Webform MySQL Views (which depends on Data and Schema), consider the Forena module. Here is a quote about it:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

So in this case you'd use Forena to report about the Webform data stored in the Webform tables, which are contained in your Drupal database.

Disclosure: I'm a (co-)maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


How to support legacy url alias' and/or support multiple url alias' (Conditional Pathauto?)

I believe the new-for-Drupal-7 Redirect module will provide what you need. Have not used it myself yet, but I used Path Redirect (which provides similar functionality for Drupal 6) to solve a similar problem. I generated a two-column table of values (old URL in one column, new URL in the other), and fed that to Path Redirect -- problem solved. Hope this helps.


Why creating the front page doesn't work?

Have you cleared the cache after you added the new template file in the theme directory? You should always clear the cache, once you change a template file for a theme already installed, or you add a new file that was not used before.


How to import content for content types with user-defined fields

I suggest you look into migrate module. This module is very flexible, very well documented and can  easily handle  and ease the pains of content migration.  Custom content, users, comments, etc .. and just about whatever you throw at it can be set up as 'migration tasks'.

Good-luck!


How do I package a distribution on Drupal.org?

On Drupal.org, there isn't yet support for a distribution composer.json file, as reported on Support for distributions.
The package system used from Drupal.org, to be able to build the package files for a distribution, requires just two files: drupal-org.make and drupal-org-core.make. The latter is only necessary when using a Drupal release that is not official.
If your system doesn't allow you to create a .make file as required from Drupal.org, you can manually create it with any text editor, as long as you use the correct file format (see Example drupal.org make file), and you follow what reported in Drupal.org distribution packaging requirements. In particular, see the notes reported at the beginning.

External libraries are validated against a whitelist of GPL-compatible libraries since all code distributed from Drupal.org must be GPL compatible
Git clones from Drupal.org sandboxes (as opposed to full projects) are not supported
Patches hosted on servers other than Drupal.org are not supported
Modules and themes hosted on servers other than Drupal.org are not supported
If you need to specify anything other than an official release of the Drupal core project itself, that needs to go into a separate drupal-org-core.make file
If you request a specific Git revision you must also define the branch that revision came from

In future, some of those restrictions could be lift. There are feature requests / bugs opened in the packages.drupal.org issue queue.


Should I use the Rules module to implement custom code when performing state transition?

Using the Rules module for this is indeed an option, whereas you should be able to implement your "custom code" using the Rules Action to "Execute custom PHP Code". If you do, make sure to not forget the PHP filter (otherwise you'll run into "Rules "Execute custom PHP Code" option not available ...").

Of course, that required 'PHP filter' might be your show-stopper. BUT: are you sure you need "custom code" at all? There may be alternative (site building only) techniques to even not need that "custom code" (and hence you'd avoid the need for that PHP filter also). And/or as a variation, you could write your own (custom) Rules Actions also ...

Not to forget these benefits also:

Less custom code (= easier to maintain and/or upgrade to future Drupal versions).
Possible out-of-the-box integrations with other modules, such as Flag, VBO etc.


Theme a link with l - redirect to translated version

I ended up doing it this way:

$nodepath = "node/26";
$languagepaths = translation_path_get_translations($nodepath);
$currentlanguage = i18n_language()->language;
$path = $languagepaths[$currentlanguage];

if (preg_match('/^node/',$path)) {
    $path = "". drupal_get_path_alias($path, $currentlanguage);
} else {
   $path = $nodepath;
}


AJAXX AutoComplete joins and unions causing error

So, I figured out how to convert MySQL to Drupal SQL, of a join and union sql transaction, I am not done - but this is the start and the rest is just copy / paste and massage.

$matches = array();
  $debug_stop = "";

  // Firstname and Lastname - Larry Adams
  $firstname_lastname_query = db_select('field_data_field_first_name', 'f')
     ->fields('f')
    ->condition('field_first_name_value', '%'. db_like($string) .'%', 'LIKE');
  $firstname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'f.entity_id = l.entity_id');
  $firstname_lastname_query->fields('l');

  // Username checks - lAdams
  $username_query = db_select('field_data_field_user_name', 'u')
      ->fields('u')
      ->condition('field_user_name_value', '%' . db_like($string) . '%', 'LIKE');
  $username_query->leftJoin('field_data_field_last_name', 'l', 'u.entity_id = l.entity_id');
  $username_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($username_query);

  // Nickname checks - lar-bear Adams
  $nickname_lastname_query = db_select('field_data_field_nickname', 'ni')
      ->fields('ni')
      ->condition('field_nickname_value', '%' . db_like($string) . '%', 'LIKE');
  $nickname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'ni.entity_id = l.entity_id');
  $nickname_lastname_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($nickname_lastname_query);

  // Execute the query
  $result = $firstname_lastname_query->execute();

  $debug_stop = "";
  // save the query to matches
  foreach ($result as $row) {
    // If we returned back a user_name accessible field
    if (isset($row->field_user_name_value)) {
      $matches[$row->field_user_name_value] = check_plain($row->field_user_name_value);
    }
    // If we returned back a first_name_value accessible field
    if (isset($row->field_first_name_value)) {
      // with a last name
      if ($row->field_last_name_value) {
       $first_last_name = $row->field_first_name_value ." ". $row->field_last_name_value;
       $matches[$first_last_name] = check_plain($first_last_name);
      }
    }

  }

  // Return the result to the form in json
  drupal_json_output($matches);


Your hoster needs to enable that extension. I don't think you can do that in a local php.ini file.

I don't believe that they can't do it, they just need to add an extension=pdo_mysql.so to the php.ini, install the package, depending on whatever setup they are using. It's their job to do that, pdo_mysql is a hard requirement for Drupal 7.


Promotions not translated on cart and checkout page?

I found work-around for this issue. Inside the template that prints that section (commerce-order-total-summary.html.twig) there is a loop that prints adjustments:
{% for adjustment in totals.adjustments %}

        {{ adjustment.label|t }} {{ adjustment.amount|commerce_price_format }}

{% endfor %}

and where adjustment label is printed I added t twig filter, so now it can be translated on standard user interface translations page:
/admin/config/regional/translate

I know that it's not optimal solution, but it works, so I hope this can help someone until bug is fixed.


Please try module Terms of Use . It won't check user age directly but the user has to sign understanding your website terms of service before registration.


Easiest way to post videos directly to S3?

If you're using Drupal 7, take a look at these two projects:

Storage API
Amazon S3

Both of these let you store file uploads on S3 instead of the local filesystem.


How to insert a new tag with chosen module ?

I believe the Autocomplete Deluxe module aims to solve that problem.

Autocomplete Deluxe is a replacement for Chosen module. It has a similar feel to the Chosen module, but allows you to add new tags/terms.


Module is enabled but none of the hooks work

Hook implementations are cached in Drupal 7. After adding a new hook, you need to clear the cache for example using the devel block or drush cc all.

Also, hook_view() is not actually a hook. It is callback that is only invoked for the module which provides the given node type.


Allow User Role To Schedule Content As Different User

That would be Administer Content. Be careful with this, because the permission provides a lot more than simply control over the node Author identity.

The alternative would be the Masquerade module, which would allow the user to pretend they were a different user, and post content as that user. A little more involved for the posting user, but safer for your site.


How to set field permission with time limit

You can hide at all links to separately edit/delete field collections values, go to Structure » Content types » YOUR_CONTENT_TYPE » Manage display, click to field collection settings cogwheel and clear fields.

Also you have to forbid an access to edit/delete by direct link, place in your custom module:

/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $path = 'field-collection/' . strtr('your_field_name', array('_' => '-'));
  $items[$path . '/%/edit']['access callback'] = FALSE;
  $items[$path . '/%/delete']['access callback'] = FALSE;
  $items[$path . '/add/*/*']['access callback'] = FALSE;
}

Don't forget to clear cache.


Responsive CSS in Bootstrap theme (more specifically "Tweme")

Your basic CSS is right. I would check to make sure:

1- Your css file is actually loading

I go to view source and look for my file name. If the file name appears in a giant weird JS object, but not in the css declarations that means the file can't be found (most likely a 404)

2- Your base theme isn't writing some overly specific CSS that you need to override.

Using the web inspector or a similar tool inspect the element you're trying to change, get your width where it should be to have your change apply (in that case greater than 1200 width) and see if there are styles overriding the one you wrote.

An easy temporary way to get around #2 would be to use !important at the end of your style, just to see if you're in the neighborhood, but that !important should be deleted of course :)


How one can display the file path once it is successfully uploaded

Please try below: file_create_url($file->uri)

function import_form_submit(&$form, &$form_state) {
  // Load the file.
  $file = file_load($form_state['values']['file_fid']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  $uploaded = file_save($file);
  if ($uploaded == TRUE) {
    drupal_set_message(t('The file has been uploaded.'));
    dpm(file_create_url($file->uri));
  }
  else {
    drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
  }

}

Also, refer the answer for pre-node save function


Getting the values and url of an entity reference field using entity query then store it inside a variable

Getting the values and url

Sounds like you want to link to the referenced node, so I will assume that you want to do that.

No need to use entity query at all.

You can do it like this, assuming your content type is Article:

function mytheme_preprocess_node(&$variables) {

  $node = $variables['node']; // gets current node object

  if ($node->getType() == 'article') { // checks if content type is article

    $reference_links = array(); // creates empty array
    foreach ($node->field_academic_experience_ref as $item) { // loop through ref field
      if ($item->entity) { // gets referenced node object
        $reference_links[] = $item->entity->toLink(); // gets ref node link, adds to array
      }
    }

    $variables['academic_menu'] = $reference_links; // creates variable

  }

}

Then in twig

{% for reference_link in academic_menu %}
   {{ reference_link }}
{% endfor %}


I was able to get this to work with the following contextual filter in my "info" block.

Filter by "Title"


How add a function in a condition method in db api

I believe the addExpression is for SELECT clause expressions

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3AaddExpression/8.2.x

For a WHERE clause expression it should be

$query->where('UNIX_TIMESTAMP(et.field_symposium_event_time_value) BETWEEN :start AND :end', array(':start' => $day_start, ':end' => $day_end));

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21QueryConditionTrait.php/function/QueryConditionTrait%3A%3Awhere/8.2.x

And then of course remove your $query->condition(...); line.


Adding javascript to admin view and user view

Is it possible that this library is being pulled in by your public theme, but not by your admin theme? Authenticated users probably are maybe not seeing the edit from in the context of your admin theme, like admins are. If so, add the library to your admin theme too (you can create a sub-theme of Seven and add it there).


Go to the language configuration page here

admin/config/regional/language

And set the default language to French.


In drupal 8 you can easily create a new view mode via backoffice : Administration > Structure > Display modes > View > User
and click Add new User view mode.
To go further see documentation : https://www.drupal.org/docs/8/api/entity-api/display-modes-view-modes-and-form-modes


using drush:

$ drush eval "field_purge_batch(500)"

you might have to run a few times, or increase the $batch_size
then there might still be field_deleted and field_deleted_revision tables, even after running cron

query

SELECT * FROM `field_config` WHERE `deleted` = 1
SELECT * FROM `field_config_instance` WHERE `deleted` = 1

if you come up empty, you can safely delete those leftover tables


Try changing your code like this

Skip
<?php print $content; ?>


How can i get prepared for DRUPAL-PSA-2016-001?

1) List all the Drupal 7 projects you maintain.
2) Have a list of used modules by project, you can use fllowing command

 drush pml --no-core --type=module --status=enabled > mylist.txt

3) Once the updates announced, you can search your modules lists to detect which project you really need to update


I found the problem, it's stupid.

I forgot to add permission to access to contextual links for this user role, so that's it.


I added the latitude and longitude in views fields and overwritten the global: Custom Text field with the replacement tokens and added "element-hidden" class so that value will be there in views in hidden. Any other Solutions?


hook_module_implements_alter() would seem to be the one you are looking for to change execution order.

However, I'm not sure It is exactly what you are looking for because it could have to do with the node edit form. One field could be higher on that form, and that could be causing the validation order issue. The weight of the fields on the form itself could be dictating the validation order. If that is the case, you can hook into the node form and run the validation in the order needed.


How add tab menu item with external link to article node content

Create custom module  Replace mymdulename with your module name.
implement hook menu to add "Menu local task" which let your menu
item to show along with view, edit ..
page call back to add the
redirect rule, in below example I am redirecting to google.com, you
can add a check according to node and add redirection rule.
access callback ensures this menu tabs gets attached to nodes for article
content type.

  /**  * Implements hook_menu().  */

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

  $items['node/%node/movies'] = array(
    'title' => 'Movies',
    'page callback' => 'mymodulename_redirect',
    'page arguments' => array('node', 1),
    'access callback' => 'mymodulename_content_type_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

  return $items;
}

/**
* Access callback
*/
function mymodulename_content_type_check($node) {
  if ($node->type != 'article') {
    return FALSE;
  }
  return TRUE;
}

function mymodulename_redirect($node) {
  dpm($node);
  $url = "http://www.google.com";
  drupal_goto($url, array('external' => TRUE));
}

Update

to open the external link in new tab use jquery to add '_blank' attribute
in your custom

jQuery('.tabs a').attr("target","_blank");

Remember to pick unique classes instead of ".tab" to avoid having this behaviour to all tabs.


How to retrieve a shipping service settings field in Views

Try configuring the shipping field with rewrite results, checking the "rewrite the output of this field and using a either a custom token or the machine name for the shipping type, and make the machine name the same as the client's code.


Where is a resource for theming drupal 7 views?

Views for Drupal 7 also provide theme information. See the advance section or follow the URL (in my case)
example.com/admin/structure/views/nojs/display/[my_view]/[type]/analyze-theme


In drupal6, you can go into the block admin screen for that block and change the title there.  If you are meaning the title/hover title for the drupal image itself, you can create a function in your theme's template.php file along the lines of:

function YOURTHEME_system_powered_by($image_path) {
  $image = theme('image', $image_path, t('Powered by Drupal, an open source content management system'), t('Powered by Drupal, an open source content management system'));
  return l($image, 'http://drupal.org', array('html' => TRUE, 'absolute' => TRUE, 'external' => TRUE));
}

and just change the t() functions in there to say whatever you want.

ADDITION:

A quick grep thru d7 suggests changing this...

/**
 * Returns HTML for the Powered by Drupal text.
 *
 * @ingroup themeable
 */
function theme_system_powered_by() {
  return '' . t('Powered by Drupal', array('@poweredby' => 'http://drupal.org')) . '';
}

in a similar way as described above would accomplish what you want, but yes, you would need to edit some code to do it in your theme.

If that doesn't work, or you aren't confident enough to do that, you could just remove/disable the powered by drupal block itself and create another one with your own created by link in it.


How to Display a pdf, rft, doc, txt on a overlay?

You chekced pdf or pdf_reader modules? in order to display it on an overlay open its link in lightbox


The setting on the performance page, unlike D6/7, does not affect the page cache module at all. The page_cache module always caches indefinitely, you can not configure it otherwise. Invalidation happens through cache tags, as you said.

The setting that you can see only affects external caching through the HTTP Cache-Control header, for example Varnish and in browsers. There are ways to invalidate caches in varnish using cache tags, but there is none to invalidate pages that are cached client-side in browsers, so I would recommend to not set that value too high.


How to create an image gallery in Drupal 7

It seems like Taxonomy, Colorbox, Views, and the Image field in D7 would be the best way to do it.

Create a taxonomy for gallery
Create a content type for image
Create a View to display the gallery taxonomy
Create a View to display the images in the gallery taxonomy term

I say that is the best approach because it gives you the most flexibility, and will only take you about 30 minutes to set up. Anything else for a gallery (in my experience) tends to be overkill unless you're an actual photo sharing website.


How can I use month name as contextual filter?

You can programmatically alter the contextual filter value of "january" to "01 - 12" in hook_views_pre_view

/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') {
    // insert here some php magic to format "January" to "01".
    $og_arg = t('@og_arg', ['@og_arg' => $args[0]], ['langcode' => 'en']);
    $date = date_parse($og_arg);
    // assign formatted value.
    $args[0] = $date['month'];
  }
}


How to access global variable from within Drupal content

Based on your comments, you might want to try using Drupals built in functions to retrieve the correct path for your assets.

The 2 you could take a look at are base_path() and path_to_theme().

For example:

<img src="<?php print base_path(); print path_to_theme()?>/images/image1.jpg" />


Add a new index of type index on the node table with these 7 columns; I would label it "status_type_uid_nid_vid_created_changed"

status, type, uid, nid, vid, created, changed

Once you have done that run explain again; odds are the index will need to be re-ordered or another table will need to have an index added to it.

Try #2. Flip nid & uid.

status_type_nid_uid_vid_created_changed

status, type, nid, uid, vid, created, changed


Theming views-exposed-form search block same like normal Drupal search block

You can try block attributes
You can edit class or ID. More readable and easy to maintain.


It should be pretty easy to create a block in your own custom module that displays this info. Take a close look at the fb_post_page function in fb_post.admin.inc and you can see what the module uses to output that data on the user/%uid/edit/fb-post page.

I'm not super familiar but it looks like the info you want to display can be gotten by calling theme('fb_post_connect', array('connection_path' => fb_post_get_oauth_url($account, $app_id))); and displaying the result in a block (or even directly in a panel pane)


For the first menu item, you didn't provide any page callback, and MENU_DEFAULT_LOCAL_TASK menu items inherited it from the parent menu item. In this case, Drupal returns a 403 error.
For the last one, the reason can be one of the following:

The page callback function doesn't exist, or it is defined in a file that is not the module file
The user account doesn't have the permission 'access content'


There are a number of scenarios where having dev, stage and live are useful.

Example:  minor updates.

Run drush pm-update on dev, test and make sure everything is okay.
Push your code to stage / test, run drush updatedb, and make sure everything is still okay.
Push your code to live, run drush updatedb, and confirm everything is still okay.

The point here is that the operation of 1. and 2. are slightly different; by testing your deployment on the stage server before bringing it live, you can confirm that the deploy will go okay (i.e. there are no uncommitted components on the dev machine, or all state needed for a successful deploy is part of the deployment process.)  If you did not test this, then you'd break the live site if you forgot to commit an important file, or otherwise did not faithfully update the components used in deployment.


Get requests did not need session authentication, POST, PUT, DELETE require session authentication to know the user and check if he has right permissions to complete the request or not.

Oauth authentication have many types of auth you must ensure that you are authentication the user not the an app (for example) so the request is authorized to complete.


How to change page.html.twig depending on the content type I am viewing in Drupal 8?

Page title is available as a block, and you can control the visibility from there.

However, to answer your question, here's how to provide different template suggestions based on content type:

function YOUR_THEME_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
  // Try to get the node, so we can check if we're on the node page.
  $node = Drupal::request()->attributes->get('node');
  if ($node && $node->getType() == 'YOUR_CONTENT_TYPE') {
    $suggestions[] = 'page__NAME_OF_YOUR_TEMPLATE';
  }
}

This will allow you to use page--NAME-OF-YOUR-TEMPLATE.html.twig template in your theme only for specific content types.

You can read more about hook_theme_suggestions_HOOK_alter() here.


What is the difference between the various log messaging severity levels?

The levels are mostly arbitrary below alert, and just represent a general priority of "badness".

In theory, a minimum log level could be set up in core, so that you could enable logging on a live site, but only have certain levels logged (say, emergency, critical, error, and alert) and the rest ignored.  To my knowledge, this hasn't been implemented (I would love to be shown wrong about this).

The current usage has more to do with filtering on the recent log messages page (admin/reports/dblog).


Find the total amount of multiple products of the same type - Commerce

Use commerce_donate module to get donation then this field use in your rules

Create a rule add events in Rule
Add condition entity has a field (your donation field)
Add variables in this you can use php field to get total amount of donation.
Add action in email section use token of variables

I am not already try this but hopefully this may work.


How to install required packages for feeds spreadsheet module as shown required by Composer Manager?

You essentially have 2 options:

Ask your hosting provider to let you install and run Composer, and access it via the command line
Run the Composer install locally, then push all the files up (including the vendor folder)


How to generate the function stack trace of the last request made?

A function trace will only show you the function calls that lead directly to that piece of code.

PHP provides the functions debug_print_backtrace() for that, which is however not very readable but it will result a huge amount of text. devel.module provides a ddebug_backtrace()function, which us much easier to read.

To see all function calls of a single page, you need to install a profiler like XhProf.


Views output into multiple columns based on variable of results

not sure what you're asking is really possible just through the Views UI.

However, this should is reasonably simple with a views template file and a bit of PHP knowledge.

http://webpartners.es/en/drupal-7-views-templates-and-preprocess provides some info about how to override the output of the view. you'll need to apply a bit of logic on how to begin/close your columns/lists but that's just a bit of arrays in PHP.


How to change scheduler date format in *_node_form

I find it the url is: admin/config/content/scheduler

The strange is that it doesn't have a "configuration" link in module page list.

Oskar


8.3: How to create a node via REST with html?

Drupal is probably expecting an array of field data, even if the field itself only accepts a single value.

When the JSON is decoded, this is still an array:

{
  "format": "basic_html",
  "value": "This is the body of the test"
},

But with 2 items, when only one is expected.

You should be able to fix by providing an array with just the one item:

"body": [{
  "format": "basic_html",
  "value": "This is the body of the test"
}],


Auction module provides auction functionality. Commerce integration is an option.

  Structure: Auctions are entities with start / end date, starting
  price, minimum price and instant buy price. Auction content type with
  auction reference field is created upon installation.

or

Commerce Auction module lets you create auction/reverse auction websites using drupal commerce. see the Demo

Features

Allows creating auctions and reverse auctions using drupal commerce
Automatic auction timeout extension
Automatically adds auctioned product to the winner's shopping cart
By default disables remove and edit quantity fields of auctioned products in shopping cart
Global and per-auction bid limits (like uc_auction)
Lists bids using views


Add an additional custom submit handler to default search api Solr view filter?

The solution was to enable AJAX on the view. This stopped the page refreshing and the double form submission.


Hacking core is strongly discouraged for the uninitiated because it effectively reduces the support community of thousands to a support community of one (or whatever your team size is). Without this best practice, helping those new to Drupal would be nigh impossible. It also hinders modularity and, in some cases, security.

This having been said, hacking core is not always as evil as we like to make it out to be. Without modifying core, we wouldn't have distributions like Pressflow and the like that augment core in interesting ways. It's just vitally important that you know exactly what you're doing, that you're distributing your patches with your distribution (preferably in a way that allows you to apply them again automatically post-upgrade), and that you're keeping detailed documentation of what you've changed and why you've changed it.

Depending on how you have things structured, you could certainly make the above change to xmlrpc_request(), create a patch, and then use something like Drush Make to automate applying it (note that Drush Make is moving  into the Drush project itself for the 5.x release), while supplying additional documentation in the makefile and elsewhere as to what the change does and why it's necessary/desired.

Another common pattern to enhance core functions is to create a wrapper that adds a tiny bit of functionality to a core function, and call the wrapper in lieu of core's implementation. When feasible, this makes things much more modular. Consider the following:

/**
 * Wrapper function for xmlrpc_request() to provide logging.
 */
function mymodule_xmlrpc_request($method, $args) {
  $xrr = xmlrpc_request($method, $args);
  watchdog('xmlrpc', $xrr->xml);
  return $xrr;
}

Again, depending on what you're doing this may or may not be feasible, but when it is you've saved yourself a few headaches in trying to make sure that core stays patched and documented. Though in this case, a one-off function like this seems like a perfect candidate for such a wrapper. If your implementation is captured in a module, you could even expand on it to control the log level of your entire solution, disabling this functionality on production sites:

/**
 * Wrapper function for xmlrpc_request() to provide logging (if enabled).
 */
function mymodule_xmlrpc_request($method, $args) {
  $xrr = xmlrpc_request($method, $args);
  if (variable_get('mymodule_log_level', 0) > 0) {
    watchdog('xmlrpc', $xrr->xml);
  }
}

In short, you want to maximize what you can do with modules (and you can do a lot), but there are legitimate reasons for altering core. It should be done with care, that's all.


Getting warning message in statistics module

Doing this in phpMyAdmin solved my problem.

  Login to phpMyAdmin
  Choose the affected database. If you only have one database, it
  should choose it by default so you don't need to do anything.
  In the main panel, you should see a list of your database tables.
  Check the boxes by the tables that need repair.
  At the bottom of the window just below the list of tables, there is
  a drop down menu. Choose "Repair Table"

This should fix your table, and let you access it again. Now that it is fixed... it's a good idea to make that database backup!

taken from this source


The username has not been activated or is blocked. using custom login form

If your requirement is displaying user login form in AJAX POPUP then you can consider Ajax Login/Register module.

This module provides a block with 2 links (Login, Register) for the
anonymous user.
When the user clicks on Login or register the
requested form appears in a nice ajax popup.


Highlight Field Errors with an Ajax Form

Not as hard as I thought, but for anyone else trying to solve the same issue, you need to get all the relevant fields from form_get_errors() and add the error class to the same - note I also clear the previous errors:

if (null !== form_get_errors()):
  $commands[] = ajax_command_invoke('#myFormDiv .form-item.error', 'removeClass', array('error'));
  $commands[] = ajax_command_remove('.alert-dismissable');
  $commands[] = ajax_command_prepend('#myErrorDiv', theme('status_messages'));
  foreach (form_get_errors() as $field => $message) :
    $commands[] = ajax_command_invoke('.form-item-'.$field, 'addClass', array('error'));
  endforeach;
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
endif;

Note that your $field will be dependent in what you've set in your validation function, so you might need to do some funky things to make sure '.form-item-'.$field is finding the right div.


In Drupal 8, views field output uses the field formatters that entities use (Drupal 7 uses its own plugins for this).

The "Today", "Yesterday", "Monday", other functionality cannot be handled by the standard field formatters.

Drupal 8 makes it easy, though, to make new formatters.  Make a custom module, and extend DateTimeDefaultFormatter.  Inside this class, you would override the formatDate() method (and possible the defaultSettings() one, depending on how fancy you want to be.  The method would look something like this

protected function formatDate() {
  $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();

  if ($date is today) {
    $output = $this->t('Today, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is yesterday) {
    $output = $this->t('Yesterday, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is this week) {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'D. H:i', $timezone != '' ? $timezone : NULL);
  }
  else {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'm/d/y H:i', $timezone != '' ? $timezone : NULL);
  }

  return $output;
}

You need to work out the logic to choose the proper format.  Set the annotation on the formatter properly, and you can use this formatter in the view (or anywhere else).

This should give you a start.


Manager of groups stopped appearing as member and groups stopped appearing in her "my groups" list

Apparently the user was still manager of her groups, but was no longer registered as a member. I was able to use the Masquerade module to assume her identity, go to the appropriate node/%/group menus for each one she was manager of and give her membership again. Everything seems to be back in line after that. My guess is it was caused by overzealous use of an alternate link/rule-set I was experimenting with to manage group enrollments/drops. I've now disabled that until I figure out how to get to function properly.


How to update my module's dev branch on Drupal.org

No need to deal with tags for the dev branch. Tags are only required for stable releases.

Since you have already added your dev branch you just have to add your files, commit them and push them, like this:

git add path/to/files
git commit -m "Commit message"
git push origin 7.x-1.x

Then you just wait for drupal.org to reroll a new dev version. It takes up to 12 hours to see a new dev version on the project page.

You should be able to see your commits though if you click the View commits link in the development sidebar block.


I think you're using a Node view instead of a Term (Taxonomy) view. So you're pulling in nodes and getting the tags associated with them. Since multiple nodes can have multiple tags, you're getting duplicates. I think the "Distinct" doesn't work because it's checking the Nodes to make sure they're distinct, not each field you add to the view.

So instead, try creating a view and choosing the Term type, instead of Node. I put together a very simple view without even using Distinct and I have no duplicated values, even though each term is definitely used on more than one node.

I don't know how you would do the count next to each term using Views, but I know the Advanced Taxonomy Blocks module does this.


Drush 8.1 Drupal 8 throws PDOException: SQLSTATE[HY000] [2002] on MAMP

Make sure your database host setting is 127.0.0.1 instead of localhost.


How to style a custom theme setting form

Basically it's just these two steps:

Define a library from MYMODULE.libraries.yml.
Attach the library to your form.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

  Attaching a library to a form

  As forms are just render arrays, attaching a library works just the same:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $entity */
  $formObject = $form_state->getFormObject();
  if ($formObject instanceof \Drupal\Core\Entity\EntityFormInterface) {
    $entity = $formObject->getEntity();
    if (
      $entity->getEntityTypeId() === 'node'
      && in_array($entity->bundle(), ['organisation', 'location', 'event', 'article'])
    ) {
      $form['#attached']['library'][] = 'yourmodule/yourlibrary';
    }
  }
}

To add additional wrapper divs around some single or multiple form elements you can nest them into containers or fieldsets. For example:

  class Container

  Provides a render element that wraps child elements in a container.

  Surrounds child elements with a  and adds attributes such as
  classes or an HTML ID.

  Usage example:

$form['needs_accommodation'] = array(
  '#type' => 'checkbox',
  '#title' => $this
    ->t('Need Special Accommodations?'),
);
$form['accommodation'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => 'accommodation',
  ),
  '#states' => array(
    'invisible' => array(
      'input[name="needs_accommodation"]' => array(
        'checked' => FALSE,
      ),
    ),
  ),
);
$form['accommodation']['diet'] = array(
  '#type' => 'textfield',
  '#title' => $this
    ->t('Dietary Restrictions'),
);

The D7 Form API Reference still is the most useful resource for that. Though you might want to check for changes on the D8 equivalent: Form and render elements.


Add a filter on the relevant "style-field".
Change it's settings to be "Exposed"

And that's all you need. See Taming the beast: Learn Views with NodeOne for a good intro to the Views module.


What top tips you have for designing drupal themes?

All you need is a consistent architecture and good planning. I think getting started on a HTML5 foundation is a good beginning. I suggest you build your project on a subtheme based on Omega or Fusion Theme kits.

Omega has a based on 960 grid system (12,18,24 columns, 20px gutter). It uses the zone/region relationship for a better block handling. Of course is a responsive theme, it starts mobile to desktop (not viceversa) which is very good.

You can even copy Omega subtheme page layout settings, alter it and save it under a new template with Delta module (created by Jake Strawn). Your settings can be then used in various context using the Context Module.

This is a good architecture to start with.

As a UX designer keep in mind Drupal is jQuery and jQuery UI ready, so learn to manipulate widgets via a module or a js (added in your info file).

Keep a consistent architecture and never mess with modules that are not necessary and only bloats your site.

In additional a good knowledge of Views module, contextual filters and relationships is a must.


I was able to solve it :-)

This helped me:
https://www.drupal.org/node/2594631#comment-11322879

It is important to map all addressfield subfields, otherwise it will not work.


Where files are used if path entered by hand

inline_image_to_field module promises turn your inline images into an image field (image entities).

  This module will take images that are embedded (copy/paste) or were uploaded via the wysiwyg and attach them to an image field.

This way you can have your Drupal installation being fully aware of any such images and take advantage of any file or image entity related modules.

DISCLAIMER: I have not used this module and it is new module with not many installs so use with caution on your DEV environment before commiting to your LIVE environment


Delete field and related data (field_delete_field, field_delete_instance)

As fields can be attachted to differents bundles

field_delete_instance deletes the field itself only when there no more bundles using it. maybe see field_info_field and this comment from field_delete_instance to clarify

So if in

 if ($field = field_info_instance('node', $fieldname, 'page')) {
   field_delete_instance($field);
 }

Applies and delete the last instance then in

  if ($field = field_info_field($fieldname)) {
    field_delete_field($field);
  }

Should be null and wont execute field_delete_field($field);


Custom module embedding existing node form

node_form() is in node.pages.inc which isn't included by default. Just add a call like this to the beginning of your my_signup() function:

module_load_include('inc', 'node', 'node.pages');

When you call drupal_get_form() with a specific type (like signup_node_form) the node module internally translates that to node_form(). This happens in node_forms() which is in the node.module file, and as such is always included.

However node.pages.inc is only included when specifically requested by a module/menu callback etc. so to use node_form() you'll need to include the file manually.

You also need to pass a node object to the function with the required content type assigned like the following code:

$new_node = new stdClass;
$new_node->type = 'signup';
$new_node->language = LANGUAGE_NONE;
$form = drupal_get_form('signup_node_form', $new_node);


Language switcher using get language variable instead of prefix in Drupal 8

The plugins you enable in the language detection configuration also contain the methods to build outbound paths and the language switcher links. The plugin for Url adds prefixes, not query strings. Others do, for example Session for anonymous users, so you probably have enabled a second detection method.


Views 3: template suggestion file for header/footer parts?

There's no template that I know about, but nothing can stop you from overriding the header and footer values in a view's general template like views-view.tpl.php, or even include a separate file instead of outputing the variable directly.


allow only the author of the comment node

In the permissions of  Comment you can allow Post comments for your author role alone.For anonymous user you can give permission of view comment alone. Hope this helps you :)


I don't think that's the best way to make this but here is an quick and dirty way :

Create your view and instead of using filter Click advanced and add contextual filter , then chose your field.
enable the PHP filter in modules
Create a block in admin/build/block and chose php filter there you will embed the php code below
now you have to load the profile of current user profile for this use this function, there you will find the current working project field and pass it to the views (I suppose that you added this field in profile 2) :
$path = drupal_get_path_alias($_GET['q']);
$path = explode('/',$path);
// if the position of viewed user id in the path is 1
$uid = $path[1];
$current_user = profile2_load_by_user($uid);
//make print_r($current_user) to find your field of project currently working on
$arg = $current_user["main"]->your_custom_field["und"]["value"]; // if I remember
print   views_embed_view('your_view_machine_name','your_view_display_machine_name',$arg);

//to find out the machine name of your view hover over its ling and you will see then name in the link below

This solution is for just one argument , if you have multiple field value (more than one current project) you will have to select mut pass arguments like this :

foreach ($current_user["main"]->your_custom_field["und"] as $record) {
            $values[]= $record["value]";
    }
$args =implode('+',$values);
views_embed_view('your_view_machine_name','your_view_display_machine_name',$args);

Hope this will help


EventSubscriber returning correct content but status code is 404

Creating an alias in /admin/config/search/path/add worked. I created an alias /api/nat/news/ to /nat/news
Thanks 4k4 for a much easier solution drupal.stackexchange.com/a/187497/47547


I solved my issue.
The links column was not rendered for the tableselect form because I didn't update my $header array with the new element name edit_link.
It appears a table form does not map the element names to the header names, meaning I did not have to update the header array for my link columns to appear.  As long as the element name was in the header array Tableselect would render the column.  I believe this to be the basis of my issue.


Panels -> Add content in panels gives AJAX HTTP-error

This worked for me: https://drupal.org/node/1036202

Posted by Kye on February 11, 2013 at 11:45am
I had the same problem today. Went through this and similar threads. We were hosting the site in IIS and the problem turned out to be URLScan, and colon in the URL plan. I had to do is exclude the colon rule and everything worked as expected.

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

; : ; Don't allow alternate stream access


Go to admin/structure/panels/settings and check Make all views available as panes.


Your menu items are probably still there but disabled. In Drupal 6, navigate to admin/build/menu-customize/navigation and check if your administrative menu items are enabled. In Drupal 7 the path is admin/structure/menu/manage/management.

If you re-enable any menu items, make sure you scroll to the bottom of the page and hit the Save Configuration button to save your changes.


How to add only "Add to Cart" Button in a view

If you are adding fields, just add Add to Cart Form field in the view.
Attaching my view image just for your reference.


CiviCRM Email Record appearing in other members profile Information

CiviCRM has a table civicrm_uf_match, which links CiviCRM contacts to Drupal (or Wordpress or Joomla) users. Here is its structure:

CREATE TABLE `civicrm_uf_match` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'System generated ID.',
  `domain_id` int(10) unsigned NOT NULL COMMENT 'Which Domain is this match entry for',
  `uf_id` int(10) unsigned NOT NULL COMMENT 'UF ID',
  `uf_name` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'UF Name',
  `contact_id` int(10) unsigned DEFAULT NULL COMMENT 'FK to Contact ID',
  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'UI language preferred by the given user/contact',
  PRIMARY KEY (`id`),
  UNIQUE KEY `UI_uf_name_domain_id` (`uf_name`,`domain_id`),
  UNIQUE KEY `UI_contact_domain_id` (`contact_id`,`domain_id`),
  KEY `FK_civicrm_uf_match_domain_id` (`domain_id`),
  KEY `I_civicrm_uf_match_uf_id` (`uf_id`),
  CONSTRAINT `FK_civicrm_uf_match_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK_civicrm_uf_match_domain_id` FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4997 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

'UF' stands for Underlying Framework, i.e. the Drupal, Wordpress or Joomla installation to which CiviCRM is linked.

Sometimes entries in this table can get out of sync, e.g. if the Drupal database has been copied from a development server to a test server without also copying the CiviCRM database.

Perhaps that is what has happened in this case. You could check by examining the civicrm_uf_match records for the relevant email addresses, which are stored in the uf_name field.

It can also be useful to join civicrm_uf_match to the Drupal users table and check for any records where the email in civicrm_uf_match differs from the email in users. Also a left join from civicrm_uf_match to users can highlight orphan civicrm_uf_match entries.


Targeting a Specific Contact Form for Altering

Thanks for your help everyone. The comments were helpful. I ended up using the var_dump($message) as suggested and then whittled that down to what I needed. As one of you suggested the form name wasn't as long as I originally thought (and it WAS NOT the ID for the form). I think one ended up being 'feedback' and the other was, as you suggested 'contact_technical_support' or something like that.

The other issue I was having was that I was ignorantly naming my module with the word 'alter' in it which was overriding, or being overridden, by the alter hook it was using, I think.

At any rate, short answer is, my code basically works, but use var_dump($message) to find the correct ID of the forms and don't use 'alter' in the module name.


Drupal 7 views - sort results after they have been retrieved from database just before they are rendered

You can implement hook_views_pre_render(&$view) within a custom module and manipulate the result array available in $view->result:

/**
 * Implementation of hook_views_pre_render()
 *
 * @param view $view
 */
function YourModuleName_views_pre_render(&$view) {
  // Check if this is the view and display you want to manipulate
  // NOTE: Adjust/Remove the display check, if you want to manipulate some/all displays of the view
  if ('YourViewName' == $view->name && 'YourDisplayName' == $view->current_display) {
    // EXAMPLE: Just reverse result order
    // TODO: Replace with your desired (re)ordering logic
    $view->result = array_reverse($view->result);
  }
}