Alter the "My Account" link in installation profile

Perhaps you could use:

hook_menu_alter

Not sure if it'll work with option attributes, but worth a try.

e.g

/**
 * Implements hook_menu_alter
 */
PROFILE_menu_alter(&$items){
  $items['user']['options'] = array('attributes' => array('target' => '_blank'));
}

Alternatively, it would be easy enough to add the _blank attr with jQuery.

e.g:

$('body.some-class #user-menu-link a').attr('target', '_blank');

Update: added example PROFILE_ option for menu_alter hook


What is the best way to make sure Array in PHP are closed correctly

It is no longer necessary to put databases into your Drush alias file. In older versions of Drush, a databases record in an alias file could be used to allow Drush to do an sql-sync to or from a remote system that did not have Drush installed.  This feature is no longer supported, and the databases record is no longer necessary.

To answer your specific question, though, any php nested array must have balanced parenthesis.  Make sure that you have one ( for every ). Folks usually keep track of their parenthesis via indentation -- add a level of indentation for each (, and remove it for each ).


Place the block in the disabled section at admin/structure/block, this creates a block instance with your block_content type, give it a nice easy machine name to remember.

By placing it in the disabled section, it won't show up, until you load it programatically.

Then using your machine name:

$machine_name = 'myblock';

$block = \Drupal::entityTypeManager()
  ->getStorage('block')
  ->load($machine_name);
if (!empty($block)) {
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  $pre_render = $block_content;
}

If you really want to get the rendered fields, you can do:

$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->build($pre_render);

But it is more standard practice to use Drupal's formatters and such and perhaps a custom template, rather than building the block and extracting elements from the rendered render array.


Conditional addition of css - hook_init?

If that CSS is in your module, then the module should really be implementing the hook.

I don't think you can do anything with CSS and JS in a hook_html_head_alter(); that is really to mess with the render array before it is turned into $head by template_process_html().  Personally, I would use a template_preprocess_html().  You can add your logic there.  For example,

function mymodule_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');
  }
}


Update url-aliase for nodes of a specific content type

To update URL for Existing Contents You could go to admin/content
In Update Options, You can choose Update URL alias after filtering a specific content type


There are a couple of ways to do it. Here are two of them:

 Through your theme

write your own mainstyle.css file.
place it in your active theme directory (directly or in a folder that you create there)
go to that theme directory and open the file: [themename].info (e.g. bartik.info or myAwesomeTheme.info)
add stylesheets[all][] = mainstyle.css after the existing stylesheets. (or stylesheets[all][] = css/mainstyle.css if your stylesheet is placed in a folder called 'css').
flush your cache

This way drupal will include your stylesheet.

 A simpler way to do it , with the help of a module, so that you don't touch any of your files, is

download the module  css injector
enable the module
go to configuration -> development -> css injector (admin/config/development/css-injector)
create a new rule and give a name to the rule: e.g. table styling
Finally in this rule write your CSS  e.g. td {background-color: red;} etc

Tip: If you want to target your elements (e.g. tables) correctly, then you may need firebug, which is an extension for Firefox.


Option for User to edit their own Profile

I've managed to find the solution to this problem.  I have to call the 'edit user' link directly from Views as a field.  Thank you.


Fire a rule only when a specific webform has been submitted

I got this to work but i don't know if my answer will be the best approach for what i need:

Let's say, we want the rule to be fired ONLY for the webform ID: "contact"

1) EVENT: After saving a new webform submission (rules_entity_insert:webform_submission)

2) CONDITION: Data Comparision;

Data to compare: webform_submission.webform_id.target_id;

Operator: ==

Value: contact

3) ACTION: Show a message on the site.

Hope it will help somebody else as well, especially that there is no documentaion yet for rules 8.

Cheers,


Book page appears in one language (of four) only

Ok, found that setting under

Home » Administration » Configuration » Search and metadata » URL aliases

Or go to Modules and configure Path module settings

Setting the language to All languages has solved my problem


Commerce line item not referenced by the orders

This typically happens when an administrator adds a line item to an existing order via the order edit form and doesn't submit the form. The line item has already been created, but the order hasn't been updated to reference it. We refer to these as orphaned line items, and they're safe to delete as needed.

I implemented a much better approach with Inline Entity Form, which defers any write action for referenced entities until the form is submitted, but last I tried its line item support wasn't fully functional for the site I was working on. May be better now.


Dropdown menu with descriptions only in sub-menu elements in Drupal 7?

Within your theme's template.php, you can override the theme_menu_link() function.

Target the $variables['element']['#original_link']['depth'] variable to check for the depth of the current menu item.

The variable $variables['element']['#original_link']['localized_options']['attributes']['title'] holds the "description" value entered on the menu item's edit page.


How to set permissions to a particular role?

Looks like you should try the Role Delegation module. Some details from its project page:

... allows site administrators to grant specific roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions on the permissions page.


Why would a (working) theme function defined in nodequeue module not be registered in theme registry?

Try

function yourtheme_nodequeue_arrange_subqueue_form_table($variables) {}

I don't think you can override module functions from the theme layer without theme_hook_function or hook_function_alter... You'll need to create a module to override nodequeue_theme() - take at look at drupal_alter()


You can click admin/people/simplenews and check on status column.
OR
you can use following code to get the data

  // fetching from the database.
  $query = db_select('simplenews_subscriber', 'ss');
  $query->innerJoin('simplenews_subscription', 'si', 'si.snid = ss.snid');
  $query->fields('ss', array('mail'))
    ->condition('ss.activated', $condition_active)
    ->condition('si.status', $condition_subscribed)
    ->condition('si.newsletter_id', $newsletters)
    ->distinct();
  $data = $query->execute()->fetchAll();

where si.status is a flag indicating whether the user is subscribed (1) or unsubscribed (0)

and $newsletters is a Array of newsletter ids to filter on


Print the query results inside the submit function

The issue is due to the form submission and rendering process within Drupal.  Long story short, Drupal submits the form then re-renders the form page, which goes through a 'submission' process.  So, all the drupal_set_message calls are getting cleared during this process.

What you want to use is an AJAX callback on the submit button, populating a section of the form with the data retrieved.  And lucky for you the process is much simpler in Drupal 7.

To use the data again in a later form, look at multistep forms.


Is it possible to limit which products users can purchase by role?

You should create an additional "VIP ONLY" product display - a node type that aggregates products and effectively shows them in the front-end.

With this new content type you could tap into its permission system using Content Access and limit the "View" permission to the "VIP user role".

When you want to create a VIP product simply create a new "VIP ONLY" node.

Steps:

Create a new node type in admin/structure/types . Call it "VIP ONLY".
Add a product reference field to the node. Use the existing field. It will now be listed in views that list product display types.
Setup the permissions as per above.
Profit.


You can simply add a new view mode for search results:

Go to admin/structure/types/manage/page/display (where "page" is your content type)
Expand the Show Custom display settings fieldset
Check Search index

Click Save
Go to admin/structure/types/manage/page/display/search_index (where "page" is your content type)

My advice would be to use the Display Suite module as well for extra fields and more options.


You need to enable touch for that. Follow this path for flexslider setting $base_url/admin/config/media/flexslider/list/default/edit.

You will see screen such as
You need to check Touch in Navigation and Control Settings & save.

Don't forget to clear cache :)


Using the PHP include in your template: Naming the file .php or .inc?

The Drupal 7 coding standards (#includes) seem to use ".inc" over ".php". If you browse the Drupal Core you see ".inc" is used everywhere. I suggest you stick to ".inc".


Customizing the form for a field in the content edit form

first of all use hook_form_alter to alter any form. so in your custom module something like this

function CUSTOMMODULENAME_form_alter(&$form, $form_state, $form_id){
   if ($form_id == 'FORM_ID'){
     --
   }


It's not an error, but a warning reminding you that you aren't using an encrypted connection, and that the credentials you are using (username and password) could be read from somebody who can intercept the data exchanged between your computer and the server. If you look at the protocol used for the page, you will notice it's http://, not https://.
It's not an error caused from the file/directory permissions.

If you don't have a SSL certificate, just enter username and password that are accepted from the FTP server, and install the modules. The warning is just suggesting that using a secure communication would be preferable.

You could also avoid Drupal prompts for FTP/SSH credentials by setting the owner of the temporary:// directory (and its subdirectories) to the owner of the sites/default directory (which, in your case, I take is akshay).


How to run a Drush command with the full site path?

Your command should be like:

drush dl views

or:

drush dl views -r /path/to/site/root

To get help manual for commands run:

drush help

Please find better explanation for drush commands at GitHub.


How do you write a drush alias for a local Vagrant box?

I was able to use drush alias with following configuration:

Let's assume two things:

vagrant box has some sort of static ip (can be private, for example: 192.168.56.101)
IP of vagrant is available in symbolic form (for example, we have single line in /etc/hosts with ip and hostname). (for example: test.site.local).

Step 1:
We need to copy settings, generated by vagrant ssh-config command into $HOME/.ssh/config

Host test.site.local
    IdentitiesOnly yes
    UserKnownHostsFile /dev/null
    StrictHostKeyChecking no
    PasswordAuthentication no
    IdentityFile [path to vagrant private insecure key]

Step 2:
With such configuration, my alias was in following form:

$aliases['example'] = array(
   'root' => '/var/www',
   'uri' => 'test.site.local',
   'remote-host' => 'test.site.local',
   'remote-user' => 'vagrant',
   'ssh-options' => "-i path_to_insecure_private_key"
);


Why does composer remove a folder it doesn't manage

It isn't Composer, per se, that's removing your hacked gesso theme. Drupal uses the composer/installers Composer plugin to move different Drupal components (e.g. modules, themes, profiles) to the dir where Drupal needs them.
Once Composer has retrieved the drupal/gesso package, composer/installers will place it the contrib theme path in extra.installer-paths, thus overwriting your pre-existing hacked theme.
If you don't want Composer & the installers plugin replacing your hacked gesso theme, you could do a couple of things:

Remove drupal/gesso from Composer management so it never tries to update or manage the theme again and add the hacked theme back to its previous location.
Use the cweagans/composer-patches Composer plugin to patch the drupal/gesso theme with your component/template hacks so they're added with every update.


How to call a view in a twig.template not page

One very simple method is to install the Twig Tweak module and use:

{{ drupal_view('testfeest', 'display_id') }}


Does Drupal override php setting by it self by .htaccess?

No.  Nor does it do it by any other method.

As pointed out in the comment by kiamlaluno,  Drupal comes with its own .htaccess file. You'll find it as one the files in your Drupal root.  You can read through it yourself and see that it does not change the setting of PHP version that you set in the account page of your shared hosting service.

The .htaccess overrides some settings that may be set different in php.ini, as shown in the directives below (copied from the default .htaccess file), but not anything else.  As you can see, it has IfModule directives that makes the overrides contigent on the versions of PHP and Apache you use, rather than overriding the version.

# PHP 4, Apache 1.
<IfModule mod_php4.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 4, Apache 2.
<IfModule sapi_apache2.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value magic_quotes_gpc                0
  php_value register_globals                0
  php_value session.auto_start              0
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_value mbstring.encoding_translation   0
</IfModule>

The changes you ask about cannot be explained by the Drupal .htaccess-file or anything else done by Drupal. Nor do I know about any backup/restore program or migration program for Drupal that does such things as those you describe.


What does 'Drupal-friendly' hosting mean?

There are some things you may want to look into:

Drupal Requirements:

PHP 5.2+ (Drupal 7)
MySQL Database
128mb Memory Limit (For Heavy Imagecache processing)

Not Requirements but perks:

SSH
Drush
Git (Latest)
Crontabs
Curl


Creating a node via REST - Entity reference field value not updating

I managed to get working by changing this...

'entity_reference_field' => array(
  'target_id' => $entity_id,
),

to this...

'entity_reference_field' => array(
  array('target_id' => $entity_id),
),

I also had to disable using an entity reference view as the 'Reference type' on the field and just have the option as 'Default'. Not sure if this is a bug or if there's something wrong with my entity reference view.


Passing dates or date ranges into a view as arguments

Please refer below URL and check the answer given by @Dmitriy

How to implement less than / greater than in views contextual filters

This may help you.


You shouldn't have that

$node = $variables['node'];

outside your function.

put it as the first line inside your preprocess function.

$variables doesn't actually exist out there (and if it does it won't be the $variables variable you're expecting in this case).


How do you get the display settings of a field on a particular content type/display

You're looking for field_info_instance()

  Returns an array of instance data for a specific field and bundle

Example usage:

$info = field_info_instance('node', 'field_foo', 'article');
$display_settings = $info['display'];

$display_settings will be an array of display settings keyed by the view modes that are customisable for that content type and bundle.


commerce_cart_order_load not working for anonymous user in drupal commerce

Every thing is ok,I had the same problem after spend a half night I found that sometimes drupal dont start session for anonymous users then you should start it manually if begin of your function

   drupal_session_start();


SearchApiException: Unknown or invalid item type node

I managed to fix the site with the help of Commerce Repair:

  This module is designed to repair missing fields from various commerce entities. After installing, visit the menu item that does the repair, admin->store->config->Repair Commerce Fields (admin/commerce/config/repair). Once you've done that you can uninstall the module.


Before watermarking the image, store the original copy in another, private file mode image field.

Then you can control access to the original image with hook_file_download().


Return to views navigation list of nodes after editing a node in the list

I found a solution, through code unfortunately, using hook_url_outbound_alter().

For anyone trying this, I have implemented the following code and it is running perfectly:

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
// get current position and list token
$position = isset($_GET['position']) ? $_GET['position'] : NULL;
$list = isset($_GET['list']) ? $_GET['list'] : NULL;

// only when viewing nodes through views navigation
if ( $position && $list && preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    $path = 'node/'.$matches[1].'/edit';
    $options['query']['destination'] = 'node/' . $matches[1] . '?position=' . $position. '&list=' .$list;
    }
}

Thanks


How can I access an external table in a MySQL database?

Here is a module that will help you: http://drupal.org/project/data

[ edit re MPD suggestion below ...]

This module will help by providing an automatic Views integration for your data, meaning that you can show the data via Views.

It also includes an API which simplifies custom programming to get access to your data (perhaps for use in preprocess functions, which would permit the data to be themed on a node page, etc.)

Regarding your desire to include taxonomy, one way to do that would be to fold the data onto a node and then attach taxonomy to that node, however, that might depend on how you're mapping your data onto individual nodes.


Where should libraries be copied to sites/all or sites/all/modules?

You must create a directory libraries inside sites/all folder.


How can i attach my content type to level 1 taxonomies in multilevel taxonomy in drupal 7?

Checkout Hierarchical Select module. It offers many features.

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!


Running a queue worker without using cron tasks

Queue is processed by cron through core. You can also use Drush and Drupal Console to run queue items as well.

Drush:

drush queue:list to get the available queues.

drush queue:run to run a single item.

drush queue:delete to clear a queue.

Drupal Console:

drupal debug:queue to debug your queue.

drupal queue:run <name-of-the-queue> To run a single item.


Including the Slick carousel .js file in the index.html file is correct.

You can use the brand the new hook_entity_view_alter to attach a pageshow handler to the node's page:

http://api.drupalgap.org/7/global.html#hook_entity_view_alter
http://docs.drupalgap.org/7/Pages/Page_Events

In the pageshow handler is when you'd initialize the carousel. The pageshow event fires after page is shown to the user. There are a few other hooks you could use to have a chance to place the pageshow event on a node's page within the app:

http://api.drupalgap.org/7/global.html#hook_entity_post_render_content
http://api.drupalgap.org/7/global.html#hook_entity_post_render_field

The hook_entity_view_alter is the most powerful and is brand new, so you need the latest bin/drupalgap.min.js file and the latest jdrupal.min.js file to run it. But that is the hook I'd recommend using


You need to search for db_select using subquery.

Look the below links to get some idea.

Using db_select with subqueries

db_select condition with subquery


Modify the date popup to only accept special days

You can use Date Restrictions in conjunction with Weekdays to acomplish this.

Just download both projects and enable weekdays_date_restrictions module. Then edit the date field and go to "More settings and values" > "Date Restrictions" > "Allowed values" > Choose restriction type: weekdays.


You need to override theme_menu_link(), so in your template.php file from your theme put this code:

function MYTHEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  //Split titles using a
 when longer than 20 characters
  $element['#title'] = wordwrap($element['#title'], 20, "
");
  //Set HTML to TRUE to display properly the HTML
  $element['#localized_options']['html'] = TRUE;

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Change MYTHEME by your theme name.
I used wordwrap() to split long menu title in small chunks but you can implement your own logic there.


How to validate all elements in Custom Widget

A GOOD example of this approach is Field_example module from Example module for developers.(link here https://www.drupal.org/project/examples/releases/8.x-1.x-dev).

The widget with the "field_example_3text" id has also 3 elements: "r", "g, "b", and the values are accessed in validation function:

  foreach (['r', 'g', 'b'] as $colorfield) {

      $values[$colorfield] = $element[$colorfield]['#value'];
  }

So create an array containing your keys elements and loop into it, accessing the values by writing $element['your key']['#value'];

Have a look at this module.
The dpm of the $element variable looks like this:


REST Export Serializer adds quotation marks to my field

I had to change my overall approach to the problem, but managed to solve the serialising problem by using two additional modules:

https://www.drupal.org/project/views_field_view

https://www.drupal.org/project/rest_export_nested

The description of the REST Export Nested explains everything.
The only thing that might provide problematic is the performance as this involves potentially calling a lot of sub-views. So maybe writing a custom normaliser as indicated in one of the comments is a better approach.


One way to do this would be to use the Conditional Fields module (disclaimer: noted as not ready for production for D7).  The way to do it with your own code would be to use the States API (the Conditional Fields module is just a GUI to States API, basically).

Using Conditional Fields, you can set it so that, for example, based on the value selected for Field A, a number of fields would be shown or not shown as per your requirements.

EDIT: To split the form into two steps, you can use the Field Group module, which provides a "multipage steps" feature.  To configure this, you will need to create a fieldgroup of type multipage for each page you want to have on the user registration form, and then place the appropriate fields under each page (on the user account manage fields screen).

Note: The Conditional Fields and Field Group module will display everything as one giant page if Javascript is disabled.  I don't know any way around this.


8 - How to run jQuery to show a div, after register form is submitted?

I used like below and it works for me:

function MYMODULE_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
      foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_message_submit';
        }
      }
  }
}
function _message_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  drupal_set_message(t('The user @name account has been created successfully.', ['@name' => $values['name']]));
}


Why does this route work with a slash and not a dash?

The dash is not the problem, you could use a dash in the fixed part, but ...

  Unlike generic Symfony routes, Drupal requires that a slug occupies a
  complete path part - the portion between two slashes (or everything
  after the last slash).

https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes

Alternatively you can use path processing to rewrite the path to comply with the Drupal routing system. See Do new routes in Drupal 8 *require* a static first portion?


Allow/restrict access based on privacy setting flags in profile

Implement hook_node_access($node, $op, $account) and check whether the user has flagged his content to be private, if so then deny access.

function MYMODULE_node_access($node, $op, $account){
  global $user;

  if($node->uid != $user->uid && $node->type=='video' && $op=='view'){
     $entity_type = 'profile2';
     $profile = profile2_load_by_user($node->uid,'main');

     $flagging_data = flag_get_user_flags($entity_type, $profile->pid ,$node->uid);

     /************ UPDATED ****************/
     if(isset($flagging_data['channels'])){
          return NODE_ACCESS_DENY;
     }
  }
}


How to resolve the negotiated theme for any other user?

As far as I remember, this type of functionality was built in in Drupal 6.

In Drupal 7 there was the ThemeKey module .

Unfortunately, as of this date ThemeKey is not yet ported to Drupal 8, however I think you can achieve pretty easy that functionality by using the user data object inside custom module.

In order get something from the user data object:

$data = \Drupal::service('user.data')->get('mymodule', \Drupal::currentUser()->id(), 'key');

In order to set something in the user data object:

\Drupal::service('user.data')->set('mymodule', \Drupal::currentUser()->id(), 'key', $value);

Update:

you can combine the code above with the solution posted here:

https://www.drupal8.ovh/en/tutoriels/259/theme-negotiators-switch-theme-dynamically

where your negotiator will be called last by adding priority in the services.yml

you can implement the business logic inside the function the function determineActiveTheme. Combine this with hook_user_login where the information is stored inside users_data and you have a working solution (If I don't have a mistake somewhere).


Do you have an HTML element with the id of "map_canvas" anywhere on the page?

Also I'm assuming you actually have your API key in your first script tag and it doesn't actually say "myKey".


Using Panels for Layout versus custom .tpl files

Panels module

"Learn Page manager" is an interesting / amazing set of videos. They contain various topics related to the Panels module. After you reviewed these videos, you'll understand that it'll be hard to come close to all the features that come with the Panels module.

Here is a summary of the entire set of videos about this topic (quote from the link above):

  Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
  The screencast series is targeted at experienced Drupal developers.
  Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
  Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
  Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
  Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
  Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about Panels.

Some more words about Page Manager:

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

  It supports the creation of new pages, and allows placing blocks within that page.

  Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.

  Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.

  It utilizes the core Conditions, Context, and Blocks APIs to accomplish this.

In Drupal 7, Page Manager was the foundation of the Panels module.

Bean module

When talking about layout in Drupal, one often brings up "Blocks" also. If you also use the (great) Bean module, it'll open lots of new possibilities. Here is a quote about it (from its project page):

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

Refer to my answers to the question about "How to control Block revisions before being published?" for more details about the Bean module (things you can also do, etc).

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8 (refer to this issue for more information). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.


You can create a menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module. You can also set up new menu items and strcutre through Drupal's admin menus management (admin/structure/menus)


You can add a script using drupal_add_js and to have it added on every page, you can call it in hook_init.

Module directory path can be resolved by drupal_get_path('module', 'module_name')

module_init() {
  drupal_add_js(drupal_get_path('module', 'module_name')."/js/myscript.js");
}


Will forcing validation on a node save result in security issues or data integrity loss?

Looking at Drupal code, I don't see any possible security flaw; there could be any, depending on the code executed from third-party modules.
For sure, I am expecting many errors raised for form fields that are added to the node edit form and whose content is not validated. None of the modules I know (and which alter the node edit form) validate the user input in the validation, and in the submission handlers they add.

Unconditionally removing any error message is not what I would do. I would rather let the users know when the node they are editing has been already changed from another user, which is the error message returned from node_validate().

  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }

I would also let the users know there is already a translation for a node in a language, which is the error message given from translation_node_validate().

if (isset($translations[$langcode]) && $translations[$langcode]->nid != $node->nid) {
  form_set_error('language', t('There is already a translation in this language.'));
}

Using drupal_static('form_set_error', NULL, TRUE) (you could simply use drupal_static_reset('form_set_error')), you are resetting all the form errors for any form present in the page. See How do I make form_set_error() affect the submitted form only?

If I were to implement that code, I would write it as follows. I don't think that avoiding the validation errors are seen from the users causes anything good.

function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (!empty($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '
Draft
';
    }

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => 0,
      '#validate' => array('mymodule_save_draft_validate'),
      // Change the following line to contain the name of the fields that
      // needs to be validated. As it is, it avoids any form field is validated,
      // when this button is clicked.
      'limit_validation_errors' => array(),
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

function mymodule_save_draft_validate($form, &$form_state) {
  $form_state['values']['status'] = 0;
}

function mymodule_save_draft_submit($form, &$form_state) {
  // …
}


You can follow the Database Abstraction API documentation. Although most of that documentation points to using the deprecated methods. You may find the current classes and methods, by clicking into each function that you need (such as db_select), and reading the deprecated messages.

This is very similar to what you have done for inserts (using Dynamic Query).

$id = Database::getConnection()->select('blood_sugar_monitor')
  ->fields('blood_sugar_monitor', ['my_primary_key'])
  ->range(0, 1)
  ->orderBy('my_primary_key', 'DESC')
  ->execute()
  ->fetchField(0);


Set Value to a select field by its key in webform

This is the way I do it and it works:

// set default value to a D7 form field
$form['FIELD_NAME']['und'][0]['value'] = $country;

// prevent user from changing the field value
$form['FIELD_NAME']['#access'] = false;

Hope this helps.


That is a great question.

Getting just the filename is not currently supported but you can pull the file's URL using [webform_submission:values:join_a_file:delta:format:url]

The current list of supported formats for uploaded files is here. I created a ticket to
add machine name to element submission display formats so that this information is exposed to site builder.

If you need just the file name, please create a new ticket in the Webform module's issue queue.


YourTheme_links doesn't work on sub theme

I believe it is a typo, the function should be MYTHEME_link and not MYTHEME_links.Possible other ways to identify is use theme engine phptemplate_link instead of your theme name.

Try clearing your theme registry. Also Check whether you have spelled your theme machine name correctly.

function MYTHEME_link($variables) {
    print_r($variables);
    die;
}


How can I disable a form's default validation functions?

As per function form_set_error: "If #limit_validation_errors is set on a clicked button, the button must also define a #submit property (may be set to an empty array)." So your preview button should be:

'preview' => array(
  '#type' => 'button',
  '#value' => t('Preview'),
  '#limit_validation_errors' => array(array('map')),
  '#submit' => array(),
),


How to transfer a block from one site to another?

Have a look at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.


Use the block Flickr: User photos corresponding with a node's taxonomy term, location and/or date field and under FILTER / SORT ORDER
leave Flickr tags as node taxonomy terms (choose a vocabulary to use) on none.

The sandbox demo at https://simplytest.me/project/flickr/7.x-1.x shows an example in the sidebar. Log in there and check the settings used with your own.


The Migrate module only provides a flexible framework for data migration into Drupal. The logic and data mappings to perform an actual migration are pretty complex. Migrate does not provides an UI to build or configure your migration. IMHO, this is good because a complete UI to build such script would be at least as complex as writing it directly in PHP.

Its documentation is pretty complete and provides all the information needed to start using it. I recently started to use it and, coming from an OOP background, find it intuitive and easy to learn.


Ignoring unpublished/published as criteria for "Has new content"

You need custom code to achieve this. There's 2 things to know here:

Updated Status Logic

The logic for driving the New & Updated labels is based on the history table (which stores the last time a user viewed a node) & the node.changed column:

$changed = $this->get_value($values, 'changed');

$last_comment = module_exists('comment') && !empty($this->options['comments']) ? $this->get_value($values, 'last_comment') : 0;

if (!$last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_NEW;
}
elseif ($changed > $last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
elseif ($last_comment > $last_read && $last_comment > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
return $this->render_link(theme('mark', array('type' => $mark)), $values);

Essentially, it's comparing when a user last viewed a node vs. when a node was last changed.

What isn't known, is what was changed (e.g. the publish status) so to implement some sort of exclusionary logic you're going to have to track the history of publishing/unpublishing to check if the last update was just a change in publish status (node.status).

Updated Status Display

Assuming you have that logic in place, it's possible to override the output a views field. Here you can extend the views_handler_field_history_user_timestamp class with your own custom class implementing a render() method that adds the logic to check whether the last change was only a publish status change. In the final step, you can use hook_views_data_alter to override the handler for the Has new content field.


How to set Exposed filters in fieldset for specific Views?

This code will work for specific view. Example for "ViewsA"(reaplce ViewsA for your Views name and "my_module" for your module name).

<?php
    /**
     * Implements hook_preprocess_views_view().
     */
    function my_module_preprocess_views_view(&$vars) {
     // Assign to your specific view.
      if ($vars['view']->name === 'ViewsA') {
        // Wrap exposed filters in a fieldset.
        if ($vars['exposed']) {
          drupal_add_js('misc/form.js');
          drupal_add_js('misc/collapse.js');
          // Default collapsed
          $collapsed = TRUE;
          $class = array('collapsible', 'collapsed');
          if (count($_GET) > 1){
            // assume other get vars are exposed filters, so expand fieldset
            // to show applied filters
            $collapsed = FALSE;
            $class = array('collapsible');
          }
          $fieldset['element'] = array(
            '#title' => t('Filter'),
            '#collapsible' => TRUE,
            '#collapsed' => $collapsed,
            '#attributes' => array('class' => $class),
            '#children' => $vars['exposed'],
          );
          $vars['exposed'] = theme('fieldset', $fieldset);
        }
      }
    }
?>


View output add a class to first and last rows

The contributed Semantic Views module has the option of adding first and/or last class attributes. Pretty snazzy solution since you can also use it to specify better html elements at the same time!


What permissions affect fields attached to taxonomies that don't affect fields attached to content types?

Leaving an answer in case it's useful to anyone else.

The permission that was affecting the display of taxonomy ckedit and geolocation fields was 'View the administration theme' - it looks like the Open Framework theme has a small issue when displaying taxonomy edit field forms.

I should have just changed to a default theme to test this.


Does "Maximum image resolution" resize before saving on the site?

that setting means that you can't upload an image with max resolution of 800x600. If you upload an images with a size more than that set, it will be not imported and drupal will return an error alter.


How to get image titles and source out of a view?

If you are wanting to get Views results to use programmatically, check out the views_get_view_result() function.  If you do something like:

$result=views_get_view_result('viewname');

you can then loop through $result, which is an array of objects relating to each row, and the tried and true:

drupal_set_message('<pre>' . print_r($result, TRUE) . '</pre>');

will give you all the information you are working with.


How to set default values for "modify entity values" form

You have to hook the form, which is shown after clicking "Modify entity values".

Here is my code to handle this:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  $account = user_load($user->uid);

  //to get the form id, you have to print it out first
  dpm($form_id);

  switch ($form_id) {
    case 'views_form_your_view_display_name':

      $nid_page = menu_get_object();

      // the next line activates the checkbox to show the input field
      $form['bundle_item']['show_value']['field_name']['#default_value'] = TRUE;

      // the next line sets the default value for the field shown
      // notice: the 'value' array field depends on the field type and may also
      // be 'target_id' (for entity references) or 'tid' for taxonomy references
      $form['bundle_item']['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = $your_desired_value;
  }
}


Should a cache tag only render array for an otherwise empty block work?

You are right about this, you need content (in form of a render element) for the cache metadata to be recognized. But you don't need to worry about this, because BlockViewBuilder detects an empty block and adds a markup render element with an empty string:

public static function preRender($build) {
    ...
    if ($content !== NULL && !Element::isEmpty($content)) {
      ...
    }
    else {
      // Abort rendering: render as the empty string and ensure this block is
      // render cached, so we can avoid the work of having to repeatedly
      // determine whether the block is empty. For instance, modifying or adding
      // entities could cause the block to no longer be empty.
      $build = [
        '#markup' => '',
        '#cache' => $build['#cache'],
      ];
      ...


Node Hierarchy: Display Children of top most parent in views

You could try adding parent node as a relationship in views, then add a filter and set it to "is empty (NULL)" as a requirement of the field with relationship parent. This will only display nodes that have no parent node set.

If you want to show only nodes whose parents have no parent, you'd add a second relationship (called something like "grandparent") and then set your filter to require the grandparent, rather than the parent, to be empty.


Here is some example raw data you should be sending (don't send it as form data):

{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hello World"}]
}

You do not need to send the Accept header, because that no longer matters because of the _format=json query string. And in this case, when successful, it will return a 201 so you can disregard the _format query string.

The POST to ?q=entity/node is correct, but don't forget to send an X-CSRF-Token header with a value that can be retrieved here: ?q=rest/session/token


Adding checkbox to select records in a view

This sounds like a task for VBO, this module provides a new view style with checkboxes for a wide array of actions you can perform on the row returned. This also comes with javascript which will allow you to remember selections between paginated pages etc which should also help with your issue.


Group results of same taxonomy term with search api and views

Open your views, in editing mode , in formatting section, near table, select settings,
and then in Grouping field Nr.1 select your taxonomy field ,save ,it makes the views result goruped by selected field in Grouping field Nr.1.


One reason i see is Entity Reference...

For Example -

A block which lists some nodes part of your delete list.
A node which has entity reference to your deleted node
A view page which has some of your deleted nodes

Reason for clearing all the caches: When a node is created/updated/deleted there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

So, It makes sense to Clear the page and block and node_load_multiple caches as documented in node_delete_multiple function.


How to get all filters and functions available in Twig templates?

From procedural code:

\Drupal::service('twig')->getFilters();
\Drupal::service('twig')->getFunctions();

Unless the Twig service is overridden this is calling the methods on the vendor Twig_Environment class.

For OO code you should inject the Twig service into your class. https://drupal.org/node/2133171 and https://drupal.org/node/2203931 have some documentation and examples on how to do that.


Use a custom view for the front page without alias

How to create a view without alias, not exactly without, but with / or
  nothing for the front page.

  How to associate a pathless view with a front page ?

You cannot create a pathless view page. (The default front-page view has a /node path)
Create a block View

Then go to blocks, and place your view block in a region. Content region perhaps?

Under Visibility settings check-mark "display only in" and put <front> so it only gets displayed in the front page.


How to change the title and add a placeholder to password and confirm password field through hook_form_alter?

In D8 You can try the code below:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\PasswordConfirm;

function mymtheme_form_user_pass_reset_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['pass']['#process'][] = 'mytheme_form_user_register_form_process_pass';
}

function mytheme_form_user_register_form_process_pass(&$element, FormStateInterface $form_state, &$complete_form) {
  $element = PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password here please');
  $element['pass2']['#placeholder'] = t('Password again here please');
  $element['pass1']['#title'] = t("New password");
  $element['pass2']['#title'] = t("New password confirm");
  return $element;
}

See more PasswordConfirm.php

In D7

function mymtheme_form_user_pass_reset_form_alter(&$form, &$form_state, $form_id) {
   // #process handler to modify the password element expanded by Field API.
   $form['pass']['#process'] = array('form_process_password_confirm', 'register_alter_password_confirm');
}

/**
 * Alter password and confirm password fields to remove title and insert placeholder.
 */
function register_alter_password_confirm($element) {
    $element['pass1']['#attributes']['placeholder'] = t("Password");
    $element['pass2']['#attributes']['placeholder'] = t("Confirm password");
    $element['pass1']['#title'] = t("New Password");
    $element['pass2']['#title'] = t("New password confirm");
    return $element;
}

See more https://www.drupal.org/project/drupal/issues/540340#comment-2782800


"Menu settings missing from all node edit forms"

You need to enable the menus for use on each content type. This can be achieved on pages via Structure->Content type->Basic page, then click on the "Menu settings" vertical tab and toggle which menus should be enabled.

Also, if you're using the revisioning system in core, or any kind of workflow type module (workflow or workbench), unpublished pages in the menu won't show up in your list of menu items in Structure->Menus->Main Menu (for example), as well as the obvious rendered menu on the front end too.


How can I print something conditionally on node.tpl.php depending on what taxonomy term the node is tagged with?

Can you try this...

<?php if ($node->taxonomy[100]): ?>
    print anything here
<?php endif; ?>


In a Quick Tabs module what does this display do in a TAB TYPE view?

I would recommend reading this post regarding purpose of Master Display in Views. It contains the standard settings for a view that take a effect when you create a new display in the view. If you don't have specific settings differing from master display in your other displays you could (and maybe should) use it in the Quicktab.


As described in Let Drupal 8 know about your module with an .info.yml file, the correct format is:

project-name:module-name for third-party modules
drupal:module-name for a core module

  Dependencies should be namespaced in the format: {project}:{module} where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name.

Since the project page for Drupal core is https://www.drupal.org/project/drupal, the case for Drupal core modules is the same as for third-party modules.


How to test if honeypot is working on a form?

Open up firefox or chrome, and inspect the form (using firebug or any equivalent). If you see any element with the class 'honeypot-*' and a label 'Leave this field blank'. Then its a honeypot field and its enabled.

To check if it works. Make the element visible by changing display: none to display: block, enter a value into the input box and hit submit. The validation should fail.


You could use a title callback, like for example this one from the core node controller:

\Drupal\node\Controller\NodeViewController::title

  public function title(EntityInterface $node) {
    return $this->entityManager->getTranslationFromContext($node)->label();
  }

Your title callback would have other route parameters, so that you can find the correct node, see also https://drupal.stackexchange.com/a/248687/47547.

When using the default option in the Bootstrap theme to display the page title you might need to add cache metadata to the breadcrumb, see Breadcrumbs are cached, which depends on how you determine the node to display.


How to export / feature the "picture guidelines" field

Use Strongarm to export the variable called user_picture_guidelines.


In Drupal 8 you are supposed to organize your themes and multi-site instances like in the following structure. I only highlight the relevant folders.

__docroot
  |__modules
  |  |__contrib
  |  |  |__devel
  |  |  |__views
  |  |__custom
  |     |__my_module_abc
  |     |__my_module_xyz
  |__sites
  |  |__default
  |  |  |__settings.php
  |  |__site1
  |  |  |__settings.php
  |  |__site2
  |     |__settings.php
  |__themes
     |__contrib
     |  |__bootstrap
     |__custom
        |__my_bootstrap_subtheme

So, if you want to create a sub-theme of a custom theme, you also have to place it inside docroot/themes/custom. Then it will appear in your back-end where you can enable it.

But what I would recommend instead of adding another sub-theme, is to simply add a template suggestion based on the multi-site instance name via hook_theme_suggestions_HOOK_alter. By that you can move on with only one custom theme (which is much easier to maintain in the end), and inside its MYTHEME.theme file you'll switch the page template for your certain multi-site instance like following.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $suggestions[] = 'page__' . $site_name;
}

Now you simply can place page--site1.html.twig in your theme's template folder and site1 will take this page template instead the default page.html.twig. (Source)

Tried it on a fresh D8 with Twig debugging enabled and it works just fine.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   x page--site1.html.twig
   * page--front.html.twig
   * page--node--1.html.twig
   * page--node--%.html.twig
   * page--node.html.twig
   * page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my-custom-subtheme/templates/page--site1.html.twig' -->


How to install multiple modules with composer at once?

You can write the names of multiple packages separated by spaces. For example:

composer require drupal/adminimal_theme:^1.5 drupal/adminimal_admin_toolbar:^1.9


Seems to be too broad to answer, few pointers that may help you.

Root Cause of problem might be at

Custom module level which can be drill down with profiling tools as devel profiling which you have already used, another tool can be XHPROF.
Ensure all your custom queries are optmised.
Uninstall all modules which you are not using.
Try to have a comparison of site performance on your local and server, your server might not be allocating required resources.

As per my experience when you have long list of modules installed it causes performance issue especially panels, to overcome you can use caching provided by views module and for panels check if this module does the trick for you.

Having said that Authenticated User Page Caching mdoule will be worth looking at.

Views and panels provide caching


How can I change the text: "Images must be larger than 200x200" in the image field for a specific content type?

you can use string overrides module or a hook_form_alter and override the text with

$form['PHOTO_FIELD_NAME']['#description'] = 'Images must be larger than 200x200';


If you use user as login path, it will visible after login.

You should replace user with user/login it will gone after login.

Also user's profile link is available in User menu, just edit it and change its parent menu to your primary nav.


Date field with granularity of Month, Year in Exposed filter, how to alter the default value?

One method would be to alter the exposed filter form date_select form element. Add this to a custom module:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
   $form['#after_build'][] = 'views_exposed_form_date_select_alter';
}

/**
 * Alter the label option on Year/Month selector
 */
function views_exposed_form_date_select_alter($form, &$form_state) {
   $form['MY_DATE_FIELD']['year']['#options'][''] = 'Year';
   $form['MY_DATE_FIELD']['month']['#options'][''] = 'Month';
   return $form;
}


Installed a feature, getting warnings on cache clear and view content not loading

I was able to get the view to display data by Disabling SQL rewriting in the view.

In the view under Advanced > Other > Query Settings: Settings > check Disable SQL rewriting.


An error upon trying to execute Drupal Console

Drupal console global executable is not at the same version as your current project

go outside any drupal project and
and execute: drupal self-update


Why does CACHE_TEMPORARY have the same value as DRUPAL_NO_CACHE

They have different uses. CACHE_TEMPORARY and CACHE_PERMANENT are values that cache_set() accepts as its last parameter. DRUPAL_NO_CACHE is used from Drupal only for blocks.

Two variables are allowed to have the same value, and this doesn't create confusion, as long as they are used in different context.

While both the variables have the same value, you should not use them when appropriate, at least because it makes more difficult to upgrade your code to Drupal 8.

In hook_block_info_alter(), as with other hooks for blocks, you should use DRUPAL_NO_CACHE. Keep in mind how the data passed as first argument to the hook is structured. With $blocks['forum']['active']['cache'] = DRUPAL_NO_CACHE; used in hook_block_info_alter(), you would avoid the block showing the active forum posts is cached from Drupal.


Passing multiple values in fields as mentioned in another field (as number of values) by user

You can ref Examples for Developers Module. The module comes with various sub-modules for developers to start with.

Similar kind of functionality is already provided as an example in "AJAX Example" module in Examples module. i.e. User has been given a dropdown field with predefined numbers to render those many fields. Check screenshot below:

Hope this helps.


How can Display Suite be used with Book module links?

you've to activate the full display to show the book navigation field on Display Suite display settings.

There is only a problem: the book navigation links are always rendered after the comment form. I know it was a known bug some months ago but I don't know if it has been fixed recently.


The way I ended up getting around this was:

Upload my file as an unmanaged file at the new URI
$test_file->uri = $new_uri;
file_save($test_file);
file_unmanaged_delete($old_uri);

It didn't like it when I used a URI that was not yet in existence, nor one that was already in use by a managed file, but using one that goes to an unmanaged file seemed to work fine.


You need to alter the default Ubercart's theming of the shopping cart form and increase the weight of "Remove" column so it is pushed to the end.
Add the following code to your theme's template.php file.

/**
 * Themes the uc_cart_view_form().
 */
function phptemplate_uc_cart_view_form($form) {

  // Increase the weight of Remove column, so it goes to the end.
  $form['items']['#columns']['remove']['weight'] = 100;

  // The rest of the code is default Ubercart's code you can see in:
  // theme_uc_cart_view_form() function in uc_cart.module.
  drupal_add_css(drupal_get_path('module', 'uc_cart') .'/uc_cart.css');

  $output = '
';
  $output .= drupal_render($form['update']);
  $output .= '
';
  unset($form['update']['#printed']);

  $output .= '
'
          . drupal_render($form['items']) .'
';

  foreach (element_children($form['items']) as $i) {
    foreach (array('title', 'options', 'remove', 'image', 'qty') as $column) {
      $form['items'][$i][$column]['#printed'] = TRUE;
    }
    $form['items'][$i]['#printed'] = TRUE;
  }

  // Add the continue shopping element and cart submit buttons.
  if (($type = variable_get('uc_continue_shopping_type', 'link')) != 'none') {
    // Render the continue shopping element into a variable.
    $cs_element = drupal_render($form['continue_shopping']);

    // Add the element with the appropriate markup based on the display type.
    if ($type == 'link') {
      $output .= '

'
               . $cs_element .'
'. drupal_render($form) .'
';
    }
    elseif ($type == 'button') {
      $output .= '

'
               . drupal_render($form) .'

'
               . $cs_element .'

';
    }
  }
  else {
    $output .= '
'. drupal_render($form) .'
';
  }

  return $output;
}


Template file is not overriding drupal 7 defaults

Overriding node templates are done by placing node--'nodetype'.tpl.php templates inside your custom theme folder.
If the template isn't accepted after cache clear, check if the Machine name on admin/structure/types is the same as 'nodetype'.


Render updated node data during views render

Assuming this is Drupal 7.

hook_preprocess_views_view() runs after the query is performed. You could try using hook_views_pre_view() or hook_views_query_alter(), both of which happen before the query runs, and save the nodes at that time. Of course the results of the view will not be available to you then, so you would have to select the nodes in some other way.

Also neither of these hooks work in themes, you would have to use a custom module.

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7.x-3.x


How can I set up roles and allow users to choose which role to be?

There is a module that is supposed to cover that https://drupal.org/project/autoassignrole.

Or if you want to make it supper slim, you can add custom code to add dropdown with existing roles to account edit form and update user account on form submit.


Are configurations written and read directly to/from .yaml files or still to the database?

Yes and no. (I am not sure if this will be too technical).

The configuration is stored in configuration objects. Drupal has by default an active and a staging storage for those configuration objects.

The default active storage is in the database, yes, for performance and easier backup/restore, among other reasons. But that is an implementation detail. It used to be read directly from files, but that was pretty slow, even with caching.

The staging storage is yaml files in the staging folder in your file system. Those are the files you manage in git.

You can export to staging and import again from staging through the click of a button in the UI or with drush. Unlike Features in Drupal 7, which uses custom processing to transform configuration between feature files and the actual drupal site, the configuration object structure is always the same. Serialized to yaml for the file storage, as serialized php arrays in the database storage. Drupal does not care (for the most part, but that is too technical). If you want to, you could write a configuration storage that stores it encoded in pictures, as long as Drupal can get the standardized array structure out of it again that it put into the storage.

So, yes, the configuration is by default still stored in the database, but not in the way you were used to in Drupal 7.


If I understand your question, the only projects that I am aware of are

jQuery Mobile (I am pretty sure this is abandoned)
Backbone
Node.js

There is a related discussion in Using Javascript frameworks like Backbone with Drupal and some of the work for Spark could probably count, too.

I don't have direct experience with any of these, but I am in the early process of determining whether Backbone is a good fit for a particular project.


Is it possible to alter $form_state before it is passed to user_profile_form_submit?

There many ways to alter the $form_state values. It would be nice if we know what you wanna change so that we can say the best way to do it. Any way the following hooks can help.

hook_form_alter
hook_validate
hook_form_submit

You can have your own submit function either by overriding the $form['#submit'] values in hook_form_alter or add one to modify the values.


"Promote to front page" to other than front page

"Promoted to front page" can be used as a views filter. So you could create views based on that (so it displays node teasers that have a certain taxonomy and are "Promoted to front page").

Another simple way to mimic "Promoted to front page" is to add a taxonomy select field to your content types, and then the taxonomy pages would display the specified content.

Does this answer your question?


The function drupal_set_message takes 3 parameters, message, type and repeat. Default repeat is TRUE. If you set it to FALSE, it will prevent duplicates.


Get all fields defined in a bundle for a view mode

If I understood your question correctly, you need to use the entity_get_display() function.

It will return the entity view display, associated with the bundle and view mode you wanted. Simplest example:

$display = entity_get_display($entity_type, $bundle, $view_mode);


hook_entity_view(), and hook_entity_view_alter() are not the hooks you should use to avoid an entity title is rendered, as the entity title is not generally passed to the $build parameter passed to those hooks.

This is the content of the $build parameter for three different entity Drupal defines.

Node

Comment

Taxonomy term

Furthermore, the purpose of hook_entity_view() is adding content to $entity->content, not altering $entity. The description given in the documentation page for the hook is the following:

  The module may add elements to $entity->content prior to rendering. The structure of $entity->content is a renderable array as expected by drupal_render().

To avoid the title is rendered for an entity, you should use a preprocess function for the template file used by the entity, and unset a variable used from the template file for the title. For example, for a node, a module could use the following code.

function mymodule_preprocess_node(&$variables) {
  $variables['title'] = '';
}

Similar code would work for comments, but in that case the function would be mymodule_preprocess_comment().
For taxonomy terms, there isn't a title but there is the term name, which is printed from the template file using the following code.

<?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

<?php endif; ?>

Setting $term_url, and $term_name to an empty string would cause the following HTML output to be printed.


how to display data in view for specific content base on permission

Create your view, in middle column, in Permissions: View Published Contentclick on it and select Role. Specify the role you want.


You can do this to make it work:

$db = \Drupal::database();
$query = $db->select('sinica_grade_summary','sgs');
$query->fields('sgs', ['coursename']);
$query->condition('sgs.uid', $id, '=');
$query->groupBy("sgs.coursename");


How to remove "display name" from edit user

The first one was easy. To hide any field from the user edit form simply set the '#access' to this field to FALSE or any other logic you desire. The second one was more difficult. Turned out the display name was still used on the password reset page. That's how we finally solved it:

/**
 * Implements hook_form__alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    $form['account']['name']['#access'] = FALSE;
  }

  if ($form_id == 'user_pass_reset') {
    // Here we take the corresponding user ID from the URL, second argument
    $user_id = arg(2);
    // Then we load the user
    $user = user_load($user_id);
    // Now we have the mail
    $user_mail = $user->mail;

    // extracting the date string with a helper function
    $sub_text = getContents($form['message']['#markup'], '', '');
    $expiration_date = $sub_text[1];

    // Now we alter the existing form
    $form['message']['#markup'] = '
This is a one-time login for '.$user_mail.' and will expire on '.$expiration_date.'.

Click on this button to log in to the site and change your password.
';
  }
}

/**
 * Helper function to extract a string between two given delimiters
 * Credit: http://stackoverflow.com/a/27078384/2199525
 */
function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }
  return $contents;
}


How can I print out large variables in hook_entity_presave for debugging?

You don't want to see all properties. That's internal data that doesn't help you much anyway. What you want to see is the field values. And the easiest way to do that is this:

debug($entity->toArray());

That gives you a simple structure of all fields and their values. You can access them in a similar way as that array looks like, e.g. $entity->field[$delta]->property, [$delta] is optional and defaults to 0. See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more details.

The other way is to use an IDE with a debugger, then you can set break points, inspect anything at runtime and even execute code.


which hook is effective for setting custom breadcrumbs?

I normally stick that logic in hook_preprocess_page(), it runs late enough in the page build to not be overwritten by anything else.

You can still get access to the node object by using the menu_get_object() function:

function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    // We're on a node page...
    drupal_set_breadcrumb($my_breadcrumbs_array);
  }
}


How to set up this view of commerce orders...?

Turns out I need to make every block of classes individual products in the store and use 'Auto product display' module to automatically create the node displays.  Then have to create a view that lists the commerce products rather than node displays


how to render a template inside a template?

When a template is not being applied, the first thing to always check for is the filename of the template :)

Make sure it matches the machine name of the content type.


How can we add a date picker in a date field exposed filter?

Try the contrib module Better Exposed Filters. At the 'Exposed form' settings in your view you can select 'Better Exposed Filters' after enabling BEF. After selecting the exposed form method you should have more options per field, a datepicker is one of them (on date fields).


How to weight a block above a custom form

In Drupal 7 the output from a page callback will be rendered inside the standard 'Main page content' block. As such it is available to be re-ordered like any other block in the system through the admin UI.

All you need to do is visit the administer blocks page ( http://mysite.com/structure/block ) and move your block above the 'Main page content' block.


Change routing behaviour for non-existent entities

Yes, routing is one way to do this. Extend the entity view controller, where you call (1) the parent method to view the entity or (2) redirect to the create form. Change the route so that it points to the new controller and remove the options for type casting and converting the entity parameter. You have then to load the entity in the controller by hand, because the controller gets only the raw parameter (the entity id), but you need to check if the entity exists anyway to decide if you need to redirect. You can change the route by extending DefaultHtmlRouteProvider or in a RouteSubscriber. You might also need to move the access check from the route to the controller after the entity is loaded.

There are more ways to do this, you could redirect in a request subscriber where you check if the entity exists before routing or you could redirect in an exception subscriber after a 404 is raised.

The last option is possibly easier to implement, because then you don't need to think about routing and access checking and simply react on a 404 caused by your specific entity route.


How do you keep production site in synch with development site?

There are a number of approaches to synchronizing configuration between environments.

A few popular ones for Drupal 7 are:

https://drupal.org/project/features (recommended)
https://drupal.org/project/strongarm
https://drupal.org/project/configuration

For example with drush and features you can revert a component to the code definition with

drush fr my_feature

For more info on drush and features https://drupal.org/node/960926

In Drupal 8, exporting configuration has become much easier:

  With Drupal 8 you can deploy a configuration from one environment to
  another. This capability replaces the need for various contributed
  modules such as Features, Strongarm and Context.
  https://drupal.org/documentation/administer/config


The data table must be marked as a Drupal Entity -- then the columns of the table may make use of the Field UI to allow an edit page per entry similar to a node_edit form.

Otherwise, you may be able to use the Editable Views module to make a table redition of your Data table -- whose cells are editable values. In this case you will likely still need to make the whole table a drupal entity.

The Data module is an API module to adopt/destroy SQL tables into Drupal. It's not really designed as a phpmyadmin replacement for a site.


How do you programmatically enable a payment method?

Just update the rules_config entity.

$config = rules_config_load('name_of_your_rules_config');
$config->active = 1;
$config->save();

If you are not sure what the name of your rules config entity is run:

$configs = entity_load('rules_config');
foreach($configs as $config) {
  dpm($config, $config->name);
}

This will list all rule config entities that you have.


How to add custom attributes to a field?

The database table "content_node_field_instance" has a "widget_settings" column which can be used to store field attributes.  Use hook_widget_settings_alter() to associate attributes with a field.  Admin will then be able to set attribute values from the cck UI.  For example, to associate a binary attribute "my_attribute" with every filefield:

function mymodule_widget_settings_alter(&$settings, $op, $widget) {

  // Apply to all FileFields
  $widget_types = _content_widget_types();
  $widget_type = isset($widget['widget_type']) ? $widget['widget_type'] : $widget['type'];
  if (!in_array('filefield', $widget_types[$widget_type]['field types'])) {
    return;
  }

  switch ($op) {
      case 'form':
        $settings['my_attribute'] = array(
          '#type' => 'checkbox',
          '#title' => t('my attribute'),
          '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
          '#default_value' => !empty($widget['my_attribute']),
        );

        break;
      case 'save':
        $settings[] = 'my_attribute';
        break;
  }
}

In this example, the filefield form will contain a checkbox labeled "my attribute".  Admin checks the box to set my_attribute to true, for the particular filefield.

To get the attribute value of a particular field:

$attribute_value = $field['widget']['my_attribute'];


You want to change '#type' => 'link' to '#type' => 'url'

public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'url',
    '#title' => $this->t('Link title'),
    '#options' => ['external' => TRUE]
  ];

  return $form;
}


drupal_render($node_view); is not working

As I don't have the Drupal sources at hand right now, I didn't digg into it yet. But I'm pretty sure the node_view() function is using your node--type.tpl.php for rendering its output.

So calling it within your template will lead to a recursion. You might want to check on that.


Display No Results Text for Individual Field Groups in View

The best to do this is using theme layer. In your case,views-view-grid.tpl.php is used to display the results.

There are different ways to alter that.

Solution A: Using template preprocessors

Add this function to template.php in your theme folder.

<?php
/**
 * Implements hook_preprocess_views_view_grid().
 *
 * Check if there is no result for this group and provide an appropraite message.
 *
 */
function phptemplate_preprocess_views_view_grid(&$variables) {
    $view = $variables['view'];
    if ($view->name == 'YOUR_VIEW_NAME') { // Only do this for a specific view
        if (empty($variables['rows'])) {
            $variables['caption'] = t('No results.');
        }
    }
}

Solution B: Overriding the template file

Copy views-view-grid.tpl.php to your theme folder and then modify it.
You may also want to rename the template file so it would only apply to a specific view. (Learn how to find the appropriate template file name for Views).

<?php

/**
 * @file
 * Default simple view template to display a rows in a grid.
 *
 * - $rows contains a nested array of rows. Each row contains an array of
 *   columns.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>

<?php // We check if there is no result we print a meesage ?>
<?php if (empty($rows)) : ?>
  <?php print t('No results.'); ?>
<?php endif; ?>

<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>

<?php print $caption; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>


Alternately, using once:

(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      $(body, context).once('foundation-init').each(function() {
        $(document).foundation();
      });
    }
  };
})(jQuery, Drupal);


The display suite module has a views integration that allows you to choose a different display mode for the first node in a view versus all the others. In this case you can easily create a separate tpl for that view mode and you're good to go. Its extremely powerful. Take a look at this post and look for "Alternating view modes" in the last screen shot.


Try the Double field module.

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

I used it for one of my project and works well.


How can I render an image stocked in a custom module with an image style?

Thank to Hudri :
Image styles only work with managed files (uploaded, with entry in DB), not with static assets. Since this is a static asset anyway, just provide the correct size in your module.


the way I did was i used global:null as the contexual filter and then selected provide default value and then went to type: taxonomy term ID from URL and added it in and then added content: has taxonomy term ID and gave it the same settings as the global:null and saved the view, now the reason why i didnt see it is because you have to add new content, for some reason it doesnt pick up the current content with taxonomies


Translate with t() function from spanish as source

If you look at the API for t() - https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7 - you'll notice that it allows you do specify $langcode in the options array, however, that is a method to override the output language - not the input.

If you don't want to translate from English to Spanish, but the other way, there is a small quirk in Drupal localization framework.  The name "English" in Drupal is reserved as the default index for languages, so you can't use that name for the target language.  But please note that you don't have to use the index named "English" to hold English strings.  You can use anything for that index. You can define new languages, and even invent them, so let us define a target language called "Ingles", and use that for English.

Now for each phrase you want to translate fro Spanish to English, you need to assign an index for lookup in the translation table.  Let say you assign "¡Hola, mundo!" to be the index corresponding to the Spanish phrase "¡Hola, mundo!".  On at least one page (it doesn't matter if it is Spanish, English or "Ingles, you must have t("¡Hola, mundo!"); to get Drupal to pick this up.  Now go to Drupal's translation interface and search for "¡Hola, mundo!".  When you've found it, you can enter the correct strings for the Spanish original ("¡Hola, mundo!") into the field for "Spanish" and its translation into English ("Hello, world!") into the field for "Ingles".  Do that with every phrase you want to translate from Spanish to English.

When done, you should be able to use t("¡Hola, mundo!"); on a page with Spanish as its default language to make the user see "¡Hola, mundo!".  To get the translation into English, you also use t("¡Hola, mundo!");, but make sure the page's default language is "Ingles" (not English).  This is how you use t()-to translate from Spanish to "Ingles" (which is just an alias for "English" - we must use this alias since Drupal has reserved "English" to hold the default translation index).

However, you may find it a bit awkward to "invent" a new language called "Ingles". And there is a simpler way!

Instead of using "¡Hola, mundo!" as an index to "¡Hola, mundo!", you pick "Hello, world!" as your index. Otherwise, you proceed like before - to get this variable into Drupal's inserted into translation interface, you must on at least one page have t("Hello, world");  (it doesn't matter if that page is Spanish, English or "Ingles).

Now, instead of "¡Hola, mundo!" showing up as am index in Drupal's translation interface, you'll see the index "Hello, world!".  But just like before must enter the string "¡Hola, mundo!" as the Spanish original phrase, and for translation into "Ingles", you enter "Hello, world!".

However, now there it is also possible to get rid of the invented language "Ingles".  It just so happens that if the default language for a page is English (not "Ingles"), t();will not look up the string in the table but just return the index.  And since we're now using English phrases as index that index will be in English on pages where the default language is English. So we can stop using the the invented language "Ingles" and instead rely on getting the index back on English pages, while on Spanish pages, the index will be used for table lookup and we will get a Spanish string back.


How do I render content "as is" from custom controller

Since this is a text area field, you need to specify a type of render element, processed_text.

$render_array['snippet'] = [
  '#theme' => 'webpart_snippet',
  '#type' => 'processed_text',
  '#text' => $node->field_content->value,
  '#format' => $node->field_content->format,
  '#prefix' => '
',
  '#suffix' => '
',
];


Composite Primary Key for a Content Type

An easy way to do this is with the Unique Field.  This provides a WYSIWYG interface for adding node validation to the node save form to check one or more fields' uniqueness.

The module is not bulletproof, though.  There are some scenarios where you can get around it.

  This module is intended to function when a node is being validated prior to being created or updated. It does not prevent nodes from being programmatically saved with duplicate values (including when a node is reverted to an earlier revision).

The reason is that the check is done at the code level via validation and is not a database enforcement via composite keys.

A similar module, that also provides a lot more features in addition to the uniqueness check, is Field Validation.

If you want to give the composite key thing a shot, I would make a test site and edit one of the field tables by hand to make the composite key.  Then install/enable Unique Field and see what happens with the cases that the module doesn't cover.


I needed to do something vaguely similar the other day and the only way I could find was to go into the db tables directly to grab the data. The problem is you need to join the line item and orders tables (for the order status), which you can't do with (for example) an EntityFieldQuery.

I think you'd be looking for a query simliar to:

SELECT SUM(li.quantity)
FROM {commerce_order} o
INNER JOIN commerce_line_item li ON li.order_id = o.order_id
WHERE o.status = :status
AND li.line_item_label = :sku
AND order.uid = :uid

But it'll probably need some tweaking for your needs (to get results for orders created between certain dates for example).


How to access a parent paragraph twig file from a child node twig file?

You can use hook_preprocess_paragraph hook to set the same id to all child nodes, in the below code snippet example all child nodes will have paragraph-PARAGRAPH-ID as id.

use Drupal\Component\Utility\Html;
/**
 * Implements hook_preprocess_HOOK().
 */
function myModule_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $identifier = Html::cleanCssIdentifier('paragraph-' . $paragraph->id());
  $variables['attributes']['id'] = $identifier;
}


Views Group By with profile with aggregation and relationship

Consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Curious to hear if this helps to answer this question.


How to get rid of the default field markup

As with pretty much everything like this in Drupal, the answer lies in overriding theme functions/templates.

That markup is added by the theme_form_element() function; to override the output for that function simply add a function like this to your theme:

function THEMENAME_form_element($vars) {
  // ...
}

And change what you need to from the original function (e.g. replace <div> with <ul> if that's what you need). You might also need to override some of the individual element templates (depending on exactly what you want to do).

Some examples of those:

theme_textfield()
theme_select()
theme_checkbox()


How to display comment form and comments per node in a view

Check if you've comment module installed, if yes, also check if you've comments enabled for that content type


Userpoints Karma - Is it possible to only charge user points for down votes?

Adding a module to override User Karma's settings is certainly one option.

Another possibility is to use Rules and Voting_Rules to control your own settings for adding and subtracting user points.

Once enabled you go to /admin/config/workflow/rules and "Add New Rule".  Set it up to React on Event "User votes on a Node".

Add the condition "Check the value of the vote" and if less than 0 add an Action to "Grant points to a user" but make them negative points.

Here's a screenshot of this Rule:

Optionally, if you want to use User Karma in conjunction, you could instead React on the Event of "User was Awarded Points" and test for Conditions and override where appropriate.


General Content Search of Content type Exposed form

This is certainly possible and there can be many approaches to this, but it would require some effort in any case.

Taxonomy terms are not indexed by core search, therefore you would need to rely on a third party module. Such popular modules are Search API and Apache Solr.

My preferred method, in short, is to use the Search API in combination with Views:

Install the modules Search API, Search API DB, Views, Ctools.
Create server and index, add the taxonomy fields in the index.
Create a view for the search page based on the index
Filter by eg. "Search: Fulltext search", exposed
Add any fields to view, such as "Rendered entity" (for teasers etc.)
Sort by any field, such as "Search: Relevance".


Node Revisions are stored in node_revision table.This table keep track of what user edited what nodes as separate revision.

Also the last uid who has revised/updated the node is available in $node entity.So try something as below in your theme template.php

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Gather last updated author info
  $revision_uid = !empty($node->revision_uid) ? $node->revision_uid : 0;
  if (!$revision_uid) {
    $revision_username = variable_get('anonymous', 'Anonymous');
  }
  else {
    $revision_user = user_load(array('uid' => $revision_uid));
    if ($variables['is_admin']) {
      $revision_username = l($revision_user->name, 'user/'. $revision_uid);
    }
    else{
      $revision_username = $revision_user->name;
    }
  }
  $variables['revision_username'] = $revision_username;

Then just <?php print $revision_username; ?> in your .tpl files.

Reference Link:

https://drupal.org/node/236523

Since above code will show only the last editor info,if you want to get all users
you can query the node_revisions table.


hook_field_presave() isn't getting called

If you are editing an enabled module, you need to first disable, and then re-enable it. Drupal saves in cache the list of hooks implemented by modules; the one I described is the way to force Drupal to update that cache.

hook_field_presave() is invoked for the module implementing the field; the other modules should implement hook_field_attach_presave(). If the Location module is not implementing the field, it should implement hook_field_attach_presave(), which is what your module should do too.

The documentation is not much clear about this; but looking at field_attach_presave() is a little more clear what happens.

function field_attach_presave($entity_type, $entity) {
  _field_invoke('presave', $entity_type, $entity);

  // Let other modules act on presaving the entity.
  module_invoke_all('field_attach_presave', $entity_type, $entity);
}

_field_invoke() invokes the hook for the module implementing the field; module_invoke_all() invokes the hook implemented by any module.

That is why the documentation for hook_field_presave() says, "Define custom presave behavior for this module's field types."


How to fix SalesForce authentication errors on localhost?

In general, to make SalesForce authentication to work on localhost, you need to:

Create an app in Salesforce with URL Callback to your local (https://localhost/salesforce/oauth_callback) with appropriate permissions.

  In Salesforce go to Your Name > Setup > Create > Apps then create a new Connected App. (Depending on your Salesforce instance, you may need to go to Your Name > Setup > Develop > Remote Access.)

Your site needs to be SSL enabled to authorize the remote application using OAUTH.
If using the SOAP API, PHP must be compiled with SOAP web services and OpenSSL support.
Use the right auth key and secret to Authorize your app (Configuration » Salesforce).
Make sure you're connecting to the right endpoints (live or sandbox).
For more help, check Help » Salesforce API in Drupal, or SalesForce documentation.
Add $conf['https'] = TRUE; to your setting file.

The error in Salesforce->requestToken() indicates that there is a problem exchanging an authorization code for an access token.

Further more, the error:

  Error opening socket ssl://login.salesforce.com:443 in Salesforce->requestToken()

indicates the problem connecting to Salesforce endpoint it-self (check requestToken() in includes/salesforce.inc for more details).

To diagnose the problem, please check Reports » Status report if you've got HTTP Failure error and that your localhost can connect to Salesforce end point via curl:

$ curl login.salesforce.com:443

If your curl is connecting fine and you've still HTTP Failure error in your Status report, then try to:

Temporary disable Secure Site or Secure Pages modules if present.
Make sure you've firewall (e.g. iptables) and antivirus is switched off (for testing purposes).
Make sure you're not behind the proxy.
Make sure you're not running LAMP in a chroot/jail/VM environment.
Make sure you some network functions aren't disabled PHP functions (e.g. stream_socket_client).
Make sure your PHP is not in Safe mode (safe_mode = On) by:

php -r "var_dump(ini_get('safe_mode'));"

Double check your /etc/hosts or ~/.curlrc doesn't have anything suspicious (you can add insecure to your .curlrc for testing purposes).
Check is there is no any problem with certificates (e.g. your system date is incorrect, you added the certificate and your PHP openssl sees your certificates correctly).

In PHP 5.6 you can specify openssl.cafile and openssl.capath,

e.g. openssl.cafile=/usr/local/etc/openssl/cert.pem

If none of above work, please check below simple PHP script which can check if your PHP can connect to external host:

<?php
fsockopen('ssl://login.salesforce.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);
?>

Save it to the file (test.php) and place it inside your web root and open via web browser.

If it fails, it's either problem with your PHP configuration or your network. You can debug it further more by using system call tracer (debugger) as below (install it if required):

$ strace -f -e network php test.php # For Linux
$ truss -f php test.php # For BSD
$ sudo dtruss php test.php # For OSX
# For Windows, you may look for StraceNT.

Then you've to analyse the log for any issues.

Or the following perl script:

use strict;
use warnings;

use LWP::UserAgent;
use Mozilla::CA;
my $ua = LWP::UserAgent->new(
        ssl_opts => {
                verify_hostname => 1,
                SSL_ca_file => Mozilla::CA::SSL_ca_file()
        }) or die;
my $url = $ARGV[0] || 'https://login.salesforce.com/';
my $res = $ua->get($url);
print $res->code . "\n";

exit;

See also:

Using cURL in PHP to access HTTPS (SSL/TLS) protected sites.
SSL Certificate Verification
Using Curl to login to Salesforce API at Salesforce Developers
token failed with status 0! at Salesforce Developers
How to fix Curl Error Ssl Certificate Problem Verify That The Ca Error?


Exposed Views Combine filter not working

Check which fields you are combining.

If e.g. you have a user field as combined field, Drupal needs the "Administer users" permission to use this filter.

An issue about this can be found at
https://www.drupal.org/project/drupal/issues/3030696


hook_form_alter function to make field visible and required?

Try changing the selector from ':input[name="field_dispongo_de_"]' to the id of the field (#edit-customer-profile-billing-field-dispongo-de-und) as below:

/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Verify the field names are as per the form.
    $form['customer_profile_billing']['field_cif_nif_id']['#states'] = array(
      // This #states rule says that the "field_cif_nif_id" fieldset should only
      // be shown if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
      'visible' => array(
        '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('cif')),
      ),
    );
  }
}


adding ckeditor color button and font size

You have to create the folder yourself as the docs say.

You can do this with command line with mkdir libraries in the webroot (where the /core folder is), or with a window and New Directory (New Folder) in either Windows / OSX.

Your application structure will then look like...

/core
/libraries
/modules
/themes

and so on.

All thats left is to download the JS plugin from ckeditor.com (v 4.5.x), unzip it, and place it in the libraries directory.