What's the difference between the components ending in .system and .module in the Bug tracking system?

You're reading things slightly wrong.

There's no file.system component, or any other component ending with .system.

There are systems:

ajax system
batch system
file system
etc...

These are for issues pertaining to parts of Drupal that are not located in a module. Anything in the /includes folder of a normal Drupal installation, basically. (ajax.inc, batch.inc, file.inc for the examples above)

Then there are modules:

blog.module
file.module
menu.module
etc...

These are for module-specific issues.


If you want to Force download PDF files.
if your server is Apache

put this line in your .htaccess file.

AddType application/octet-stream .pdf

If there is any issues with browser try this

SetEnvIf Request_URI "\.pdf$" requested_pdf=pdf
Header add Content-Disposition "attachment" env=requested_pdf

If its NGINX

location ~* /orig/(.+\.jpg)$ {
    internal;
    add_header Content-disposition "attachment; filename=$1";
}


I am not sure if this is The Drupal Way to fix this, but I fixed it with jQuery hide() and show().

// Hide the Name Column when Nick Name is shown
$('#edit-dyfield-field-girls-nickname').change(function() {
                if ($('#edit-dyfield-field-girls-nickname').is(':checked')) {
                    $(document).ajaxStop(function() { // Forcefully stopping Ajax function in the page as other ajax load was main culprit in my case
                        $('.views-field-title').hide();
                    });
                }

                if ($('#edit-dyfield-field-girls-nickname').is(':not(:checked)')) {
                    $(document).ajaxStop(function() {
                        $('.views-field-title').show();
                    });
                }

            });

Note: In the above example jQuery toggle() doesn't work, so, I have to put 2 if(){} statements for Check and UnCheck.


for anonymous user, webform not submitted because of private file

First and foremost, you've got an error in how you set up your private files path. It should be located outside of your web root, not as a subfolder of your public files. The way it is now, your private files are actually public. That is the reason why you can acces the file at '/sites/default/files/private/webform/abc.jpg', you shouldn't be able to do that.

Now as to why you get an error uploading it is probably an issue with how your permissions are configured for private files. The anonymous user can upload to the private files, but does not have sufficient permissions to access the uploaded file.


How to call AJAX on check-box of form API?

Try This, may be helpful for you

$form['checkbox'] = array(
    '#title' => 'Select',
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('Orange'), t('Apple'))),
    '#ajax' => array(
      'callback' => 'fruits_callback_form',
      'wrapper' => 'fruit-check',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  $checkbox = !empty($form_state['values']['checkbox']) ? $form_state['values']['checkbox'] : 0;
  $form['slots']['#prefix'] = '
';
  if ($checkbox == 'Orange') {
    $color = array(0 => t('Red'), 1 => t('Blue'));
  }
  $form['color'] = array(
    '#type' => 'radios',
    '#title' => t('Select Color'),
    '#options' => $color,
  );
  $form['slots']['#suffix'] = '
';

  //Callback function

  function fruits_callback_form($form, &$form_state) {
    return $form['color'];
  }


How to propely add views grouped filters with exposed filter in one of them

I am still waiting for a response to do this more elegantly but since I am in a hurry I wrote a query alter to accomplish what I need. Maybe it's helpful to someone

function custom_views_query_alter(&$view, &$query) {
  if ($view->name == 'ts_group_events' && $view->current_display == 'calendar') {
    if (empty($query->where[2]['conditions'])) {
      foreach ($query->where[1]['conditions'] as &$condition) {
        if ($condition['field'] == 'node.type' && $key = array_search('birthday_event', $condition['value'])) {
          unset($condition['value'][$key]);
        }
      }
      $query->where[2]['conditions'][] = array(
        'field' => 'node.status',
        'value' => 1,
        'operator' => '='
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'node.type',
        'value' => array('birthday_event'),
        'operator' => 'in'
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'og_membership.gid',
        'value' => NULL,
        'operator' => 'IS NULL'
      );
    }
  }
}


Form states with "and" and "or" conditions

You can use or/xor in form states. For and, continuation of the conditions is enough. For example your code the condition can be written as:

'#states' => array(
  'visible' => array(
    array(':input[name="question_inhabitant_type"]' => array('value' => 'owner')),
    array(
      array(':input[name="question_building_type"]' => array('value' => 'house100')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house150')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house200')),
    ),
  ),
),

Note: jQuery 1.7 doesn't support OR/XOR's for #states. So, make sure you have latest jQuery version on you site (>1.7).

Unfortunately the above code didn't worked as expected. Please help through your comments to correct it. Also meanwhile you can try this code:

'#states' => array(
  'visible' => array(
    ':input[name="question_inhabitant_type"]' => array('value' => 'owner'),
    ':input[name="question_building_type"]' => array(
      array('value' => 'house100'),
      array('value' => 'house150'),
      array('value' => 'house200'),
    ),
  ),
),


The Revisioning-module is exactly what you are looking for. It keeps revisions of every change and offers you the possibility to moderate the content.
I use it for a few project and I'm very happy with the results!


If you want to add a style to a particular element in CSS, you should use the ID of the element rather than the class as IDs are unique.

e.g

#edit-circle {
}


View won't render any content/teaser, only shows fields

check if this view did not get somehow to disabled list... go views list it's divided into Enabled and Disabled lists check there...


Do non-enabled modules affect performance?

Generally no it will not affect performance - except for when you are viewing your Modules selection page (admin/build/modules or admin/modules). Disabled modules are not loaded into memory and never executed.


How to theme one specific Views 3 exposed filter form template and HTML?

For the .tpl file

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

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

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

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

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

For template.php

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

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

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

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

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


Views exposed filter: Upcoming/Past events

Add a date filter.

Expose the date filter.

Select the grouped filters option

Scroll down and define your filters as shown in next image

And you are good to go. You will have an output like this

You can change the options to make it a drop-down too.

To fix for the UI bug in exposed filters groups:

Make sure your date module is at Version: 7.x-2.9 or later, then apply the patch exposed_grouped_filter-1876168-71.patch (https://www.drupal.org/node/1876168#comment-10344663)


Difference between field form hooks for settings

Let me explain to you briefly what each of them does. Basically a field has two prime components, one is widget and the other is formatter. The widget is the input part( like checkbox, select list, textfield). This helps field to grab data from the user. The other one is formatter. Formatters are responsible for how output is rendered by that field.

Now regarding the hooks you mentioned:

I will try and help you visualise these by comparing to the steps which you encounter while creating a field.

hook_field_settings_form - this is the global settings form, the first page which you encounter when you create a field.
hook_field_instance_settings_form - this the instance level field settings form, usually same options as global settings form but applicable to each instance.
hook_field_widget_settings_form - This is the settings form for the widget, which i have already described above.
hook_field_formatter_settings_form - This is the settings form for the formatter. This exposes options that will be used to render the value of the field.

Observe closely the forms and steps that come up while you create a field through UI in Drupal and you will gain more insights on these components. hope that helps.


Field with '#type' = 'hidden' in hook form alter doesn't show #id in the source and it's not possible to show it with jQuery

You've converted the element to a hidden input type.

Hidden inputs cannot be rendered, as the name suggests (they're hidden by their nature). So trying to use javascript to "show" them will never have any effect - there's nothing to show.

Add that to the fact that a changed hidden input element will invoke a validation failure for a tainted form, and it should be easy to see why the Drupal devs didn't bother to add an HTML ID to the element. Trying to access it with CSS/JS makes very little sense most of the time.

If you just meant to hide the original input, not convert it to a different input type, just use CSS to hide/show it as normal.


Custom node template based on field condition

You can actually do that in the preprocess node function something like this:

function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  if($node->field_solo[0]['value'] == 1)
  {
       $vars['theme_hook_suggestions'][] = 'node__theme1';
  } else
  {
       $vars['theme_hook_suggestions'][] = 'node__theme2';
  }

}

Here if the condition is true then the node template would be node--theme1.tpl.php

and if the condition is false then the tpl would be node--theme2.tpl.php.


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

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

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


How to get date values from field collection to a node?

I suppose that field_course_starts_on and field_course_starts_on are fields that represent date and you want to print it as date. Correct me if I'm wrong.

So you can print those fields as date like:

print date('d F, Y', $item->field_course_starts_on['und'][0]['safe_value']);
print date('d F, Y', $item->field_course_ends_on['und'][0]['safe_value']);

The part 'd F, Y' is a date format. Take a look at PHP Documentation to see all options for format parameter.

Update

First you have to load the ids of the field collection fields of the node:

$formtype = field_get_items('node', $node, 'field_latest_schedules');

// Extract the field collection item ids
$ids = array_column($formtype, 'value');
foreach ($formtype as $ft_field) {
    $ids[] = $ft_field['value'];
}

To iterate over all fields you can use the following code:

//Get the entities
$collections = field_collection_item_load_multiple($ids);

//Loop over the array - if you have more than one entity
for ($i = 1; $i <= sizeof($collections); $i++) {
    $collection = $collections [$i];

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (isset($value['und']) && is_array($value ['und']) && isset($value['und'][0]['value'])) {
                print "Field ".$key." ".$value['und'][0]['value'];
            }
        }
    }
}

And than debug, target wanted fields and print those fields' values.


I recently answered a question similar to this over at stack.

Basically, you should be doing all the form building and manipulation in the form builder function. The ajax callback function in your case should just return the form element.

This is because when the ajax is fired, just before the ajax callback function is executed, the form is rebuilt and the form building function is executed again (this time with a different form_state which will include the ajax elements current state)(I think).

So you would have something similar to:

$form['module']['cities'] = array(
    '#type' => 'radios',
    '#title' => t('City'),
    '#ajax' => array(
        'event' => 'change',
        'wrapper' => 'sector-wrapper',
        'callback' => 'module_field_city_change_ajax_callback',
        'method' => 'replace',
    ),
    '#options' => array("1" => "New York", "2" => "Moscow"),
    '#required' => TRUE,
);

  // Check if a city is selected and set sectors
  //something like this.

  // $sectors = array("Sport"=>"Sport", "Media"=>"Media");
  // if(city is selected){
  //   $sectors = array ('Aerospace' => 'Aerospace', 'Art' => 'Art' );
  // }

  // you should be able to check if a vocabulary is selected by checking the
  // $form_state['values'] or $form_state['input'] (I forget which)

$form['module']['sectors'] = array(
    '#type' => 'radios',
    '#title' => t('Sectors'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => $sectors,
    '#required' => TRUE,
);

ajax callback

function module_field_city_change_ajax_callback($form, $form_state){
    return $form['module']['sectors'];
)


Can I set a CSS-class on the node in a view list based on a text field of the node?

/**
 * Implements hook_preprocess_html().
 */
function themename_preprocess_html(&$variables) {
$node = load_your_node// Load you node here and add proper condition and type for following code
    $variables['attributes']['class'][] = 'page-node-' . $node->custom_textfield();
}


I eventually got the site working by disabling caching. But better approach to this problem is, creating the site on your local instance first.
You need to create and install Drupal on your local system. If you install it directly on Heroku, it creates some temporary file on Heroku, which Heroku discards after every dyno restart. Even settings.php loses all the changes made to it(during installation) after dyno restart. (I installed my site directly on Heroku, so I got through this issue by adding changes to settings.php manually)
Once you create the Drupal site on your local instance (using the GUI), you will have some files in sites/default/files, as well as some changes in settings.php (hash salt, database setting etc). Now, you can track all these files and push it to Heroku.
The site should work fine, except you won't be able to store any public files, you will need S3 bucket for that.
Hope this helps who encountered similar issue!


You can do this in two ways,

Using the module Similar By Terms
Using views, Read more here


You can try Views Fluid Grid module

This module provides the Fluid Grid style plugin for Views. This plugin displays the view as a fluid grid using an HTML list element.

  The plugin settings form provides options to define the width and
  height of the elements in the grid. But it also provides advanced
  layout options implemented in separate CSS classes that allow you to
  define item margins, alignment and a couple of CSS3 properties
  (box-shadow and border-radius).


Help me with my page, when open this page shows me this:

Not a drupal question, but you need to repair your table in the MYSQL database, if you can access the db server via command line:

REPAIR TABLE <table name>;

Otherwise, tools like phpmyadmin have repair tools, check this tutorial: http://www.siteground.com/tutorials/phpmyadmin/phpmyadmin_optimize_database.htm


user-profile-edit.tpl.php not working for user#1

It seems that your themes are different for your users because the template name is fine.
It will work fine with the theme in which you have added the template.


How to compute fields from different content types and then show the result in Views table

Ya definitely,

Include those fields in views, Take another field Global: Custom text OR Global: Math expression and that's field setting text or expression, use previous field value as a token as per your formula. Make sure this field will be below the all other field that you will use in formula. You may exclude the fields that you use in formula if not want to display.


how can I hide ShareThis icons from teasers

Go to content type's manage display section and select Teaser tab on top right. There you can change the display settings of the teaser.


Making a username/password syncronization scheme - D7

When a form is submitted, its values are validated by the functions listed in $form['#validate'] then processed by the functions in $form['#submit']. If there is no $form['#validate'], then the function FORM_NAME_validate will run (if any). Same for submit.

See user_register_submit. The plain text password is in $form_state['values']['pass']. Write a hook_form_alter and add a new submit function to $form['#submit']. Declare that function and put the logic you need in it.


Can't get Ajax data sent to my PHP function

Check your URL again...  should it have /site/ ?   I am guessing not, unless you have something going on it should be:   http://localhost:8080/api/feedback

url: '/api/feedback',


how to rename password label on user edit page in Drupal?

If you're willing to do it in a module (you mentioned String Overrides module) you can easily do it with a simple hook_form_alter() in a small custom module.

function mymodule_form_user_edit_form_alter($form, &$form_state) {
  $form['desired_element']['#label'] = t('My label');
  return $form;
}

This method uses hook_form_FORM_ID_alter(). This way you'll be able to set individual labels as you see fit, though.


Storage of the images in Drupal-Commons 6.25: serious troubles acompanied with CHMOD & CHOWN-issues

setuid and setgid are for execution and not access control.

I can't comment on your exact problem, but when I move a site, I do

sudo find /path/to/site/default/files -type d -exec chmod 755 {} \;
sudo find /path/to/site/default/files -type f -exec chmod 644 {} \;
sudo find /path/to/private -type d -exec chmod 755 {} \;
sudo find /path/to/private -type f -exec chmod 644 {} \;
sudo chown -R apache.apache /path/to/docroot/site/default/files
sudo chown -R apache.apache /path/to/private

By default, files are in site/default/files but this location can vary for a few reasons

Admin setting for public files
Admin setting for private files
Whether the files use public or private
Whether you use the default location, or a site alias

and probably some others I can't think of.  I suspect that your write errors will show up in your Apache error_log and you should also see what the status report (admin/reports/status) says.

Note that the private paths/settings are for Drupal 7 only, but the rest applies.


How do I create an AND filter for the same field

By default, drupal filters with AND. Maybe you clicked the rearrange and/or option by mistake intsead of just adding a new filter. Try removing both and creating again by clicking add.


How to change the default date format in Rules?

Try to use what you have defined as the format for short / medium / long format in your Drupal date settings, using either of these tokens:

[commerce-order:field_delivery_date:value:short]
[commerce-order:field_delivery_date:value:medium]
[commerce-order:field_delivery_date:value:long]

However, since your date seems to be a data range, you may have to enable the Entity API module and its "Entity tokens" sub-module to access the date values.

Also, be aware that Entity tokens replaces underscores  (= "_") in the tokens names by dashes (= "-"), so in your case "field_delivery_date" becomes "field-delivery-date". And with that, this is how it should look like:

[commerce-order:field-delivery-date:value:short]
[commerce-order:field-delivery-date:value:medium]
[commerce-order:field-delivery-date:value:long]


Upload multiple files (with multiple attr) in custom form: how to get files?

I haven't tried HTML5 Upload yet, but it might help you out.


Yes, you can test it against any Active Directory you can connect to.

But if you want a local copy of active directory, you can install a local copy of Active Directory Lightweight Directory Services (AD LDS) for Windows7 or equivalent.

Once installed, you will also need to configure to work with drupal's ldap module as normal. Then you will be able to work locally.

I have done this using XAMPP on a windows laptop.


How do I use Path Matcher for front page?

Your code is assuming that the request URI for / will retrieve /node on the getAliasByPath() method call. It won't. Setting the Drupal front page isn't the same as setting a path alias in the Path module.

Use the following code, which will return Drupal's internal /node path even on / requests.

$current_path = \Drupal::service('path.current')->getPath();


How do you display all the tpl.php template files that are being loaded on the current page?

the only thing that comes to mind is to uncomment $conf['theme_debug'] = TRUE; in setting.php. The description for this setting pasted below.

  Theme debugging:
  When debugging is enabled:
  -- The markup of each template is surrounded by HTML comments that contain   theming information, such as template file name suggestions.

  -- Note that this debugging markup will cause automated tests that directly check rendered HTML to fail.    For more information about
  debugging theme templates, see
  https://www.drupal.org/node/223440#theme-debug.

  Not recommended in production environments.

If anyone knows of a better way - please share.


How to set different languages for different domains, and display the language switcher accordingly?

A complete summary of the multilingual system for Drupal 7 can be found here: Drupal 7's new multilingual systems compilation. Specific to your question of "...some domains to have different languages", setting / detecting the language by domain can be setup in http://YOURSITE.com/#overlay=admin/config/regional/language/configure -> Detection and selection tab after the Locale module has been enabled. Details on the Detection and selection tab.

Notice that new to Druapl 7 this is now a weighted list that is processed to determine what method to use for the display language. The higher in the list the more likely that the method will be used.

In the case of you situation I suspect you'll have to write your own language selector to add to this list. I have to confess that the situation you describe sounds like it could better be solved in configuration that in code. Perhaps consider add the language into the domain in addition to the country - for example ca.example.com could be French: fr.ca.example.com and English: en.ca.example.com.


To force SSL for login, admin, node editing etc, I use http://drupal.org/project/securepages - also has has configuration options to force plain HTTP when browsing the site as well (which can save you load).


I managed to figure out that this is how you have to put an additional callback into the entityform submit function, hopefully this will help someone out in the future

$form['actions']['submit']['#submit'] = array(
  'entityform_edit_form_submit',
  'mymodule_notifty_review',
);


Views display settings are in the database but don't show up in views UI

FWIW - you might want to install drush and use the drush archive-dump command which will extract your entire site (database, drupal instance and files) into a single tarball file.  You can then use drush archive-restore to import that site into a different site on the same or different machine.

There are other ways, of course, but this seems to be one of the easiest as there is nothing to remember or think about other than doing it.

Good luck - B


When editing the view, under Basic Settings -> Style -> Settings (the "gear" icon) you can choose to group the results by a certain field. Hope this helps.


Install profile that automatically inserts data / config settings

You might find drush-make useful, especially if you already have a codebase setup that you would like to replicate.  As outlined in this blog post:

  Drush Make includes 2 commands which are already built in Drush
  itself:

  make — Turns a .makefile into a Drupal codebase.
  make-generate — Generates a .makefile from the current Drupal site.

  Both commands are related to a .makefile — flat text file with Drush
  Make instructions. You can read more about .makefile syntax here.


How do i ajaxify /Use ajax on Side bar custom menues so that links are loaded to my content div without refreshing page

You can use ajax_pages module.

  Features

  Works inobtrusively out of the box
  Requires only minimal theme modifications
  Browser address bar updating using HTML5's history.pushState()
  Full page reloading (page_top, page and page_bottom regions)
  Transparently ajaxifies forms, including GET ones Handles redirects
  Loads additional CSS and JS files as required
  JS/CSS preprocessors and aggregation friendly
  Ajax requests are GET and fully cacheable (also with Boost!)


How do I force rebuilding/generation of files generated by an imagecache preset?

Imagecache images are generated on the fly when a browser requests them, rather than when you create the preset or flush the images.

Basically, this is how the process works.

When a URL 404s, the request gets punted to /index.php and handled by Drupal.

The imagecache module has a hook_menu() entry that handles all of the requests to sites/default/files/imagecache (or whatever file_directory_path() returns for your site).

The callback for this checks for the requested filename.  If the file exists (ie, the derivative has been generated and exists in the filesystem), it gets served up.  Otherwise, the module makes the derivative, saves it to the filesystem, and then serves it up.

So, the net result is that you don't need to explicitly generate the derivatives.  When a page that has them on it is requested, they will be automacically generated.

If you would like to pre-generete them for performance reasons, then my suggestion would be to write a bash script to find all of the images in your sites/default/files directory, and then wget them with the proper imagecache preset path name.

If you are looking at a page and the thumbnails aren't being shown, then you have another problem.  Checking the system report would be the first place to check.  Typically, the webserver can't write to the filesystem or your image toolkit is messed up.


For $vars['id'] == 1 render field Y instead of field X

Ok so the way I achieved this was to go into my node--content_type.tpl.php file and do a simple check for 'feature' in the classes string. Printing the correct image depending on the outcome of the check.

So first in admin I set both header and thumbnail images to display when showing as a teaser. But then in the template file I began by hiding them:

hide($content['field_blog_thumbnail_image']);
hide($content['field_blog_header_image']);

This means that they don't render with print render($content);

In the place where I wanted to display the image I then used simple logic to check the $classes variable to see if the string contained 'feature'. If it did I render the header image, if not, the thumbnail image:

if(strpos($classes,'feature')==true){
    print render($content['field_blog_header_image']);
} else{
    print render($content['field_blog_thumbnail_image']);
}


How to get php error logging working properly in a production site

Just to be sure that you are in the right path...

PHP.net says that:

  Note:

  Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

Also check http://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors and http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log


$base_url not working when in anchor link to theme folder

Try this...

In your themes template...

function YOURTHEME_preprocess_page(&$variables) {
   global $base_url;
   $variables['base_url'] = $base_url;
}

In page template...

$base_url;


I might be misunderstanding you but I think you just want a foreach loop:

foreach ($data as $item) {
  $answers[] = $item["value"][0];
}

Or even shorter:

$answers = array_map(function($item) { return $item['value'][0]; }, $data);


How to set up APC on Drupal 7 with httpd + fastcgi?

We finally managed to set this up properly.

Apc works fine for multiple processes with apache/2 + php 5.3.x + php-fpm + fcgi in FPM/FastCGI mode.

PHP 5.3.x is configured with following options
--enable-force-cgi-redirect
--enable-fastcgi
--enable-fpm


Implementing Area 51 with Acquia Commons?

Here's a simple solution:

Create a content type, say 'proposal', that any user can add for the petition group (with title as group name and body for reason).
Users can comment on nodes of that type so they can discuss the proposal.
Create a view to show nodes of type 'propsal' and enable filtering, sorting etc.
Use the Votingapi module and one of the voting widgets (like vote up/down) to allow people to vote on the node.

For the creation of the groups, you can either:

Do it manually, monitoring when a proposal gets a specified number of votes.
Use the Rules module to do it automatically.


want to create custom rule for like post or comment?

You can use flag module.

  Def: Flag is a flexible flagging system that is completely
  customizable by the administrator. Using this module, the site
  administrator can provide any number of flags for nodes, comments,
  users, and any other type of entity.

Once you install the module, its very simple. Goto structure->flag->add new flag. Give title for the flag and use the count option to display the like-count.

In my example, 'Node Like' is the title of the flag, the flag count can be achieved in token

[node:flag-node-like-count]

To answer your question, its possible but complex to achieve just using rules.


Make a new flat rate shipping quote called 'No shipping' with zero cost. Then in the Delivery method pane at checkout the user can choose between your shipping option and your no shipping option.

You make shipping quotes at /admin/store/settings/quotes specifically the 'Add flat rate quote' link /admin/store/settings/quotes/methods/flatrate/add

Obviously you need both the ubercart shipping quotes module and ubercart fulfilment flat rate module enabled.


Well I answered my own question eventually.  The issue was the format for saving to this particular type of field 'file'.   I changed

$node->field_file_upload[$node->language][0]['value']=(array)$file_object;

to

$node->field_file_upload[0]['fid']=$file_object->fid;

For some reason the formatting that was given in other answers was not functional for me.  The file field type seems to be very particular about it's format, but it only NEEDS, the fid.  Once the node is loaded the full file array is loaded.

To answer longboardnode what I wanted was the array of data about the file that is stored when the file is uploaded.  Unfortunately node fields seem very picky about formatting.


Drupal 7 prepopulate form values for embedded field collection

you can use the MODULENAME_form_alter hook to achieve this, by iterating through its nested array, maybe this can help

If this help, awesome, ping me if not, I can share some snippets that achieve that :)


"Search Setting" missing from 'Search And MetaData' section on configuration page

I found the answer out.
I thought that the "Search Setting" configuration section was created for the "Search API" module, but it is actually for the core "Search" module.
Re-enabling the core "Search" module caused the "Search Setting" configuration section to reappear.


How can I use drupal_add_js() to include the following script?

I recently came across this issue and was able to work around the limitations of drupal_add_js() with the following hack:

//this can be any string of js that's already wrapped in <script> elements
$my_script = '<script ...[all the things]... ></script>';

drupal_add_js('</script>' . $my_script . '<script>', array(
  'type' => 'inline',
  'scope' => 'header', //or 'footer'
  //...any other options you want to add
));

You end up with two empty <script> elements in your markup, which I find annoying, but they don't actually do any harm.


Bought Drupal Organization Membership But Cannot Create Listing

I understand that you've already created an organization page for Elsner Technologies Pvt. Ltd. on the Drupal marketplace, but that you want the listing to appear as a Drupal services provider.

If this is not yours, you may request its removal, or that ownership of the node is transferred to you so that you can edit it in the Drupal webmasters issue queue.

I've found this 4 year old application – which was denied.

The guidelines for being listed in Marketplace still apply, and you still do not qualify.  Unfortunately, having a Drupal organization membership does not qualify for a listing.  I suggest you re-read the comment given by lizzjoy as it contains good advice.


Create email everytime a webform is sent off (in custom module)

I've solved this issue in Drupal 6 by adding a secondary submit function to the webform.  In that submit function, I use webform's email handler to send my email.

In hook_form_alter:

function custom_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
        case 'a_form': // the value we stole from the rendered form
        case 'another_form_form': //Fall through, instead of trying to do case A OR B:
        case 'the form I want to send emails from':
            $form['#submit'][] = 'my_submit';
            break;
    }
}

Then the secondary submit function:

function my_submit($form, &$form_state) {
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    module_load_include('inc', 'webform', 'includes/webform.components');
    global $user;

    $node = $form['#node'];
    $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);

    //Build the custom email array for the webform email handler
    $email = array(
     array(
      'nid' => $node->webform['nid']
      ,'eid' => count($node->webform['emails']) + 1
      ,'email' => $form_state['values']['submitted'][3]
      ,'subject' => 'Your Custom Subject Line!'
      ,'from_name' => 'default'
      ,'from_address' => 'default'
      ,'template' => '

Hello '.$form_state['values']['submitted'][1].',

More HTML goes here

'
      ,'html' => 1
      )
     );
     webform_submission_send_mail($node, $submission, $email);
 }

You could also probably just use the drupal_mail function to send the email in your custom submit function.  I just haven't tested that option.

For further info, take a look at  webform_client_form_submit and webform_submission_send_mail


Drupal 7 has the oauth2_server module that allows you to run an OAuth2 server. It is well documented and integrates a well known and stable PHP library.
OAuth2 is probably a better option for you than OAuth1 because it has grant types optimized for different usage scenarios (mobile app, web app, etc).

If you're limited to Drupal 6, your only option is the OAuth module (also available for D7), but keep in mind that Drupal 6 is basically a deprecated version so when it comes to contrib support and bug fixes you are pretty much on your own.


Trying to create a table with an uid field that auto-increments and is the primary key, but keep getting an error

First of all please provide which version of drupal you are using ?

If you are using d7 than you don't need to check in hook_install is table exists ?

Just provide hook_schema in your module file and it will create your tables.
For floormap_coords make uid as primary ( primary key itself unique)
'primary key' => array('uid'),


Form Permissions not working in Module with Multiple Forms

This was my fault for not completely understanding how the permissions function worked.  I didn't realize only one function is needed to house all form permissions.  The following code works great.  Hopefully it will help others who aren't all that bright like myself:

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

  $items['sar_performance_form'] = array(
    'title' => 'SAR Performance',
    'description' => 'SAR Performance Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_performance_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR Performance Form Access'),
  );

    $items['sar_sdr_form'] = array(
    'title' => 'SAR SDR/NCR',
    'description' => 'SAR SDR Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('sar_sdr_form'),
    'access callback' => 'user_access',
    'access arguments' => array('QCA SAR SDR Form Access'),
  );

  return $items;
}

//***PEFORMANCE FORM***
function sar_performance_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_performance_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_performance_overview']['sar_performance_overview'] = array(
     '#markup' => t('Performance form overview goes here'),
   );

   //Display the form
   $form['sar_performance_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//***SDR FORM***
function sar_sdr_form($form, &$form_state) {

   //Display the overview
   $form['fs_sar_sdr_overview'] = array(
     '#type' => 'fieldset',
     '#title' => t('Overview'),
   );

   $form['fs_sar_sdr_overview']['sar_sdr_overview'] = array(
     '#markup' => t('SDR form overview goes here'),
   );

   //Display the form
   $form['sar_sdr_something'] = array(
     '#markup' => 'Form input can start here',
   );

   return $form;
}

//This function adds the forms to the permissions menu
function glatfelter_supplier_action_register_permission() {
    return array(
       'QCA SAR Performance Form Access' => array(
       'title' => t('QCA SAR Performance Form Access'),
       'description' => t('Allows users to access the SAR Performance form.'),
       ),

       'QCA SAR SDR Form Access' => array(
       'title' => t('QCA SAR SDR Form Access'),
       'description' => t('Allows users to access the SAR SDR form.'),
       ),

    );
}


How do you output taxonomy terms and the fields thats attached to it?

You just need to add these 2 fields to your view (and remove the "all taxonomy terms" field you've already added):

 Taxonomy term: Name

 Taxonomy term: City

Your precise field names may vary.

I was able to do a test view like this and State and City display OK.

I'm not doing any fancy relationships or anything with the view. If you don't see these fields as options, it may be we have different modules, but I'm also Drupal 7 views 3.


My custom Save button does not save the new form values

Add the original form's submit function to your #submit array in addition to your custom function.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#submit_property


Did you try Aggregator? It's the first one listed on the modules page then on the configuration page it's call Feed Aggregator.

I then use Views to style my results.

Hope this helps!


how to find out if a custom filter handler is in use when in hook_views_query_alter()

Found a way, you can check for the filtername in the view object
e.g.  if (isset($view->filter['myfiltername'])) {


How to limit access for some special user to a single (Views) page?

Not sure if it is the "best" approach, but for sure a "possible" approach for this would be to use the Rules module for this. All you'd have to do is to create a (rather basic) rule like so:

Rules Event: Drupal is initializing.
Rules Conditions (both must be true):

Check if the user's Id (uid) or user's name matches your "special user".
If the URL being accessed (= "site:current-page:url") does NOT match with the URL of your  "single (Views) page"

Rules Action: Perform a redirect to your "single (Views) page".

Done ...

Happy Rules-ing!

Note: Obviously, this rule only takes care of what that special user is allowed to use as URLs (while logged in). If that user does not login (yet) or logs out again, then anything an anonymous user is allowed to navigate to will also be available to this not-yet-logged-in-user. For whatever that is not allowed as an anonymous user, you must ensure that the permissions for anonymous users are set to deny such access.


Change the way results are shown when using the Quiz module

Generally speaking when you need to alter the output of a module, you need to override the theme function which is responsible for formatting the data you'd like to alter.

You can do this either by overriding the theme function within template.php within your theme (can get messy quite quickly with a lot of overrides), or by overriding the theme function within a custom module (I would rather recommend doing it this way).

There's plenty of reading material on the subject out there to get you started. Just remember never to hack away at the core or contrib module's theme functions!! :)

Good luck!


Is there any way to create validation function in system_settings_form

The system_settings_form should be used to set simple variables for your module, see the approved answer and related comment here:

Is "system_settings_form" voodoo?

If you want to be sure both form fields are filled out during submission you don't need a validate function -- you can set both fields as being required when you create your form array:

$form['SOMETHING']['#required'] = TRUE;

where something is your form field key.

If you have complex logic and your form isn't simply setting a configuration variable you will call with variable_get or variable_set later -- then implement a custom form_validate and form_submit function for your form as your form is not simply a variable settings form.

See the Form API Handbook. Also of use is this drupal $form lifecycle or workflow illustration. Lastly form validation helpers and submit handlers are touched on briefly on this page of the handbook.

EDIT:

Just to complete my answer, hook_form_alter can change many aspects of a form used by drupal.

EDIT 2:

You can add a custom validator on the form you use to build return system_settings_form($form); for an example see the Commerce Admin include file here: http://cgit.drupalcode.org/commerce/tree/includes/commerce_ui.admin.inc

They set:

$form['#validate'][] = 'commerce_currency_settings_form_validate';

in their form builder function then they provide a validation function:

/**
 * Form validate handler for the currency settings form.
 */
function commerce_currency_settings_form_validate($form, &$form_state) {
  // Ensure the default currency is always enabled.
  $default = $form_state['values']['commerce_default_currency'];
  $form_state['values']['commerce_enabled_currencies'][$default] = $default;
}


View (Read Only) access for Drupal Commerce - Orders

Inside your view, what are you access options (located under "Page Settings")?  That would be a good place to start.  Naturally clear the cache after every permission change.

I also don't think it would be wise to allow anonymous users to view any/all orders.


While developing a custom module, which function creates table in database?

First things first, you are using the correct hook.

If your module is already enabled, then the implementation of hook_schema() won't get called.  This is also the case if the module has been enabled, and then disabled without uninstalling.

I would try disabling your module, and then ensuring it is uninstalled by either heading to admin/modules/uninstall/ or (if you have Drush installed) run drush pm-uninstall mymodule

From the documentation:

  The tables declared by this hook will be automatically created when
  the module is first enabled, and removed when the module is
  uninstalled. This happens before hook_install() is invoked, and after
  hook_uninstall() is invoked, respectively.

I'm not sure why you'd be defining a controller class though, or even which one you're defining.  Drupal 7 does this with an array, it's not very OO (Drupal 6/7 is array soup).

If this doesn't solve your issue perhaps you could paste a munged version of your implementation of hook_schema.


Is it possible to create content and link it to an existing menu item?

I guess you have to write a custom module. This may be a similar situation.


How do i customize theme_link() for a particular node, or view only?

You can use hook_node_view_alter(&$build) and overwrite the link. Here is an example to change the Read More title and removing Add comment link. You can use dpm()  function of devel module to see the array structure.

function mymodule_node_view_alter(&$build){
  if($build['#node']->type == 'DVD' && $build['#view_mode']=='teaser'){
    $build['links']['node']['#links']['node-readmore']['title'] = t('New Title');
    unset($build['links']['comment']['#links']['comment-add']);
  }

}


Is it mandatory to clear cache for each and every change made?

Disable Drupal 8 caching during development

  When you are developing a module or a theme you have to clear Drupal's
  cache (render cache, dynamic page cache, Twig cache) very often to see
  the changes being applied. You can disable caching for development.

Steps

Copy and rename the file sites/example.settings.local.php to sites/default/settings.local.php:

$ cp sites/example.settings.local.php sites/default/settings.local.php

Uncomment these lines in sites/default/settings.php:

if (file_exists(__DIR__ . '/settings.local.php')) {
    include __DIR__ . '/settings.local.php';
}

If you want to keep CSS and JS aggregation and preprocessing, change these lines in sites/default/settings.local.php to TRUE:

$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;

Uncomment these line in sites/default/settings.local.php:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = cache.backend.null';

Add the following lines to sites/development.services.yml:

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

(source: drupal.org)


myModule.module

function myModule_theme($existing, $type, $theme, $path) {
return array(
 'pagina_3' => array(
   'variables' => array(
     'titulo' => 'title',
     'descripcion' => 'description',
     'formulario'   => NULL
      ),
    'template' => 'pagina_3'
   )
  );

}

mymodule/templates/pagina_3.html.twig

{{ titulo }}

{{ descripcion }}

        {{ formulario }}

myModuleController.php

public function verPagina3() {

    $form = $this->formBuilder()->getForm('Drupal\myModule\Form\InsertarGastoForm');

    // Le pasamos el formulario y demás a la vista (tema configurado en el module)
        return [
            '#theme' => 'pagina_3',
            '#titulo' => $this->t('Formulario crear empresa'),
            '#descripcion' => 'Formulario para crear una nueva empresa en Drupal 8',
            '#formulario' => $form
        ];

   }


EDIT: Updated to use a preprocess function.  This still might not be pretty, but works fine.  In your template.php file in your theme, add this function (replacing YOURTHEME with the name of your current theme):

function YOURTHEME_preprocess_comment(&$variables) {
  $display_order = _comment_get_display_setting('sort', $variables['node']);
  if ($display_order == 1) {
    $variables['end_comment'] = db_result(db_query('SELECT MIN(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
  else if ($display_order == 2) {
    $variables['end_comment'] = db_result(db_query('SELECT MAX(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
}

Now copy comment.tpl.php from modules/comment and place it in your theme folder.  Add this code

print $end_comment == $comment->cid ? ' last' : '';

to the class area of the div html.  It should look something like:

<div class="comment<?php print ($comment->new) ? ' comment-new' : ''; print ' '. $status; print $end_comment == $comment->cid ? ' last' : ''; ?> clear-block">

You now have a class of last on the bottom comment, no matter which way they are sorted.  Now simply add some simple CSS to your stylesheet:

div.comment.last {
  border-bottom: none;
}

You can also use jQuery or CSS to remove the bottom border from the last comment, but they are less reliable depending on a user's browser, browser settings, etc.

jQuery:

// Remove border from last comment
$('#comments div.comment:last').css('borderBottom', 'none');

CSS (Works in IE9, but unfortunately will not work with IE8 and below):

div.comment:last-child {
  border-bottom: none;
}


How to require a user to be logged in to access files

You have to setup the private file system. You can do this on /admin/config/media/file-system.

Next you will have to alter your field to use the private file system instead of the public file system. If this field already has data, you can use https://www.drupal.org/project/filefield_paths to migrate the files from public to private


Fieldsets 'IF ELSE' based on checkboxes?

Assuming you are looking for a #states based solution, which is new in Drupal 7.

First, note that you cannot use 0 as a key for #options. So rewrite your first field set as follows:

$form['Contract']['first'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Products applying for:'),
 '#options' => array('b' => 'Product B', 'c' => 'Product C'),
 '#required' => TRUE, // Added
 );

Now, we hide/show the other fieldsets depending on the above checkboxes' values.

$form['Contract']['product B'] = array(
  '#theme' => 'form_panel_table',
  '#type' => 'fieldset',
  '#tree' => TRUE, // not necessary if parent element has #tree = TRUE.
  '#title' => t('product b'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE
  '#states' => array(
      'visible' => array(
        ':input[name="first[b]"]' => array('checked' => TRUE),
      ),
    ),
);

Likewise,

$form['Contract']['product C'] = array(
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#theme' => 'form_panel_table',
  '#title' => t('example'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="first[c]"]' => array('checked' => TRUE),
    ),
  ),
);

What we are doing exactly is that we ask the Form API to generate necessary jQuery code that it should only show the field set in question only if the input tag (it's a specially jQuery selector that selects input, textarea, select, etc tags at once) with name "first" and its value c/b is checked. These 2 visibility settings are individual so there is no else if concept here.

Also note that #tree has nothing to do with the form's settings. if the code above didn't work, try setting if off. When you have #tree, name attribute of input fields get changed so PHP can build an array of submitted information. There is nothing to do with the visibility settings (except it can make our visibility rule never become true)


You will have to work on custom module implementation.

Custom solution would not effect content on account page.

hook_menu will define the menu items like account/orders and account/billing

If you are using Ubercart then you will have to carefully investigate if your required information are being stored and in which table. I am not sure if Ubercart stores Credit Cards data. I think Ubercart uses DPM (Direct payment method) to process cards which totally happens on Authorize.net pages.

Pathauto normally defines url alias also for user profile pages. But I think there is no way to skip user id from url while editing a user.


It depends what type of javascript you are adding.

drupal_add_js will only add files once, no matter how often it's called ;
Settings would overwrite previous values, so it's not a major problem ;
Inline code would indeed get added multiple times.

Given that your script needs including only once no matter how often the field is present, I assume you are not generating it's code on the fly - so putting it in a file would be an option.

Otherwise, as suggested by Clive, you could have your own wrapper around drupal_add_js that ensures a given inline js is only added once by using a static variable.


After posting this, I was perusing the site, and came across a similar question where someone had suggested disabling the Update module.  I had noticed a lot of calls to the update_xml_parser object in Update module, so it made sense.  I disabled the module and voila! the page change speed went to a couple of seconds.


How do I configure facet items to remain visible when they are selected?

I figured it out. Go to "Configuration » Search and metadata » Search API" and click the facets tab. Next to the desired facets you will see "configure filters" with an arrow pointing down next to it. Click the arrow. In the drop down select "configure filters". Make sure that "Do not display active items" is NOT selected. This worked for me.


Has anyone implemented a tablesort with ajax?


Why I cannot change views page title using views_post_render?

I always use a hook_views_pre_view():

function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "foo" && $view->current_display == "bar") {
    $view->display[$view->current_display]->display_options["title"] =
    $view->display[$view->current_display]->handler->options["title"] = "The New Title";
  }
}

This should then funnel up to be pulled in as the page title, but I never use views directly as pages.


Why Role::getPermissions() method return an empty array for admin users?

That is because a role that is marked with is_admin (which from the UI is possible for just a single role) has all the permissions. Consider it as an extension of the user #1 concept; the difference is that there is just a user #1, but there could be many users assigned to the role marked as is_admin.
In fact, the code does the same it does for the user #1: It explicitly checks for the role being is_admin. So, returning an array of permissions that will never be used doesn't make sense. See Role::hasPermission().

  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

Similar code is present in other functions/methods, for example Role::revokePermission().

  if ($this->isAdmin()) {
    return $this;
  }
  $this->permissions = array_diff($this->permissions, array($permission));
  return $this;

As for why Drupal uses that code, it is because from the UI it is possible to change which role is marked as is_admin, including one for which permissions were already set. Once it is marked is_admin, the permissions explicitly set can be ignored, but they are kept, just in case you change from the UI the role marked as is_admin. In such case, you would not want to set again the permissions you set for the old is_admin role.


Commerce/Rules - Multiply the price by a custom field value

I found the solution to this, so I thought I would post it to help anyone else out who is struggling:

1) Before you can call your field under actions, you have to bring it "into scope" under conditions.
Select "Entity has field". Under data selectors choose "commerce-product (saved commerce product).

2) For some reason, it seems impossible to use the "Multiple the Unit Amount by" option, as no matter what data selector you use, you will get an error.
Instead select "Calculate a value"

3) Under "Input Value 1" select "commerce-product:commerce-price:amount".

4) Select which calculation to use. In my use case, I used multiply (*).

5) Under "Input Value 2" click the "switch to data selection button". You can now select your custom field. It will be located under "commerce-product: (saved commerce product)"

6) Under "Provided variables" give the result of the calculation a name. Choose a good name, as you will be using it later on.

7) Now create a new action called "Set a data value".

8) For the data select pick "commerce-product:commerce-price:amount"

9) Finally, under value, click the "switch to data selection button". You can now select the variable you created in step 6.

This is everything you need to change the price based on the value of a custom field.

Notes:
1) For the event, I used "Before saving a commerce product"
2) I would recommend creating a custom field called "base price", where the user can enter the price before calculations. The rule is applied every time a product is saved, so the commerce price field will keep on changing each time the product is saved. If you use a base price field, you can avoid this problem.


It took me a while to find out how to do it in Drupal 8, and since this post is one of the first google hits I'll add the solution here:

function MODULE_form_node_NODETYPE_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    $form['my_embedded_view'] = [
        '#type' => 'view',
        '#name' => 'my_view_name',
        '#display_id' => 'block_1',
        '#arguments' => [
            'arg1' => $arg_1,
            'arg2' => $arg_2,
        ],
        '#weight' => 30,
    ] ;
...
}

I used a block display for the view, I don't know if it's relevant.


Generate unique ID in hook_redirect_form

$unique_id = $order->order_id . '-' . microtime();

The advantage of this is you can explode on the - later and get the order id back again.


Where to find custom Content type related files in Drupal directories?

Actually, content is managed through the database, so you won't find a specific dir named Content Types in the drupal folder.


Generating links from words using an input filter


I'm not really sure this is correct, but I guess you are looking for the id for the block:

function THEMENAME_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  if (isset($variables['view'])) {
    $view_id = $variables['view'];
    $id = $view->id();
    $block_id = $view->getDisplay()->display['id'];
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $block_id);
  }
}

You can also print out the contents of the $view->getDisplay()->display array to check for other values that you might use.


That's the correct behaviour.

If current_path() wasn't the URL of the file, then the file must never have been requested, and that hook would never have fired.

When you request a private file the current URL must be the file's URL, by definition. It sounds like you're looking to track the page that originally contained a link to your file. That's going to be almost impossible to do reliably.


Create container.html.twig template for specific page

Am not sure if this contains the answer, but you should definitely read this:

Twig Debugging


I need to update jQuery version for drupal manually?

1- @see /misc/jquery.js

2- its better to add ur jquery to your theme .info file

go to your theme folder
insert your jquery file into the same folder of your theme (E.g theme name new_jquery.js)
in the same directory open yourThemName.info file
add this line  scripts[] = new_jquery.js

3- its not prefered to use Jquery 1.6 with Drupal 6

4- use jQuery.noConflict() to avoid conflict


Extracting user field values from dynamic SQL queries

Assuming your field is a string, the field in the database will be field_first_name_value
Assuming the field is attached to a user entity, the table for that field should be user__field_first_name (2 underscores between user and the field name) your need one more join to get that field value, it's not stored in users_field_data

$database = \Drupal::service('database');

$select = $database->select('flagging', 'f');
$select->fields('f', array('uid', 'entity_id'));
$select->leftJoin('node__field_start_datetime', 'nfds', 'nfds.entity_id = f.entity_id');
$select->fields('nfds', array('field_start_datetime_value'));
$select->leftJoin('node_field_data', 'nfd', 'nfd.nid = f.entity_id');
$select->fields('nfd', array('title'));
$select->leftJoin('users_field_data', 'ufd', 'ufd.uid = f.uid');
$select->leftJoin('user__field_first_name', 'uffn', 'uffn.uid = f.uid');
// TODO extract first name
$select->fields('ufd', ['mail', 'name']);
$select->fields('uffn', ['field_first_name_value']);

$executed = $select->execute();
$results = $executed->fetchAll(\PDO::FETCH_ASSOC);

$username = $result['name'];
$email = $result['mail'];
$first_name = $result['field_first_name_value'];


I wound up creating a new site in Lando and a new site folder just for simpletest. I created a site directory for my main site and moved settings.php into that, and installed a minimal Drupal site to the other.

This resolved my issue, since the site/db specifically for SUT does not use memcache.


I just found out that you can add a db_select as a table into the left join. So the solution for this will be:

$subselect = db_select('og_membership', 'ogmk');
$subselect->join('node', 'kompas', "kompas.nid=ogmk.etid AND kompas.type='kompas'");
$subselect->join('publication_date', 'pd', 'pd.nid=kompas.nid');
$subselect->condition('pd.published_at', $end, '<');
$subselect->condition('pd.published_at', $start, '>');
$subselect->condition('kompas.status', 1, '=');
$subselect->fields('ogmk', array('gid', 'etid'));

$select->leftJoin($subselect, 'ogm_kompas', 'ogm_kompas.gid=og.gid');


How to deal with block cached for anonymous user?

In general the Internal Page Cache is a rather simple solution. If you need more features replace it with Varnish or a CDN. Most of them provide similar features, like for example ESI to serve dynamic blocks if you can't use Javascript. I think most people would use Javascript in this case, though, and there is a fully cacheable solution. You can deliver all eligible node IDs in drupalSettings and then select and fetch a random node in Javascript. Both, the page containing all eligible nodes and the node randomly fetched, are cacheable, so you can provide the dynamic behavior without any performance hit.


Managed File is stuck with a temporary URI, even after saving it as permanent file

You need to mark file as "used", there is file.usage service for that, you can do it by next code: \Drupal::service('file.usage')->add($file), but after removing file from config or changing it by another file don't forget to remove file usage by \Drupal::service('file.usage')->delete($file), otherwise file would not be removed from file system.

In drupal 8.3 default behavior about unused files was changed and by default all unused files should not be deleted, until variable make_unused_managed_files_temporary is true.


Looks like the system is tossing in an unusual min-height value for each div.  Can you locate this in your code:  div class="grid-inner col-inner clearfix" style="min-height: 2694px;"
You might have to work your CSS to get it all formatted properly.  If you remove that min-height variable, it formats correctly (in FireFox)


Can't get Flagging API to accept POST request

I tried to create a flag, however, I had the same results.

To solve this, I have created a module.

note: to make tests I installed the "Flag Bookmark" module.
file test_api.info.yml.

    name: Test API
    type: module
    description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
    author: Minnur Yunusov
    core: 8.x

file test_api.routing.yml.

# Test API endpoints

  test_api.get:
  path: 'my-api/get.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::get_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

test_api.put:
  path: 'my-api/put.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::put_example' }
  methods:  [PUT]
  requirements:
    _access: 'TRUE'

test_api.post:
  path: 'my-api/post.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::post_example' }
  methods:  [POST]
  requirements:
    _access: 'TRUE'

test_api.delete:
  path: 'my-api/delete.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::delete_example' }
  methods:  [DELETE]
  requirements:
    _access: 'TRUE'

we create the following directories and file TestAPIController.php
src/Controller/TestAPIController.php

<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function get_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'GET';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/put.json` API method.
   */
  public function put_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'PUT';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/post.json` API method.
   */
  public function post_example( Request $request ) {

    // This condition checks the `Content-type` and makes sure to
    // decode JSON string from the request body into array.
    if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {
      $data = json_decode( $request->getContent(), TRUE );
      $request->request->replace( is_array( $data ) ? $data : [] );
    }

    //get value json
    $flag_id= $data["flag_id"];
    $entity_type= $data["entity_type"];
    $entity_id = $data["entity_id"];
    $uid= $data["uid"];
    $created = REQUEST_TIME;

    //get user
    $user= User::load($uid);

    //get field uuid
    $user_uuid= $user->get('uuid')->value;

    //add entity_id to the field field uuid (unique value);
    $user_uuid= $user_uuid.'-'.$data["entity_id"];

    $fields=array(
      'flag_id' => $flag_id,
      'uuid' =>$user_uuid, //unique value
      'entity_type' =>$entity_type,
      'entity_id' => $entity_id,
      'uid' =>$uid,
      'global' =>0,
      'created' => $created
    );

    if ($data["flag_action"]=='flag') {

        //verify if exists record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if not exists record, create flag
        if (count($result)>0) {
          $response['¿Flag exists?'] = 'true';
        }
        else {

              $resultado= db_insert('flagging')
              ->fields($fields)
              ->execute();

              $response['newflag'] = $resultado;

        }

        $response['data'] = $data;

    }

    else if ($data["flag_action"]=='unflag') {

        //verify if exits record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if exists record, delete flag
        if (count($result)>0) {

          $num_deleted = db_delete('flagging')
          ->condition('entity_type', $entity_type)
          ->condition('entity_id', $entity_id)
          ->condition('flag_id', $flag_id)
          ->condition('uid', $uid)
          ->execute();

          $response['¿Delete flag?'] = 'true';
        }
        else {

          $response['¿Flag exists?'] = 'false';

        }

        $response['data'] = $data;

    }

    /*

    //send json example
    //change "bookmark"  by "my_flag"

    {
      "entity_id":31,
      "entity_type":"node",
      "flag_id": "bookmark",
      "uid": 1,
      "flag_action": "flag"
    }

    */

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/delete.json` API method.
   */
  public function delete_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'DELETE';

    return new JsonResponse( $response );
  }

}

Note: in the tests change "bookmark"  by "my_flag"

test:
url: http://jeremiselxi.260mb.net/drupal8/my-api/post.json
method:post;
headers:
Content-type: application/json
X-CSRF-Token: token()

note: this token is obtained through the GET method to the url
localhost/session/token

create flag

{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "flag"
}

result:

200 OK

Headers
{
  "newflag": "22",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "flag"
  }
}

note: If the flag does not exist, then create the flag

"newflag": "22"

else

"¿Flag exists?": "true"

create unflag

{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "unflag"
}

result:

200 OK

Headers
{
  "¿Delete flag?": "true",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "unflag"
  }
}

note: If the flag exists, then delete the flag

"¿Delete flag?": "true"

else

"¿Flag exists?": "false",


How would I make a search view display results in a new page instead of on the same page?

You can show your exposed views filter as a block, and place the block on your search page, then all submissions will show results on your view page.

Under the advanced field-set in the views UI, once you have created an exposed filter, an option will appear under the EXPOSED FORM heading that will allow you to create a block.

You can see an example of a front page search leading to a views results page here... http://www.myweddingfayre.com


How to disallow commerce checkout if no payment method is available?

The core payment module offers this option in the checkout pane's settings form.


Adding a link to a node in a Views export

You need to add a new field "content:path" and check the option in the rewrite results section "Use absolute link (begins with "http://")". This should do what you want.

If you want to output it as a working link, you can check the option " Output this field as a link" and fill the replacement pattern [path] into "Link path".


This module looks like similar to your query Hide Submit


It's easiest to stay out of node.tpl.php for this one and instead use a field specific template file.

You'll need two copies of /modules/field/theme/field.tpl.php in your theme folder. The first is an exact duplicate with no changes and the same filename. The second you should rename to field--field-body-list.tpl.php. Consult Drupal 7 Template Suggestions if that filename doesn't work for you.

In field--field-body-list.tpl.php I would change the div with class="field-items" to <ul> and the div with class="field-item" to <li>.


How do I consume JSON data via a hook_menu callback?

Well, it turns out I was getting the data, but I forgot to decode it...

In my hook_menu callback:

$received = file_get_contents("drupal://input"); // Use inputstream module.
$received = json_decode($received, TRUE);

Then I can play around as much as I'd like with the $received value.

Additionally, the inputstream module is invaluable in letting me get to the input stream more than once (if you try using php://input more than once, the second time, and those following, will return NULL).

As an additional note, I just noticed today a new module that might be an even simpler way of handling this: Content as JSON


Show items not linked by a view relationship

This looks like the answer:

https://www.drupal.org/project/drupal/issues/2744777

There is a known bug in Drupal 8 whereby filter groups in views are not saved. The two filters (content type is empty and content type) Order are being AND-ed rather than OR-ed so therefore nothing is displayed as content type cannot both be empty and = Order.


Drupal Commerce - Product Variation Type missing Nodes

You can add and remove Displays to your content types by expanding the 'Custom Display Settings' section right under all those fields in the 'Manage display' tab.  It's hard to notice because it's collapsed by default.

You'll probably see a different list than me, because it also depends on the modules you have enabled on your site:

However, my feeling is that - though I haven't used kickstart and its examples - the differentiation in the look of your content type and theirs also has a lot to do with theming.  That's a big topic, but I'd check to see whether there are templates and css styles that apply to those sample content types that you can copy over to yours...


Sounds as if you need the Redirect 403 to User Login module:

Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:
"Access denied! You must login to view this page."
Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.


In Drupal cache content is language specific. Default is a cache context for the language. Sometimes you need to clear the cache one more time, but then this should work.

You can check this in the database table cache_render. All cid's should contain [languages:language_interface]=langcode and if you visit the same page in different languages you should see multiple cache entries.

Disabling the cache with a null backend is only for development. For production you need to find a solution for the language specific caching issue.


Automatic way to delete users with no content

if I understand you correctly then you have somekind of users and one content type "Artist Page". That users must fill (create) a node of that Artist Page content type. but some users may skip this step. In that case you can do following I think:

node table has a uid field (author of content).
Fetch separately (as array) uids of node and users tables and compare them;
Get difference of arrays and compare there created time with current time, if difference is reaches(notification time) then send them an email, if difference is reaches(deletion time) then delete them.... These operation can be done on cron job. I recommend Elysia cron module.

Example:

function MY_MODULE_cronapi($op, $job = NULL) {
  $items['my_custom_task'] = array(
    'description' => 'My custom task description',
    'rule' => '*/20 * * * *', // Example rule - execute job every 20 min
    'callback' => 'my_custom_task',
    'arguments' => array(),
  );

  return $items;
}

function my_custom_task() {
  $subquery = db_select('node', 'n');
  ->fields('n', array('uid'))
    ->condition('n.type', 'MY_TYPE', '=')
    ->execute()
    ->fetchCol();

  $uids = db_select('users', 'u')
    ->fields('u', array('uid', 'created'))
    ->condition('u.uid', $subquery, 'NOT IN');
  ->execute()
    ->fetchAll();

  if(!$uids) {
    foreach($uids as $key => $uid) {
      $user_id = $uids[$key]->uid;
      $user_created = $uids[$key]->created;

      $notif_time_min = time() + 60*60*24*7; // example
      $notif_time_max = time() + 60*60*24*8; // example

      $del_time = time() + 60*60*24*15; // example

      if((time() - $user_created > $notif_time_min) && (time() - $user_created < $notif_time_max)) {
        // send_email()
      }
      elseif(time() - $user_created > $del_time) {
        //del_user()
      }
    }
  }
}

//P.S: I'd recommend to modify the callback part of cronjob. You can have too many users and every time cron job queries the tables(users and node tables) for existence of left users;
Good solution will be creating a custom module which holds somekind of flag, which verifies that user is valid or not, you can flag as unverified  on registration and change to verified on creation on node. This can be achieved by Rules or Action or custom code...


Use the API: node_save().

Saving data directly to field tables is not possible, you shouldn't even consider this. There are many ways to import data into nodes, for example the Migrate or Feeds modules, if that's what you're after.


For people interested to the solution, you have to use the hook_field_extra_field() hook.

There you can declare your own "virtual fields" and they will appear as fields also in the Display Suite.

To link them to the content you create, just be sure to use the same name as a key both in the field name and in what you add as a node->content.

To provide you with the solution related to my example:

/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  $extra['node']['my_custom_bundle_type']['display'] = array(
      'ds_column' => array(
        'label' => t('My column'),
        'description' => t('Description is also mandatory'),
        'weight' => 99,
      ),
  );
  return $extra;
}

As you can see ther key ds_column is the same used in the mynode_view (or in any other function implementing a hook able to modify the content render array).


list of supported value in entity baseFieldDefinitions setDisplayOptions type(field widget)

What you are looking for are the field widget plugins, these depend on what modules you have installed.

Use Drupal Console to run this command:

drupal debug:plugin field.widget

This is what I have on a local site with some contrib modules:

 -------------------------------------------- ---------------------------------------------------------------------------------------
  Plugin ID                                    Plugin class
 -------------------------------------------- ---------------------------------------------------------------------------------------
  boolean_checkbox                             Drupal\Core\Field\Plugin\Field\FieldWidget\BooleanCheckboxWidget
  datetime_datelist                            Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget
  datetime_default                             Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDefaultWidget
  datetime_timestamp                           Drupal\Core\Datetime\Plugin\Field\FieldWidget\TimestampDatetimeWidget
  email_default                                Drupal\Core\Field\Plugin\Field\FieldWidget\EmailDefaultWidget
  entity_reference_autocomplete                Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
  entity_reference_autocomplete_tags           Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteTagsWidget
  field_example_3text                          Drupal\field_example\Plugin\Field\FieldWidget\Text3Widget
  field_example_colorpicker                    Drupal\field_example\Plugin\Field\FieldWidget\ColorPickerWidget
  field_example_text                           Drupal\field_example\Plugin\Field\FieldWidget\TextWidget
  field_permission_example_widget              Drupal\field_permission_example\Plugin\Field\FieldWidget\TextWidget
  file_generic                                 Drupal\file\Plugin\Field\FieldWidget\FileWidget
  image_image                                  Drupal\image\Plugin\Field\FieldWidget\ImageWidget
  language_select                              Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget
  link_default                                 Drupal\link\Plugin\Field\FieldWidget\LinkWidget
  menu_item_extras_view_mode_selector_select   Drupal\menu_item_extras\Plugin\Field\FieldWidget\MenuItemExtrasViewModeSelectorSelect
  moderation_state_default                     Drupal\content_moderation\Plugin\Field\FieldWidget\ModerationStateWidget
  number                                       Drupal\Core\Field\Plugin\Field\FieldWidget\NumberWidget
  oembed_textfield                             Drupal\media\Plugin\Field\FieldWidget\OEmbedWidget
  options_buttons                              Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget
  options_select                               Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget
  path                                         Drupal\path\Plugin\Field\FieldWidget\PathWidget
  string_textarea                              Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget
  string_textfield                             Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget
  text_textarea                                Drupal\text\Plugin\Field\FieldWidget\TextareaWidget
  text_textarea_with_summary                   Drupal\text\Plugin\Field\FieldWidget\TextareaWithSummaryWidget
  text_textfield                               Drupal\text\Plugin\Field\FieldWidget\TextfieldWidget
  uri                                          Drupal\Core\Field\Plugin\Field\FieldWidget\UriWidget
 -------------------------------------------- ---------------------------------------------------------------------------------------


The 'id' property in the annotation defines the unique, machine
   readable ID of your block.

The 'admin_label' annotation defines the human readable name of the
   block that will be used when displaying your block in the admin
   interface.

The 'Category' defines which section belongs to under block listing page.

The Drupal block manager scans your module's classes for a class that contains the @Block Annotation (a special comment right above your class declaration)

<?php
/**
 * @file
 * Contains \Drupal\article\Plugin\Block\XaiBlock.
 */
namespace Drupal\article\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'Article' Block
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article block"),
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => 'This block list the article.',
    );
  }

custom block programatically


There really isn't any right answer to this question. I do something similar to what tenken suggests; see:

https://github.com/greg-1-anderson/utiliscripts/blob/master/drupal-backup-all

The basic idea is, every time I back up a site, I also make a second local copy, and run pm-updatecode on it.  The backup and update sites are live (but accessible only on the internal network), so it's possible to look at either and see if they are running or not.

My experience in doing this is that the task of copying a site and running pm-updatecode is not the main bottleneck in upgrading sites promptly and frequently.  The main bottleneck is testing.  You have to set aside time to do this, or you won't be able to confidently deploy your sites.  Upgrades rarely, but sometimes do break your site, so you cannot really automate this last critical step.

One thing that can really help is good automated tests.  Behat and Selenium are really useful here.  See the small project below for a quick start template:

https://github.com/arithmetric/badcamp2014-behat-travisci


Variables are serialised (as are session writes as I understand it), and complex objects like entity API entities don't serialise well.

The better solution would be to store the entity type and ID in the session, then load it when reading:

$_SESSION['saved_entity'] = array('type' => 'node', 'id' => 1);

...

$saved_entity = entity_load($_SESSION['saved_entity']['type'], array($_SESSION['saved_entity']['id']));

And do the same thing for the variables.


Custom image style conversion - how to read back from a file?

Here's how I did it.

public function applyEffect(ImageInterface $image) {

    // Save the image and process it externally...
    $some_tempoaray_filename = '/tmp/foo';
    $image->save($some_tempoaray_filename);
    call_some_external_process($some_tempoaray_filename);

    $toolkit = \Drupal::service('image.toolkit.manager')->getDefaultToolkit();
    // Re-call the existing Image object's constructor with the name of the
    // new file.
    $image->__construct($toolkit, $some_tempoaray_filename);
    // Next we have to make sure it loads the file into memory
    // because $image->save() requires it to be loaded, but this
    // happens outside of this function and we want to delete
    // the $some_tempoaray_filename so as not to leave temp files.
    $toolkit->getResource(); // forces a load.
    // Now we can lose our temporary file.
    unlink($some_tempoaray_filename);

    return TRUE;
}


Can I still start a "stable" D8 project now that D9 is stable?

You are missing a :

This works:
composer create-project --no-install drupal/recommended-project:^8.9 my-recommended-project


Last version of webforms lets you do this outofdabox (put fields in a fieldset though)

You can also achive this using a hook_form_alter implementation (Have not tested this but i think that should work) and using the FAPI #type container element, for example:

$form['left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array(
      'left',
      drupal_html_class($class_left),
    ),
    'id' => array('lefttoleft'),
  ),
);

Create as many container as you want and then move all fields FAPI element inside the container


Selecting content type using panels/pages

You can use views for that solely too you know... Don't use a content pane as described below but a page with path /latest-news/%type.

But for panels:
Create a views content pane that gets all types of nodes @ once. Set contextual filter to node->type and choose raw value from url 2.

Create a page in pagemanager with this path:
yourdomain.com/latest-news/!type
Don't set up a context.

Add the contentpane as content in the page.
Now if you visit latest-news/article it shows all article-nodes. If you visit latest-news/page it shows all page-nodes.

Now you can have all benefits from panels together with a view.


How to send a notification to a user at specified time (between 9am to 10 am) daily?

Part 1: Rules

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", a question that is a variation of part of your question. It explains how you can use the Rules module for this (using the Rules Scheduler also).

Part 2: Message Stack

Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

Message:

  The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

  This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

  With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.


According to README.TXT:

  API NOTES

  Geofield fields contain nine columns of information about the geographic > data that is stores. At its heart is the 'wkt' column
  where it stores the full geometry in the 'Well Known Text' (WKT)
  format. All other columns are metadata derived from the WKT column.
  Columns are as follows:

  'geom'         Raw value. By default, stored as WKB, loaded as WKT
  'geo_type'     Type of geometry (point, linestring, polygon etc.)
  'lat'          Centroid (Latitude or Y)
  'lon'          Centroid (Longitude or X)
  'top'          Bounding Box Top (Latitude or Max Y)
  'bottom'       Bounding Box Bottom (Latitude or Min Y)
  'left'         Bounding Box Left (Longitude or Min X)
  'right'        Bounding Box Right (Longitude or Max X)
  'geohash'      Geohash equivalent of geom column value

  When a geofield is saved using the provided widgets, these values are
  passed through the geofield_compute_values function in order to
  compute dependent values. By default dependent values are computed
  based on WKT, but this may be overriden to compute values based on
  other columns. For example, geofield_compute_values may be called like
  so:

  geofield_compute_values($values, 'latlon');

  This will compute the wkt field (and all other fields) based on the
  lat/lon columns, resulting in a point. As a developer this is
  important to remember if you modify geofield information using
  node_load and node_save. Make sure to run any modified geofield
  instances through geofield_compute_values in order to make all columns
  consistent.

This translates to:

      $spot->field_coordinates[LANGUAGE_NONE][0] = geofield_compute_values(
          array(
              'lat' => $venue->location->lat,
              'lon' => $venue->location->lng,
      ), GEOFIELD_INPUT_LAT_LON);


That happens because the class normally handling the email sending (PhpMail) uses the following code, in PhpMail::format().

  // Convert any HTML to plain-text.
  $message['body'] = MailFormatHelper::htmlToText($message['body']);
  // Wrap the mail body for sending.
  $message['body'] = MailFormatHelper::wrapMail($message['body']);

In particular, this is the code handling the links. (See the comment before the code.)

  // Replace inline  tags with the text of link and a footnote.
  // 'See the Drupal site' becomes
  // 'See the Drupal site [1]' with the URL included as a footnote.
  static::htmlToMailUrls(NULL, TRUE);
  $pattern = '@(]+?href="([^"]*)"[^>]*?>(.+?))@i';
  $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  $urls = static::htmlToMailUrls();

To send HTML emails, you need a different class implementing MailInterface. The Swift Mailer module implements it, for example, and allows to send HTML emails; it also allows to select in which way to send a message (server SMTP, MTA agent, mail() function).
The Mail System module provide a UI that allows to select the mail plugin used to send emails, so you don't need to mess with the configuration to do it.


How do I embed a form in a controller response?

To embed a form in a renderable array, you use:

$form_class = '\Drupal\my_module\Form\MyForm';
$build['form'] = \Drupal::formBuilder()->getForm($form_class);

Which is similar to your code.

But the problem is of a different nature. You are extending a special controller, one that returns a renderable array of '#type' => 'page'. It uses the page template to render the output and that template does not contain the {{ layout_control }} variable to output your form. If you use $page['header']['layout_control'] = ... to add the form to the render array, it should show the form in the header region of the layout demo page.


EntityMetaDataWrapper exception when calling commerce_cart_product_add()

You are using commerce_cart_product_add wrong.

You can pretty much replace your entire code with:

$product_id = ...; // You need to product id, from somewhere, you can get it from the SKU
commerce_cart_product_add_by_id($product_id);


Seeing if node has been changed in custom submit handler

As far as I know, there isn't such flag, but you can use entity_load_unchanged() to get a copy of the entity before any change, and compare the field value with the one you get from the form.

The function is called, for example, from node_save(), which contain the following code.

// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

field_attach_presave('node', $node);
global $user;

// Determine if we will be inserting a new node.
if (!isset($node->is_new)) {
  $node->is_new = empty($node->nid);
}

// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

This means that the implementations of hook_field_attach_presave(), hook_node_presave(), and hook_entity_presave() will get the unchanged version of the node object in $node->original (or $entity->original); if you are writing code for one of these hooks, you don't need to call entity_load_unchanged() because node_save() already did it for you.

Similar code is present in comment_save(), taxonomy_term_save(), taxonomy_vocabulary_save(), and user_save().

if (!empty($comment->cid) && !isset($comment->original)) {
  $comment->original = entity_load_unchanged('comment', $comment->cid);
}

field_attach_presave('comment', $comment);

// Allow modules to alter the comment before saving.
module_invoke_all('comment_presave', $comment);
module_invoke_all('entity_presave', $comment, 'comment');

  if (!empty($term->tid) && !isset($term->original)) {
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  }

  field_attach_presave('taxonomy_term', $term);
  module_invoke_all('taxonomy_term_presave', $term);
  module_invoke_all('entity_presave', $term, 'taxonomy_term');


How to set a new value in a paragraph field on submit?

I'd imagine the first didn't work because your custom submit handler is run after the form default submit handler so it's too late (You didn't provide this code so can't be certain). You'd need to make sure your submit handler is run before any other submit handlers. To do that in the array of submit handlers your needs to be first in the array

Similarly for the 2nd option you've tried, you're in hook_presave so you're changing things but then when the normal entity save function happens after this any changes you made are overwritten


I hope I understand your question. If you want to add class to l(), then it must be an array, so your "$link=..." line would read

$link = l($output, $element['#href'], array('attributes' => array('class' => array('YOUR_CLASS_NAME')), 'html' => TRUE));

You can also read more and see other examples in Drupal's l() documentation

Hope this helps.


Create a faceted search like eRecruiter without solr?

You can also use the Facet API module. It allows site builders to easily create and manage faceted search interfaces. Facet API works with the core Search and Search API.