Found the answer myself.  I had to run drush as admin:

drush -u admin rets-flush

I thought drush ran as admin automatically, but I guess not.


How to filter a View by Date Range (start, end)?

Surprisingly this is not possible with Drupal 8 yet. But there is a long history of trying to make it work: https://www.drupal.org/node/2786577
The last patch, you find in this post, seems to work. You can download and apply it, using the following commands:

wget https://www.drupal.org/files/issues/improve_the_views-2786577-76-core.patch
git apply improve_the_views-2786577-76-core.patch

If git isn't available on your server, try:

patch -p1 < improve_the_views-2786577-76-core.patch

TO apply the patches you have to navigate to the core folder first. And be aware that you have to reapply this patch, after committing a core update. (This sucks!) So let us hope, the Drupal Gods will get this into core soon!


How can I hide revision information on node forms?

Please try below code in your theme-name.theme file.

/**
 * Implements hook_form_alter().
 */
function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['revision_information']['#access'] = FALSE;
}


Is there a way to let users edit something only if they are a members of an OG?

You could, for sure, use the Group module to let users edit something if they are a member of some group. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Entity browser not showing image after selecting an entity (Drupal 8)

Go to Manage Display of your media bundle. You may have disabled the image from Manage Display, you can enable it and update the format to Image / Responsive Image or whatever best suits you. Please check the attached screenshot


Modify "head-placeholder" in html.html.twig

I suggest you look at https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme, which provides pretty good documentation on how to add CSS in a theme.

If you don't extend from a theme then you technically extend from a special theme called "stable". You should get almost no default CSS then, at least from core modules. Unless that really results in a problem, in which case there are some options to override it (documented above), I wouldn't worry about that.


Creating configuration files manually is tedious and like @Berdir mentioned in the comments it is better to export them.

First install your theme, so you can place the blocks for your new theme.

Create the blocks in the UI.
Make sure you have installed the module: Configuration Manager (already installed if you use Standard profile)
Export the configuration using the UI (/admin/config/development/configuration/full/export) or using Drush: drush cex
Depending on how you exported the configuration:

If you used UI, you have a .zip that you must extract.
If you used Drush, the files are exported to sites/default/config_longname/sync

The blocks file names are block.block.BLOCK_MACHINE_NAME.yml
Copy those block files that you created and put them config/optional in your theme folder.
Now open these files and remove the first line, looking something like: uuid: f95127a4-7947-48e3-a0f1-1dae6c61940d

That's it, if you move the theme to a new site and install the theme, the blocks will be installed and placed where you originally put them.


Organic groups: permissions groupadmin not respected

Three steps solved my problem:

1.On admin/config/group/settings i selected a default administrator member

2.and disabled the : 'Strict node access permissions' setting.

On admin/config/group/permissions/node/mycontenttype i disabled the administer group permission.


It turned out to be a CTools problem, I simply applied the patch mentioned in this comment:

https://www.drupal.org/node/2336985#comment-9748735 (#16)

diff --git a/plugins/content_types/entity_context/entity_field.inc b/plugins/content_types/entity_context/entity_field.inc
index 5861d1c..070266e 100644
--- a/plugins/content_types/entity_context/entity_field.inc
+++ b/plugins/content_types/entity_context/entity_field.inc
@@ -129,8 +129,7 @@ function ctools_entity_field_content_type_render($subtype, $conf, $panel_args, $

   $all_values = field_get_items($entity_type, $entity, $field_name, $language);
   if (!is_array($all_values)) {
-    // Do not render if the field is empty.
-    return;
+    $all_values = array();
   }

   // Reverse values.


I removed all '#value' keys and replaced date('Y') with idate('Y') and for me it's working without any problem. Flush cache!

$form['start'] = [
  '#type' => 'number',
  '#title' => t('Between') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#min' => 1900,
  '#max' => idate('Y'),
];
$form['test'] = [
  '#type' => 'number',
  '#title' => t('TEST') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#max' => idate('Y'),
  '#min' => 1900,
];
$form['end'] = [
  '#type' => 'number',
  '#title' => t('and'),
  '#required' => TRUE,
  '#min' => 1900,
  '#max' => idate('Y'),
  '#default_value' => 1999,
];


Which library is better for image processing, GD2 or ImageMagick?

Drupal 7 supports ImageMagick with the ImageMagick module

I suspect better is subjective depending on your specific image manipulation tasks. The benchmarks I could find didn't conclusively favor either one overall but specific tasks were faster in one or the other. Opinion favors ImageMagick for quality but recent posts suggests GD2 has caught up.


How do I programmatically change the query "limit"?

If you can make your change by altering the query itself than hook_views_query_alter() is a reasonable approach, although given your description I suspect hook_views_pre_render() is more likely to give you access to the data you are thinking about.  The query alter lets you change the actual query run against the database, while prerender lets you edit the result set before Drupal renders it as HTML (or similar) for output.

Depending on the details of your use case it might make sense to actually use two queries: one that pulls the value you want to highlight and one that pulls everything else.  If the highlighted item is identified because it's the 6th, this approach would be just as hard as yours, but if it's highlighted because of some other factor (a taxonomy term, or some other field value) than this approach would likely be easier. You can have 1 query that generates the listing page, and a second with a block display that's placed at the top of your listing page.


Form submit button with ajax, replace form with another one (error 500)

You need to add your namespaced class to the callback property.
For example:

'callback' => 'Drupal\mymodule\Form\ProjektForm::form_ajax_submit'

or

'callback' => [$this, 'form_ajax_submit']

You also need to make sure the wrapper and the prefix html id are the same.

Finally, after you do all that, do check your logs for more details on the error that caused the 500 response.

Good luck!


What hook for triggering an action after saving a new node?

You can use Hook Post Action module which will provide you hooks like:

hook_entity_postsave

hook_entity_postinsert

hook_entity_postupdate

hook_entity_postdelete

hook_node_postsave

hook_node_postinsert

hook_node_postupdate

hook_node_postdelete
These hooks are fired after node is saved to the database. So the process you want to do after node save can be done using these hooks which comes with Hook Post action module.


Im not able to reproduce it on my drupal 8 projects. It might come from your front-end theme. Try to use an administrative theme for edition, like seven.

{yoursite}/admin/appearance
At the bottom of the page check use administrative theme for editing.

If the issue doesn't occur anymore on theme seven, you should start by checking in your front-end (custom?) theme for styles on thoses classes :

ui-dialog ui-widget ui-widget-content ui-corner-all ui-front editor-image-dialog ui-dialog--narrow ui-dialog-buttons


It's a unique value that allows to identify the site asking for updates. It is used on Drupal.org when giving the number of site using a module, which is shown in every project page.

Without that value, Drupal.org could not report the number of sites using a module, since it could not understand which site is asking for updates.

Since site_key is a crypted hash derived from $base_url, you cannot get the value of $base_url from its hash; that is how hash works. Hashes are used to save the passwords in the database; nobody can get the value of the password from the hash saved in the database.


Add javascript to a content type form in Drupal 7

This:

node-accommodation-form

Is the HTML ID of the form, found in $form['#id'] (confusing I know). You need the internal ID, which is

node_accommodation_form

As in:

function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node_accommodation_form':

Using #attached, as mentioned in comments, is far preferable to drupal_add_js() when you get to that part.

As an aside, you may find coming back to your code later on a bit easier if you separate out your form alters like so:

function MYMODULE_form_node_accommodation_form_alter(&$form, &$form_state, $form_id) {
  // Logic specific to the accommodation node form, no need to check form ID.
}

Also, as noted in another answer, theme hooks are only run when the theme is actually in use. So if you're using the admin theme for your node edit forms, your code will never run. If that's the case, you need to move the logic to a module.


Status report says database out of date, but update.php and drush say up-to-date

Here are the steps I took to solve the problem. @rooby gave the URL that helped to determine which module.

As you can read on the given URL (https://www.drupal.org/node/1263908) the problem is caused by a module having a version of -1 in the system table. The URL has instructions how to find out which one is acting up. I've followed the one in this comment: https://www.drupal.org/node/1263908#comment-9059569

This basically means:

open [drupalroot]/modules/system/system.install
find the line $requirements['update']['severity'] = REQUIREMENT_ERROR; In drupal 7.39 this is on line 412
add the watchdog line as described: watchdog('module update db', $module); // <-ADDED THIS LINE
open the status page again
now open the watchdog page. You should see a line that starts with 'module update db'. After it you can read the module that causes the problem.

In my case that was environment_indicator. I'm no PHP developer, so I solved the problem by opening the database in Sequel Pro and checking the version column of the system table of this module.

The file environment_indicator.install shows several updates, the first one creating a table. Since the table was present, I entered its version number (7200) in the system table. Now I was able to run the update.php which showed there were 2 updates. I let it update the database, which ran without problems.

When opening the status page everything was fine and I deleted the watchdog line from the system.install file.

I'm just curious why update.php doesn't find any updates, while status page does.


There's an issue that does exactly what I was asking for. Problem solved!


Commerce Search API with Custom field search

I have added related fields to the index configuration page under the "fields" tab. First have added the store then the zip code.


Undo/redo drupal console generate:plugin:block?

I think I found the answer myself:

 drupal config:delete active block.block.my_block

(For my specific case)  Good luck finding the configuration name.  There's no listing from the console.  I had to export the whole damn thing to a directory and grep for it.


Can we add different fields to instances of the same entity?

This single entity will use all of the fields you attach to it – it's still 1 instance (what we call a 'bundle') of an entity.

If you want to conditionally allow fields to be displayed on the entity edit form (or the display of the entity) use the Conditional Fields module: http://drupal.org/project/conditional_fields

If you really want to use different sets of fields, you need 2 different bundles, i.e. a "city" entity of bundle "foo" and a "city" entity of bundle "bar".


Webform entity select submission displaying different result than element

I was able to get the desired result for the book title by using twig and string manipulation.

I noticed {{ item.label }} returns MyBookFieldCollection 0 of Dune. MyBookFieldCollection is the name of the field collection and 0 represents the selected item. There will not be more than five items in a given collection. I can remove the start of the string using {{ item.label[27:] }} and this returns a value of Dune.

Here is the modified element source:

book_title:
  '#type': entity_select
  '#title': 'Book Title'
  '#select2': true
  '#format': custom
  '#format_html': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#format_text': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#target_type': field_collection_item
  '#selection_handler': views
  '#selection_settings':
    view:
      view_name: entity_reference_for_form
      display_name: entity_reference_1
      arguments: {  }

This outputs Dune - 9780441013593 - Paperback in the form submission.


A PHP segmentation violation is a PHP bug. You can not solve this at the PHP, or Drupal level, this needs a bug report for PHP itself, here.

Segmentation violation means that PHP somehow mismanaged it's memory, which is impossible to directly cause with PHP code, since pointers aren't available.

Notice though that there are two releases of 5.3 after the one you're running, upgrading should be your action, as a problem in method_exists() should have gotten a lot of attention, and is hopefully already fixed.


How can I display a taxonomy term's parent ID in Views?

Thanks Clive! Yes - I just found the solution. I took the following steps:

Under "Relationships" add "Parent term" and untick "Require relationship"
Under "Fields" add "Taxonomy term: Term ID" and under that select from the "Relationship" pulldown "Parent"

Since the relationship is not required, it will correctly show both top-level terms and all children term. Top-level terms has parent ID of 0.


In Drupal 7, The front page is normally set via system_site_information_settings().  It is an unaliased URL, so it is best to use the API.  I would do it as:

$home = url(variable_get('site_frontpage', 'node'), array('absolute' => TRUE));

In Drupal 8, there is a special route <front> that you can use with the Url() object

use \Drupal\Core\Url;

$home = Url::fromRoute('<front>')->setAbsolute()->toString();

However, in most circumstances you don't need to explicitly render out Url() objects as strings; you can just use the object itself.


How can I generate a list of the numbers of users with Roles B, C, and D that have Role A?

To do this, I ended up having to make several views, each with a filter of Role = A, etc., as suggested by Praveen S's comment.


How do I list modules on my site that are not covered by the Drupal security advisory policy?

I'm not aware of a report (a good home for such a thing might be the Site Audit project? (#2882555)

Here's a very quick report for D7 that shows:

Custom modules
Modules without a release covered by Security Policy

You can download this and use it with drush scr, or copy it for drush eval directly. Feel free to improve on it!

<?php
$projects = update_get_available(true);
$uncovered = [];
foreach ($projects as $name => $project) {
  if (!isset($project["releases"])) {
    $uncovered[$name] = "No releases found";
  }
  else {
    $latest_release = reset($project["releases"]);
    if (!empty($latest_release["security"])) {
      $uncovered[$name] = $latest_release["security"];
    }
  }
};
print_r($uncovered);


Node Reference Argument In loadByProperties() while Creating API

Thanks to 4k4

I modified my code to

    $entities = \Drupal::entityTypeManager()->getStorage('node')-
    >loadByProperties(['field_author' => '469']);

Where 469 is the nid of my Referenced Node


Which Drupal function inserts the data in the history table?

It is node_tag_new(), the function that is part of the Node module (line 299 of that file in Drupal 7).

/**
 * Updates the 'last viewed' timestamp of the specified node for current user.
 *
 * @param $node
 *   A node object.
 */
function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')
      ->key(array(
        'uid' => $user->uid,
        'nid' => $node->nid,
      ))
      ->fields(array('timestamp' => REQUEST_TIME))
      ->execute();
   }
}

Here's the same function in Drupal 6.

/**
 * Update the 'last viewed' timestamp of the specified node for current user.
 */
function node_tag_new($nid) {
  global $user;

  if ($user->uid) {
    if (node_last_viewed($nid)) {
      db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
    }
    else {
      @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
    }
  }
}

The function is called by node_show(), which uses the following code.

// Update the history table, stating that this user viewed this node.
node_tag_new($node);

As said from that comment, the purpose of the function call is updating the history table to record the fact the current user viewed the node.


Add class on row by modifying view.tpl.php file

I tested it out, and it didn't work for me....until I cleared the cache!

Just go to yoursite.com/admin/config/development/performance/ and click "clear all caches".

Update: since clearing the cache didn't work, check if you are editing the right file: delete all the code in the tpl.php file.

If the view disappears, you are editing the right file.
If it still shows, close your editor window and select the file again.


So, you have a variable. Lets say $object, and you call dsm, dpm, dvm or one of devel's other debugging functions to inspect it:

$node = node_load(1);
dpm($node);

Devel gives you something back like this:

object(stdClass)[79]
  public 'nid' => string '1' (length=1)
  public 'type' => string 'profile' (length=7)
  public 'language' => string '' (length=0)
  ...

The stdClass part just means that its a generic empty class, not any particular type of object. So, you can access all of its properties using standard object notation, but there are no object specific functions that you can call from the object.

So, for example, you can call:

$nid = $node->nid;
$type = $node->type;

But you can't do anything like this:

$result = $node->some_special_node_function();

Because there are no special node functions.

In Drupal, most things that get retuned as objects are just generic objects without any type special attributes or functions.


How does a view (/admin/build/views/) relate to a .tpl file

Actually, a view will use many template files (which you can override in a theme if desired); it depends a lot on how you configured your view (e.g. style, content).

The most useful information can be found when you're configuring your View. Just click Theme: Information in the Basic settings pane of your View, and the View itself will give you a list of tpl.php files that are used for rendering. Don't forget that there isn't only one tpl.php - there are many, and they wrap each other a lot (they're nested). Reading about generic Drupal theming will help a lot. The same rendering basics are used for Views.

If you want a template file for one specific View, look at the suggestions given by "Theme: Information." You can override any template file, for a specific View only (identified by its machine-name). This is probably what you're asking for, actually.

A good link on the subject is Theming Views.


Redirect to 404 page, if URL alias does not exist

You could redirect 301 the specific node id's to 404 using .htaccess file

Redirect 301 /ar/node/123 /page-not-found


How to position Image field in body content

Try the CSS Injector module and use CSS float property or other properties on the  .class or #id of the image field or body/description/captions.


The "commerce-order:mail" token will only show the user email associated with whoever is logged in and submitting the order, while the webform email value from the token [data:e_mail-value] is a component in the webform submission and generally stores the submission with the author/owner being "anonymous".

If your webform automatically redirects to the commerce cart/checkout, then I'd suggest forcing the user to be logged in before they even fill out the webform and hit submit. Then you can set the default value of the webform email field with a token for the email of current user and hide it from view.
Otherwise, you'll need to write custom functionality to somehow store and pass the webform submitted data:e_mail-value to a hidden field associated with the order itself in the checkout process.

Also as a reminder for the "To" address field in the workflow rule for sending an email, you need to format it to comply with RFC 2822- by wrapping the email address string with <>.  For example:

Should you want to send to multiple recipients, then you'll want a comma separated list of emails, each wrapped in <>.


Setting cache max-age to 0 has no effect on Block built using BlockBase?

This is a known problem for anonymous requests, see this issue PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF.

Until this is resolved, put this trigger in your block build():

\Drupal::service('page_cache_kill_switch')->trigger();


How to change menu links items title programitically?

Use theme_link function for altering your link markup. I have recently come across a scenario where I needed to change my account name to user name I did with the following code.

function THEMENAME_link($variables) {
  if ($variables['text'] == "My account") {
    $variables['text'] = $GLOBALS['user']->name;
  }

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


public files config in settings.php creates .htaccess file

The main culprit was extra trailing / in the files path in settings.php file. Which I changed to

$conf['file_public_path'] = 'sites/default/files';
$conf['file_temporary_path'] = '/tmp';

And deleted the .htaccess file, now the files inside sites/default/files are readbale by server even after clearing the cache.


Recover the field from one Drupal page to another

First off, dsm().   You have to install a devel module.  In you code if you do dsm($user) then it would show you a nice user interface of the $user object/array

The location to the user picture (or avatar) is in your $user->picture object.  If $user array is not available, then you can do global $user;


Programmatically remove content from a group

I believe that function was overlooked by the developers. In the issues queue for the Group module, which is what your error message refers to, I can see that the inverse of addMember(), removeMember(), was added later in the project's life. It seems reasonable to suppose that the inverse of addContent() was also overlooked, with the only difference being that it has remained unimplemented to this day.

There are no functions with names hinting at content-removing behaviour evident in the module's GroupInterface definition, so I recommend opening a new issue with the project to let them know about the gap.


How to return content with shortcodes from drupal module?

Shortcodes are processed with a filter, so the most reliable way to get what you need would be:

Create a new input format (shortcodes_only or something)
Enable and configure the shortcodes filter for that format, but disable any HTML or other processing that you don't want to apply to your string
Process the string before adding it to the render array like so:

$markup = check_markup($markup, 'shortcodes_only');

If you need to do it programatically it's a bit of a hack, as the shortcode processing code isn't completely decoupled from the filter concept. You need to mock a filter object and give it a couple of properties (a dummy format ID and an array of shortcodes keyed by ID, with a boolean value indicating each shortcode's status).

This is untested but should get you close:

$filter = new stdClass();
$filter->format = 'not_a_real_format';
$filter->settings = array_fill_keys(array_keys(shortcode_list_all()), 1);
$markup = _shortcode_process($markup, $filter);

If you choose the programmatic method, there's something else to bear in mind: by convention, any function whose name begins with an underscore is considered to be private to the module, and its implementation is subject to change in future releases without warning (potentially breaking your code in unpredictable ways). It's probably not that likely in this case, but you never know.


You can use different formatters for the exact same field when you are in a different context. So, while the full node is shown, you can use the full date (as set in CT's Manage Display). When displaying the date in views, you can use the time ago. For correct grouping, add the date field once more, exclude it from display, then set the formatter to a custom one which only shows the year and finally use that rendered output to group the view's rows.


How do I add Google +1 to Addthis Button?

There is a tutorial http://www.addthis.com/features/google-plus1-button

Anyway, +1 is not a sharing service, I'm not sure that Addthis will add this (like there is no Facebook Like button). You can use the Customize service that addthis.module supports to add code described here.


How to access single field in views-view-fields.html.twig

You can retrieve it with:

{{ fields.machine_name_of_field.content }}

So for example if your field is a title with:

{{ fields.title.content }}

Install devel to list key / values inside the array of fields with:

{{ dsm(fields) }}


Filter condition for entity reference field

you can use Views Reference Filter Veiw Reference Filter Module for reference fileds.


How is the class loader set to load the files containing classes?

For modules with composer dependencies in 7.x, try https://www.drupal.org/project/composer_manager. If you want to support modules with PSR-4 autoloading, see https://www.drupal.org/project/registry_autoload (integrates with the standard 7.x class loading registry) or https://www.drupal.org/project/xautoload.

That said, the code you pasted is just the APCu wrapper for the class loader. The actually relevant line is this, in \Drupal\Core\DrupalKernel::discoverServiceProviders():

$this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));

What it does is register a PSR-4 namespace for each module with composer. Below that, everything follows the standard rules.

But composer dependencies is something else, that's handled automatically by composer's autoload.php and all the files that that then loads. Which is basically what composer_manager does, load the generated autoload.php file.


Problem with Unorganized content on page

Since you tagged your question with "Views", I assume your screenprint is created via a view. And the view itself relates to some sort of entities like nodes, products, whatever.

If that's the case, decide about the "sort field" that you want to use in your view, and adapt it to fit your needs. If you cannot find any appropriate field that you want to use for such sorting, then just add an extra field (named something like sequence nr, and like an integer of say 4 digits). Then edit each of your entities to assign a relevant sequence nr, and use that as the sort field for your view.

BTW, this is true for pretty much any Drupal release.

PS: as per the "drag the item" in your question, it could well be that you're using the "DraggableViews" module to create such view.


How to force a selection in one field if another webform field is a certain value

You could use normal conditional fields for that. Simply create two "How many t-shirts" fields, one with only one enabled option, second with both available. Then, make them visible depending on value in "Membership type". It is possible since Webform version 7.x-4.0-alpha2, and earlier using this module.

Sure, this will create two separate entries in results, and only one filled, but if your traffic is low, it will be easy to read. And if it's high, you can aggregate easily in your warehouse handling software. Or in spreadsheet of your choice, after export.


Jeff Eaton provides a pretty comprehensive post in Understanding 8: Where Drupal Is and Where it's Going, where he discusses these differences (at least in Drupal terms).

Drupal as a Framework

  The foundation of that stack is the essential "web framework" code for
  Drupal. It's the portion of Drupal that provides essential services
  any web application would require. Rendering data into HTML and other
  formats, identifying and loading plugins, handling HTTP requests and
  responses, caching, database and storage access, and so on all live at
  this layer...

Drupal as a Platform (i.e CMS)

  Moving up in the stack, we find the "building blocks" layer that Catch
  referred to as the "Platform" in his blog post. This is where we begin
  to encounter Drupal-specific approaches to CMS and web building
  problems. The Entity system, users, nodes, taxonomy terms and
  vocabularies, actions, roles and permissions, FieldAPI, text formats,
  and our concept of "Blocks and regions" live here, and can be used to
  assemble features and functionality. Reusable user interface tools and
  UX components are also here: things like drag-and-drop tools, Drupal
  7's Overlay mechanism, and so on are all reusable tools used to craft
  usable interfaces.

These differences and more, are also covered in his DrupalCon London Presentation. Product, Framework, or Platform? What They Mean, And Why You Should Care

Essentially Drupal is both, a CMF and a CMS (and more) and why these discussions have come up recently in an effort for the community to define Drupal a bit more.


Prevent Multiple Form Submissions (Server side)

I had the exact same problem and managed to fix it using the Locking mechanisms from Drupal

In the validate function I used:

function mymodule_custom_form_validate($form, &$form_state){
  if (lock_acquire('your_custom_lock_name')) {
    // long operations here
  } else {
    form_set_error("", t("You submitted this form already."));
  }
}

And in the submit function I released the lock:

function mymodule_custom_form_submit($form, &$form_state){
  // submit code
  lock_release('your_custom_lock_name');
}


Enable the 'PHP Filter' module available in drupal core:

Go to modules list: /admin/modules and than in Core you will find PHP filter module as indicated below, so just enable it.


How to disallow node authors to change node content if comments were submitted for that node?

If coding this is an option, you should look at hook_node_prepare.
As mentioned there on the first line:

  Act on a node object about to be shown on the add/edit form.

A code snippet idea that could do this for you:

function SOME_MODULE_node_prepare($node) {
  if (isset($node->nid) && $node->type == 'YOUR_CONTENT_TYPE' && $node->comment_count> 0) {
    drupal_set_message('You cannot alter this node anymore', 'warning');
    drupal_goto('node/' . $node->nid);
  }
}

Good luck!


Hide blocks from the administration page according to the user role

To make this work, you will need a custom page, the "admin / structure / block" won't do the work.


Should I share the same image style as much as possible or create different styles for each size?

I would zoom out the thinking and try to get two things into perspective:

user interaction "paths" and which images they "touch"
graphics design decision for the image sizes

What is the likeliest user scenario for downloading each image size?

What is the path your users take through the site that would trigger downloading those image sizes? Will the user see many of the 100px images in a list, then click through to only one that would display the 120px one, and then clicking on that one so 150px is displayed in a lightbox?

Aim to reduce downloaded data bandwidth

Diagram some likely user paths (if you have some analytics on your site you probably already know this, better to get data instead of making assumptions) and calculate how many Kb/Mb of image data users would most often download under those paths.

Compare if the data load is larger with 1, 2 or 3 sizes for those "user paths".

If you have a lot of mobile visitors the data size is super important. Your goal should be to provide meaningful content and experience while keeping the data exchange to a minimum.

If users click through a lot and you end up serving the largest 150px size very often, it may not be useful to have the smaller sizes, better use 150px and size down with CSS.

If your images are such that with the change in pixel size the file sizes also vary greatly (if the 100px image is disproportionately smaller in file size than the 150px one) then it may be useful to have a smaller size, especially if users mostly view "list pages" with smaller images and don't click through, so they rarely see the larger image.

Don't forget server resources and requests

The downloaded data size isn't the only criteria, reusing the same size pulls it out of cache, so saved bandwidth again, fewer server requests.

If you upload a lot of images and have a lot of image styles, server processing power is being used for that and can get congested in extreme cases. You also end up with a lot of data on the disk so storage is also important, as mentioned in comments.

Graphics design refinement

Having so many close-but-not-identical style elements might be a sign you could improve your graphics design by making different design elements more consistent. How justified is it to display some image type in that many different sizes, is there a need for it?

Taking a blind guess I don't expect a lot of difference between 100px, 120px and 150px so I would try and see whether I'd need 100px and 120px at all, maybe 120px and 150px would be enough? 3 sizes do seem excessive here, 3 sizes are usually used when there is a much larger difference between them (100px, 500px, hero).

I have a real-world example where I disabled image sizes completely because the uploaded originals were so well optimized that the smaller versions made by Image styles were bigger in file size than the large pixel original, even after using custom imagemagick rules!


How to create block to list all children of an entity?

Finally, I figured it out!
First, I learned more about contextual filters and relationships, and what they each mean and do (relationships basically relates to the FROM query, contextual filters to the WHERE query)
https://www.youtube.com/watch?v=mRWtpcUm9pI
Another user had a similar question and solved it like so:
https://www.drupal.org/project/views/issues/1724396
So all I had to do was:
/admin/structure/views/add

show content of type "Locations"
Create a block

Then under "advanced" add a contextual filter, check "parent_location (field_parent_location)", press the button to "Add and configure".
Then under "When no filter is available" say "provide a default value" and select "content ID from URL"
Hit apply, save the view.
Under /admin/structure/block place the block to the content region and make it visible for Locations.
This was super simple! :-)


Line breaks are stripped by ckeditor after saving a node programmatically

I would try disabling the Advanced Content Filter in CKEditor as a starting point.

In a typical scenario, most people are exclusively using CKEditor to set and update their field values, so the content stays exactly the same between viewing and editing the node, which is the behavior you're expecting.

However, since you are setting the field programmatically, when you edit the node it's the first time CKEditor is seeing the field value (i.e. the first time CKEditor filters are being run). CKEditor will filter and "correct" your HTML to its standards, so it's not safe to assume your field value will be untouched if it's the first time CKEditor is seeing it.

Your options are to 1) tweak how CKEditor filters your HTML, or 2) conform the HTML you're programmatically saving to the CKEditor standards.


How can I change the published state of a node before it is saved with hook_entity_presave()?

I have tested with hook_entity_presave() and setPublished(0) and setPublished(FALSE) both worked.  So the issue is somewhere else.

If you have workbench moderation installed, you may need to set it to one of your moderation states that set it to unpublished.

See admin/structure/workbench-moderation/states

$entity->set('moderation_state', 'draft');

or

$entity->set('moderation_state', 'unpublished');

or perhaps a custom moderation state.


How to change datatype of field in database table from varchar to int?

You must have some error message if the conversion is not accepted.

You first have to validate that this field is not a key or an index. See the db_change_field documentation about this.

After, I think 255 is not a valid value for the size key. The Schema API documentation tell :

  'size': The data size: 'tiny', 'small', 'medium', 'normal', 'big'.
  This is a hint about the largest value the field will store and
  determines which of the database engine specific datatypes will be
  used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT). 'normal', the
  default, selects the base type (e.g. on MySQL, INT, VARCHAR, BLOB,
  etc.). Not all sizes are available for all data types. See
  DatabaseSchema::getFieldTypeMap() for possible combinations.

And finally, I'm not sure if the DB engine can support the VARCHAR to INT conversion. Then it means your column will be empty and cannot support the 'not null' => TRUE property.

Maybe you have to do this in more than one step.


How to prevent data loss from custom field when using Views Bulk Operations?

The action does this:

  $node->status = NODE_PUBLISHED;
  entity_save('node', $node);

So the fail is not coming from VBO, you have a bug in your field code. Hard to tell where without looking at it.


For nodes image field you can use Field Slideshow module with your JCarousel
it solves your problem


How to add contextual links to the main content block?

Contextual module (core) will preprocess the block renderable array and turn $block->content['#contextual_links'] into the block template $title_suffix using the contextual_links element type (see contextual_element_info). See contextual_preprocess for the implementation of this behavior.

While block module relies on _block_get_renderable_array for performance reasons, contextual links example module (from the examples package) shows an example of setting #contextual_links on hook_block_view.

As for CCL, it relies on hook_contextual_links_view_alter which will only alter or add links if there is already a #contextual_links element in the renderable array. The main content block doesn't get the default 'Configure block' contextual link (see _block_get_renderable_array), and therefore CCL doesn't affect it by default. Let's just add the default contextual link:

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function MYMODULE_block_view_system_main_alter(&$data, $block) {
  if (user_access('access contextual links')) {
    $data['content']['#contextual_links']['block'] = array(
      'admin/structure/block/manage',
      array('system', 'main'),
    );
  }
}


I've figured it out.  If I import the ID field as GUID when adding the taxomony terms, then I can select that as an option when I import into my content type :)


Is it possible to add css class to the page's body tag with rules when certain conditions are met?

Yes - the Context module allows you to add CSS classes to the body (Theme HTML condition) based on whatever events you specify. You would then combine this with the Context Rules module which extends Context to allow for context events from Rules.


How to get URL parameters values inside access callback

You can specify arguments in the URL path you are registering by using the "%" character:

$items['members/get-certificate/%'] = array( ... );

You can then pass the argument value to your page callback and/or your access callback by specifying which segment of the URL path to pass. The segments are the parts of the path separated by "/" characters, and you start counting them from 0. So to pass the value of '%' from the above example, you will specify the integer value 2 in your 'access arguments' value:

  'access arguments' => array('access content', 2),

So when a user attempts to access the path 'members/get-certificate/30', the access callback will be passed the argument values 'access content' and '30'. The callback you provided would then have the correct intended values.

Here then is your hook_menu item definition, corrected as outlined above:

$items['members/get-certificate/%'] = array(
    'page callback'    => 'members_get_certificate',
    'access callback' => 'members_access_get_certificate',
    'access arguments' => array('access content', 2),
    'type' => MENU_CALLBACK,
    );


How to show "field-image" in search page?

If you're using default core search, you can modify "Search result" display there.


Its problem with my custom module. Wherever I am installing that module, it is creating a mess. I am trying to sort out the issue with my module.

This is due to the menu routing problem in my custom module. Please see the below link: https://www.drupal.org/node/2635308


It depends on what you want/need. Not only for content types, for theming generally; my suggestions:

For little/cosmetic changes(font, color etc.) and basic layout settings you can use node-type-yourcontenttypename class and style with CSS.
For moderate+ structural and visual needs you can use Views, Context, Panels  etc. alone or combined(and CSS of course).
For the things you can't achieve without dirtying your hands; you can create special template files for pages, nodes, block, views etc.
For the things you can't achieve with above ways; you can hack core, module, theme files. But this would be last and worst way to go.

You can do lot of things with 1, most of things with 1+2 and almost everything with 1+2+3.


I post my answer for anyone who is facing this problem. After all it worked by some changes:

newest comments

oldest commenst

most popular comments

<?php print views_embed_view('comments_views', 'block_3'); ?>

and jQuery code is:

function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.yoursitename.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views', //view name
        view_display_id: 'block_3', //view display
        view_args: nid,   //view contexuall filter
    },
    dataType: 'json',
    success: function(response){
        //alert(response[1].data);
        $('#cm').html(response[1].data);
    }
});
    return false;
}

for each of the sort functions above it must be exist.


Show entries in view only if other nodes with same term reference exist

After sifting through several modules, I decided that it's easiest to achieve this with theme pre-processing. Here is what I did:

I used the drupal 7 schema that I created years ago (http://upsitesweb.com/blog/2011/06/drupal-7-database-schema), to figure out which tables to join. The vocabulary I am using has the vid 14. I pre-processed the view and checked for each line, whether the corresponding node in the details content type exists, rewrite the view entries to only contain matched entries.

It must be possible to also achieve the same with contributed modules. However, it was faster and more efficient to use views pre-rendering instead, especially, since other aspects of this view are getting pre-rendered anyway.

function theme_views_pre_render(&$view) {
   if ($view->name == "summary_details") { //filtering summary entries without detail
      $nids = array(); // array of nodes
      $nodeswithdetails = array(); // manipulated results
      foreach($view->result as $key => $result) // check each node of the result array on it's nid
      {
        $nid = $result->nid;
        $return = theme_ensure_details($nid);
        if ($return == 1) {
           $nodeswithdetails[] = $view->result[$key];
        }
      }
      $view->result = $nodeswithdetails;
   }
}

function theme_ensure_details($nid) {

   $results = db_query('SELECT s.nid AS sum_nid FROM {node} n, {node} s, '
                      .' {taxonomy_index} t, {taxonomy_index} t1, '
                      .' {taxonomy_term_data} td WHERE t.tid=t1.tid '
                      .' AND t.tid=td.tid AND td.vid=14 AND n.type=:dettype '
                      .' AND n.nid=t.nid and s.type=:sumtype AND s.nid=t1.nid '
                      .' AND s.nid= :nid',
         array(':nid' => $nid,':revtype' => 'details', ':reptype' => 'summary'));

    $found = 0;
    foreach ($results as $row) {
       if ($row->sum_nid == $nid) {
       $found= 1;
    }
  }
  return $found;
}


'Page not found' but hook_menu() is correct!

If you're getting a 404 it's due to one of the following:

You haven't cleared Drupal's cache since you implemented the menu item, OR
Your event_load() function is returning FALSE/NULL for the provided ID, OR
The function event_load() doesn't actually exist

Judging from the rest of your function/file names (events_view, events.pages.inc) your module is called events so your router load function will probably be called events_load() (note the additional s).

If that's true then you need to change your menu item to match that:

$items['events/%events'] = array(
  // ...

And clear Drupal's cache to pick up the change.


I need get the MID for specific Entity Drupal 8

If you want to load by uuid, you can use this:

\Drupal::service('entity.repository')->loadEntityByUuid($entity_type_id, $uuid);


I have found a solution, its so simple. Just have to tweak display setting for the rate field in managed display to "user's vote". Enable permission to vote for reviewer only.

For editor, I have used hook_node_view and displayed average rating. Since editor has no permission to vote, he can only see the average votes on the field in the node view. While reviewer can see his vote as per display setting.


n.b. The error message says that your memory limit is 32MB, not 128MB.  The 128MB setting must be for your web server.  Check the php.ini for PHP CLI; it's quoted in the output of Drush status, above:  /Applications/MAMP/bin/php/php5.4.10/conf/php.ini.  You should find that memory_limit is 32M, or perhaps unset.  Set it to 128M, or perhaps even 256M or more, and you should be fine.


Could not find package with stability dev in a version installable using your PHP version

The package that triggers the error is  drupalcommerce/project-base. If you check the composer information for that package you see:

  "require": {
        "php": ">=7.0.8",
        "ext-curl": "*",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        [...]

As you see, it requires PHP 7.0.8 or higher. You have PHP 5.6.40. You should upgrade your PHP, not only because this package but also because PHP 7.x is much faster and PHP 5.6 is not recommended anymore, not to forget that PHP 5.6 end of life was hit a year ago, on the beginning of 2019.


How to change the "Add new comment" message for custom comment form?

The Add new comment header is a part of theme layer.

You can copy your theme's existing comment template (e.g. core/themes/classy/templates/field/field--comment.html.twig if you're using a theme that utilizes the base classy theme) over to your theme's template dir and rename it to match your specified field (e.g. field--field-my_custom_comment_machinename.html.twig). If you're not familiar with this, enable Twig template debugging.

Once you've create a copy of the template, you can then edit template header as you see fit.


How can I make the list of exposed filters hide options with no existing nodes?

I am not sure if that can be done with views. Even if it can be done, I am sure it will take a considerable amount of coding and I am not sure if it will be performant enough(might reduce the performance).

This can be done easily with Apache Solr module.

  Faceted search is supported if you use the facet API module. Facets
  will be available for you ranging from content author to taxonomy to
  arbitrary fields.

When you enable facet API with apache solr module, you should get the facets(similar to filters). Facets will be displayed only if there are some results which have the value of the facet in their node.

Note : You will need to set up a Java server to have the Apache Solr running.


How to embed all comments and comment form to other website

I think the best solution is to expose the comments as a REST resource on example1.com. You can achieve this with the services module (you will probably have to create a custom resource).

Then on example2.com execute a GET request on the REST resource and display the comments.

Edit: If you want to fetch the comments per node you will have to add a query param to the resource containing the node ID for which you want to fetch the comments.


how to upload an image of product in drupal commerce

Finally, I found the way, field_product_image can only accept array value. Here is my code,

function commerce_services_product_create($data, $flatten_fields) {
    $status =1;
    $commerce_price = array();

    $sku = $data['sku'];
    $title = $data['title'];
    $type = $data['type'];
    $commerce_price = $data['commerce_price'];
    $price = $commerce_price['amount'];

    $wrapper = entity_metadata_wrapper('commerce_product',  commerce_product_new('product'));
    $properties = entity_get_property_info('commerce_product');

    $wrapper->title = $title;
    $wrapper->sku = $sku;
    $wrapper->commerce_price->amount = $price;    // Price in minors units 500 = 5$
    $wrapper->commerce_price->currency_code = 'MMK';
    $wrapper->cmp_store = 2;
    $wrapper->field_product_color = 106;

    $file = file_save_data(file_get_contents('C:\\Users\\ASUSS\\Desktop\\Nexus_5_(1).jpg'), 'public://products/Nexus_5_(2).jpg');
    $image_val = array(
        array(
            'fid' => $file->fid,
            'title' => $file->filename,
            'filename' => $file->filename,
            'filepath' => $file->filepath,
            'filesize' => $file->filesize
        ),
    );

    $wrapper->field_product_image = $image_val;

    try{
        $wrapper->save();
        $result = "success!" ;
    }catch(Exception $ex){
        $result = "not success! -> ". $ex;
    }

    $reply= (array('status' => $status,'result' => $result) );
    return $reply;
}

Thanks,


Rule to send an email on node save printing a field value of a referenced node

Go to /admin/config/workflow/rules/reaction/add and create a rule. Then in rules action section under system category select Send email. Then you will be redirect to a new page, here you can define the subject,content,recipient of mail. By using Replacement Patterns you can add dynamic variable in to mail content.


Setting value of form element from $form_state not working

This:

(isset($values['element1']))

will always return TRUE, since the form element exists, and therefore a value is always passed to the submit hander, even when the value is empty.

You likely want this:

!empty($values['element1'])


How to make 2 or 3 xml sitemaps in drupal for example for different taxonomies?

I suggest installing the Views Data Export module. It will allow you to create XML pages from your taxonomy and as many as you want.

I would create one view and 4 page displays with the varying filters to generate your pages.  Then change the output to XML.

I looked over the XML Sitemap, and the error you are experiencing seems to be something they are trying to troubleshoot. You can follow along there, or try some of their methods.


Assign field permission to individual users?

You can manage this with #access if you're using hook_form_alter to make and manage the fields.

  Description: Whether the element is accessible or not; when FALSE, the
  element is not rendered and the user submitted value is not taken into
  consideration.

Another idea is get help of access callback in hook_menu

  "access callback": A function returning TRUE if the user has access
  rights to this menu item, and FALSE if not. It can also be a boolean
  constant instead of a function, and you can also use numeric values
  (will be cast to boolean). Defaults to user_access() unless a value is
  inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
  items can inherit access callbacks. To use the user_access() default
  callback, you must specify the permission to check as 'access
  arguments'

The idea is to make a function that resolves permissions for individual user for certain pages.


AJAX Views arguments: how to specify quantity of results and what are other options that can be used?

Previous experience tells me with Drupal 7 that if I don't find an answer after a day of research then people probably haven't approached it like this and I'm unlikely to find much assistance, so I'm doing the custom menu item approach instead, as people have suggested in the discussions I've read.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items['ajax/%'] = array(
        'page callback' => 'get_view_with_args_get_ajax',
        'page arguments' => array(1),
        'type' => MENU_CALLBACK,
        'delivery callback' => 'ajax_deliver',
        'access arguments' => array('access content'),
    );

    [....etc....]

function get_view_with_args_get_ajax($args) {
    views_get_view($name);
    return 'Args: ' . $args;
}


It may be that your Apache vhost and/or .htaccess need updating.

Yosemite uses Apache 2.4, which replaces some access control statements used in 2.2 and prior.

'Allow from all' becomes 'Require all granted'

'Deny from all' becomes 'Require all denied'

See htaccess protections do not work on Apache 2.4 without mod_access_compat for the ongoing Drupal 7 core discussion. Upgrading to 2.4 from 2.2 gives some guidance on upgrading configurations.


How can I copy some content from one site to another site?

You'll need to use Drupal Core's migration module with Drupal 8 migration (source).

  This is an Migrate source to import Data from a Drupal 8 site.

If you're not familiar with creating custom migrations, you'll need to read up on that. Also read the README file.


filter homepage content based on term id

Okay, now i understand your problem!

When a user clicks on a link in the "countries" page, he will see the standard taxonomy term "view". But i guess you want him to see your normal "homepage" BUT with filtered content.

You have two options:

Alter the taxonomy term page.
Use contextual filter on the "homepage" and change the links on the "countries" page according to use the filter.

In my opinion you should clearly prefer option two. Also have a look at the view "Glossary", which should be included, but not activated out of the box, this should help you a lot in configuration!


How can I find out the machine names of user variables?

All of the user variables are located in configuration->People->Account Settings->Manage Fields. So simply look at them over there.


It is not necessary to write an entire Drush command just to run some php code.  Use:

drush php-eval '$a = callSomeFunction(); print $a;'

or:

drush php-script /path/to/script.php

Drush will bootstrap your site and run your code.


Use the full name instead of the user name as author of articles

There's a module for that - RealName

  The RealName module allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

EDIT - since your new to Drupal you might want to checkout - http://drupalmodules.com/ - great way of finding modules that you might need.


Add block programmatically in the right region

I think you need to set 'status'.
eg.

function events_block_info () {
    return [
        'events_list' => [
            'info'       => "Events list",
            'status'     => TRUE,
            'region'     => 'content_post',
            'visibility' => BLOCK_VISIBILITY_NOTLISTED
        ]
    ];
}


How to set a mini panel to display node fields?

As per Beebee comment, you should first try removing the "Node" required context and see if that renders the block. Make it work at the most basic level possible and then add various customisations and contexts.


Link To Already Defined Path In Menu Using hook_menu()

You can best use hook_menu_alter(), which should be used when "Additional items may be added, or existing items altered."

In custom_node_add.module :

function custom_node_add_menu_alter(&$items) {
  if (aray_key_exists) { //some sanity checking;
    $items['node/add']['page callback'] = 'custom_node_add_page'
  }
}

function custom_node_add_page() {
  return t("Hello World! This is content on my node/add page");
}


I would second the comment on trying out Views. You should be able to achieve what you want with the menu tabs and a specific calendar on that page with Views. Maybe try checking out the documentation. Without more detail in your question it is hard to say, but I'm pretty sure you don't need to make a custom module to do what you have written so far.

Also you probably should also specify which version of Drupal you are using. I'm assuming 7 but it is always better to let people know.


How to display node image in page header for custom theme?

You can find @var $node on page.tpl.php. you can display your field using this code.

<?php
if(isset($node->field_review_nationality) && !empty($node->field_review_nationality['und'][0]['uri'])) {
   <img src="<?php print file_create_url($node->field_review_nationality['und'][0]['uri']); ?>"/>
}
?>

If you have a style of the image then you can display using below code.

<?php print theme('image_style', array('path' => $node->field_review_nationality['und'][0]['uri'], 'style_name' => [STYLE NAME])); ?>


How to use data in fields from one node to create a new node of different content type?

Have a look at the Node_convert module. From it's project page:

  adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). So that would be like your "Submit a photo" content type. When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago). In your case it'd be the "Look" content type.

By combining it with an access module such as Content Access (my preference) or Taxonomy Access Control you can make it more restrictive to give access to it. E.g. public (anybody) to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.


How to theme the user picture to appear in lightbox

An alternative approach to wrapping the user picture around the necessary  tag for lightbox, would be to append a custom CSS class to the user picture. Then navigate to /admin/config/user-interface/lightbox2/automatic (D7), down to custom class images and type in the name of the CSS class you chose before.


Migration of field_collection with migration_d2d

The answer is: the logic is not flowed, it is correct.
when you write your own custom migration module you can establish dependencies to other migrations that you have done via code or done via UI using migrate_ui or d2d_migrate_ui modules.
here is custom migration code that depends on a class generated by d2d_migrade_ui. this code worked for me:

$this->description = t('casey will migrate this field cllection even if it kills him!!!!!!');
// class of prviously imported node, this class name was generated by d2d_migrate module
// that is why the name is diffrent
$this->dependencies = array('7f4f1882cNodeorg_vote');

$query = $this->getConnection()
// start with the field that embeds the field_collection
->select('field_data_field_org_member_votes', 'nodeField')
->fields('nodeField', array('entity_id', 'field_org_member_votes_value', 'delta'))
->groupBy('nodeField.field_org_member_votes_value')
->orderBy('nodeField.entity_id')
->orderBy('nodeField.delta');

// join it to the fields that make up the field_collection, in my case there were 3 fields
$query->leftJoin('field_data_field_org_votes_member', 'member',
'nodeField.field_org_member_votes_value = member.entity_id');
$query->addField('member', 'field_org_votes_member_nid');

$query->leftJoin('field_data_field_org_votes_vote', 'vote',
'nodeField.field_org_member_votes_value = vote.entity_id');
$query->addField('vote', 'field_org_votes_vote_value');

$query->leftJoin('field_data_field_org_votes_majority', 'majority',
'nodeField.field_org_member_votes_value = majority.entity_id');
$query->addField('majority', 'field_org_votes_majority_value');

$this->source = new MigrateSourceSQL($query);

$this->destination = new MigrateDestinationFieldCollection(
    'field_org_member_votes',
    array('host_entity_type' => 'node')
);

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'field_org_member_votes_value' => array(
            'type' => 'int',
            'not null' => TRUE,
            'description' => 'Unique ID for each commitee vote',
            'alias' => 'nodeField',
    )
  ),
  MigrateDestinationFieldCollection::getKeySchema()
); //map END

$this->addFieldMapping('host_entity_id', 'entity_id') ->sourceMigration('7f4f1882cNodeorg_committee_vote');

$this->addFieldMapping('field_org_votes_member', 'field_org_votes_member') ->sourceMigration('7f4f1882cNodemember');
$this->addFieldMapping('field_org_votes_member:source_type') ->defaultValue('nid');

$this->addFieldMapping('field_org_votes_vote', 'field_org_votes_vote');

$this->addFieldMapping('field_org_votes_majority', 'field_org_votes_majority');

}//construct END

 function prepareRow($row) {
   // this is a good wat to test and make sure
   // A) you have connected to the db
   // B) you are getting proper values from your query
   // drush_print_r($row);
 }//prepareRow END
 function complete($row) {
   // drush_print_r($row);
 }
 public function prependTextNotes($row) {
     return 'Imported notes: ' . $row;
 }//prependTextNotes   END

 }


How to manually or programmatically delete a field?

You can also use drush to run field_delete_field(). Just run:

drush eval 'field_delete_field("yourfield")'


Filter for previous time periods in views

I would suggest
data between today 1 sec ago and yesterday


How to log in a user and inspect their role in a functional test?

You should be able to load the user object using user_load_by_name(), and then just make your assertions:

$account = user_load_by_name('foo');
$expected_roles = [
  'foo',
  'bar',
];
$this->assertEquals($expected_roles, $account->getRoles());

As an aside, it may be worth pursuing a mocked/testing authentication service for your tests. This way they don't rely on an external service, and will be more stable and reliable.


Add a Relationship Content: Taxonomy terms on node under Advanced section:

Select the vocabulary:

Add the filter Taxonomy term: Name.

Enter Value  Accountancy.

Click "And/Or, Rearrange" for the Filter Criteria and make it read like:

  Content: Published Yes AND (Content: Type = Accountancy OR (term) Taxonomy term: Name = Accountancy)


Undefined error: 0 OR Unable to load autoload.php. Drush now requires Composer

Drush switched to requiring composer. The documentation provides details on how to install both composer and drush, but it boils down to:

Install composer globally:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Install drush globally (for your user), you can specify the version:

composer global require drush/drush:6.*

Add the composer path to your path (in your .bashrc or .zshrc or other):

export PATH="$HOME/.composer/vendor/bin:$PATH"


If I recall correctly, you need $form['account']['name']['#attributes'].


Unfortunately, as suggested, programmatically changing the config won't work, as all dates will show empty. Which explains why it's locked in the UI.
You'll need to browse your DB and find the node__{field_date} table and manually remove the time part for all values.

Then make a sql export of this table.
Repeat the above with node_revision__{field_date}.
In Drupal, manage fields, delete your field_date. Recreate field_date with Date only. Import your sql db table exports you had made.
Flush cache in Drupal.


How to get the url of a file field of a given node?

First you need to load it with the fid :

  $file = \Drupal\file\Entity\File::load($fid);

  And after :

  $imageSRC = file_create_url($file->getFileUri());


This is late, but other people will come here (just like I did).

I had to go into the profile module source code to find this, but I guess it's obvious when you think about it:

$list = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->loadByProperties([
    'uid' => $account->id(),
    'type' => 'profile_type',
  ]);

You'll probably want to wrap it up in a service - and if you don't, you should take a long hard look at yourself as to why not :-)


Search api solr result reordering on field value

Finaly i was only able to solve this with hook_preprocess_views_view_table().

$to_search_top = array();
foreach ($vars['rows'] as $index => $row) {
  if ((int) $row['field_company_review_number_1'] > 0) {
    $to_search_top[] = $row;
    unset($vars['rows'][$index]);
  }
}

// Sort reviewed by distance.
usort($to_search_top, function ($item1, $item2) {
    if ($item1['field_free_capacity_coordinates_latlon'] == $item2['field_free_capacity_coordinates_latlon']) {
            return 0;
    }
    return $item1['field_free_capacity_coordinates_latlon'] > $item2['field_free_capacity_coordinates_latlon'] ? -1 : 1;
 });

// Move to results top.
foreach ($to_search_top as $row) {
  array_unshift($vars['rows'], $row);
}


How can I use tokens for Addressfield values without using Addressfield_tokens?

If Pathauto uses the core Token system, then you can follow along in this issue where we'll be adding token support directly to Address Field asap.


Civicrm membership expiration date after renewal

This works in the 4.5.2 sandbox (unknown if it works in 4.4.6)

Set your membership type to rolling instead of fixed
Disable the "Grace" membership status
If you are having a membership period shorter than 3 months, also disable or shorten the "New" membership status

An alternative workaround, which however may be a bit too clunky, would be to create a new membership type monthly and update the contribution page, so that it forces people to sign up for a new membership rather than renewing their existing one. This would, however, lead to the potential for overlapping memberships if they sign up for the new membership before the end of their old one.


Composer package is updated, but core still asks to update

CREDIT TO @CGMonroe

I had started since early stages of Drupal 8, so my themes folder was in

sites/default/theme/bootstrap
sites/default/theme/bootstrap_subtheme

but in composer.json, it updates in directory:

"installer-paths": {
  ...
  "themes/contrib/{$name}": ["type:drupal-theme"],

so what I needed to do was, move my /bootstrap_subtheme from sites/default/theme to theme/
you should end up with:

theme/contrib/bootstrap
theme/custom/bootstrap_subtheme

and here is the correct way of configuring a theme/subtheme: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme


Do we have an option to change/override the drupalsettings variable which is defined by some other module through our custom module?

You can alter the drupalSettings with the hook "hook_js_settings_alter":
function hook_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {

  // Add settings.
  $settings['user']['uid'] = \Drupal::currentUser();

  // Manipulate settings.
  if (isset($settings['dialog'])) {
    $settings['dialog']['autoResize'] = FALSE;
  }
}

For more information see: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_js_settings_alter/8.9.x
I checked the code and the theme hook is run after the module hook. So if you really want to be last. Add the hook to your theme.
web/core/lib/Drupal/Core/Asset/AssetResolver.php:
$this->moduleHandler->alter('js_settings', $settings, $assets);
$this->themeManager->alter('js_settings', $settings, $assets);


Delete all nodes where the taxonomy term matches a given value

The major problem here is the "except last 5" constraint. I suggest the following solution:

db_select the nodes' nids that you don't want to delete in the first step, like

$savenids = select nid from node where -whatever- limit 5.

Then db_delete the rest of the nodes like

delete from node where -whatever- and nid not in $savenids.

The -whatever- terms strongly depend on your field setup, take a look at your tables for that.


Display block after some action (saved node)

You can use Rules + Rules Bonus Pack for this. The Rules Bonus Pack module has actions for enabling and disabling blocks upon a certain event (e.g. save a node). See this screencast for an explanation.

Note; Rules Bonus Pack is a testing ground for new functionality for the Rules module, so test thoroughly. However, the linked screencast above was published in 2011, so perhaps the code had some test mileage already.


How to select by default nodes of a content type in admin/content through a link?

It looks like you're making use of the Admin Views module, so you can add filter options as GET parameters in the URL: http://localhost/admin/content?type=article

You can also make a clone of the content admin view and modify it. This would allow you to set contextual filters, modify the exposed filter fields, or adjust visible columns to make a more targeted content listing.


How to store values to field collection or paragraphs programmatically?

Paragraphs and field collections are both their own entity and the fields pointing to them are just entity referenced.

So if you want to create a node with a referenced paragraph, you first create the paragraph with all the values you want, save it, then create the node and point it to the paragraph you created.

The Paragraph demo module has example code that does exactly that in paragraphs_demo_install():

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

  $paragraph3 = Paragraph::create([
    'type' => 'text',
    'field_text_demo' => 'Apart from the included Paragraph types, you can create your own simply by going to Structure -> Paragraphs types.',
  ]);
  $paragraph3->save();

  // Add demo content with two paragraphs.
  $node = Node::create(array(
    'type' => 'paragraphed_content_demo',
    'title' => 'Welcome to the Paragraphs Demo module!',
    'field_paragraphs_demo' => array(
      array(
        'target_id' => $paragraph3->id(),
        'target_revision_id' => $paragraph3->getRevisionId(),
      ),
    ),
  ));
  $node->save();


Like Gian says, you can't have a default value of CURRENT_TIMESTAMP for an int field.

Due to Drupal's database abstraction layer timestamp is not a supported field type.

This is due to not all databases supporting timestamp or now() as a field default value as apposed to mySQL where it is supported. The solution / work around if you're using mySQL is to add a query to your .install that modifies the field default to now() where the field type is int. See the Data Type doc page for further discussion: http://drupal.org/node/159605 or see here for more info on Drupals DB Schema: https://api.drupal.org/comment/48593


(Views) How to style an image field conditionally based on term

Method 1. Use a node preprocessor
Add this to your theme's template.php, then clear the cache:

function THEMENAME_preprocess_node(&$variables) {

  // This only applies to content type 'article' in teaser view.
  if ($variables['node']->type == 'article' && $variables['view_mode'] == 'teaser') {

     // Find out if node has at least one tag and an image.
     if (isset($variables['content']['field_tags']) && isset($variables['content']['field_image'])) {

      // Map tags to style names.
      $settings = array(
        'apple' => 'medium',
        'banana' => 'large',
      );

      // Build an array of tag names.
      $tags = array();
      foreach ($variables['content']['field_tags'] as $k => $v) {
        if (is_int($k)) {
          $tags[] = $v['#title'];
        }
      }

      // For each mapping, check if the tag exists in the $tags array;
      // if yes, apply the style.
      foreach ($settings as $tag => $style_name) {
        if (in_array($tag, $tags)) {
          $variables['content']['field_image'][0]['#image_style'] = $style_name;
        }
      }
    }
  }
}

Note that we could also do something similar in node--article.tpl.php, but generally you want to keep code logic out of the template files.

Method 2. Use Rules and Field formatter conditions modules (no coding required!)
The example below will set the image style of field_image to 'thumbnail' in the node's teaser view if field_tags contains a term with an ID of 18.
The Field formatter conditions module an image style to be conditionally set based on the outcome of a rule. It involves creating a rule, then going to Structure > Content types > [content type] > Manage display and adding the condition in the configuration options of your display (in this case the "Teaser" display).
Note: This example only checks for a single term. To compare against more terms, add more "List contains item" conditions, one for each term.
Here is the rule:

Here are the formatter settings:


How to execute a specifc job after some time interval like 5 minutes?

Using the "Rules Scheduler" sub-module of the Rules module seems indeed a possible approach.

However, be aware that the actual trigger wil only happen the next time your Cron job runs, similar to what's mentioned in the question about "Is there anyway to get more control over when CRON runs?". Maybe that's what the missing part is that you're looking for?

So at least as a way to check if the logic of your code is running as you want, try to trigger running your cron job from the admin panels. If that's how such check is performed at least 1 time, then your question is like simplified similar to the question I referred to in my link above.

PS: I don't it says in your question (correct me if I missed it), but if the first time your "verify order" indicates that the verify didn't pass yet, make sure to reschedule the same rule to be executed 5 minutes later on also.


Field depandancy module can not work for textfield in field collection

You can use Conditional Fields module which define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields.

Thank you.


What does Drush error "Unknown option: --db-url" mean?

Pantheon site aliases are only compatible with Drush 5. I had the same message when trying to use Drush 6.

On a Mac with Homebrew, I ran "brew install drush5" and then symlinked the resulting file (/usr/local/Cellar/drush5/5.9/libexec/drush) to "/usr/local/bin/drush5" not to interfere with my existing Drush installation.

Now I can run commands such as "$ drush5 @pantheon.xxx uli" when needed for Pantheon.


How to create another html.tpl.php file for logged in users?

Implement hook_preprocess_html() in your theme (or module, both are equally valid) like so:

function MYTHEME_preprocess_html(&$vars) {
  // Determine if the user is auth'd
  if (user_is_logged_in()) {
    // Add a theme hook suggestion.
    $vars['theme_hook_suggestions'][] = 'html__auth';
  }
}

Then add a html--auth.tpl.php file to your theme, clear the caches, and you should be good to go.


How do I enable the Views Contact Form module?

The Views Contact Form module doesn't actually works for Drupal 8, since it puts its class files in [module directory]/lib/Drupal/views_contact_form (PSR0), when Drupal 8 now requires them to be in [module directory]/src (PSR4), inside the module directory. Looking at the code, I notice the module has not been updated to work with the official releases of Drupal 8.0, nor 8.1.

For this reason, not even removing the dependency on the Email Field module from
the views_contact_form.info.yml file would work. Otherwise, I would have suggested to change the views_contact_form.info.yml file as follows.

name: Views Contact Form
description: Views Contact Form
core: 8.x
type: module
dependencies:
 - views

To add more details about the dependecies, the Views Contact Form module declares its dependency from the Email Field module, which is only for Drupal 7. In the project page of the latter module, it's clearly stated:

  The basic email field type is in core now: #1668332: Add an E-mail field type into core, making this contrib module obsolete. Specific formatters (like the contact form) can live in separate contrib modules.

It seems the Views Contact Form module implements one of those formatters, so it would just require the email field already present in core. Unfortunately, the module has not been updated to work with the latest releases of Drupal 8.


I would set up a vocabulary, with a machine name such as site_nav,

then on your nodes, you would add a taxonomy term reference field to the site_nav vocabulary.

Then set up automatic path aliases using pathauto at /admin/config/search/path/patterns

You could use the title of the page or add an additional field, such as field_short_name to use in the url.

Then the pattern would be

[node:field_site_nav:url]/[node:field_short_name]

or

[node:field_site_nav:url]/[node:title]

or some such (I forget the exact pattern for urls of terms).

You could also use the content type names, if you have content types such as "products" and "about us", then the pattern would be

[node:content-type]/[node:title]

There are some more examples here:

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


What you're asking for is not an obvious task to get completed.

The most recent, fairly successful, funding campaign that I'm aware of is for upgrading the Rules module to D8, via #d8rules. For some pointers about it, start from the community promotion ad (disclosure: I posted it) which looks like so:

Depending on what the subject of your project is, maybe your project also fits the criteria for starting a similar ad ... free of charge (just a relevant image and URL will get you going)!


Google translate service not available on Translation Management module(Drupal 6)

Like is said on that page http://code.google.com/apis/language/translate/overview.html access to Google Translate API is now limited.

If you still want continue to use the module you should have a look into this discussion http://drupal.org/node/1215426 where they are looking for another solution.


replace css on certain pages by another css

You would need to use your theme to watch for it. You'll need to hook into preprocess_page and look for the global.css file in the css array and unset it. Below is an example of how to remove the modules/system/system.css you'll need to see where in the array global.css is and do the same thing. You'll want to wrap that inside of an if for your paths. In this example I use arg() to get the first path value (ie cart) and turn it on for that case. You can do what ever you want.

function phptemplate_preprocess_page(&$vars)
{
    if(arg(0) == 'cart') {
        $css = $vars['css'];
        unset($css['all']['module']['modules/system/system.css']);
        $vars['styles'] = drupal_get_css($css);
    }
}


Adding the following line to the beginning of the script fixed it:

PATH=/usr/local/bin:$PATH

I assume Drush uses the $PATH in turn to call other commands.


How to put google analytics script PHP to my sites?

You can install module Google Analytics. Or paste script to file html.tpl.php.


How can I maintain redirects from a non-existing path to an existing one?

After you've installed and enabled the "Redirect" module (https://www.drupal.org/project/redirect), you can manage your redirects by going to the redirect list page at /admin/config/search/redirect:

You can find this route and all the other routes provided by the "Redirect" module in redirect.routing.yml:

redirect.list:
  path: '/admin/config/search/redirect'
  defaults:
    _entity_list: 'redirect'
    _title: 'URL redirects'
  requirements:
    _permission: 'administer redirects'


How to apply css to the maintenance page?

Override the maintainence stylesheet in the theme layers .info file...

  stylesheets[all][] = system.maintenance.css

To be honest if none of your theme stylesheets are loading then not sure it will work but ideally it should.

Heres some more info on theming the maintence page...

http://drupal.org/node/195435

UPDATE

Alternatively, try the following in your theme...

/**
 * Implements hook_preprocess_maintenance_page().
 */
function YOURTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'YOUR_THEME') . '/css/maintenance-page.css');
}


Copy search-result.tpl.php into your theme folder..

Override above tpl using below code..

<?php

/**
 * @file
 * Default theme implementation for displaying a single search result.
 *
 * This template renders a single search result and is collected into
 * search-results.tpl.php. This and the parent template are
 * dependent to one another sharing the markup for definition lists.
 *
 * Available variables:
 * - $url: URL of the result.
 * - $title: Title of the result.
 * - $snippet: A small preview of the result. Does not apply to user searches.
 * - $info: String of all the meta information ready for print. Does not apply
 *   to user searches.
 * - $info_split: Contains same data as $info, split into a keyed array.
 * - $module: The machine-readable name of the module (tab) being searched, such
 *   as "node" or "user".
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Default keys within $info_split:
 * - $info_split['module']: The module that implemented the search query.
 * - $info_split['user']: Author of the node linked to users profile. Depends
 *   on permission.
 * - $info_split['date']: Last update of the node. Short formatted.
 * - $info_split['comment']: Number of comments output as "% comments", %
 *   being the count. Depends on comment.module.
 *
 * Other variables:
 * - $classes_array: Array of HTML class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $title_attributes_array: Array of HTML attributes for the title. It is
 *   flattened into a string within the variable $title_attributes.
 * - $content_attributes_array: Array of HTML attributes for the content. It is
 *   flattened into a string within the variable $content_attributes.
 *
 * Since $info_split is keyed, a direct print of the item is possible.
 * This array does not apply to user searches so it is recommended to check
 * for its existence before printing. The default keys of 'type', 'user' and
 * 'date' always exist for node searches. Modules may provide other data.
 * @code
 *   <?php if (isset($info_split['comment'])): ?>
 *
 *       <?php print $info_split['comment']; ?>
 *
 *   <?php endif; ?>
 * @endcode
 *
 * To check for all available data within $info_split, use the code below.
 * @code
 *   <?php print '
'. check_plain(print_r($info_split, 1)) .'
'; ?>
 * @endcode
 *
 * @see template_preprocess()
 * @see template_preprocess_search_result()
 * @see template_process()
 *
 * @ingroup themeable
 */
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>

Clear Cache

Author / date / number of comments from the search results is getting rendered using below code

<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

which we removed from above overridden tpl....

You can also remove it using below function in your theme template.php

function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
}


Programatically render a block in a twig template

You're on the wrong track with module_invoke(). That's just a fancy way of calling the {$module_name}_block_view() function.

The fact that it changed doesn't matter, the point is that the block system completely changed in 8.x and is now using plugins and config entities, those functions no longer exist.

You have a few options.

a) Re-use an existing block config entity and view it. Very easy, but requires that configuration to exist, e.g. as a disabled block.

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

b) Create the block plugin instance directly, pass it the configuration (you can find the block plugin id and configuration easily in an exported block config entity). The downside is that you don't get render caching, but if you display it somewhere that is already cached (like a node template), that doesn't really matter.

$variables['block_output'] = \Drupal::service('plugin.manager.block')
  ->createInstance($plugin, $configuration)
  ->build();

c) In case of a view, you can also load the view directly and display it.

d) You can also re-think your approach completely and use block regions or Page Manager (which uses standard block plugins in 8.x).


How can I search internal blocks in the admin section?

If the block you're looking for is a "custom block", i.e. one that you create via structure->blocks->Add block rather than one defined in a module then you should be able to query the database for it like this:

SELECT * FROM block_custom WHERE body like '%my-class%'

...changing "my-class" as appropriate.

Alternatively, you can inspect the markup of the block on the front end and look for a class such as block-123, then navigate to /admin/structure/block/manage/block/123/configure, replacing 123 with whichever block number you found.

If there's no body field on that page then it's probably a block defined by a module.  Then you can try to find a clue as to where it's defined in the classes on the contents of the block, for example if you see lots of classes with the word views in it then it will be a block defined in views and you should look in the views UI to find where it's defined.

Also, turning on the core contextual links module may help as well.

n.b. All this is based on the assumption that we're talking about Drupal 7.  Much of it applies for other versions with some tweaking.


Set a theme for a single content types edit page

Using hook_menu_alter you can override even the theme a path uses.

function hook_menu_alter( &$items)
{
    $items['path']['theme callback'] = 'variable_get';
    $items['path']['theme arguments'] = array('theme_default');
}

like this you set the theme for that path to whatever the user theme is, even for admins.


I found this article which describes one method of doing this.  Looks promising not sure if it's the best way.   For one I'm not immediately sure how to handle multiple images.  How To: Inline Images with ImageField and ImageCache using HTML

UPDATE

Yes I can confirm this works.  You can use a single ImageField and check the "Multiple values" checkbox when creating the image field to support multiple images.  I named my field "blog_images".  Then on the "Display Fields" tab I set the label, teaser, and Full values to all be "<hidden>"


From the naming of your module and template file, I suppose you want to add a template for a custom block returned by your module.

The reason, that your template is found by adding it to the theme is not that you implemented hook_theme() in your custom module, but the way you named the template. It is found by the theme registry's template suggestions used for the block within your panels pane.

If you want your own theme hook jsblock_custom_theme to be applied to the block, you will have to add the theme hook to your block output by using the theme() function. An abstract example:

/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'jsblock_jsblock':
      $variables = array();

      // Prepare your block variables here.

      $block['content'] = theme('jsblock_custom_theme', $variables);
      break;
  }

  return $block;
}

Some further suggested checks/improvements:

Check your template path: Keep in mind that drupal_get_path returns a path without trailing slashes. You will have to add a / to your path.
Place your template in a theme subfolder to keeping a cleaner module structure.
Don't name the template like the natively used template suggestions to avoid collisions while the theme tries overriding templates.


How to use $query->add_where_expression in hook_views_query_alter

If you look at the documentation for views_plugin_query_default::add_where_expression(), you will notice the following note. (The emphasys is mine.)

  The caller is reponsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query. Internally the dbtng method "where" is used.

Looking at this Stack Overflow question, I would get your code should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'latlong':
      $alias = $query->add_table('field_data_field_latitude');
      $query->add_where_expression(0, "$alias.field_latitude_value = :latitude", array(':latitude' => 53.9519);
      break;
  }
}

Since the latitude is a floating point, I would use a comparison that is different from $alias.field_latitude_value = :latitude, for example checking the latitude is inside the range [$latitude - $epsilon, $latitude + $epsilon].


Theme the landing page after saving new content

with hook_form_alter you could for the form for the node type add a submit handler that will redirect to a custom page. Alternatively you could use drupal_set_message.

function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

function my_custom_submit_handler(&$form, &$form_state) {
  // Use the drupal_set_message solution.
  drupal_set_message(t('Your Testimonial has been saved!'));
  // Redirect to custom page solution
  $form_state['redirect'] = 'url/to/page';
}


How to embed a view in hook_page_build()

The docs say hook_page_build()'s $page variable is for render arrays.

Less obvious from the docs without digging a little further but views_embed_view() returns a string of HTML markup.

So just assigning the result of views_embed_view() to the render array breaks it.

Instead you can use a #markup element.

Because it is the default element type you don't have to specify an element type or theme function or anything, so you can just do this:

/**
 * Implements hook_page_build().
 */
function MODULENAME_page_build(&$page) {
  $page['sidebar_second']['blogs']['#markup'] = views_embed_view('blogs', 'block_2');
}

If that is your entire code for this though (if you don't have some complex logic relating to when this view is being added) I would not recommend adding a block to a region in this manner.

There are lots of options already out there for adding blocs to regions without custom code. For example you could use one of these:

Drupal core block module
Context
Panels


Does storing my database as a .sql file in my site git repository cause problems?

It should be the right way  so that both site & database are in sync.

I'd suggest you better backup the (zipped) mysql dump from backup-migrate module. If you can use lzma compression then you can save another 20% space on mysql backups using this way.


How to disable new user registered email to admin

This email is not configurable via the UI.

You can use hook_mail_alter(), which will allow you to stop the sending of a message.
So you would create a custom module that does this:

/**
 * Implements hook_mail_alter().
 */
function MODULE_NAME_mail_alter(&$message) {
  // Stop the default drupal email that goes out to admins when a user
  // registers on the site. An alternative email is sent out via other means.
  if ($message['key'] == 'register_pending_approval_admin') {
    $message['send'] = FALSE;
  }
}


Enable twig debugging to pin down the used template file(s) (if the output was added inside of a template). Search the templates before the !important output for that markup.
If you can't find it look at the preprocess functions used for those templates.


From my child theme, how can I remove a library loaded by the parent theme?

You can add overrides to your child theme's info.yml file, telling Drupal not to load the slick library from the parent theme.

Refer to the "Libraries-override" section of this well documented blog post explaining and demonstrating the many options available in terms of removing/replacing files called by other modules and themes with specific ones in your theme.

For your use case, you probably just want to remove (aka disable) both css and js files for slick.js from the parent theme.  So your "library override" will resemble either:

Case 1: slick is part of a library in the parent theme that includes multiple css and js files for the theme, not just slick

libraries-override:
  parent_theme/parent_theme_library_that_includes_slick:
    css:
      theme:
        path_to_parent_theme_or_vendor_slick_library_folder/slick.css: false
        path_to_parent_theme_or_vendor_slick_library_folder/slick-theme.css: false
    js:
        path_to_parent_theme_or_vendor_slick_library_folder/slick.min.js: false

Case 2: slick is part of a standalone library in the parent theme

libraries-override:
  parent_theme/slick_library_name: false

You won't need to declare a replacement in your libraries-override, since you're using the Slick module itself, and it will load relevant files needed.


Error in simplesamlphp_auth.module: no valid attribute set

The General values for same will be as follows:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress

but if these not works you can also check the values in Metadata XML received from your IDP.


Display message or block when View Page is null or empty

On your configuration Views in the right you've "Advanced" zone, if you click on it you will see more options and "No results behavior" that will let you do what you want when the view doesn't return results.


Blocking a certain user from apearing in user search results

If you're using drupal search out of the box to search users, that should still call implementations of hook_search_page

Build a small custom module that implements hook_search_page, parse thru $results and remove anything you don't want appearing in search results.

function custom_module_search_page($results) {
  foreach($results as $result_index => $result) {
    //do something, maybe detect for a user id
    //and run unset($results[$result_index]); if the criteria is met
  }
}


How to get $form_state['values'] after a drupal_get_form() call?

I realise this is an old question but: drupal_get_form() is mostly a wrapper for drupal_build_form(), and (the docs say) is intended to be used "instead of drupal_build_form() when $form_state is not needed", with the implication that if $form_state is needed, it's OK to go straight to drupal_build_form().

The only extra bit drupal_get_form does is assemble a 'build_info' array in the $form_state, so instead of (e.g.) $block['content']['form'] = drupal_get_form('myform_name', $arg);, you could do something like this:

  $form_state = array();
  $form_state['build_info']['args'][] = $arg;
  $block['content']['form'] = drupal_build_form('myform_name', $form_state);

You should find your $form_state variable is now populated as it would be if you were operating inside the form building function, including any $form_state['values'] or $form_state['input'] in the event that your form is being rebuilt.


hook_module_implements_alter() not working for me. What am I doing wrong?

Double check the weight in the system table on your d7 database. You can try giving module one a higher weight therefore making it run second.


I used this patch from here - http://drupal.org/node/1014522#comment-5719202

After you patched it you can then use drush features-import-all --yes or drush fia -y to import features to database.