db_select with subquery including conditions from 2 tables

To achieve your desired behavior you have two options.

If you really like to filter by using a subquery, you should execute it first, parse its result set to an array and set this array as parameter to the condition method of your second queries db_select:

// Run your subquery first.
$subquery = db_select('referential', 'r')
  ->fields('r', array('job'))
  ->condition('r.category', 'j.category')
  ->condition('r.label', $label)
  ->condition('r.activity', $activity);
$result = $query->execute()->fetchAllAssoc('job');

// Make sure $results is initialized for further evaluation.
$results = array();

// If we have referential results, execute the query on job orders.
if (!empty($result)) {
  $query = db_select('job_orders', 'j')
    ->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('j.job', array_keys($result), 'IN');
  $results = $query->execute();
}

The far more elegant and therefore suggested solution is to using an INNER JOIN on your query. The target query would look like:

SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

You can achieve this solution using db_select by adding a join to your $query:

  // Run the query using an INNER JOIN.
  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();

Edit:
As I don't see any special reason for using db_select in your use case, I'd also suggest on sticking to db_query here for better performance of your application.

Edit 2:
In the above 'solutions' I have overseen you are using two conditions between the tables. In this case, you have to add both conditions to your JOIN:

SELECT j.*
  FROM job_orders j
  INNER JOIN referential r ON (r.job = j.job AND r.category = j.category)
  WHERE j.statut = 'To do' AND r.label = :label AND r.activity = :activity

Which would need the following db_select:

  $query = db_select('job_orders', 'j')
    ->join('referential', 'r', 'r.job = j.job AND r.category = j.category');
  $query->fields('j')
    ->condition('j.statut', 'To do')
    ->condition('r.label', $label)
    ->condition('r.activity', $activity);
  $results = $query->execute();


Can Display Suite render content without my theme around it?

aDisplay suite should allow you to modify the output for the fields and even choose some layouts but AFAIK it won't let you completely omit the site theme (i.e. create a page without header or footer).

You can use js/ajax to grab just the portion of the page you want to appear in the modal pop-up so that it doesn't pull in the header/footer. Depending on the JS library(ies) you are using this could be easy or challenging.


Get the breadcrumbs for a specific node other than the current

Core breadcrumbs in Drupal 7 are implemented in a way that they only work for the current page. So to achieve this with core, you would have to "simulate" a page request and somehow harvest the breadcrumb. This is probably painful and not worth the effort.

In Drupal 8, you have breadcrumb builders that take a route match as an argument. This route match can be any page. So yeah, what you want would be possible in D8. But you are in Drupal 7.

In Drupal 7 with Crumbs module, breadcrumbs are calculated independently of the current page. You can see this in action on admin/structure/crumbs/demo.

E.g. crumbs_get_trail() accepts a $path argument, which can be any path you want. But this gives you a "trail", not a breadcrumb itself.

Unfortunately there is no one-liner to give you the breadcrumb for any page.

But here is what you can do:

  // Create a local version of the Crumbs service container.
  $services = new crumbs_DIC_ServiceContainer();
  $page_info = $services->page;
  $page_info->path = 'node/123';

  // Optional: Set display settings.
  $page_info->minTrailItems = 1;
  $page_info->showFrontPage = TRUE;
  $page_info->showCurrentPage = TRUE;

  // Now choose which piece of information you want.
  $trail = $page_info->trail;
  $breadcrumb_html = $page_info->breadcrumbHtml;
  $breadcrumb_data = $page_info->breadcrumbData;
  $breadcrumb_items = $page_info->breadcrumbItems;
  $raw_breadcrumb_items = $page_info->rawBreadcrumbItems;

This can be starting point for you to play around with.

If you use Crumbs for this purpose, you get the full package: All your breadcrumbs will now be controlled by Crumbs. Maybe this is what you want, or maybe not.

I am not aware of other breadcrumb-customizing modules which provide this functionality.


Using a View's exposed Sort Criteria redirects to home page

if you use panels, and i think you are, use content panes only, not block views, etc. and make sure in views UI in middle column to set "use panel path" to yes.


How do I modify the text on a breadcrumb?

See How to get rid of the "/blog"-page that displays all user-blogs (or change the breadcrumb-link)? I think that you will find an example on how to change a specific text of your breadcrumb.

For example, in your template.php file you can use phptemplate_breadcrumb() to search and replace text:

function phptemplate_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    $breadcrumb = preg_replace("/old text/", "new text", $breadcrumb); // This line will search and replace text.
    return '
'. implode(' >> ', $breadcrumb) . '
';
  }
}
?>


I use this, it's a little bit more dynamic then if you would hardcode the language code yourself. Hope it helps. This example works with the language switcher block.

function theme_preprocess_links__language_block(&$variables) {
    foreach(array_keys($variables['links']) as &$code){
        $variables['links'][$code]['link']['#title'] = $code;
    }
}


How to open accordion when setting error?

I have added this an issue on the field_group module and have posted a patch: https://www.drupal.org/project/field_group/issues/2923831


I think a small custom module will probably be the method with the least overhead. You could store the legacy ID in a field during the migration and access it from there if the appropriate query string is set.

Very rough examples...

Drupal 7:

mymodule.module

function mymodule_init() {
    if (!empty($_GET['an'])) {
        $query = new \EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_old_id', 'value', $_GET['an'])
            ->execute();

        if (!empty($result['node'])) {
            $nids = array_keys($result['node']);
            $nid = reset($nids);
            drupal_goto(url("node/$nid"), [], 301);
        }

    }
}

Drupal 8:

mymodule.services.yml:

services:
  mymodule.redirect_subscriber:
    class: Drupal\mymodule\RedirectSubscriber
    arguments: ['@entity_type.manager', '@path.alias_manager']
    tags:
      - { name: 'event_subscriber' }

src/RedirectSubscriber.php:

namespace Drupal\mymodule;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RedirectSubscriber implements EventSubscriberInterface
{

    protected $nodeStorage;

    protected $aliasManager;

    public function __construct(EntityTypeManagerInterface $entity_type_manager, AliasManagerInterface $alias_manager)
    {
        $this->nodeStorage = $entity_type_manager->getStorage('node');
        $this->aliasManager = $alias_manager;
    }

    public function Redirect(GetResponseEvent $event)
    {
        $old_id = $event->getRequest()->get('an');

        if (!empty($old_id)) {
            $ids = $this->nodeStorage->getQuery()
                ->condition('field_old_id', intval($old_id))
                ->execute();

            if (!empty($ids)) {
                $nid = reset($ids);
                $url = $this->aliasManager->getAliasByPath("/node/$nid");
                $event->setResponse(new RedirectResponse($url, 301));
            }
        }
    }

    static function getSubscribedEvents()
    {
        $events[KernelEvents::REQUEST][] = array('Redirect', 20);
        return $events;
    }
}


How to set page title for forum's Active and Unanswered tabs in Drupal 7?

I have solved my problem by setting custom page title in our theme's template.php file.

i have used bartic theme so in my function in template.php file is as follows

 function bartik_process_page(&$variables) {
    $path = $_GET['q'];
    if (strpos($path,'forum/active') !== false)
       {
        $variables['head_title'] =  drupal_set_title('Your_Page Title');
       }
   }

 function bartik_preprocess_html(&$variables) {
 global $theme_path;

// Add conditional CSS for IE7 and below.
  drupal_add_css($theme_path . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

 $variables['head_title'] = implode(' | ', array(drupal_get_title(), variable_get('site_name'), variable_get('site_slogan')));
  }


How to fix field collection ajax #edit-submit clash with node #edit-submit?

The problem was that that large node was hitting the max_input_vars cealing. So I just had to increase that and it worked.


The view and display of an exposed form are stored in $form_state.

function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $view = $form_state->get('view');
  $display = $form_state->get('display');
}


Email field does not show up when I view node, only when I edit

Check 'display fields' in your content type settings.


Blocks aren't being assigned to a region

(Luis already answered eir own question, in the comments above, but I thought I'd add something here; all kudos to Luis though.)

The status property returned by a module's implementation of hook_block_info() must be TRUE. This is slightly unintuitive because when enabling blocks in the UI, one only has to choose the region—however, in doing so a block's status is also changed. Programmatically, we must set both status and region properties. (I'm not sure there would ever be any reason to set one and not the other.)

When doing this to an already-enabled module, it would seem that clearing the block cache (drush cc block) is not enough, nor is dis- and re-enabling the module; it must be uninstalled and reinstalled for the change to take effect (drush dre custom_module if you've got Devel).

Note also that Drush seems to get confused when doing this with a region that doesn't exist in the default theme (reporting that "The block Carrousel was assigned to the invalid region hp_content and has been disabled."). This is not true; the block is enabled.


Custom form Edit, populate form field value by ajax (NOT dependent fields)

You're going to have to trigger a javascript function, or a javascript event in your ajax callback
There are several different ways you can do that, some number of ways here:
How can I trigger a javascript function when a Drupal ajax call is complete?


Really confusing composer error output relating to working composer.json/.lock files

Someone else recently reported not being able to update from RC2:

Updating core with Composer doesn't work

There are two different things, drupal/drupal and drupal/core. You can't mix the two, that's why when you download drupal from drupal.org by hand, you have drupal/drupal and it contains the replace line, as it says that it replaces that.

As suggested there, I'd recommend to use the drupal-project template, I've upgraded many drupal installations to 8.3 with that without a problem.

Note that that has quite a different file structure, specifically it has a web folder that contains the public files.


It all depends on whether your Ubuntu 18.04 machine is intended for use as a local workstation or a web server exposed to the Internet.

If it's your local workstation, you should absolutely just make a subdirectory in your home directory.

I like to keep my projects in ~/repos/clientname/projectname/ directories. I call the directory repos because I recommend always keeping your project in a local git repository and pushing all your changes to a private repository on github/gitlab/bitbucket or wherever. That way you can always pick up work on a new computer if yours crashes.

Your local workstation is probably not (indeed, hopefully not!) the server where you will expose your Drupal site to the Internet. You want a local copy that you can break and fix a dozen times a day without taking the real site offline.

Then, you want a way to serve that to yourself on localhost. Check out my other answer here to see one way of serving the files locally. I recommend Lando for newbies because it manages a lot of the complexity for you, providing Docker containers for web server, database server and other services as needed. And you can easily free up system resources with lando stop and switch to another project with lando start. See my linked answer for more details.

Then you can worry about deploying the site to a production server ... ideally, multiple environments for Dev, Stage (Test), and Prod (Live) environments.

There are many ways to approach this depending on your hosting. Just take things one step at a time, start with local development and work your way up to DevOps concepts like automated testing and deployment.

If your Ubuntu 18.04 installation is intended to be a web server, then you'll want to install a complete LAMP stack and set up the directories as @pinueve suggests in his answer.

There is also a middle ground. You can test deploying your site from the local dev instance in your home directory to the local Apache server, but just be aware that you can run into port conflicts between your Ubuntu host's Apache server and the Docker guest's Apache server if you try to start both at once. This can be mitigated by changing your default Apache ports.

Edit the VirtualHost entries in /etc/apache2/sites-available/000-default.conf and change port 80 to something like port 8080:

<VirtualHost *:8080>

If you do this, you can browse the host machine's Apache on http://localhost:8080 and you will still be able to start and stop your Docker containers with Lando.


Is there a D7 equivalent to the Unlimited Field module?

To implement a field allowing either a numeric value or "unlimited" in D7, you can define such field using the desired widget (like a textfield maybe?). And then use the Rules module to validate the actual data that is entered before the entity (like a node or user where you use that field?) is saved (created or updated).

Some more details about the validation part of such rules to be created:

Add the appropriate validations you want within the Rules Conditions.
You may want to specify multiple conditions and combine them with an "OR", eg to validate that the value entered is either the string "unlimited", or a digit equal to "0", "1", "2", "3" or "4".
If you have lots of allowed digits (say dozens), just use an appropriate regular expression (instead of a loooong list of digits).

Have a look at my answer to "How to make the permissions of a module more granular?", which you can use as examples of what might be needed to implement Rules conditions as in bullets "2." or "3." above.

Of course you'd also have to pick the most appropriate Rules Event for this rule to be triggered. But there are quite a few, straight forward, events you can pick from (depending on where exactly you want to use this field), just to mention a few:

Before inserting a new node (optionally limited to content type ABC). E.g. if your field is used to "Store the maximum speed on highways in country X".
Before saving an update to a user profile. E.g. if your field is used to "Store the duration (in days, months or years) of some type of membership subscription".

And your Rules Action is probably just a simple "Drupal set message". Though I can think of honeypot-scenarios where some specific values that got selected could result in a rules action like "block this user".

If you want even more granularity, you might also want to have a look at Conditional Rules, which allows for using "Rules Conditions" within "Rules Actions". Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of using this module.


Views: Using Pager With Single Node, Multiple Fields

You can use Nivo Formatter to make your image field to a slider. There is no need to build this with views.


why are Twig template variables with markup not being rendered?

Because twig auto-escapes unsafe content and your content isn't marked as safe.

You can explicitly tell it that it is with $test = Markup::create($test); but you should be very careful with that. If it contains any sort of user input, you might open yourself for XSS issues.

Better approaches are using a render array like ['#markup' => 'your text'] which by default will allow a certain amount of html tags but not all of them. You can also use an inline template as documented here: https://www.drupal.org/node/2311123.

Twig natively understands render arrays, so it doesn't matter for your template if you provide a render array or a string.


How to add captcha to "Printer, e-mail and PDF versions" email form

I just added my send form ID to the CAPTCHA form list, and it worked fine.


Drupal 7 Commerce - How would you increase or decrease a checkout total price depending on payment type?

In the checkout methods rules you should be able to add an action that decreases the total or subtotal cost.  So when a certain payment method is used, the subtotal will decrease.

If one of those rules actions isn't available you might need to look at some other modules like Commerce Rules Extra.

Another option would be to apply coupons automatically to orders with those selected payment methods with the Commerce Coupon and Commerce Coupon Fixed Amount modules.  That might give you better control over how many times a user or how many users can use a discount like this.


Automatically update Drupal core/modules for a large number of sites (with Drush)?

What I would suggest, is to store all your Drupal sites in GIT repositories. With a separate branch / repo for Core and as many as necessary for /sites/*

Then you can easily do updates to cores by a simple pull. For shared hosting, pull locally, then sync by lftp to your distant hosts.


Try the Save Form State module. Here is a quote about it (from the module's project page):

... provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.
It works using the jQuery Sisyphus plugin, which is a lightweight jQuery plugin that uses Local Storage to save form fields every specific time span that is configurable from the module settings page.


Custom fields in User registration, how to save?

If you insist use code I suggest below method

function all_data_form_submit($form, &$form_state) {
$fname = $form_state['values']['field_first_name']['und'][0]['value'];
$lname = $form_state['values']['field_last_name']['und'][0]['value'];
$name=trim($form_state['values']['name']);
$myuser=user_load_by_name($name);
if(!empty($myuser)){
        $edit = array(
                'field_first_name' => array(LANGUAGE_NONE => array(array('value' =>$form_state['values']['field_first_name']))),
                // .. and every field you want to save
                );
        user_save($myuser, $edit);
    }
}


Views 3: display "block" doesn't show full node

When you select teaser view instead of full content you can see comments in your block.

If you see implementation of comment_node_view() comments are displayed only in node lading pages.

if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

If you enable the same block in node landing pages you can see the comments in your view.

If you enable the block other than node landing pages, then you cannot see the comments because of node_is_page($node) condition i think.


How to add 'add to cart' button in custom content type using Commerce 2?

Follow below steps to show Add to cart button into any content type.

Add field with reference as Product and select list of product bundles you want to show in content type.
And in field settings select reference as shown in below.

Go to content type manage display and select as "Rendered Entity" as shown below.

Go to the product type which you selected in content type and click on manage display.
See for variations and select as "Add to cart form" as shown in below.

And that's it after adding node with product you will be able to see the Add to cart button into node view like below.


Print comment form inside node's page instead of a link to comment page

You can set that under "Comment settings" on the edit page of your content type.


Show block in /user/* page, not /user/*/edit

If you use this module then the exclamation prefix would work to exclude paths: https://www.drupal.org/project/block_exclude_pages


How to redirect user using Rules when user visits a link with view?

Use 'Drupal is initializing'

To get this to work, you should be able to use the "Drupal is initializing" event (which is NOT shown in the rule included in your question). That will ensure that the rule gets triggered BEFORE the actual content of your "link with view" is shown (otherwise you are too late, it "is" already shown).

Use a 'Regular Expression'

That link that you want to "intercept", should be formatted in some type of regular expression, which you then use as your Rules Condition. So that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules Action is probably fine.

Sample rule

Refer to the "Option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this Rule in export format:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Here is some suggested tuning of the above sample to make it work for your case also:

machine name and label.
replace the node/* by your path of your view (in the "label", and the regular expression).
replace the action part of the rule by your action that you have already.

Note: the rule included in your question also shows that you tried to use the Path Rules module, which implements Rules Conditions for checking an URL against a given string for triggering Rules Actions. That module is another interesting add-on module the Rules, but if you just use a regular expression as shown in my answer, you don't need that module for getting your rule to work.


hook_form_search_block_form_alter is not working with bootstrap theme?

You can try a bootstrap plugin:

themes/THEMENAME/src/Plugin/Form/SearchBlockForm.php

/**
 * @file
 * Contains \Drupal\THEMENAME\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\THEMENAME\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends \Drupal\bootstrap\Plugin\Form\SearchBlockForm {

  /**
   * {@inheritdoc}
   */
  public function alterForm(array &$form, FormStateInterface $form_state, $form_id = NULL) {
    // Call the parent method from the base theme, if applicable (which it is
    // in this case because Bootstrap actually implements this alter).
    parent::alterForm($form, $form_state, $form_id);

    $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.')
  }
}

Reference:

http://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8


Path field not available in Search API View

\/organize$

\/: forward slash escaped

organize: letters "organize" matches the characters "organize" case sensitive.

$: Must be the end of the string.

Regex101


Batch simply says "I will do N number of things (at most) and then do a page refresh ... and do more."

If you say do 5 items per job chunk that take 5 seconds each you would be fine with the default php timeout value of 30 seconds.

If you say do 20 items per job chunk that take 5 seconds each, your workload per request is too high and will likely timeout.

Remember when your in PHP the lifecycle of a page is request in -> response out. And that your webserver keeps each thread alive for a finite amount of time. You have to work around that timeout -- which the Batch API helps you do.

Running stuff from say Drush, server side using community modules such as Migrate can help you completely avoid timeouts if need be.

EDIT

Also bear in mind that every page request is a full drupal bootstrap and Batch API picks off where it left off. That is one of the most expensive operations when using the Batch API, reloading drupal every N items. That's why people have been working on server side techniques to create nodes, import content, etc. Batch API is great for simple, repetitive tasks. But it tends to fall apart in either complex, or very very large datasets.


Handling mobile images in responsive theme

There are many modules to handle responsive images, including;

Responsive Images
Client-side adaptive image
Adaptive Image Styles (ais)
Adaptive Image
Borealis


Pass the "--working-copy" switch to Drush Make.

drush make --working-copy site.make


OK, I think I'm noticing this difference: when I don't set a field to sort by, my content types seem to be in separate tables too.

But if I set the 'Sort Criteria' to a field that all of the content types have, like 'Post date', desc, then I get all the content types correctly incorporated into one table:

Anyway, hope this helps you!


You can do this with theme_menu_tree() hook in your theme's template.php file.
Or with a more specific version of theme_mene_tree() hook like MYTHEME_menu_tree__MYMENU().

function MYTHEME_menu_tree__MYMENU(&$variables) {
    return '
' . $variables['tree'] . '
';
}

See more here https://gist.github.com/gagarine/3201854

UPDATE:

if menu machine name have hyphne like main-menu then change hyphen to underscore, like MYTHEME_menu_tree__main_menu()


How do I add a custom style to node by its type?

If the content type of the node is Article, then the template file Drupal looks for is node--article.tpl.php.
If the content type name contains underscores, those are replaced with hyphens. If the content type machine name is snippet_code, then the template filename is node--snippet-code.tpl.php.


How to use Solr Index to display node in a Google Map

I have been able to accomplish this task following these steps:

Installed modules for search: search_api, search_api_location, search_api_solr
search_api_views, search_api_facetapi, Search API location views
Installed modules for "geosearch": geofield (to store lat, lon...), addressfield (make it easier for users to enter an address and don't worry about geolocation).
Installed modules for mapping: leaflet, leaflet_more_maps (for more maptiles options out of the box).
Solr server 4.7.1 (I've just downloaded today)

So, with all these things, my goal is to have a view with an exposed full text field and show the results in a map (and afterwards be able to facet this view).

I've started like this:

Create a content type with address field and geofield fields
Set geofield field widget to "Geocode from another field" (and geocode from Address field using google geocoder). Not multivalued fields allowed here.
Create a solr server and make sure it runs ok.
Create an index connecting with the solr server (Remember this name for later)
Add fields to the index, just making it simple:

a) nid

b) title

c) Save changes

d) Add related fields (collapsible fieldset right bellow save button)

e) We choose "Geofield" (Watch out here, if you share the geofield field between
two or more different content types, you need to add this field twice or more and it is not easy to distinguish them because they have same name in the UI)

f) Now we have added geofield as related field, we should have the option to choose "Geofiled » LatLong Pair" and as type "Latitude/longitude" as a field for indexing in solr
Disable the index, disable the server, enable the server and enable the index,
and some clear cache between them. Important to do this.
Once we have server and index enabled, just index all items.
If we now go to the solr interface, and run a query for all results, we should see
a field (among the others we have indexed) which is called something like "locs_your_field_name$latlon" (Notice here that older versions use ":" instead of "$" ). If you can't see it, review before steps.
Now we can set up a simple view:

a) Create a new view

b) Set up a name and description for the view

c) Select "Show" (content is default, we want to change this): The name of the index that you set before, Remember?

d) Create a page: "myviewpath"

e) Save

f) Select fields: "Indexed Node: Node Id" and "Indexed Node: Geofield"

g) Filter criteria: "Search: Fulltext search" -> Exposed filter

h) Format: Unformated list

i) Test and see if we have results, if not, something went wrong, review.

j) Format (again): "Leaflet Map"

k) Data Source: Indexed Node: Geofield

l) Title field: Indexed Node: Nid

m) Description: Indexed Node: Nid

n) Map: Choose from list the one you like the most

o) Map height: 400px

p) Save format

q) Save view. At this point, the map is not visible (in views UI), but if everything is ok...
Go to the path of your view: You should see all results in the map (if you have the default solr server configuration). If not, try to type some text and see if you get the expected results...

Hope this helps!


as @Human love mentioned there is a module out there to accomplish this Field Permissions. There is usually a module to do just about anything in Drupal -- but therein lies the problem; 80+ modules later you may regret installing so many modules.

There are plenty of examples of leveraging Drupal Core and not just using 3rd party contrib modules to meet your needs to keep a lean(er) codebase. Here's an example with EFQ from Phase2 in place of using Views.

That being said you just need to check for a UID or Role in your hook_form_alter. See the next 2 examples:

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Allow admin.
if($form_id == 'erp_reco_node_form' && $user->uid !== 1) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

Or:

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Dont show items for SOME_USER_ROLE.
if($form_id == 'erp_reco_node_form' && in_array('SOME_USER_ROLE', $user->roles)) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

Ideally the contrib module will be more flexible in the long run for many many content types etc. But, if you understand your own requirements then this is perfectly fine.


How do you populate an image field in a field collection programmatically?

There should be no difference between setting the field on a node versus a field collection item.

This should work

$fc_wrapper->field_signature_image->file->set($file);

This should also work

$fc_wrapper->field_signature_image = (array) $file;

assuming $file is a valid file object.  When I have trouble with adding files, it is usually because I have a property missing.  In that case, I will make a node and field collection item via the UI, and then dpm() to see what us missing.  Half the time, it is $file->display, and the rest is usually $file->description.  My guess is that $file->description is your problem.

What I don't recall is whether using File Entity changes this.  Both line above are based on import scripts I have where this module is disabled.


How do I execute code before update the content?

I use the Hook Post Action module because it's execute after the action. So you know that the node is really updated.

So this module introduces several new Drupal hooks to overcome this
limitation

hook_entity_postsave
hook_entity_postinsert
hook_entity_postupdate
hook_entity_postdelete
hook_node_postsave
hook_node_postinsert
hook_node_postupdate
hook_node_postdelete

But, if you want you can use the hook_node_update.
To show info in the node page you can use the EVA module.

"Eva" is short for "Entity Views Attachment;" it provides a Views
display plugin that allows the output of a View to be attached to the
content of any Drupal entity. The body of a node or comment, the
profile of a user account, or the listing page for a Taxonomy term are
all examples of entity content.


Commerce 2.0: How can multiple email addresses receive copies of orders?

Their current configuration is that four different people in the office all receive email copies whenever an order is placed.

See our documentation for order receipt emails: https://docs.drupalcommerce.org/commerce2/user-guide/orders/customer-emails

I think you'll be fine adding those four emails separated by commas.

EDIT: Also see our docs for setting up HTML emails https://docs.drupalcommerce.org/commerce2/developer-guide/core/html-emails


How do I make a rule that deletes a node when it hasn't been viewed for "X" amount of time?

I am unfamiliar with any current modules that accomplish this. D7's default structure does not store last_accessed or similar statistics outside the watchdog, which would be complex to parse and use.

IMHO accomplishing this goal would involve creating a custom module that :

Adds a field to store a 'last accessed' field linked to your nodes.
Hooks into hook_node_view to update this field each time a node
is viewed
Hooks into hook_cron to conditionally select any nodes with
viewed age greater than your maximum. Call node_delete for each. You could also set $node->status=0 and archive the content without deleting it.

Optionally, you could also add an admin dialog through hook_menu that set a variable defining the maximium unviewed age of nodes.


How to use conditions on a COUNT Expression?

Conditions on aggregates are addressed with HAVING in MySQL, so something similar to:

$select->having('count > :cnt', [':cnt' => 2]);


Yes, name your function my_entity_load and it will be passed the id.

From the Drupal hook_menu documentation (emphasis mine).

  Auto-Loader Wildcards Registered paths may also contain special
  "auto-loader" wildcard components in the form of '%mymodule_abc',
  where the '%' part means that this path component is a wildcard, and
  the 'mymodule_abc' part defines the prefix for a load function, which
  here would be named mymodule_abc_load(). When a matching path is
  requested, your load function will receive as its first argument the
  path component in the position of the wildcard; load functions may
  also be passed additional arguments (see "load arguments" in the
  return value section below). For example, your module could register
  path 'my-module/%mymodule_abc/edit':

  $items['my-module/%mymodule_abc/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/123/edit' is requested, your load function
  mymodule_abc_load() will be invoked with the argument '123', and
  should load and return an "abc" object with internal id 123:

  function mymodule_abc_load($abc_id) {
    return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  }


Attach a particular profile2 form to user registration form

try this,

$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));


How to import git commit from development to testing in Aegir

With the Hosting site Git module you can create a git pull task from the hostmaster frontend.

  This module extends Aegir with the option to do a 'git pull' in a site directory.


Is there any difference or advantages between use of libraries in theme or module level with using of "Libraries API" module instead?

The real purpose of Libraries API module is to serve as a central point of information about libraries, so modules can rely on this module to request loading libraries. This avoids modules to include libraries in their module package and just ask Drupal for them.

The main advantage is it avoids conflicts and duplication between several modules shipping same library. With this module, both modules declare the need of a certain library, that should be installed in the Drupal librarires directorty.

Also, modules don't need to include code to detect and load the libraries, version detection, etc

See The ideas and design behind Libraries API 2.x for a detailed explanation.


Saving additional node fields programmatically

You'd need to set the value for the Distance field just like you have already for the Body field. Lets assume that the name of your Distance field is field_star_distance. (To find the name of your field, check if you have the Field UI module enabled and head over to the Manage fields page for your content type)

// Your code
$node->{'field_star_distance'}[LANGUAGE_NONE][0]['value'] = 100;
// Your code

The general skeleton for setting the value for a field of an entity is:

$entity->{$field_name}[$language][$delta][$field_property] = $value

To understand the different field properties for a given field (like value in our example here), you need to look up its schema (see hook_field_schema() and see text_field_schema())

To see if $delta can be  > 1, you need to check the cardinality of the field instance.


States don't work for a block rendering a form

I had to override the twig files for the form-element so some classes were missing like js-form-item' and 'form-item'. After adding thoses classes in the twig file,  the states worked.


How to select a Taxonomy term in a Pane's settings and send it as an argument to Views?

Maybe my initial request has a valid answer, but it is easier to forget about the contextual filter and only keep a relationship Content: Taxonomy terms in node to select the correct vocabulary. Next, filter on Taxonomy Term: Term and select the previously added relationship. Now you can select the required term from a list! Of course, you can duplicate the Views block as many times as needed and only override the taxonomy term. Finally, these blocks can be used in a Panel or elsewhere.


How do I change the top picture for blueprint theme?

First of all: You shuldn't use Drupal 6 anymore as it has reached EOL (https://www.drupal.org/drupal-6-eol).

The regular way to replace the page logo is through the admin interface. You should have an logo file field on your theme settings page.

Another way is to check out the logo path with with firebug (or F12 for the regular browser console) and replace it directly with your ftp client.

Edit: If "Top Image" means something else then the logo, you can also use the second method, but make sure the determined image is not processed through imagecache, otherwise it will be overridden after the next cache clear.


You don't need to put in the update function.
It can go anywhere in your module just Remember to clear the cache after you update the module so you can see it.

If you're adding new menu items in a module update you should put:

cache_clear_all('*', 'cache_menu', TRUE);

In the mymodule_update_7000 function and it will clear the menu cache automatically when you update the module.

Additionally: You might be better using hook_menu for the menu items in your module.

something like this:

function mymodule_menu() {
  $items['guarantee/validto'] = array(
    'title' => 'meeeeeeeeeeeeeeeeeeeeeeeeeeeeeenu',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
    'menu_name' => 'main-menu',
    'page callback'   => 'drupal_goto',
    'page arguments' => array('guarantee/validto'),
  );
  return $items;
}

It can go anywhere you like in your mymodule.module file but generally goes near the top. Again, you don't need to put in the update function but remember to clear the cache after.


Storing uploaded files according to node ID

You can use the File (Field) Paths module in combination with the Token module for this.

Enable module
Go to admin/structure/types/manage/your_content_type/fields/your_file_field
Make sure Enable File (Field) Paths? is enabled.
Under File (Field) Path settings you can now use e.g. myfiles/[node:nid]


I can only assume your media mover process is upload file(s) to site, moved files to S3, copy S3 file location to the CCK field

For Drupal 6:

Install imagecache module and its dependencies.   Create a imagecache preset call thumbnail of the size you want.

Create a view.   Add the CCK field.   In the settings select the format of the thumbnail preset.


Is it okay to ignore the error notices I get on a Drupal site?

Between the two errors, the first is more worrying.

As variable_set() passes the variables value it receives to serialize(), if unserialize() is not able to understand the saved data, it means the database content is probably corrupted. variable_initialize() calls unserialize() using the following code.

  // Proceed with variable rebuild.
  $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  cache_set('variables', $variables, 'cache_bootstrap');
  lock_release($name);

The second error says the code is using a feature that is deprecated, which means that in future PHP versions the code could not work anymore, but in the actual PHP version is still working.


Heartbeat - user delete comment from node -> delete also from heartbeat stream

Heartbeat module implemented hook_user_delete() and hook_node_delete() hooks itself. take a look at their implementations.. I think you can implement hook_comment_delete($comment) hook in your module to delete activities from heartbeat_activity table. Here is the documentation.


Drush installation problem - Non-empty values for magic_quotes_gpc

Be sure you are editing the right php.ini file. As far as I recall the file used from PHP CLI could be different from the one used from PHP when running as Apache module; plus, Drush could use a completely different file, basing on its options, or settings.

To see which php.ini file Drush is using, use drush status. Drush can use a php.ini file that is saved in the $HOME/.drush, or /etc/drush directory; it can also use a drush.ini file present in the same directories. Alternatively, the path of a php.ini, or drush.ini file to use are taken respectively from the PHP_INI, and DRUSH_INI environment variables. (See the content of the README.txt file for more information.)

The function that checks the PHP settings in the php.ini file is _drush_environment_check_php_ini(), which contains the following code.

  // Test to insure that certain php ini restrictions have not been enabled
  $prohibited_list = array();
  foreach ($ini_checks as $prohibited_mode => $disallowed_value) {
    $ini_value = ini_get($prohibited_mode);
    $invalid_value = FALSE;
    if (empty($disallowed_value)) {
      $invalid_value = !empty($ini_value);
    }
    else {
      foreach ($disallowed_value as $test_value) {
        if (strstr($ini_value, $test_value) !== FALSE) {
          $invalid_value = TRUE;
        }
      }
    }
    if ($invalid_value) {
      $prohibited_list[] = $prohibited_mode;
    }
  }

On my computer, the directive for which the error message is reported is set with the following line.

magic_quotes_gpc = Off

When I execute dpm(ini_get('magic_quotes_gpc')); I get 0 as output.


With Drush:

drush php-eval 'node_access_rebuild();'

With Drupal Console:

drupal node:access:rebuild

Which is of course similar to Chamil's answer, but accessible and copy pastable :)


Created custom entity with Entity Construction Kit but cannot filter in Views by taxonomy

SHS doesn't work with entities, only nodes.  The Hierarchical Select module doesn't support Views exposed filters yet either.

The taxonomy terms didn't show up as filters because I hadn't selected the bundle in the Views preselector screen.  I was trying to generalize the view to filter at any level with SHS but no workee.

This forces me to use nodes where entities are more appropriate, or try some other taxonomy scheme to get some useable exposed filter UI, using entities.

Ugh.


Can any of the cache_* be emptied safely?

With one exception, yes. That exception is cache_form. That is not actually a cache table but contains temporary $form_state information of forms currently displayed on your site. Clearing that table would invalidate these forms and when a user then tries to submit that form, he will get an error message and has to fill out that form again.

Note that drush sql-dump and Backup and Migrate automatically leave out the content of these and other tables when creating a database dump with these instead of mysqldump or phpmyadmin.


Views managing fields with style in Drupal7

Exculde From display first and second field  and in third field  use rewrite output  something like this

[field_movie_image]

[title] [body]

it is working for me. itself in a view


The answer is in the error message:

FieldItemBase has a constructor, and it waits a parameter (actually multiple), but it doesn't get any:

$instance = new FileItem();

Even though the constructor function can't be find in FileItem, in this case you have to investigate which parent has it. You will find out that "FieldItemBase" has it.
I don't know why you want to use this like this, but things like Controllers, Plugins, Services were mean to be to get instantiated by Drupal.


How to delete all duplicate node with the same field value in drupal type

If your nodes are not  too many you can achieve it by something like  following   :

$query = \Drupal::entityQuery('node')->condition('type', "diffusion");
$query->groupBy('field_id_diffusion');
$nids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

$diffusion_checklist = [];
foreach ($nodes as $node) {
   $diff_id = $node->get('field_id_diffusion')->value;

   if (!in_array($diff_id ,$diffusion_checklist)) {
     $diffusion_checklist[] = $diff_id;
   }
   else {
     $node->delete();
   }
}

And if you have too many nodes  another solution is implement the same strategy with setup a batch operations


If you're looking for clean and easy base themes, there's Stark (which has a contrib version, as well as the version in Drupal core)

  This contrib version of Stark is an exact copy of the one in Drupal 7
  core with one exception. This version now uses a responsive design that matches a Drupal 8 proposal to make Stark use a responsive layout.

There's also Mothership, which I've never used - but it looks pretty awesome!

  The Mothership is a HTML5 base theme that offers a workaround to
  Drupal’s obscure love for wrapping everything in 2 divs and slapping
  on 3 CSS classes wherever possible.


Enable new modules dependencies on deploy

There is a feature request issue in a Drush queue, just stumbled on it. In donquixote's Drux project are commands you need:

  drux-enable-dependencies (dep-en) - Download and enable dependencies of existing modules.
  drux-find-obsolete (obs) - Find modules that are not direct or indirect dependencies of the modules given as arguments
  drux-generate (obs-gen) - Generate a list of dependencies[] = .. to copy+paste into a module info file.
  drux-list-dependencies (dep) - List dependencies that would be enabled with drush dep-en. (The help text seems to be wrong).

So for the task at hand, drush dep-en should do the job.

You can download it here.

UPDATE:
Now available on github: https://github.com/donquixote/drupal-drux

Alternatives, part I

As pointed out by Jesse Pinho in another answer, you can also run drush fr DEPENDENT_MODULE.

Or you can run drush en DEPENDENT_MODULE.

The difference is that for these commands you need to know the "DEPENDENT_MODULE" which has the added dependencies.

With drush dep-en you can just run the command without any arguments, and it will check all enabled modules for dependencies.

Alternatives, part II

Instead of such drush commands in combination with dependencies, you could also use hook_update_N() to enable additional modules. This seems a common technique for Drupal 7 projects.

See the answer by reubidium.


Inserting "sponsored content" into a fixed position in a view

I found a pretty great solution that i hope others can use.  I simply made a new view with my list of sponsored content in a node queue.  I then used the function views_embed_view inside my view template of content and displayed each block at a certain row ID whick looked a bit like this:

<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>
 <?php if ($id == 3): ?>
<?php print views_embed_view('sponsored_content','block_1'); ?>
 <?php endif; ?>
 <?php if ($id == 8): ?>
<?php print views_embed_view('sponsored_content','block_2'); ?>
 <?php endif; ?>


Based from the first sample code found in Drupal's Batch API page, it says,

  If this function was called from a form submit handler, stop here,
  FAPI will handle calling batch_process(). If not called from a submit
  handler, add the following, noting the url the user should be sent to
  once the batch is finished.

And that we need to add the batch_process('node/1'); (still based from the sample code). So you just need to add this line of code with the Drupal path where you want the user to be redirected after the batch process after the batch_set() line.

The die() line also isn't needed anymore based on the sample code. I have also tested your code on my local D7 site with the batch_process() addition.

Unrelated Update

In your for loop declaration for ($i = 0; $i < $max; $i = $i + $increment), I noticed that the afterthought section doesn't increment the loop because the variables $i and $increment has no incremental operation.


Display both sort icons on sortable table columns

I used some jQuery and CSS to accomplish this:


Show fields from diffrent content types in same view?

Depending in the setup, the person who makes the reservation might also be referenced via the author field in views, but I don't know how your reservation system works.

Properties of other entities can be embedded in a view via the relations in the advanced section. There has to be a common field such as an entity reference linking the two content types together, but author, tags and several other properties can be used as well.

After adding such a relation, New fields will become available in the fields, filter and sorting sections.

UPDATE

I believe there is some misunderstanding about the modules. An entity reference (or any other reference in Drupal) uses the user id (uid) not a custom field #L. So when you add such a reference to a content type, you can only find users by username (or common name if realname module is installed). Since you said you have the customer name this should not be a problem as you select the users by name, but their uid is stored in the database.

Make sure there is only one relation on the content type that is created on the desk (registration). Adding an entity reference on the user (or both content types) makes no sense; a registration is made for one or more users, user's don't own one or more registrations.

Create a view listing fields of the main content type you want to display (registration). Then add a views relationship to the user object via the entity reference field. Finally you can add all fields of the user object to your list of fields.

The only filters you will need are filters for limiting the set of registrations (you could add contextual filters to list registrations per user), but I'd leave out all registrations to start with. You can always add them later.


Modify Drupal pagination to restrict shown page numbers on Drupal 8

It would seem that at the point you're trying to modify the quantity, the pager items have already been generated so your quantity value doesn't have any effect.

Similar to Drupal 7, I believe you're going to need to implement the full pager function, just copying the core pager function to your theme and changing the quantity.

function MYTHEME_preprocess_pager(&$variables) {
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = 5; // hardcode your quantity here
  global $pager_page_array, $pager_total;

  // Nothing to do if there is only one page.
  if ($pager_total[$element] <= 1) {
    return;
  }

  $tags = $variables['tags'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  // Create the "first" and "previous" links if we are not on the first page.
  if ($pager_page_array[$element] > 0) {
    $items['first'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, 0),
    );
    $items['first']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[0])) {
      $items['first']['text'] = $tags[0];
    }

    $items['previous'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
    );
    $items['previous']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[1])) {
      $items['previous']['text'] = $tags[1];
    }
  }

  if ($i != $pager_max) {
    // Add an ellipsis if there are further previous pages.
    if ($i > 1) {
      $variables['ellipses']['previous'] = TRUE;
    }
    // Now generate the actual pager piece.
    for (; $i <= $pager_last && $i <= $pager_max; $i++) {
      $options = array(
        'query' => pager_query_add_page($parameters, $element, $i - 1),
      );
      $items['pages'][$i]['href'] = \Drupal::url('<current>', [], $options);
      if ($i == $pager_current) {
        $variables['current'] = $i;
      }
    }
    // Add an ellipsis if there are further next pages.
    if ($i < $pager_max) {
      $variables['ellipses']['next'] = TRUE;
    }
  }

  // Create the "next" and "last" links if we are not on the last page.
  if ($pager_page_array[$element] < ($pager_max - 1)) {
    $items['next'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
    );
    $items['next']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[3])) {
      $items['next']['text'] = $tags[3];
    }

    $items['last'] = array();
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_max - 1),
    );
    $items['last']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[4])) {
      $items['last']['text'] = $tags[4];
    }
  }

  $variables['items'] = $items;
}


When you edit an installed and enabled module, Drupal will not notice you added new hooks, since the list of the hooks implemented by a module is cached from Drupal. In order to make Drupal notice you edited the module and added new hooks, you need to disable and re-enable the module, without uninstalling it.

The reason why this is necessary is that module_implements(), the function that returns TRUE when a module implements a hook, contains the following code.

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }


Composer update Drupal core, 8.5.1 to 8.5.2 Nothing to Install

You can try to delete the vendor directory and the composer.lock file, and then run the update again.

UPDATE:

You need to add the line "drupal/core": "~8.5.2" to the 'require' statement (or update it to whatever version you require).
Then remove the drupal/core line from the 'replace' statement.
Add the following line somewhere (at the end? I believe this should replace the existing repositories statement):

"repositories": {
  "drupal": {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
}

Then delete the vendor and composer.lock, and try again.

It should work.


Use the Block API to add the blocks

i.e:

hook_block_info
hook_block_view

Use menu_get_object to get the node object for that page.

e.g:

function mymodule_block_view($delta){
  $block = array();
  switch($delta){
    case 'my_delta':
     if ($node = menu_get_object('node') && $node->type == 'my_type') {
       $block['subject'] = t('Example block on %node', array('%node' => $node->title));
       $block['content'] = render(field_view_field('node', $node, 'body')); // for example
     }
    break;
  }
  return $block;
}


Organize files attached to a node into folders

Just make a taxonomy vocabulary to simulate the folder structure. Install File Entity module. It makes fieldable files, so you can attach taxonomy for the file own - with the module Media you can do that during editing the node.

To display files grouped by folders, you can make a view to do that, and use EVA to embed it into the node. In the view you have to make a 'File' based view, just add a relationship to the node, and add a Content Id contextual filter, which use that relationship.


Drupal 8 does not create path alias' valid for all languages

That's currently not supported.

Partially blocked by core, which also doesn't allow to create language-neutral aliases while editing nodes and then also wouldn't show them anymore. See https://www.drupal.org/node/2511968 and https://www.drupal.org/node/2689459. Once those are resolved, pathauto could follow those definitions.


You need to choose a specific token context from those available such as [current-page-what?]:

[current-page-number]   The page number of the current page when viewing     paged lists.
[current-page-path] The URL alias of the current page.
[current-page-path-raw] The URL alias of the current page. Warning: Token value contains raw user input.
[current-page-title]    The title of the current page.
[current-page-url]  The URL of the current page.

You should specify your fallback global page titles under '/admin/settings/page-title' and for specific node types, such as 'story' 'page' or 'blog' for example.

You should input the page title tokens as follows;

Example 1:  [current-page-path] [page-title]
Example 2:  [page-title] | [site-name]
Example 3:  [page-title] | [site-slogan] - mysite.com

Note that you can insert symbols or text between the tokens or after.  In this case we've inserted the vertical bar '|' and a hyphen '-' plus the site name 'mysite.com' within the pattern.

I think you've understood correctly.

Although the example above relates to Drupal6, I've tried to recreate your problem in Drupal7 and can't because the default [current-page:page-title] | [site:name] always kicks in, as it should.

Have you tried completely removing the Page-Title module, running Cron, updating the database and installing the module again?


Rules is definitely the way to do this.

Create a new rule...

Name: Order Status Update
Tags:
React on event: Commerce order > After updating an existing commerce order

Then, add an action. System > Send mail
Email "To" value. Use the [commerce-order:mail] token
Fill out subject and message. Then save.

Updated: To make sure you dont send an email everytime the order is updated, set the following rules...

Add condition: Data Comparison. Commerce-order:status = Completed
Add "AND".
Add condition: Data Comparison. Commerce-order-unchanged:status = Completed, but check NEGATE.

This avoids having to enable the PHP filter module.


Webform limit to multiple choice question

Discovered a module called Webform Validation, works fine. But the user will only know that he can't submit more than x answers after clicking the submit button.


Use sites.php to point https and http to diffent sites

Please read through the default example.sites.php file again. A protocol is the same thing as a port (they have a 1-to-1 relationship when we talk about a webserver).

http is implied by default in the rule describing www.example.com. http is also implied to be Port 80, otherwise known as :80 in a URI-scheme.

Your format is completely wrong for any subsite defined in $sites. From the documentation it would be:

$sites['www.example.com']='site1';   // Normal HTTP www.foo.com
$sites['443.www.example.com']='site2';  // SSL version (port 443 by default for www.foo.com)


Here is an example taken from All functionality of hook_menu() is replaced by new systems for routing, menu links, local tasks, actions and contextual links:

Drupal 7

in modules/book/book.module:

function book_menu() {
   $items['book/export/%/%'] = array(
    'page callback' => 'book_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access printer-friendly version'),
    'type' => MENU_CALLBACK,
    'file' => 'book.pages.inc',
  );
    $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'book_outline',
    'page arguments' => array(1),
    'access callback' => '_book_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'book.pages.inc',
  );
...
  return $items;
}

Drupal 8

in modules/book/book.routing.yml:

book_export:
  pattern: '/book/export/{type}/{node}'
  defaults:
    # What's being returned is the entire response (not HTML, or even if HTML, we don't want additional blocks around it), so use _controller instead of _content.
    _controller: '\Drupal\book\BookController::export'
  requirements:
    _permission: 'access printer-friendly version'
book_node_outline:
  pattern: '/node/{node}/outline'
  defaults:
    _controller: '\Drupal\book\BookController::outline'
  requirements:
    # Indicates that the book outline access access system should be invoked.
    _book_outline_access: TRUE


how to make unique fields in profile type in drupal 7

You can use the http://drupal.org/project/field_validation for unique validation. When this module is enabled, there is a validation tab for each fields in content type. If you want to validate the unique value. Just go validation tab and click on the "Unique values", do some configuration, the unique value rule will be applied for current field.


How does a Webform able to differentiate among radio buttons, check boxes and Lists

the webform_component table also has an extra column you've cropped out.

It's SQL column help description is:

  Additional information unique to the display or processing of this
  component.

A select can simply be rendered many ways -- I believe the display settings for the "selectable options" used in rendering a radio, list or checkbox are in that column.


Views Pager, Can I change Items per page dynamically as provided input?

I think this might help. I normally use hook_views_query_alter in order to alter my view results.


Changing background color in table when status is changed

You can add use fields as classes to table rows and then through CSS assign background color to it. Check the screen shot, in the screen shot I have used a field as Row class. You will get your field replacement pattern in "Rewrite the output of this field" for all fields.


How do I get the display id of a view in Drupal 6?

Edit the view, then hover over the tab link for your display.  Look at the URL.  It will look something like:

http://thesite.com/admin/build/views/edit/the_view_name#views-tab-the_display_id

You should be able to use "the_view_name" and "the_display_id" in the drush command.


How do I use "DOES NOT CONTAIN" with \Drupal\Core\Entity\Query\QueryInterface?

You can make use of NOT REGEXP if we assume that $state is an array of multiple states.

I will explain with example:
for example if want to get all nodes with the field title DOES NOT  CONTAIN page, hello, and test.

Sql statement should be something like:

SELECT * FROM `node_field_data` WHERE `type` = 'page' AND `title`  NOT REGEXP '^.*page.*$|^.*hello.*$|^.*test.*$';

Drupal Code:

  $excluded_strings = array('page', 'hello', 'test');
  //- Add regex prefix and suffix
  $excluded_strings_with_regex = array_map(function ($val) {
    return '^.*' . $val . '.*$';
  }, $excluded_strings);
  //- Join array elements with a string | glue
  //- result $regex_p_string = "^.*page.*$|^.*hello.*$|^.*test.*$"
  $regex_p_string = implode("|", $excluded_strings_with_regex);
  //-Build Query
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'page');
  //- Add regex Condition.
  $query->condition('title', $regex_p_string, 'NOT REGEXP');
  $nids = $query->execute();


Table form valueCallback strange behaviour

My solution is below. It is a weird solution because It requires small changes.

Define a table value callback.

    $form['links'] = [
      '#type' => 'table',
      ...
      '#value_callback' => array($this, 'valueCallback'),
    ];

Implement the callback.

 /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    return $input;
  }

The data has structure as it has been sent. So the standard data processing works badly for my case.


Try accessing user/logout, and then log in the usual way.


Problems with SQL Syntax using Left Join and OR

The answer it appears is to use the GROUP BY statement in my SQL right after the WHERE clauses. So, the following:

GROUP BY rn.entity_id, rn.field_resource_name_value

The returns just one entry for each field resource name.


Am I missing a step with using Features?

Features can sometimes be finicky. Often times, just clearing caches after reverting will cause your changes to go into effect. In other cases, it can be necessary to revert the specific item (such as views or rules).

Personally, I haven't used Page Manager with features, but the general concepts apply consistently across the board.


Translated node does not use translated entity reference, how to fix this?

Some people told me this happends on default, but I've just set up a test site with i18n and entityreferences enabled, and it gives the same result.

But I found a sandbox project that worked for me after changing one line of code in the entityreference_translation.module:

This didn't work:

if ($item['target_type'] == "node") {

This works:

if ($field['settings']['target_type'] == "node") {


Try looking at yoursite.ca/admin/build/themes/settings.

When there, check that under "Display post information on" that your content type is checked.

After looking at this, it seems like a bug in the date module. Try updating the date module, but make sure that you have a backup of the site before doing so.

You should also soon upgrade to Drupal 7 or 8, as Drupal 6 sites risked being hacked.


Adding a vertical tab the the content type form page

Try this. Or read about hook_form_FORM_ID_alter()

function mymodule_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['mymodule'] = array(
    '#type' => 'fieldset',
    '#title' => t('mymodule'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

}


how to change save button to Save and keep published?

This looks like you want to change the node edit form back to the old layout of Drupal 8.3. You can use this module:

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


Node Metatag data migration with the Migrate-Update\Drupal-Upgrade module

Both redirect and Metatag have to provide their own migrations (migration templates), it's not something that you can just configure.

All you can do, if you don't know how to do it yourself is open issues for those projects and hope someone will do it. Or find someone you can pay that does it for you.


How to create form on users account page?

You'll have to define a form function using the drupal form API
See this tutorial for more info on how to make your own forms.

So the actual form function would look something like this

MY_FORM_FUNCTION($form, &$form_state){
  // Build form array here
  return $form;
}

MY_FORM_FUNCTION_validate($form, &$form_state){
  // Validate function here
}

MY_FORM_FUNCTION_submit($form, &$form_state){
  // Submit function here
}

Now in the tutorial they use HOOK_menu to display the form on a page. But you can call drupal_get_form('MY_FORM_FUNCTION') from everywhere and generate a render array for the form.

So this would show your form on the user page via HOOK_user_view_alter

 $account['form'] = drupal_get_form('MY_FORM_FUNCTION');


know if the last cron run automatically or manually?

I'm not sure why you really want to check this. However, I can think of a few methods:

Alter the admin/reports/status/run-cron menu router item, and add some flagging to mechanism to detect the call. If the user runs cron through this page, that's definitely a manual "Run Cron" call. Implement hook_menu_alter, and change page callback (probably file and file_path aswell) to your own function. In this function, add some flagging mechanism, and run previous page callback. It's unlikely that another module will need overwrite the page callback so you are almost safe. A little performance hit during menu rebuilds.
Add your own cron handler, and check $_GET['q'], or better, $_SERVER['PHP_SELF'].
For $_SERVER['PHP_SELF'], if it's index.php, that's a manual run. Otherwise it will be  cron.php, which is likely an automatic call. However one could click the URL containing the token, which is not actually an automatic. I think this is the best method since it does not need to assume other modules does not need to override page callback. A little Performance hit in each cron run.
Hack the cron.php (better yet, copy it to a new file). For example, copy cron.php file to scron.php, and make your crontab request that file instead of the the regular cron.php with token. You can then edit the scron.php file, and right after the bootstrapping, add a custom code to flag the cron that the file is about to execute is an automated one. Requires some custom effort that you can't do with a regular hook_install implementation. Performance wise, this will work almost same since there are no any hooks involved.


How can I trigger a Drupal Core action without writing any PHP code?

In your specific case the commment notify module would be helpful.

From description,

  Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

Otherwise is could be done using Rules I think.


How to find out who and when created taxonomy term

No, not in Drupal core. Unlike the Node entity, the Taxonomy term entity does not define a field that stores a field denoting ownership. You'll need to add your own field to your taxonomy terms to give them an ownership property.


Field data is stored in arrays.

Here is a sample user account information I save from information retrieved elsewhere:

 $roles = user_roles();
 $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      'roles'        => array(array_search('student', $roles) => 1),
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['last_name']))),
      'field_secret_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['secret_number']))),
      'mail' => $ldap_details['mail'],
    );

So as you can see field data is stored as:
array(LANGUAGE_KEY => array(INDEX => array('value' => 'SOMETHING HERE')));

You just access/set it as you would any PHP array.

You may get stuck if you find your fields arent in the user record -- attached fields are not eagerly loaded you have to call a function to be sure they are attached to the User entity:

// For speed, typically Drupal does not attach additional fields to $user
// objects, if they are not found we request attached fields now.
if (!isset($account->field_first_name ) || !isset($account->field_last_name)) {
  field_attach_load('user', array($account->uid => $account));
}


How to use Feed importer to import content type in which one of the field is node reference field type?

I have used feeds tamper. Multiple values are comma separated in the file that I intended to upload. I have added explode plugin and , delimeter in the feed importer page (tamper).


How to display Views fields as a drop down menu?

It depends on the specific context - are you simply wanting to use the view results as a menu (in which case Menu Views would do this), or are you wanting to display a number of items e.g. users, and have more detailed info on the items spill out on hover (in which case, a display format such as Views App Folders might be what you're looking for).


Display User Relationship request dialog on content profile page

I've created Add as friend likes in a project once doing this:

l(t('Add as friend'), 'relationship/' . $account->uid . '/request');

It served me fine, but I'm not sure if you want something different.


It sounds like you have a "Pager ID" value set in your view. From your example my guess is that it's set to "6" instead of the default "0". Check within the "Pager Options" of your view display to see if this is the case, and if so, change that value to 0 to restore the URL to a more standard form.

It's important to note that there are of course some situations where your need this pager ID to be set, notably if you have multiple views, each with pagers, displayed on the same page. If this is the case, and you have to use a pager ID > 0 on one of your views, you could set it on your "secondary" view (the one users are less-likely to page through) and leave it at 0 for the "main" view.

It also looks like you have the "Clean Pagination" module installed, or something similar? Normally I think a paged URL would have the pager query string (?page=#) exposed, so you must be doing some special clean URL processing for that. Still, I think the "Pager ID" notes above would apply regardless.


How to align views pager url with real page number?

As 4k4 mentioned in the comment there is an issue for this you should check out.

In the meantime you might implement a workaround (outside of Views)

with the help of the Query Parameters To URL,
or outside of Drupal through your server configuration and redirects.


This question has nothing to do with Drupal but with CSS order of precedence. If more than one identical CSS rules are found, the last one takes precedence.

As @leymannx pointed in their comment, your page is loading first your CSS file, then Bootstrap. Just move your Bootstrap into a new library as you just did with 'mymovies', then add a dependency to 'mymovies'. Declaring it as a dependency, it will load first the need libraries, then the library being called.

Edit - after saying you are using OnePage Zymphonies theme:

If you check 'onepage_zymphonies_theme.libraries.yml' you will see that the Bootstrap library is defined. Following my answer:

mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}
  dependencies:
      - onepage_zymphonies_theme/bootstrap


How to filter a view by "Group administrators" ?

You can add a relationship to "OG roles from membership" in your view and then filter on the OG role. No need for custom code.


How to use the filter flag in drush config:status

If you look at the Consolidation\Filter\OperatorFactory class mentioned with the error, you'll see documentation at the top of the Class that outlines the acceptable syntax.
**
 * Convert a simple operator expression into an Operator.
 *
 * The supported operators include:
 *
 *      key=value           Equals
 *      key*=value          Contains value
 *      key~=#regex#        Regular expression match
 *
 * It is also possible to negate the result of an operator by
 * adding a logical-not operator either before the entire expression,
 * e.g. !key=value, or before the operator, e.g. key!=value.
 *
 */

Using the above documentation as a guide, the following all work for me - examples two and three should work for your example case.
// 1. Use the *Equals* option to show only the config entity with name "webform.webform.contact"
drush --filter="name=webform.webform.contact" config:status

// 2. Use the *Contains value* option to show any config entity with name containing "webform.webform"
drush --filter="name*=webform.webform" config:status

// 3. Use the *Regular expression match* option to show any config entity with name starting with "webform.webform."
drush --filter="name~=#^webform\.webform\.*#" config:status


AJAX in Form API element returned in another AJAX callback

After a lot of reading, I solved this by returning $form on the AJAX callback, and including the second button on a form rebuild. My code now looks more like this, and it's working fine:

function my_form($form, &$form_state) {
  $wrapper_id = drupal_html_id('some_wrapper');

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  if (isset($form_state['my_flag']) && $form_state['my_flag']) {
    $form['my_other_button'] = array(
      '#type' => 'button',
      '#name' => 'my_other_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      )
    );
  }
  else {
    $form['my_button'] = array(
      '#type' => 'submit',
      '#name' => 'my_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      ),
    );
  }
}

function my_form_submit($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'my_button':
      //code for when user presses the first button
      $form_state['my_flag'] = TRUE; //show the other button
      $form_state['rebuild'] = TRUE; //this is necessary!
      break;
    case 'my_other_button':
      //code for when user presses the second button
      break;
  }
}

function my_callback($form, $form_state) {
  return $form;
}

I think the problem had to do with a button being outside an actual form. I hope this helps others...


How to include order details in eMail notifications created with the Message module?

You just goto
http://localhost/project/admin/commerce/config/checkout/rules/manage/commerce_checkout_order_email/edit/3

then as screenshot into the message value you can set your custom message and also use "Replacement patterns" for order detail to the message.

thank you..


How to close the overlay after form submission

The callback should be:

function fullcalendar_ajax_node_save_callback(&$form, &$form_state) {
  // Could check that the overlay is open? Part of core, so overkill
  if (module_exists('overlay') && overlay_get_mode() == 'child') {
     $current_path = current_path();
     overlay_close_dialog($current_path,
        array('query' => drupal_get_query_parameters(NULL, array('q', 'render'))));
    $form_state['redirect'] = FALSE;
  }
}

See overlay.module, about line 148 function overlay_init() for an example in core that uses as much drupal API as possible.


Convert integer retrieved from node field to uid?

You have to fetch the User entity by ID using the value from the content type field without any conversion.
Then in the "Send Push Notification to Specific User" rule, you can use the ID from the fetched entity.
Not sure why you can't use the variable directly, but this is the case.


How can one determine if a view is empty using views_embed_view()?

You could use views_get_view_result() which returns an empty array if the view has no result to display.


Views Grouped by *each* value of a content field (multivalue).

Grouping is done by the information you have in your results.

Fields with multiple values return results differently, depending on the Multiple field settings you set on them.

If you choose to Display all values in the same row then each node will show all "Research Areas" related to it, and if you enable grouping groups will reflect the option combinations from results. This is your current behavior.

If you untick the option Display all values in the same row each node will be displayed in a separate row showing only one "Research area" it belongs to, but it will be listed as many times as it has "Research areas" attached to it. When you enable grouping in this scenario each "Research area" option will behave "independently".

So to achieve your desired behavior you need to untick the option Display all values in the same row on your "Research Areas" Field (mind you this is under Fields, and not under Format where Grouping options are).


How to seperate products images folders based on product display categories?

What you are proposing to do won't really work since you cannot embed tokens within tokens. You're going to need to split the images up based on something else. Here are some options:

Product type [commerce_product:type] (e.g. "shirt" - I haven't checked this one.)
Date [current-date:custom:Ym] (e.g. "201512")

Furthermore, unless you have hundreds of thousands of images, you're likely not going to see much of a performance degradation. If you do have that many images, perhaps you should consider using a CDN or some external system to offload image handling.


First, form/user mode and form/user display isn't the same thing.

But the schema for all of them is in in core/config/schema/core.entity.schema.yml.

That said, I'm not sure why you want to build that file? Especially for a node type. Create the node type and the fields, configure the form and view displays in the UI, export it, add the files to your modules, don't. You don't have to build them yourself.


DrupalGap's implementation of Private Message has not evolved enough to take into consideration any Private Message configuration set on a DrupalGap Manage Display page for User Entities.

That being said, I would recommend creating your own page to custom render a User Entity. With these docs, essentially replace the usage of node with user and that'll give you a custom page in which you can render your users.

Then in your page_callback function to render the users, you can add a widget to the content render array, which could display a button that when clicked will navigate the user to a custom DrupalGap form+page where you can build the input elements (recipient, subject, message, etc).

Then in your form's submit handler, you'll actually send the message to the user.


Since there's logic involved (check records based on this date, if there are no results, check the previous date) I would do this with a custom module making use of Entity Field Queries.


How to prevent newline character in textarea

If using jQuery is an option for you, you can do something like this:

$('#yourTextAreaID').keyup( function() {
  $(this).val( $(this).val().replace( /\r?\n/gi, '' ) );
});

This code will replace the newline character on the fly, after the user types it. This code can be added in a custom.js file of your theme that you include in every page of your site, or you can alternatively use a hook_form_FORM_ID_alter in your custom module in conjunction with the drupal_add_js function to add the specific js file only in the specific form's edit page.

Keep in mind that if Javascript is disabled in the user's browser, he will be able to insert newline characters. In order to prevent this, you will have to add a custom validation function in your form. A very good tutorial on how to do this can be found here. The most important parts are:

1) Use a hook_form_FORM_ID_alter (in the tutorial he uses the old-school approach with hook_form_alter).

2) Add an extra validation function with something like:

array_unshift($form['#validate'], 'MYMODULE_form_validate');

3) Write your custom validation function (name it: MYMODULE_form_validate) that checks for \r?\n in the value of the textarea in the $form_state variable and return a descriptive error if there is a newline character.

Regarding the second part of your question, you should add some more information about what exactly didn't work. Did you clear the cache after following the steps? Do you get any errors in the log messages? Did you add console.log in your Javascript to verify that is being executed?


Installing TinyMCE plugins on Drupal 7 with the WYSIWYG module

You need to inform the WYSIWYG module that you've installed a plugin, it won't know it's there otherwise. It will involve writing a small custom module.

Have a look in the wysiwyg.api.php and wysiwyg.api.js files included in the root of the  WYSIWYG module folder; there are examples and very good documentation explaining exactly what you need to do.

The most important (perhaps only) hook you'll need to implement is hook_wysiwyg_plugin()


How to make scheduled Feeds importers run consecutively?

You've entered that territory where you would be better served by a custom module than trying to force Rules to do what you want.

If I were posed with this problem I would do the following:

Create two CRON jobs one for each of the importers in a new module. See hook_cron().
Turn off all of Feeds default importing for those feeds.
Install Elysia Cron.
Schedule your cron jobs with Elysia to run at appropriate intervals leaving enough
time for the first to complete before running the second.
For extra credit you could programatically check that the first import is
complete before allowing the second to run.


An AJAX HTTP error occurred using commerce coupon percentage

This seems an error in Commerce Coupon Percentage module. Your problem comes from the EntityMetadataWrapperException: when processing the AJAx petition something goes wrong and an Exception is throw. This is fatal, so Apache ends the petition with the status 500.

I think this a bug in the module code, so you may go the issue queue for this module and create a new bug report with your problem.

By the way, the Commerce Coupon Percentage is only comptabible with Commerce Coupon 1.x, check your are using a 1.x release.


How do I change the default configurations for the node options?

Unfortunately in that case, I guess that you should do your own module and use hook_form_alter()


Override default table template In custom module

Add a module path to the Drupal 7 theme registry by implementing hook_theme_registry_alter().

Here's an example - replace the usual with your own data :)

/**
 * Implements hook_theme_registry_alter().
 */

function MYMODULE_theme_registry_alter(&$theme_registry) {

  // Get module path
  $path = drupal_get_path('module', MYMODULE);

  // Find all .tpl.php files in this module's folder recursively.
  $template_files = drupal_find_theme_templates($theme_registry, '.tpl.php', $path);

  // Itterate through all found template file objects.
  foreach ($template_files as $key => $template_file) {
    // If the template has not already been overridden by a theme.
    if (!preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file);
    }
  }
}


It's possible to set up 2 filters:

Filter operating on date (as you described)
Filter "job expiry" field is empty

Then use the drop-button right of Filter crieria, go to And/Or, Rearrange and change the operator for group to OR

Let me know, if you need further assistance.


Add non mandatory fields to user registration form

I have never encountered such problem before. But since you have such problem then I think the best way is to write a hook_form_alter. And set the required field that you don't want as mandatory to false.

function mymodule_form_alter(&$form, $form_state, $form_id){
switch ($form_id)  {
    case 'registration_form_id':
                $form['field_name']['und'][0]['value']['#required'] = FALSE;
            break;
                   }
               }

Hope this helps.


How to make taxonomy term name field work with 'Full HTML' text format?

Try using the check_plain function in your template file. Similar to what is shown in this example (which is for menu items though).


How do I display a content author's userpoints next to the author's name on posts?

The API function to get the points is userpoints_get_current_points() *. Just call that function with the uid of the author and display the returned result.

* Note that my API documentation page only lists the Drupal 7 versions, this function works the same way in Drupal 6 and 7 but others might not.


Show a menu block only on nodes that belongs to this menu

Take a peek at http://drupal.org/project/menu_block. I think it might do what you want, or, if not, at least maybe its code might give you an idea on how to do so yourself.


drupal 6 to 7 site upgrade using drush_sup - how to download compatible drupal 7 modules

I would run through the site upgrade process with the --prompt-all flag set to see if anything strange appears.

drush drush_sup will upgrade core and find good candidates for contrib modules, I think it'll even accept dev releases, but with a warning.

You could also pass in --auto to the command which will just do the defaults.

Source: http://drupalcode.org/project/drush_sup.git/blob/refs/heads/7.x-2.x:/README.txt


You might want to look into the hook_admin_paths function where You can define the pages that should use the administration theme.

For this to work on specific roles just use something like:

function mymodule_admin_paths() {
  global $user;
  if(in_array('administrator', $user->roles)) {
    //Make the changes for the administrator
  }
}


How to programmatically create file entity reference on entity

The file entity module wraps around the core file field, which defines only three field columns that you need to worry about providing:

fid (file id)
display (boolean indicating if the file is displayed or not)
description (self-explanatory)

You can safely ignore any other values that you find on the field as they'll be discarded anyway when it comes to committing the field data.

If I remember rightly it's the core file module that adds the extra data to the field, which is essentially the file object converted to an array. If you're seeing any other 'foreign' values in there they're probably coming from the file_entity_field_load() function.


Is displaying a working Field Widget Form on its own possible?

VBO does something like this in modify.action.inc:

$form_key = 'bundle_' . $bundle_name;
$form[$form_key] = array(
  '#type' => 'fieldset',
  '#title' => $label,
  '#parents' => array($form_key),
);
field_attach_form($context['entity_type'], $entity, $form[$form_key], $form_state, LANGUAGE_NONE);

So, you need the entity type, the entity (which can be a blank object with just the bundle key set, that's what's actually used), the form where the widgets are added, and the language.
If you want to embed the widgets deeper into the form (not in $form, but in $form[$form_key] as I did, or even deeper), then that form array needs to have #parents set.

Of course, notice that this will embed the widgets of all fields belonging to that entity type & bundle. This is how the attach functions were written.
Going around that would require you to reinvent quite a lot of code; see the actual code that does the heavy lifting.
What I do is go through field instances, get each $field_name, and if that field type doesn't interest me, I set $form[$form_key][$field_name]['#access'] = FALSE;
which hides those widgets from sight.

EDIT: Okay, ctools has ctools_field_invoke_field() which could in theory allow you to work on a per-field basis. I've never used it though. The text above is my direct experience.


Here is a little working piece of code for you. You may extend it according to your needs

document.onselectionchange = function() {
    var selectedText = "";
    $('div').mouseup(function() {
      //Save selected text in localStorage.
      selectedText = window.getSelection().toString();
      if (selectedText.length > 10) {
        var noteData={
          "sourcePath": window.location.href,
          "selectedText": selectedText
        };
        localStorage.setItem('noteData', JSON.stringify(noteData));
        window.location.href = '/node/add/page';
      }
    });
  };

  // Get saved data from localStorage and insert in the form.
  var savedNoteData = JSON.parse(localStorage.getItem('noteData'));
  if (savedNoteData && savedNoteData.selectedText) {
    $('.form-item-title input').val(savedNoteData.selectedText);
    localStorage.setItem('noteData', '');
  }


Get display name from hook_preprocess_views_view

You can get the display ID through the current_display property of the View object, e.g.

$view = $vars['view'];
if ($view->name == 'foo' && $view->current_display == 'bar') {
  // ...
}


In your form_submit, add $form_state['redirect'] = <your_url>, at the end.


what are some considerations to help me decide whether I should configure through the UI, when to configure programmatically

You should make configuration changes in code as much as possible, in particular it helps with

Ease of deployment
Consistency across deployment environments
Consistency across developer team environments
Configuration changes are tracked in version control.
The required configuration for the application is in the code base.

If you haven't already, checkout the Features module for a good approach to exporting and synchronizing configuration between environments.

For example, you can build a Feature module for your

Views
Panels
Content Types
Fields
etc..

and synchronize the changes in code by rebuilding the relevant feature module on dev, deploying it and reverting the feature module on the deployed environment.


If you're working in Drupal 7, check out the Field Groups Module.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

If you're on Drupal 6, you want the MultiGroup module, which is a part of the 3.x branch of CCK.


Create 2 separated taxonomy pages with views

Your template file name should be like this -> taxonomy-term--tid.tpl.php
Source


Change '/user(/*)' URLs to 'profile(/*)'

The routes you've defined are new routes with different names and this is the reason the standard routes are still in place. If you want to override the standard routes you would have to use the same route names like user.page:.

But this is not the best approach to alter multiple routes. Better use a route subscriber:

src/EventSubscriber/RouteSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      if (strpos($route->getPath(), '/user') === 0) {
        $route->setPath(preg_replace('/^\/user/', '/profile', $route->getPath()));
      }
    }
  }

  public static function getSubscribedEvents() {
    $events = parent::getSubscribedEvents();

    $events[RoutingEvents::ALTER] = array('onAlterRoutes', -250);

    return $events;
  }

}

mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\EventSubscriber\RouteSubscriber
    tags:
      - { name: event_subscriber }


I'm reporting back to provide my solution.

The site itself was Drupal v 7.51. As you can see, I was using Drush v. 8.1.5.

Reverting back to 7 corrected the issue and was done fairly easily following the modules unraveled tutorial here: https://modulesunraveled.com/blog/install-drush-7-and-8-and-automatically-switch-versions-based-project.

Regards


Safely change module without losing change at module update

Add your own library with a JS file, make sure the file has a weight higher than the image widget crop's JS file, then simply monkey patch the existing object like so:

Drupal.ImageWidgetCropType.prototype.defaultOptions.toggleDragModeOnDblclick = false;