How can i maintain pagination with filter using tableselect?

The search form method type is post thats why when you are submitting the search form the form values are sending as post therefore the form values are coming properly for  first page. When your are clicking on second page the form state values are reseting with new form state values as form has default value.

So rather than using post method form I will suggest to use get method type form for search so that the search keyword will always persist in url.

So you have to add

$form['#method'] = 'get';

Access all filtered values using $_GET like

$form['search_ew_partner'] = array(
            '#type' => 'textfield',
            '#prefix' => '

',
            '#suffix' => '
',
            '#default_value'=> $_GET['search_ew_partner'],
            '#attributes' => array(
                'placeholder' => 'Search by name'
            )
        );

And change your code like

if(!empty($_GET['search_ew_partner'])){
            $query->condition('ept.name', '%' . $_GET['search_ew_partner'] . '%', 'LIKE');
        }


Facets and Apache Solr in Drupal 7 - Clicking Facets results in no results being show

This is very odd behaviour, can you ensure you are:

running the latest version of apachesolr (3.6.1)
running the latest version of the apachesolr module (7.x-1.1) OR search_api module (7.x-1.3)
are running the latest schema.xml and solrconfig.xml (hopefully the 3.x version)

Also, try dropping and re-creating the entire index, this normally addresses more problems.


going to post answers to help people that is having the same issue, I used one of this modules to help me fix the issue I am having :

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

hope this can help someone :)


for how long is Content considered "new" by the filter criteria "Content: has new content"?

In Drupal 7, the Views module uses the NODE_NEW_LIMIT. If you look at the code used by the views_handler_filter_history_user_timestamp class, which filters the new content, you will notice the following code (in views_handler_filter_history_user_timestamp::query()).

  // Hey, Drupal kills old history, so nodes that haven't been updated
  // since NODE_NEW_LIMIT are bzzzzzzzt outta here!

  $limit = REQUEST_TIME - NODE_NEW_LIMIT;

  $this->ensure_my_table();
  $field = "$this->table_alias.$this->real_field";
  $node = $this->query->ensure_table('node', $this->relationship);

  $clause = '';
  $clause2 = '';
  if (module_exists('comment')) {
    $ncs = $this->query->ensure_table('node_comment_statistics', $this->relationship);
    $clause = ("OR $ncs.last_comment_timestamp > (***CURRENT_TIME*** - $limit)");
    $clause2 = "OR $field < $ncs.last_comment_timestamp";
  }

The same constant is used from node_mark(), which the function that returns a value used to decide if outputting updated, or new in a list of nodes, such as the one shown by the Tracker module.

  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;

The value of the NODE_NEW_LIMIT is the number of seconds in 30 days.

To notice that when you visit the node, "new" is not anymore shown.


Commerce checkout - Update cart pane after user select a shipping option (ajax)

You are right. Shipping rates are applied only after you submit the form (Click "Next").

On submit all your shipping rules(or flat rates) applied and order is saved with new line items (Shipping is implemented via custom line item type).

The calculation is executed in the commerce_shipping_pane_checkout_form_submit()

So you can try to execute this function (or some parts of it) in the ajax callback before the cart is updated.

Here is an example how to apply shipping rates if you are using using Flat Rate Module:
Adding shipping to order programmatically via module.


The Views Slideshow module relies on the Cycle library, if I'm correct. It supports AJAX / progressive loading in it's current version as seen here:

http://malsup.com/jquery/cycle2/demo/progressive.php

In my experience, a lot of Drupal modules make the integration of library options unneccessarily complex:
So you could just generate the necessary code via views instead and load the lib yourself via template. Most current slideshow scripts support AJAX loading, so you can choose one that suits you.


If I remember correctly, try this.

Create a relationship to the taxonomy parent term.
Add a taxonomy term name field, add relationship to Parent.
Add another taxonomy term field.
Group by Parent term.

Hopefully that works out. You can also look into Views Tree, I've used it before and works pretty well for specific use cases.


Where should I store 3rd Party external js libraries?

One option is to do it exactly like in D7. Put it in /libraries or /sites/all/libraries and use the libraries module to detect the location.

location.module itself unfortunately doesn't work that well in 8.x yet, so you have to define an 8.x-1.x library and then use the libraries API to get the location and dynamically alter. Or I guess you could also do that part yourself.

I'm doing that in the JW Player project, see jw_player_libraries_info() + jw_player_library_info_alter(). It unfortunately still requires a bit of code, maybe that will improve in the future when libraries.module works better in 8.x.


$render_array['maintable'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);


How to add multiple value field in webform

Webform Multiple File Upload allows user to upload multiple files on a webform and you can also limit the number of files, see the below image.


Pass variables from custom module to its template?

To use the theme API it requires three portions: the template file, the theme hook, and then displaying the defined theme. The below examples are for Drupal 7.

<?php
  // defines the theme hook - should follow the naming format "_theme()"
  function mymodule_theme(){
    return array(
      'example_template1' => array(
        'template' => 'mytemplatefile1', // mytemplatefile1.tpl.php
      ),
      'example_template2' => array(
        'template' => 'mytemplatefile2', // mytemplatefile2.tpl.php
      ),
    );
  }

  // in this function is where you would do your DB queries,
  // and pass to the theme function as shown
  function mymodule_customfunction(){
    $calculation = 1+1;
    return theme('example_template1', array(
      'example_variable1' => $calculation,
      'example_variable2' => '123',
    ));
  }
?>

The mytemplatefile1.tpl.php file could look something like this:

<?php echo $example_variable1; ?>

To display your output, you could then just execute the following and it would print your value, wrapped in the "example-markup" div.

<?php echo mymodule_customfunction(); ?>


"skip_process_on_empty" plugin does not exist

skip_process_on_empty and skip_row_on_empty were combined into a single plugin. Try this:

plugin: skip_on_empty
method: process

To skip a row:

plugin: skip_on_empty
method: row

Hope this helps!


access field data in template.php and create variable for header image in page.tpl.php

I recently tried to do this but stumbled then over the Header Image Module which does this perfectly. It allows you to create a block which holds any content (for example a custom content type) and ads it to a block. You can specify on each content where it should be displayed (nid, path, term etc.).


using EntityFieldQuery to find a custom taxonomy field

The code_description field does not appear in the WHERE condition of the original query. Therefore there is no need to add a fieldCondition on the EntityFieldQuery neither.

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->entityCondition('bundle', 'fund_code')
  ->propertyCondition('name', $fund_code) ;

$results = $query->execute();
foreach($results['taxonomy_term'] as $tid) {
  $term = taxonomy_term_load($tid);
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}

However there is already the core function taxonomy_get_term_by_name doing exactly what you need here:

$terms = taxonomy_get_term_by_name($fund_code, 'fund_code');
foreach ($terms as $term) {
  dpm($term);
  $items = field_get_items('taxonomy_term', $term, 'code_description');
  dpm($items);
}


Pager disappears when adding "GROUP BY" in the SQL query

Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without an aggregate function.

Also if you put a GROUP BY in your query, you should also include it in your count query. Generally a brutal way to make the count query is to put it this way:

$sql = "SELECT  * FROM journal";
$countSql = "SELECT  COUNT(*) FROM ($sql) ";

Try to modify your queries and amend your question with further precisions.


How to display the same views exposed form block twice?

This code worked for me. I'm using Views 6 Alpha 4.

$view = views_get_view('your_view');
$view->set_display('the_display_you_want_that_have_a_exposed_block');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);


How do I add a payment view block to Commerce Order page?

For the block, you can set the visibility to user/*/orders/*

For the info in the block, you can use a contextual filter that checks the user and displays the needed info.


What is the difference between context layouts and the delta module?

The Delta module is not an alternative to Context Layouts, you should use them together.

Delta allows you to create different versions of your Omega theme with different settings/layouts each.
Context Layouts is part of the Context module, and will allow you to switch the different layouts you previously created with Delta, when a specific 'context' is active.


The page title is by default the title defined in hook_menu for the menu item. If you want to alter the title, you should use drupal_set_title.

Note: Drupal set title can't be used to late in the theming process (like template_preprocess_page), as the value for the title has already been populated at that point. Using it in the menu callback should work just fine.


How to display a create node form together with a referenced node of a different type

If you need to put that info in a block near the form, you can create your custom hook like

function mymodule_menu(){
  $items = array();
  $items['mynode/add/%/%'] = array(
      'title' => t('Create content'),
  'description' => 'Calls to a drupal_get_form',
  'access callback' => 'user_access',
  'page callback' => 'my_function',
  'page arguments' => array(2,3),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
 );

 return $items;
}

So now you have a page called /mynode/$type/$id_user

In that page you can render the form of that content type using drupal_get_form() and returning it rendered. Now in the blocks config you can add your block view to the pages called /mynode/mytype/* , getting the user id argument from the url will let you render that view with the user data.


Insert date programatically in custom module

I think correct format is 'yyyy-mm-dd', try to insert '1938-12-19'


How to get media entity field value in twig?

Right now, the Media module does not pass its object in the variables like Paragraphs and Node does. This is why media.field_my_boolean.value does nothing.

You can correct this in your theme by implementing theme_preprocess_media, which adds the media object to the variables:

/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  $variables['media'] = $variables['elements']['#media'];
}

You can then access media. in your twig template and any connected fields on it just like Paragraph or Node.


A way to make one Drupal site act like several sites

Have you looked at the Domain Access project?


Loop trough items in view template and access field values?

Use {{ dump(item) }} to see the structure.

Once you have the structure you can reference in a faily regular way: if a sub-item is an array or an object, then it's a dot, if an array with a #, reference as an array eg xxx.yyy['#zzz']


Path is not available in Views filter criteria

You can add path in Filters section if you installed views_url_alias module.

Please, take a look on screenshot.

I hope this helps.


How can I open Poll for Anonymous users?

Visit admin/user/permissions and check the checkbox for vote on polls for anonymous.


After a long night of debugging I finally found the bug. I always thought that hook_node_presave is called twice when submitting a form. That is wrong. Took me a while to find out.

I then searched for node_save operations in my code through like 20 modules and found a module calling node_save in a custom node form submission handler. I removed it and it works now.

Thank you all for your help!


Migrating SQL dump from Drupal 5 into Drupal 7

There isn't any other way to update to Drupal 7, if not following the steps you listed. I would rather update to Drupal 6, and then to Drupal 7.
Probably, you could avoid installing Drupal 5, if you restore the database tables used from Drupal 5; you could start with updating to Drupal 6, if you have a copy of the setting.php file used from Drupal 5 (or you can rebuild it). I have never tried this; it could be working in theory, but have some practical problems I didn't think of.

Updating the data from Drupal 5 to Drupal 7 means to execute the update functions Drupal runs to update itself. There isn't any other method, since Drupal executes the updates in a specific order, and hook_update_dependencies() implementations change that order.


How to unblock my own admin account after 5 failed login attempts?

To answer the question in your title (which appears to become more complicated following your actual question), you just need to clear the flood table in your database.  If you're running Drush, then the following should sort you out:

  drush php-eval 'db_query("DELETE FROM flood");'

Failing that, just clear the flood table from your database manually :)


How do I modify a menu link title dynamically?

It looks like the other answer on that post you linked to is quite relevant. It references hook_menu_alter() as a tool to:

  ... add a title callback that will be called every time a link to the menu item will be rendered

However, I'm not sure if that solution would work for manually-created menu links items with custom title text. The other, possibly more universal, option that I can think of is using hook_menu_link_alter() along with hook_translated_menu_link_alter(). The former is used to "flag" a link as alterable (when the link is saved), and the latter is used to actually alter it (at render time).

Actually, it looks like this post covers both these options in even more detail, so I won't repeat any of their code samples here.

This distinction about which alter hooks fire at save/cache-clear time vs. render time is important as it often means that you have to leverage a hook + callback, or 2 hooks, to implement dynamic alterations. For example, if you choose the second option you use hook_menu_link_alter() to declare the link as alterable, and though that hook does not fire each time the link is rendered, it "registers" the fact that hook_translated_menu_link_alter() should in fact be called at render time for that specific link.


Moving field content to new field collection fields automatically

Create your Field collection,
Add new fields to it
Add field Collection Field To your content type
Create a Custom module ( if you don't have)
With Getting help of Batch Operation Docs, Create A Batch Operations on your desired content type
On each epic load node, get your fields data,
Add those values to field collection ( add an item at field collection programmatically)
Check the Results
remove old fields from the content type

I Strongly Recommend befor write batch, try it on one node, I mean create a route ( I mean item with hook_menu) then in call back try to achieve what you want, after success convert it to a batch operation or do it with VBO + Php Filter module(instead of batch processing)


Pulling #hashtags and displaying them on site

This is possible using the dev branches of a few modules put together:

feeds, >= 7.x-2.0-alpha8+56-dev

feeds_oauth, >= 7.x-1.0-beta3+2-dev

feeds_jsonpath_parser, >= 7.x-1.0-beta2+12-dev

I think there are a few other necessary modules you'll need to have installed, like oauth, ctools, feeds_ui.
One of the most important things is that you need to register an app at dev.twitter.com, and get an API key / secret. You put that into the feeds setup (admin/structure/feeds/FEED_NAME/settings/OAuthHTTPFetcher). When you setup your feed, you will want to choose the HTTP OAuth fetcher (oauth2 does not work) as the Fetcher type.

You create a new feed importer.

Additionally, you'll want to create a content type like "tweet" and add the fields you want to parse (like author, date, name, body, location).

Back in the feeds setup, setup your mapping, and create several jsonpath_parser maps to your respective fields. After that, click "settings" under JSONPath parser, to map your json contexts to your fields.

It should be something like this:

Context: $.statuses.*

Title: id_str

body: text

etc, etc, etc

Finally, once this is all setup, you can go to SITEURL.com/import
and input your search string, which will look like this:

https://api.twitter.com/1.1/search/tweets.json?q=%23HASHTAG

Anyway, I hope this is helpful. I realize that my answer could be better organized, but it should give the gist as to how this is done.

For my "tweet" content type, I have the default setup to be NOT published, so that I can moderate what actually shows up on my site.

One more caveat is that non UTF-8 strings (common in foreign languages for example) will error out and break your feed importer (which should run on cron automatically). Ideally you want to sanitize the input before writing it into the database anyway.

Here's the PHP you can put into a quick custom module to sanitize the input of the body field for example. You want to make sure your jsonpath_parser:ID matches the ID you setup in the node-processor settings.

<?php

/**
 * Implements hook_feeds_after_parse().
 */
function feeds_custom_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
//dpm($source); // look at source variables, requires devel
//dpm($result); // look at result variables, requires devel

  foreach ($result->items as $delta => $item) {
    $result->items[$delta]['jsonpath_parser:1'] = utf8_encode($item['jsonpath_parser:1']);
  }
}


make more rare content type appear in result

AFAIK you'll have to manually modify the query to get such advanced conditional sorting.

You could group by the type (under Format), and set the Pager to such a high number that you can always be sure there will be at least one Resource there, so the second group will appear for it. But it's not a very reliable method if you can't predict the longest range of blog entries without Resources.

Usually, this is handled by creating two Views displays, one for blog entries, and the other for resources. You can set the Resources one to be Attachment type, and attach it to the blog one so they display one below the other. In that case you will be able to override the number of items in the Pager to show less Resources than Blog entries, to show Blog entries are more frequent.


Create user in Drupal 8 but password not working

I try with you code, I not see any problem and work for me (drupal 8 beta7).

$authData['name'] = 'testuser';
$authData['pass'] = 'testpass';
$authData['mail'] = 'sss@test.com';
$authData['status'] = 1;
$account = entity_create('user', $authData);
$account->save();

Note that user and pass are different when you try to log in

user: testuser

pass: testpass

That drupal 8 version are you using?


Changing the Open Atrium 2 login hyperlink

Try this:

Goto admin/config/people/accounts
Select Registration and cancellation
Under Who can register accounts?, chose Visitors instead of Administrators only

Then users can create an account from the user/login page.


How to fix "This display does not have a source for contextual filters"

This is frustrating.  AFAIK

"Content Pane" displays do not have context passed to them ever.
Views have "master" displays that do get context passed.

The "master" display is essentially the view's defaults.  To see it, there is an option here:  admin/structure/views/settings/basic
(or just delete all other displays)

To add a view's "master" display to a panel, you need to see it first:
http:///admin/structure/panels/settings

Now go back to the panel, add content, select "views" instead of "view panes" to see your view.


A good way to import tweets, blogpost, flickr photos, slideshare,

You're on the right track, but it sounds like your site may have some "too many modules" issues.  If you're having modules randomly overwritten or enabling is throwing errors, it is usually time to clean up the site.  If you can, start with a brand new site and only enable the modules you absolutely need.  Keep things as basic as possible.  If you want to try out other modules do it on a separate "sandbox" site that is just for testing.

There isn't going to be a single-solution for all social media.  However some places to get started:

Feeds module - for anything using RSS (YouTube does, so does SlideShare, Twitter kinda does, etc)
Specific modules could be used too like Twitter Pull and the Media module as you mentioned.


Using drush to sql-sync local to remote, without remote MySQL binaries on remote

Drush version 3 and onward (via the sql-sync command) can only copy the database via the ssh + mysql executable method that you describe above.  If you download drush 2.1 (https://drupal.org/node/614830), you will find a command drush sql-load that works as you describe.  It's a lot slower than sql-sync, so if your database is very large, you might find this technique to be too cumbersome.  If it works for you, though, it probably wouldn't be very hard to make your own external Drush commandfile to provide sql-load on a more recent version of Drush.


This is almost certainly a permissions issue. You need to ensure the web user (apache?) has access to these files. I typically just

chmod -R www-data:www-data sites/default/files

and it does the job.


Adding Content to Drupal 7 through a remote PHP script

Services module can be used to allow to create node remotely

Check out some reference links as below

https://groups.drupal.org/node/144394
How do I POST a new node using the Services module?
https://drupal.org/node/1354202


I'm assuming you have already come up with a solution to upload the files and put them in the database, and that you have a good reason not to use Drupal's built-in file handling (I question that second assumption particularly given the reference to health policy but I'll grant it).

The block you created needs to just provide the list of links, but you should not set the headers there, just generate the links.  The link should probably be in the form of something like:  /custom_files/[filename]  (or something clearer based on your complete context.

First you need a hook_menu() to define the menu router to get your files. Something like:

function mymodule_menu() {
  $items['custom_files/%mymodule_filename'] = array(
    'page callback' => 'mymodule_filedownload',
    'page arguments' => array(1),
    'delivery callback' => 'mymodule_file_delivery',
  );
}

You should also add some permissions handling here, the documentation on hook_menu() explains how that works.  Also read the section on deliver callbacks because those also have security implications I'm glossing over.

Next you need the page callback function to actually send the file:

function mymodule_filedownload($mymodule_filename) {
   // Validate permissions
...
   // Validate filename
...
   // Load file object from database
   $query = db_select('health_policy_document_upload_dtl', h)->fields('h')->condition('filename', $mymodule_filename,'=');
  $result = $query->execute();

   // Prep an array to hand data off to the delivery callback. It might just be the results, but often you want to tweak details...
...
  return $file_data_array;

}

function mymodule_file_deliver($file_data) {
   // Check $file_data to see if this is a valid file or an error of some kind.
...
  // Process and errors found and send proper error response.
...

  // Send file
  drupal_add_http_header("Content-length: ".$file_data['size']);
  drupal_add_http_header("Content-type: " .$file_data['type']);
  drupal_add_http_header("Content-Disposition: attachment; filename=".$file_data['filename']);

   print($file_data['data']);

   drupal_page_footer();
}

Obviously lots of details are glossed over here. In addition to hook_menu()'s documentation you likely will also want to read drupal_deliver_html_page().  Note the use of drupal_add_http_header() instead of PHP's header(), for most basic tasks Drupal has internal functions that provide some clean up and standardization to avoid basic mistakes and conflicts with other module; you should use them whenever possible.


Drupal 7?

Use admin/config/regional/date-time/formats and create a new Date/Time format that only outputs the time. Then in your view set the field display to use that format by selecting  "date and time" under "formatter." Now select your newly created format under "choose how users view dates and times."

I think that is the same in D6 as well or at least similar.


In order to replicate the desired behavior you can create several Views blocks and use the pager Display a specified number of items option. Then for each block change the amount and offset:

If you would do this with 3 different blocks and use offset/amounts of 0/1, 1/2 and 3/4 you should be able to stack them and have the desired result.

If you really really want to change the class per row, have a look at the great example Dynamically adding a CSS class to a view row with template.php where you can use a views preprocessor to set the right class per row.


Make Commerce Checkout Form Submit via Ajax

I see two problems with your code:

#ajax should be set on one of button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield. You are setting it directly on form, not on form submit element, so it cannot work.
You should also set ['#ajax']['prevent'] if your form gets reloaded. In theory:

  Description: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'.

In practice, it often fails to work as expected and I found it safer to set it explicitly.

In the button's array, be sure your #ajax definition is on the same level  [#type] => submit is. Don't put it under #submit or any other button's sub-array.


Why is my MONTH view still showing a DAY as the title?

It appears that the fix isn't in the latest release (7.x-2.8) yet and is instead in the current (7.x-2.x-dev) version. According to the comment #70 in that thread you posted, the patch is meant to be applied to the current release and not the latest dev (which is why it failed). If you run the patch in comment 70 against your 7.x-2.8 version it should correct the issue. As you stated that isn't an option, you can try to have the drupal update page grab the latest dev.

You can always check the release date for different branches on the project page. For example, Date currently shows the 7.x-2.8 branch as having been released on July 29th, 2014 while the latest commit, 7.x-2.x-dev, was released on June 16th, 2014. Hope that helps


How do you override Commerce checkout pane output?

Checkout panes are fieldsets within the context of per-page checkout router form. You can use a hook_form_alter() to modify the contents of the entire page that a form is shown on. For instance, if you want to modify objects that appear on the checkout page (which is the first one in Commerce Core), you'd use this hook:

MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  // Make the customer profile billing pane's locality field a bit smaller.
  $form['customer_profile_billing']['commerce_customer_address']['und'][0]['locality_block']['locality']['#size'] = 20;
}

Where commerce_checkout_form_checkout is commerce_checkout_form_ concatenated with the current checkout router step. See commerce_checkout_router(). Each of the panes within the page exists within this form. As Ryan also points out in the comments, the main form traps errors and other items to present them inline with the checkout pane, so a payment error won't show up at the top of the page, but it will show up above the payment pane for instance.

If you're wanting more info on how to theme checkout, I'd recommend you go review the code for Commerce Responsive UI and mimic what it does.

This includes the complete pane which is still a form. If you want to override the form completely, you can just change the callback that is called when the completion pane is being built:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['checkout_completion_message']['callbacks']['checkout_form'] = 'MYMODULE_completion';
}

Then, you put your own output into the new callback. Just copy what commerce_checkout_completion_message_pane_checkout_form() does and put your own content in.


How to get File entity in media_presave hook?

I've found a solution.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function hook_media_presave(MediaInterface $entity) {
  if ($entity->bundle() == 'image') {
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($field_definitions as $field_definition) {
      if ($field_definition->getType() == 'image') {
        /** @var FieldItemListInterface $field_value */
        $field_values = $entity->get($field_definition->getName())->getValue();
        if (is_array($field_values)) {
          foreach ($field_values as $field_value) {
            if ($field_value['target_id']) {
              /** @var File $file */
              $file = File::load($field_value['target_id']);
              $image = getimagesize($file->getFileUri());
              // If the image has channels '4' it is cmyk.
              if ($image['channels'] == '4') {
                $imagick = new Imagick($file->getFileUri());
                $imagick->setImageColorspace(Imagick::COLORSPACE_RGB);
                $imagick->writeImage($image);
                $imagick->destroy();
              }
            }
          }
        }
      }
    }
  }
}


In the specific page.tpl.php adding an include file

Try create a custom module and use module_load_include() it might be a better approach than the standard PHP include() then include the custom php.


how to connect to database in drupal in order to display the content in a table

You need add the followings lines in settings.php for connecting 'external' database.

$databases['default']['default'] = array(
      'database' => 'drupal8',
      'username' => 'username',
      'password' => 'password',
      'prefix' => '',
      'host' => 'localhost',
      'port' => '3306',
      'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
      'driver' => 'mysql',
    );

$databases['external']['default'] = array(
  'database' => 'external',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

To activate external database

\Drupal\Core\Database\Database::setActiveConnection('external');

//code to fetch data and display

To activate drupal database

\Drupal\Core\Database\Database::setActiveConnection();

If you are looking some example refer How to connect to another database in your Drupal 8 site ?


How to import context module export -drupal 7

Way1: Using Features module

I would recommend you to use features module to export your configurations like context, it will automatically pull the context configurations in code.

Way2: Using custom module

If for some reasons you want to do it in custom code then

Use context export module to export your context. This module will let you the configuration code for context.
Then create a plugin using hook_ctools_plugin_api and hook_context_default_contexts. Refernce link

Sample Implementation for hook_ctools_plugin_api.

This will let Drupal aware of the context export plugin using ctools API.

Sample Implementation for hook_context_default_contexts.

Create file as _context.inc inside your
Add the implementation of hook_context_default_contexts on _context.inc file. As in this example code.


Is there an event before and after form is submitted via ajax?

When you look in ajax.js you find several prototype functions, that can be used like hooks in drupal:

core/misc/ajax.js:

 /**
   * Modify form values prior to form submission.
   *
   * @param {object} form_values
   * @param {HTMLElement} element
   * @param {object} options
   */
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
    // This function is left empty to make it simple to override for modules
    // that wish to add functionality here.
  };

You can override this prototype-functions in your own js-file:

(function($) {
   var ajaxBeforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
   Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {

      // your code

      // call original function since it can be already overridden
      ajaxBeforeSubmitOriginal.call(this, form_values, element, options);
   }
})(jQuery);

This is the most basic version. More info: https://www.drupal.org/node/1372840


What is the pattern '' referred to in Drupal speak?

According to this Drupal 8 issue queue, <front> is a "special token." Yes, it still works in Drupal 8.

Reading the whole issue queue will give you some insight into the core developers' thought processes as they decided whether or not to support this legacy Drupalism in Drupal 8. They had a lot of good reasons to drop support for it, but they erred on the side of caution and left it in.

You can also try it for yourself in a Drupal 8 site; it definitely still works!

Help text for adding a menu link says:

  Start typing the title of a piece of content to select it. You can also enter an internal path such as /node/add or an external URL such as http://example.com. Enter <front> to link to the front page.

I guess you might want to give more weight to Clive's comments above, since his answer is based on the actual code and comments in Drupal core. Technically, all strings processed by index.php are considered "paths" and the ones that resolve to valid destinations are "routes." (Under the hood, Drupal 8's routing system is based on the routing provided by the Symfony HTTP kernel, and is used to connect paths to controller logic.)


Provided your project's machine name is contacts_blocks, make sure that your implemenation of hook_update_N is located in a file named contacts_blocks.install that is inside your project directory.  (Make sure you spell it exactly right contacts_blocks.insall will not work.)

The four digits should be [major version][minor version][2 digits for sequence], so the correct name in your case (branch 7.x-2.x) should be 72XX, where XX is some sequence number.

To figure out what number to use for the last two digits, run the following query:

SELECT schema_version FROM `system` WHERE name = 'contacts_blocks';

If it returns no result, then use 7200.
If it returns something below 7200, then use 7200.
If it returns a number above 7200, but below 7298, then increment with 1 and use that (e.g. if it returns 7202, use 7203).

If there is a weird value for schema_version in the systems table, and you're just experimenting (i.e. nobody else have your module, so you're not going to distribute the contacts_blocks.install file with your update to anyone), you can get a fresh start by disabling and uninstalling the module (just disabling is not enough), the reinstalling it again.

API link: function hook_update_N


Drupal Commerce: How to perform a complex calculation of order's final cost (VATs & discounts)?

You can achieve what you're looking for using some module and disabling others. This explanation is based on Drupal Commerce (7.x).

Uninstall standard Commerce Tax module since it leads to weird results with different VAT if you aren't a Rules master as exposed in this issue on drupal.org.
Install Commerce European Union VAT (commerce_eu_vat) choosing the right country: the module has a good written API and you can adapt it for extra-EU countries easily. Now you can assign product by product the right VAT and even assign a default VAT by product type via "manage fields" on product variations administration.

Install Discount (commerce_discount) module. You can set discount per product and per order (your case). Create a new discount, e.g. "My funny discount".
Now you can create your per-order discount. Every time you create a new discount it appears on both Discount page and on Pricing rules. Since VAT is sometimes applied before Discount (in my case it was) then you have to change the Rule weight for your new discount. Go to the Pricing rules administration page, search for "My funny discount" > edit > Settings > Weight and give it a negative weight to apply the discount before the VAT. Note: when you override the discount you cannot save it anymore since you've changed the parent Rule. Just revert the rule to make it editable again and then reapply the weight trick.

Now you have to hide unwanted components from your price on display: to do this install Commerce price by components (commerce_price_components). On your product type > Manage display you can change your price field widget from "Formatted amount" to "Price by components" and check only Discount and Base price, excluding VAT and other components.

Here the result on checkout:

Hope this helps.


List of parent and child taxonomies and related content

There is more than one way of solving this.
If you start from your existing case of Content Views and listing your Products, you can add the Taxonomy ER Field. This field will show the Term that the node is directly linked to, the "child" in your Taxonomy hierarchy.
To get the "parent" Taxonomy term you have to add the Relationship for the ER field in question. Once you add that you will be able to access the Parent Field from the "Taxonomy term" Category.
You can then set Grouping under Format Settings. Set the first grouping to the "Parent" Field, and the second one to the "child" regular taxonomy field.
You can hide the taxonomy fields with Exclude from display since they'll appear in the grouping output.
Alternatively, you can add a second Relationship on top of the first one, for the Parent of the term, but that approach isn't necessary unless you have 3 levels of taxonomy hierarchy, and it can add to the performance strain.

You can also start from the Taxonomy term type Views, show hierachy with Depth, and use a Relationship to add the nodes/content into the View.


This is being worked on, see https://www.drupal.org/node/2493559 and https://www.drupal.org/node/2621598.

In the meantime, you need a bit of custom code to connect the dots. You need to implement hook_token_info()to define a token on nodes for your field with type term. You can also switch the type of the generated field token to term. The second part is a hook_tokens() implementation that forwards [node:yourtokenname:...].

It's similar to what node_tokens() does with node:author:name for example, which forwards the part after author to the user token generation:

if ($term_tokens = $token_service->findWithPrefix($tokens, 'yourtokenname')) {
  $replacements += $token_service->generate('term', $term_tokens, array('term' => $node->field_yourfieldname->entity), $options, $bubbleable_metadata);
}


Drupal 7 Override Image Alt and Title attributes

I think a template preprocess would be fine for this, specifically hook_preprocess_image():

function MYTHEME_preprocess_image(&$vars) {
  // alt
  if (empty($vars['attributes']['alt'])) {
    $vars['attributes']['alt'] = DEFAULT_IMAGE_ALT;
  }

  // title
  if (empty($vars['attributes']['title'])) {
    $vars['attributes']['title'] = DEFAULT_IMAGE_TITLE;
  }
}

Pretty much all images (including those provided by a field) run through theme_image() so this is pretty much the best place for your code.


Weird Drupal Error (The character encoding of the HTML document was not declared)

I turned on errors in the settings.php with ini_set('display_errors', 1); and I found it was a memory issue.

I added ini_set('memory_limit', '500M'); to the settings.php file, and all works.


Field formatter only displays file name not link to file

You should go to (structure -> content types -> page -> manage display):

/admin/structure/types/manage/page/display

and set your fields format and its corresponding settings the way you prefer.

Further reading on the topic: here

Youtube tutorial: here


How to change the machine name of the content type in Drupal 7

Go to structure, click content types, click edit next to the content type you want to edit. Click edit next to the machine name and change it to the name you want.

If you merely want to change the administrative name, then change that instead.


I'm not familiar with the computed field module and not sure I completely understand the relationships between your nodes and fields, but here's about how you should be able to get things working.

The first query seems like it would be alright if you'd remove that extra closing bracket and used fetchField() to retrieve the value:

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
')->fetchField();

The second one needs some more work. I'm assuming that you have review nodes with the ratings and every review node is linked to a business node with a reference field of some sort.

First I would get the nid-s of those review nodes that are linked to the current business node as an array (using fetchCol()) with something like this:

$nids = db_query('
  SELECT entity_id FROM {field_data_field_business_reference}
  WHERE field_business_reference = :nid AND entity_type = :type AND bundle = :bundle',
  array(':nid' => $entity->nid, ':type' => 'node', ':bundle' => 'review')
)->fetchCol();

Then get the average:

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids) AND entity_type = :type AND bundle = :bundle',
   array(':nids' => $nids, ':type' => 'node', ':bundle' => 'review')
)->fetchField();

UPDATE:

To avoid the error you're getting you can try wrapping the code inside some if statements to make sure it won't be executed when necessary criteria is not met:

$node = menu_get_object();
if (isset($node->type) && $node->type == 'venue') {
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }
}

If that's too restrictive you might get away with just this much:

  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }


How to pass pagination value to drupal view programatically?

I found setCurrentPage more suitable for my use case
$view = Views::getView('schedule');
$view->setCurrentPage($pageNum);


How do I figure out what module is using drupal_set_message()?

Are there any messages in your error log? You should be able to see a module name there.

drupal_set_message has no parameter to add a module name to the message so there is no straight forward method of finding the module. You could copy the string from the message and search in the translation page (if you have the locale module enabled. Or throw the string at Google and see what you find. That usually helps!


Drupal updating form fields on file upload

After many hours, I've found a solution!  Thanks goes to Matthew Davidson, who posted this workaround on drupal.org, full post The working code looks like this:

function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'mymodule_node_form'){

       // create a button to populate the form
       $form['mymodule_pop_btn'] = array(
           '#type' => 'submit'.
           '#value'=>t('Populate Fields'),
           '#submit'=>array('mymodule_populate_fields'),
       );
    }
}

//function to populate the form fields
function mymodule_populate_fields($form, &$form_fields){
    $form_state['input']['my_field']['und'][0]['value'] = 'Some New Value';
    $form_state['rebuild'] = TRUE;
    $form_state['no-cache'] = TRUE;
}


Well, there's the Cache Warmer module you can set up if you have drush access on your server.

You can also use a 3rd party service like Pingdom to do that as well.


Associative arrays must use curly brackets in Twig:

{% set twigAry = {} %}

Arrays with square brackets [] defined in Twig don't have key names


Remove one item in cart removes all - Ubercart/Webform

Yes, but not with the module itself. You can build a custom module to modify UC Webform Integration to suit your needs. This would involve 3 parts:

Implement a HOOK_form_uc_cart_view_form_alter() function such that cart Delete link for each submission and they have 2 arguments: cart/delete-form/$NID/$SID. You may need to adjust your custom module weight so that it executes after, uc_webform_form_uc_cart_view_form_alter().
Implement a HOOK_menu() function that defines the new cart/delete-form/%/% path. uc_webform_menu() should give you an idea how it's done.
Implement your own form/submission handler for the cart/delete-form/%/%. The function uc_webform_submission_delete_products_form() & uc_webform_submission_delete_products_form_submit() should give you an idea how it's done. The key thing here is you'll be adding something like $wf_sid = arg(3); and replacing isset($cart_item->data['webform_sid']) with $cart_item->data['webform_sid'] == $wf_sid so that only the selected submission is deleted instead of all submissions on that form.


Is it possible to have custom, default fields added to all new product types In Commerce 2?

Nothing that just works.

You could define them as a base field through code by defining them in hook_entity_base_field_info(), so for example how scheduler module does that. Then they will be non-configurable fields that are always there. If they're not multiple, they will even be added to the product base tables.

Those kind of fields are a bit tricky to uninstall.

The other option is implementing a hook_commerce_product_type_insert() and then copy the configurable fields you want from the default type and add them to that new bundle as well.


How to get hook_form_FORM_ID_alter field value in hook_ENTITY_TYPE_presave

The form field you've added is not a node field.

If you want the field to be accessible in the node, then add it to the content type. In this case you don't need a form alter hook, because the entity fields are added to the form automatically. You can create multiple form modes with and without the field and select them dynamically, for example with Form mode manager.

If you don't want the field to be stored in the node, but want to do something else with the user input, then add a custom submit handler in the form alter hook to process the field value.


Dont Refresh Drupal's Page after a button is click in Forms API

You should do something like this:

function myid_user_page_form() {
    $form = array();
    $form['id'] = array(
      '#type' => 'fieldset',
      '#title' => t('ID Information'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
      '#type' => 'button',
      '#value' => '...',
      '#attached' => array(
        'js' => drupal_get_path('module', 'your_module') . '/js/your_file.js'
      ),
    );
    return $form;
}

Then, add a directory "js" in your module and a js file. In that js file use:

(function ($) {
    Drupal.behaviors.yourModule = {
        attach: function (context, settings) {
            $('#your-element').click(function(e){
                e.preventDefault();

                // Your functionality.

                return false;
            });
        }
    };
})(jQuery);


add a search bar on a page and limit it to search only under post titles?

Use custom_search module.

By this module you can create customize search form that searching on custome content type and custome fields on content type.


Open a view getting nid from previous view

Yes it is possible.

You can do the following

In the first view add nid field
In the field settings go to rewrite result
In rewrite result give something like Link Text

[nid] will work as a place holder for the current content nid. You can see all the replacement patterns with in the view itself.


Is there a hook function for a module's settings form being submitted?

You can implement hook_form_alter or hook_form_FORM_ID_alter and add a custom submit handler to the form in which you can clear the session data. It would look something like this:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "some_form") {
    $form['#submit'][] = 'mymodule_some_form_submit';
  }
}

function mymodule_some_form_submit($form, &$form_state){
  // Do your fancy stuff here.
}
?>

This example implements hook_form_alter. If you only have one form to alter, I recommend using hook_form_FORM_ID_alter because it results in cleaner code.


Where does the mysterious blue bar and question mark come from (when logged in as admin)?

I think You should try to:

search Your modules or themes directory for usage of drupal_set_message function or dsm if You are using devel module.
check trigger module settings for User under admin/structure/trigger/user
check theme template for empty container with alert-info class


How to limit number of displayed images within one field under views?

When you use field collection in Views, go to the settings of field collection field in views and follow these steps :

1. There is a setting named "Multiple Field Setting"
2. Enter the number of pictures in the textfield you want to show in Field 'Display'

and you also specify Start from to where to start.


drush sql-sync tries to rsync unknown dump file

This is a bug in Drush master.  Please put an issue in the queue on Github.


Drush custom command not found in context of running --root option

To call a command on a certain instance of a multisite you are supposed to pass the -l option. Also be sure that the custom module that provides the custom command is enabled on the multisite instance you are trying to call that command on.

$ drush custom-command -l subsite


How to make a menu link on a subdomain use the main domain as base_url

It will depend on your theme, but typically the menu array (e.g. $mail_menu in page.tpl.php) can be altered such that each menu item have the array element 'absolute' set to TRUE so that l() will generate the link with an absolute path.

For example, in a MYTHEME_preprocess_page() function:

/**
 * Override or variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  foreach ($vars['main_menu'] as $id => $menu_item) {
    $vars['main_menu'][$id]['absolute'] = TRUE;
  }
}

As long as $base_url is set to http://example.com, it should render the menu links to your original domain.


I achieved it in a work-around. I am downloading images inside my drupal accessible folders with the fixed names. Updating these images with fixed names using a background script. Applied cache buster techniques so that images with same names are updated.


It turns out that my theme was hiding any term reference fields by default, which I discovered after switching back to the default theme (thank you too @NoSssweat for suggesting I do this).

I created the theme using Artisteer (please keep comments about my decision to do so to a minimum - I only use it as a starting point) and following @JimmyKo's comment I found the following lines in the node.tpl.php file:

$terms = themename_art_terms_D7($content);
hide($content[$terms['#field_name']]);

After I commented these out the term reference field started appearing. Thinking back, I may have ticked an option in Artisteer to say that I didn't want tags to appear so I can't definitely lay the blame on the software!


What does `OWNER` value mean in Rules export?

OWNER means what module provided this rule. The reason for this is so we have a good way for contrib modules like drupal_commerce to have a section in their administrative area to only show an interface for their rules and not ALL rules.


I don't know of a module that would provide a user interface you could use to achieve what you're after. It is quite simple, however, to put together a tiny module and implement hook_nodeapi('view') to remove the body part from the node content before it is built for display.

The most basic example would be the following, removing the body part from all nodes' teasers:

function YOUR_MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view' && $a3 /* teaser */) {
    unset($node->content['body']);
  }
}

Just pop a function like this into your module and adjust the if condition as needed.


How can I validate that a date is available before prompting the user to complete the rest of a webform?

You have to use AJAX to check if the date is available.

In your form add a button to check for the date, for example:

  $form['submit-check'] = array(
    '#type' => 'submit',
    '#value' => '('Check date'),
    '#ajax' => array(
      'callback' => 'mymodule_check_date_callback',
      'wrapper' => 'datecheck-result-wrp',
    ),
  );

When user clicks on the button, an AJAX call is made. inside the AJAX callback you can check the date availability and return the result in the callback fucntion (mymodule_check_date_callback() in the above example).

AJAX forms are beyond a simple answer, you'll have to check the documentation. I recoomend the Drupal 7 AJAX Forms documentation, the Example for Developers  module that includes AJAX form examples and the Form API Internal Workflow Illustration


Try different way

This works for me if I substitute the logged-in username for 'user', like this:

http://my_site/my_user/logout

ie:

http://example.com/jdoe/logout

this might be problem with not enabling clean url in your site go to

http://example.com/admin/config/search/clean-urls

enable clean url and check if its working

as you mentioned use http://example.com/user/logout will logout the current user section

Further readings:
logout problem - https://www.drupal.org/node/1572984

enabling clean url - https://www.drupal.org/node/1572984

access denied + logout - https://www.drupal.org/node/2192401


Views Rest Export and sending page numbers in it's response

As of now there is no way to display total page count in views rest export. But you can get total pages, current page, items per page and total number of items using new custom style in your custom module which extends existing Serializer class as shown below:

<?php

namespace Drupal\custom_module\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "custom_serializer",
 *   title = @Translation("Custom serializer"),
 *   help = @Translation("Serializes views row data and pager using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class CustomSerializer extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    $pager = $this->view->pager;
    $class = get_class($pager);
    $current_page = $pager->getCurrentPage();
    $items_per_page = $pager->getItemsPerPage();
    $total_items = $pager->getTotalItems();
    $total_pages = 0;
    if(!in_array($class, ['Drupal\views\Plugin\views\pager\None', 'Drupal\views\Plugin\views\pager\Some'])){
      $total_pages = $pager->getPagerTotal();
    }

    $result = [
      'rows' => $rows,
      'pager' => [
        'current_page' => $current_page,
        'total_items' => $total_items,
        'total_pages' => $total_pages,
        'items_per_page' => $items_per_page,
      ],
    ];
    return $this->serializer->serialize($result, $content_type, ['views_style_plugin' => $this]);
  }

}

After adding above file clear drupal cache and edit the view. There you need to change the format from Serializer to Custom serializer.

In this style there is a little difference in the output. All rows are children of rows and pager information is part of pager. Sample output is as shown below:

{
   "rows":[
      {
         "title":"Test"
      },
      {
         "title":"Test"
      },
      {
         "title":"Title 5"
      },
      {
         "title":"Title 4"
      },
      {
         "title":"Title 3"
      }
   ],
   "pager":{
      "current_page":0,
      "total_items":6,
      "total_pages":2,
      "items_per_page":5
   }
}


Adding a Select List (Text) field to an entity bundle programmatically

The field type would be list_text (as defined in list_field_info(), and the widget type is options_select, as defined in options_field_widget_info().

Kind of tricky to track down, but this little snippet should help in future:

$entity_type = 'node';
$field_name = 'field_name';
$bundle_name = 'article';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

It'll get you a complete field and instance definition of an existing field, ready to use in code.


Horrible permissions bug, anonymous users can edit products

Node access rights can be a little hard to debug.  You need to enable the Devel module, and the Devel Node Access submodule.

Then goto your block configuration.  There will be two new blocks: Devel Node Access and Devel Node Access By User.  Add these to your page, and configure them for your admin role(s).  Also goto the Devel settings (admin/config/development/devel) and enable Devel Node Access debug mode.

Then visit a page with access problems.  Look at the debug info.

The Devel Node Access block will show you the {node_access} rows for the node in question.

The Devel Node Access By User block will show you who has permission to do what, and why.

Then you need to do some sleuthing.  If it is a permission, then you need to find that permission and edit it.  If it is a hook_node_access(), then you need to find the module that is implementing it.  If it is a grant, then you need to use the realm/gid and track down who is implementing a hook_node_access_records() with that pair.

The module_implements() function can be used to track down who is implementing what.  I typically do this with

drush php-eval 'print_r(module_implements("node_access"))';
drush php-eval 'print_r(module_implements("node_access_records"))';

My guess is that one of your features has a rogue hook_node_access() in it.  You could also try disabling your features one by one and seeing what happens.


show field of entity for editing according to path

One way to do it is by using field gropups and custom permissions.
Start by installing field groups module to make it possible to group your fields at all.
Move your fields into different control groups and use for example tab groups and tab items in a way to make the editing page pleasing.

If you want detailed asccess rights for different user groups, add some code to do this.

Add your own permissions by using hook_permissions()
For example

function my_module_permissions() {
  return array(
     'edit group1' => array(
      'title' => t('Edit group1 section'),
      'description' => t('Edit field group group1 in Building.'),
     ),
   );
}

In a hook_form_alter() function, you can hide/show field groups like this:

// Check if the current user has rights to see this group and its fields
if(!user_access('edit group1', $user)) {
 // Loop through all group fields and hide them
 foreach($form['#groups']['group1']->children as $index => $groupField){
   $form[$groupField]['#access'] = FALSE;
 }
}

You don't have to hide the group itself, hideing all it's fields will render it invisible.

Then it's just a matter of settings the right permissions to the right user groups.

Pros:

Detailed permissions just for the things you need
Field groups are pleasing to use :-)

Cons: You need to do some coding

Second way

An other way is to use field collections module where a collection itself will be treated as fields in a sense. I guess by adding field permissions you will be able to control each fild collection's permissions.

Pros: no coding :-)

Cons:

By adding field collection you adding a new layer of abstraction wich might complicate things for you later on.
field collections isn't supported by all modules you might use - check it before starting this path.
It will get a bit messy in the permissions hanlding page


Getting all the nodes NOT tagged with a taxonomy term

Create a new views page
Select/Add the node related fields that you would like to refer while filtering the nodes.
Add a filter to filter the nodes by content type
Add a filter: Taxonomy term: Term
Select: Expose this filter to visitors, to allow them to change it
Select: 'Expose operators' and 'Reduce duplicates'
Save the filter and view.
Now go run the url of the views page.

You will see the filter at the top of node fields.
1. Select the filter as (Operator: Is none of) and select the term (Term 1) as per your eg.
2. Click apply button
3. You will see all the nodes which are not tagged to Term 1


You should be able to do this using css, or try using the code below or the tab tamer module

function MYMODULE_menu_alter(&$items) {
  $items['node/%node/view']['access callback'] = 'MYMODULE_disable_node_view';
  $items['node/%node/view']['access arguments'] = array(1);
}

function MYMODULE_disable_node_view($node){
        return false;
}


Drupal 8, don't automatically execute the view after the first load of the view page

I find from the view ui how configure for "force" the user to submit the view for show results ! In the view ui, to the right (in the advanced settings), click on "exposed form style" and choose "Input required" :)


Why is my Rules Component not being scheduled accurately?

When scheduling a Rules Component, you specify a value within Scheduled evaluation date. One of the options to do so, is to specify Relative dates like "+1 day", as mentioned within the Rules UI:

  ... any other values in GMT known by the PHP strtotime() function (like "+1 day")

As per your "offset = 224 days", I'm assuming you used a value like "+224 days".

However since you want to schedule the Rules Component a certain number of weeks after admission (like "week 28, week 32, week 45."), try to specify Relative dates like "+28 weeks", "+32 weeks", "+45 weeks". That might help for the Rules Scheduler to show a more accurate date.


drush sql-sync structure tables in alias dont work

There are three places you can reference aliases when using sql-sync:

drush @site sql-sync @prod @dev

@site - Where the sql-sync will execute. If this is a remote site, then the other two aliases must be defined in files that reside on the remote machine.  Options from 'command-specific' will be applied to the command.

@prod - The source for the sync.  Options from 'source-command-specific' will be applied to the command.

@dev - The target for the sync.  Options from 'target-command-specific' will be applied to the command.

The alias @site is not usually used with sql-sync; most people just run drush sql-sync @prod @dev.

Drush is going to look for different 'command-specific' records depending on the position of the alias appears on the commandline.

@site - The alias that appears before the command name will have options from the 'command-specific' -> 'sql-sync' record added to the evaluated options list.

@prod - The alias that appears in the first position after the command name will have options from the 'source-command-specific' -> 'sql-sync' record used.

@dev - The alias that appears in the second position after the command name will have options from the 'target-command-specific' -> 'sql-sync' record used.

In the typical case (drush sql-sync @prod @dev), the 'command-specific' record is not used at all, the 'source-command-specific' record from @prod is used, and the 'target-command-specific' record from @dev is used.

Try using alias records more like the following set:

/**
 * Dev/Local alias
 */
$aliases['dev'] = array(
  'root' => '/var/www/example_dev',
  'uri'  => 'example.dev',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'target-command-specific' => array (
    'sql-sync' => array (
      'no-cache' => TRUE,
      'structure-tables-list' => 'cache,cache_admin_menu,cache_block,cache_bootstrap',
      ),
    ),
  ),
);

/**
 * Live alias
 */
$aliases['live'] = array(
  'remote-host' => '000.000.00.00',
  'remote-user' => 'username',
  'root' => '/var/www/html/example-live',
  'uri'  => 'example.net',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'source-command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
    ),
  ),
);


Flag state as contextual filter in views

Not with contextual filter, in views I think it's posible with a normal filter (not exposed) since you have already the flag relationship, first add your flag as a field (don't display it if you want) then just filter your nodes with the flag status (flagged). Then you clone the view and change flag status on filter (now to unflagged)  and you will have an opposite view (non-flagged) content.


Add a class name for node locations field, for example "nodeLocation"

and in style.css

.nodeLocation{
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
}


How can I export content-type and content from one site to another?

Node Export

Looks like you are already familiar with the Node export module, allows users to export nodes and then import it into another Drupal installation.

Bundle copy

The Bundle copy module has support for export/import of:

Node types.
Taxonomy.
User.
Field API fields.
Field groups.


Deleting a node just after it has been added

I think Rules module will be helpful for you in this kind of scenario. Rules module help us to define actions on different events(like user creation, node creation/updation/deletion). It is a very powerful module.


How to selectively import and export specific content without overriding existing destination database?

As you already mentioned, use features module to transfer configuration.

For actual content, you will need to use Views Data Export to export stuff. Make a CSV file.

VDE tutorial

Then use Feeds module to import the CSV file content into your other site.

Feeds Tutorial

Alternatively, for nodes you could just use Node Export, but you will still need feeds for the taxonomy importing.


I've had this problem before too!  Very annoying.  ;-)  The reason that happens is that, by default, the list of tags are displayed as a comma-separated list when the node is tagged with more than one term.  The way you can change that settings in your view is to click on the field that is your term in the Fields section of the view and expand the 'Multiple field settings' which should exist for this field (since it's an input field that accepts multiple values.

In your case, it would be best to select that only the first value is displayed like so:

That should work for you.  You'll see that the content type will still appear under all of its categories if it is tagged with multiple tags, but they won't be grouped in long lists with commas.  :-)

Let us know if this works!


How to create a node out of a webform submission?

The answer from @owenpm3 is great for adding this as an administrative duty.

In order to automate this and make it occur on a successful submission, I would create a custom WebformHandler that you add to your form in the configuration settings, the same way you configure your form to send an email upon a successful submission. So under your web forms Settings tab, under the sub-tab: Emails / Handlers.

To build this you would need to create a custom module, mymodule and place the custom webform handler in: mymodule/src/Plugin/WebformHandler/

I will call the WebformHandler MyWebformHandler.php. Aside from this you will need an info file and that should do it.

Code for MyWebformHandler.php as follows:

<?php

namespace Drupal\mymodule\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create a new Article node from a webform submission.
 *
 * @WebformHandler(
 *   id = "article_from_webform",
 *   label = @Translation("Create a node on submit"),
 *   category = @Translation("Content"),
 *   description = @Translation("Creates a new Article node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MyWebformHandler extends WebformHandlerBase {

  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Get an array of form field values.
    $submission_array = $webform_submission->getData();

    // Dump the $submission_array to acquire the fields if you don't know what fields you're working with.

    // Prepare variables for use in the node.
    $title = $submission_array['subject'];
    $body = "
" . $submission_array['name'] . "
";
    $body .= $submission_array['email'] . "
";
    $body .= $submission_array['message'];

    // Create the node.
    $node = Node::create([
      'type' => 'article',
      'status' => FALSE,
      'title' => $title,

      'body' => [
        'value' => $body,
        'format' => 'basic_html',
      ],

    ]);

    // Save the node.
    $node->save();
  }
}


Get term ID of a field vocabulary in for templating

It sounds like you need to inspect your node.
You can do this with the vital devel module.

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

Once installed it will give you a few new tabs on your node page to see how the node is constructed when it is loaded using node_load($nid) and rendered using node_view($node).

In the node template itself, you will have access to the rendered node as per node_view($node) so anything you see in the devel modules render page you can print out in your node.tpl.php

Devel uses the excellent Krumo library to display PHP objects and array nicely, this is also accessible using dpm($object); however it can not be used in templates, but you can call krumo directly using krumo($node);

So in your node template, call krumo($node); to find the field you want, then once found add it to a variables $tid = $node->taxonomy[LANGUAGE_NONE][0]['tid']; and pass it to you link print l("taxonomy", "view/$tid");


Easy way to get this custom module to work with multiple Nodes (NID's)

Would have been good if you explained what the module does so we don't have to read through the code to understand the module.

I am going to assume you mean the nid condition in the query.

The condition function of the query object defaults to 'IN' if you send it an array.
eg.

$nid = array(4, 5, 6);

and then:

->condition('nid', $nid)

will check nids 4, 5 and 6.
If you want to check all submitted webforms, just remove the nid condition.


how can I get a list of all of the permissions a user has?

Can you try the following snippet:

$user = \Drupal::currentUser();
$user_roles = $user->getRoles();
$roles_permissions = user_role_permissions($user_roles);

This will give you permissions grouped by roles.
But most likely you want them in one array.

Therefore you can use this

$final_array = array();
foreach ($roles_permissions as $role_key => $permissions) {
  foreach ($permissions as $permission) {
    $final_array[] = $permission;
  }
}

In case you want to load different user than the currently logged-in user, you can use

$some_user = \Drupal\user\Entity\User::load(123);

Where 123 stands for the user id.
For more information:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Aload/8.2.x

Best regards,

Oleg


How to automatically generate a table of contents for a list of nodes?

You can make use of the attachment display in Views.

Create your normal view
Add an attachment display to that view:

Set "Attach to" to your normal view display
Configure the attachment display to show titles of your content types nodes.


How can I get the $delta of block created using UI?

If you go to admin/structure/block and mouseover the "configure" link you'll see something like this for blocks added through UI:

/admin/structure/block/manage/block/1/configure

something like this for blocks created with views:

/admin/structure/block/manage/views/81e6b321879efa58ba9e546521c14467/configure

something like this for blocks created with webform:

/admin/structure/block/manage/webform/client-block-50/configure

something like this for blocks created by the system (core):

/admin/structure/block/manage/system/main/configure

I've bolded the deltas and italicized the modules in each example.


using panels to create custom page for all blogs

If you enable the pre-provided page named node_view, it does exactly what you ask for. It loads any (and every) node then.

You can add what's called selection rules to limit to to certain content types, or based on other arbitrary conditions.


How to user listen the songs after purchasing their songs or products using Drupal commerce?

You could probably place a view on the confirmation / download page to link to the mp3 inside html5 audio tags.

<audio controls>
  <source src="mymusic.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

You could make the default view in a block, place it on the confirmation page where the link to download the mp3 is, and get the mp3 file with a contextual filter with a default value of get ID from URL.


You'll want to employ some sort of stemming algorithm for that.

The Porter-Stemmer module is a possible choice:

  This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.


You can use rules module to create a redirect when anonymous user view the /user page.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

You can follow below step:

Go to Administration -> Configuration -> Workflow -> Rules
Click on Add new rule link in top of page
Fill the name and select Drupal is initializing from React on Event drop down in the form and save the form.
click on Add Condition link in the page and select User has role(s) from the "Condition to add" drop-down and select anonymous user as user role and save the form.
Click on Add condition link and select "Data comparison" from the "Condition to add" drop-down and set site:current-page:path as "Data selector" and click on continue button and set 'user' in the value field and save the form.
Click on Add Action link and select Page redirect event and set user/login in the value field and save the form.


How to allow multiple email addresses on webform module?

Are you able to upgrade to the latest version of webform?

On your webform page, click the "webform" tab, and then the "e-mails" tab.
Add a single e-mail address, and click add.
Either click edit, or after adding an email, you should see a settings page. The first label is "E-mail to address".
Make sure the custom field is selected, and enter a comma separated list of emails in this field.


Drupal 7 Views bulk operations based on terms

I use admin_views
to do that and more.

After enabling it, you'll find Views -> Administration: Nodes, Edit that view.

Under Filter criteria you will find a default "(term) Taxonomy term: Vocabulary (exposed)".
Add your "(term) Taxonomy term: Name (exposed)" and use the other as referene to get your settings correct.

Pending on how many terms you have, this dropdown can get messy, so you could refine your filter settings to only show some terms in the filter.


What is the reason for you adding the form in that manner and having custom validation etc. when drupal already gives you this?

For example, why not just use the drupal block system or the context module to place the login block on your homepage within one of the regions?

Another thing is that your custom module should not have

function hook_form_alter(&$form, &$form_state, $form_id)

it should be

function MODULE_NAME_form_alter(&$form, &$form_state, $form_id)

Where you replace MODULE_NAME with your module's name.
Although maybe you only had it that way for this post.

Also, regardless of the method you use to show the user_login_block form, it already has its own validation functions that come with it. It already has these three validation functions:
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_name_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_authenticate_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_final_validate/7

With the last of those doing (among other things) essentially the same validation your custom function is trying to do.

You can still use the form alter to add your attributes and change titles, etc.
In this case though the module weight does not matter.
It only matters if two modules are both using hook_form_alter() and are changing the same parts of the form.


It looks like it's expecting a string, but your code is returning an array.

Try changing your code to the following:

if (arg(0) == 'user' && is_numeric(arg(1))) {
  return arg(1);
}

That should return the string value rather than returning [0] => uid.


how to use an entity query to make a sortable table

EntityQuery doesn't appear to have the extend() function that this example relies on, so much of what's happening in the example will need to be done manually.

You can get the sort parameters from the request object

$sort_field = \Drupal::request()->query->get('order');
$sort_order = \Drupal::request()->query->get('sort');

With those, you can update your query to something like.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'blog_post')
  ->sort($sort_field, $sort_direction);
$nids = $query->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

Then use $nodes to build your $rows array as in the example.


Can I get a upload progress bar when submitting the form with "submit"?

Is this just "how it works"? - Yes, it's just how it works. This is a problem with HTTP protocol, if your site does not provide client-side implementation for that progress bar, it will not be shown. And Drupal forms are standard HTML / HTTP POST forms, so no implementation provided for traditional, old style POST.

What I do in such situations is:

With plupload

uploader.bind('QueueChanged', function() {

to automatically start upload and disable form's submitting. Then

uploader.bind('StateChanged', function() {

to reenable form's submitting once upload is done.

Without plupload

AutoUpload module has some good example code how to react on file selection and upload finish. I steal from it to do basically the same thing as above - disable form submitting when new file is added, enable it when it's uploaded. Alternatively, form submit behavior may start uploading files not yet uploaded, and only submit form when uploads finished.

Without traditional POST

If you can give up traditional submit, and re-write it with AJAX, leaving traditional way in place for graceful degradation, you can have a progress bar for a whole form. But it is a quite big task, too broad to cover in Q&A format (at least for me).


I resolved this by first re-enabling the PDF module, and then by updating core.

In my composer setup, the PDF module was a git submodule.  However, my shared host would not work with that.  So, I removed the cached information

git rm --cached web/modules/contrib/pdf

And then I added the code in that directory to my main repo.

Next, enable the PDF module.

Finally, proceed with the update process, and run update.php or drush updb


how to alter main menu to add custom class

I can't tell you how this works programatically, but with menu-position module you can achieve exactly what you're looking for. You'll just add a position-rule for your node-types (or taxonomy item used) to highlight a parent item accordingly.


How to translate custom fields in taxonomy terms?

If you use 'Localize' option for taxonomy translation mode, it is possible to add taxonomy custom fields to string translation:

/**
 * Implements hook_i18n_string_list_TEXTGROUP_alter().
 */
function YOUR_MODULE_i18n_string_list_taxonomy_alter(&$strings, $type, $object) {
  if ($type == 'taxonomy_term' && $object) {
    if (isset($object->FIELD_NAME)) {
      $term_FIELD_NAME = field_get_items('taxonomy_term', $object, 'FIELD_NAME');
      $strings['taxonomy']['term'][$object->tid]['FIELD_NAME']['string'] = $term_FIELD_NAME[0]['value'];
    }
  }
}

After clearing cache the field will be available in translation form.


How to make my Drupal custome Service return data on GET?

The short answer is you can't, unfortunately (AFAIK). For all non action resources, the Services module assumes that they are part of the entity C.R.U.D. spectrum, and then decides what to do based on the HTTP method. For example:

POST = Create
GET = Retrieve
PUT = Update
DELETE = Delete

So unless you're building an entity C.R.U.D. layer, you'll have to use POST on the actions array. Alternatively you could use hook_menu() to make your own custom page_callback that outputs JSON, then it could be accessed over GET. Another alternative is to use something like Views Datasource and compose a Views JSON to output your data (also available via GET).


How to hide the inside page for anonymous user?

Go to your view. and set Role permissions like follows

Click on Permissions

Select Role

Check all roles except anonymous user.


Find out which theme is loaded in a given page

In Drupal 8, you can do two things from custom code:

\Drupal::theme()->getActiveTheme();

\Drupal::theme()->getActiveTheme()->getName();

The first will return a theme object, the second will return just the theme name.

See the ThemeManager docs for more details.

You can also install Devel/WebProfiler for more information about the current page request and other variables.


How to get a list/array of all content entities?

This is what you need:

use Drupal\Core\Entity\ContentEntityType;

$content_entity_types = [];
$entity_type_definations = \Drupal::entityTypeManager()->getDefinitions();
/* @var $definition EntityTypeInterface */
foreach ($entity_type_definations as $definition) {
  if ($definition instanceof ContentEntityType) {
    $content_entity_types[] = $definition;
  }
}

But a better approach would be to get the field first and then the bundles which has this field. For example, we are looking for the "field_image" in "node" typed entities:

   use Drupal\field\FieldStorageConfig;

   $field_image = FieldStorageConfig::load('node.field_image')
   $bundles = $field_image->getBundles();


Create a directory under the sites directory besides default with the exact name as your domain and place the settings.php file in it. You can delete the default/settings.php after this.


Why is the apostrophe converted to ' in account activation e-mail?

The easiest way to fix this is simply set the formatter to the Default PHP Mailer, if you want to stick to plain text mail.

This is a known bug in the SwiftMailer module where Html::escape is called, even for plain text. Bug report here: https://www.drupal.org/project/swiftmailer/issues/2937293 .

The Html::escape function declares:

  /*
   * This method escapes HTML for sanitization purposes by replacing the
   * following special characters with their HTML entity equivalents:
   * - & (ampersand) becomes &amp;
   * - " (double quote) becomes &quot;
   * - ' (single quote) becomes &#039;
   * - < (less than) becomes &lt;
   * - > (greater than) becomes &gt;
   */

And that's where your &#039; comes from.


File uploads: Warning: session_start(): Cannot send session cookie - headers already sent

I'm also getting the exact same issue on a Pantheon hosted site. This is on a more complex content type (number of fields) with the image field using the multiupload_imagefield_widget module so we can upload multiple images. The error can also appear on removing an image, where the image field is updated via AJAX. Occasionally, a WSOD will occur.

Location or Path always relates to files/styles/....

Tried to duplicate this on a basic content type but it was not occurring. The issue appears on the main content type 80% of the time.


The simplest way is using format_string(), you can have 3 kind of replacement token for different sanitisation and formatting.

  @variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.

  %variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.

  !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

Example code:

$message = variable_get_value('variable_name');
$message = format_string($message, array('@yourcompany' => $company_name));


Use Views field output as a class? Tokens?

If you're looking to use it as a class for the whole row rather than just for the field, use a views template.

The Advanced -> OTHER -> Theme: Information section of your view usually has good ideas on what to call files but it doesn't seem to include anything for the row.

If you're using row style: fields... try making a template file called views-view-fields--myviewname.tpl.php.

To dig into the variables available to that template file, the first thing you want to do is install the Devel module, turn it on, and put this in the template:

dpm($content);

or maybe

dpm($output);

dpm() prints the named variable on the screen when the file is run.


The vertical tabs don't show when is one vocabulary

It's the setting for "Minimum number of tabified fieldsets to show vertical tabs:" found at: /admin/settings/vertical-tabs

It's defaulted to 3, which means you must have 3 vocabs on the node type for it to put them in a tab... you can change the minimum value.


In the settings for payments, what is the meaning of "Test transactions in a live account"?

The language used varies by payment gateway, but they almost all include some sort of development environment that is completely separate from the production environment. Some will also permit test transactions in the production environment itself by letting you turn on test mode and use a test credit card number that passes the "Luhn algorithm" used to validate card numbers but is not a real number.
As this varies by payment gateway, you're going to have to consult the payment gateway's documentation. In Drupal Commerce itself, how you configure this differs between Commerce 1.x and Commerce 2.x. Make sure you're viewing module documentation that matches the version of Commerce you're running.


Why does not the preview of the loaded image appear?

do you have access to the nginx configuration for this website? If so, you can add the following to the configuration and see what happens. It might set already to 1m:

http {
    #...
    client_max_body_size 10m;
    #...
}


Create a view with a list of webform without any submission by current user

I'm not sure if there is a solution to create such kind of view using the Views module. But the Forena module (disclosure: I'm a co-maintainer) can be used for this type of reporting. More specifically by using its facility to create a Display of a table in crosstab format.

A crosstab table is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

Below is a sample of such crosstab report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

Specific to your question here, I'd create such table in crosstab format with rows/columns like so:

The rows should represent your users (1 row for each user).
The columns should represent your webforms (1 column for each webform).

With such setup, the answer to your question is then contained in the intersections of all rows and columns that are shown as "blank" (= zero submissions of the specific webform by the specific user).

PS: I'm assuming you're using D7 ...


Just to be sure the install is all good, try

sudo apt-get install --reinstall php5-gd php5-mysql

Also, make sure you don't have any odd php.ini file in your drupal root.


Views - getting Title field from other content types via entity reference

You should choose the one that says "Content: Title". In the next page you can choose the relationship you want this field's value to come from, i.e. your entity reference field.

e.g.


HI please follow the below steps.

Step 1: create routing
docroot\modules\custom\product\product.routing.yml

product.custom_form:
  path: '/product/details/{product}'
  defaults:
    _controller: '\Drupal\product\Controller\ProductDetailsController::details'
    _title: 'Product Details'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      product:
        type: entity:node

Step 2: create controller ProductDetailsController.php

docroot\modules\custom\product\src\Controller\ProductDetailsController.php

/**
   * Callback for route product.custom_form.
   */
  public function details($product)

return [
  '#theme' => 'product-details',
  '#content' => [
    '#contextual_links' => [
      'node' => [
        'route_parameters' => ['node' => $product->id()],
      ],
    ],
  ],
  '#product' => $product,

];

}

Step 3:

In theme
create file product-details.html.twig

docroot\themes\custom\mytheme\templates\product-details.html.twig

Sample code of above twig file:

        {{ product.title.value }}
        {{ title_suffix }}

            {% if product.field_title_description %}
                {{ product.field_title_description.value }}
            {% endif %}


Programmatically override permissions in Drupal 6

There is a way to override programmatically drupal's permissions defined in admin/user/permission. Example:

<?php

function set_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  $permissions[$permission] = true;
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}

function unset_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  unset($permissions[$permission]);
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO permission (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}


How to delete old images uploaded via FAPI

Its always the way! You spend an hour fussing over it, but when you actually write the question down, you think of it in a different way!

Its a bit long winded, but my complete example is this...

 function MYMODULE_admin() {
      $form = array();
      $form['style']['business_logo_fid'] = array(
        '#title' => t('Business Logo'),
        '#type' => 'managed_file',
        '#description' => t('Upload a logo for your business in one of the following formats: jpg png jpeg.'),
        '#default_value' => variable_get('business_logo_fid', ''),
        '#upload_validators' => array(
        'file_validate_extensions' => array('jpg png jpeg'),
        ),
        '#upload_location' => 'public://',
      );

      $form = system_settings_form($form);
      $form['#submit'][] = 'after_save_ui';
      return $form;
    }

    function after_save_ui($form, &$form_state) {

        // Save the Business Logo Permenantly.
if (isset($form_state['values']['business_logo_fid'])) {
        $new_logo_id = $form_state['values']['business_logo_fid'];
        $old_logo_id = $form_state['complete form']['style']['business_logo_fid']['#default_value'];
          if (($old_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $business_logo_file = file_load($old_logo_id);
            if (!empty($business_logo_file)) {
              file_usage_delete($business_logo_file, 'webfroth_booking_ui', 'business', $business_logo_id);
              file_delete($business_logo_file, TRUE);
              drupal_set_message(t('Old Logo Removed.'));
            }
          }
          if (($new_logo_id != 0) && ($new_logo_id != $old_logo_id)){
            $current_business_logo = file_load($new_logo_id);
            if (!empty($current_business_logo->fid)) {
              $business_logo_file_id = $current_business_logo->fid;
              variable_set('business_logo_fid', $business_logo_file_id);
              file_usage_add($current_business_logo, 'webfroth_booking_ui', 'business', $business_logo_file_id);
              $current_business_logo->status = FILE_STATUS_PERMANENT;
              file_save($current_business_logo);
              drupal_set_message("New Logo Uploaded Successfully.");
            }
          }
        }
    }

This works great, but it CANT be the standard way to handle this everytime I want to use an image field in a custom module surely? Seems like a massive hassle!


Add multi-level taxonomy term selection field with multiple selection for last level

Have a look at Taxonomy Term Reference Tree Widget module. This does exactly what you need as per its documentation.

Edit: Since now I bettter understand your requirement, you might want to try Hierarchical Select.


Contextual Filter (Author's Username) Multiple usernames

You have to have the "Allow multiple values" option of the contextual filter set (it is in the "MORE" collapsible fieldset).

Then you have to separate the names with a plus symbol (+) or a comma (,).

If you separate with a slash views will treat it as 2 separate arguments and your view only has one argument.


Views Arguments formatted nicely for the title

Restore your view so that the query works. Then, make sure the PHP Filter module is enabled and that you have permissions to use it.

In the view, add this header:

<?php
$view = views_get_current_view();
$my_title = ucwords(str_replace("-", " ", $view->args[0]));
drupal_set_title($my_title);
?>

Make sure the input format for the header is PHP.

The view's preview will show the wrong title. That's ok. When you navigate to the page, you'll see that the title is as you want it.