How to display term images instead of term names in the term selection process?

Looks like the Taxonomy Term Reference Tree Widget module gives you the ability to add images to term references. Here is a quote about it (from the module's project page):

  ... provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


I believe you are looking for Empty text under Basic Settings.  This will allow you to set some text (message) that will be displayed if the view returns no results.

You can choose any of your available input filters, the above is just an example.


Finally i got the answer . Actually it should be used like YOURMODULE_form_views_exposed_form_alter only . No need of activities_page_1_ as expected . Am adding the answer below :

/**
 * Implements hook_form_FORM_ID_alter().
 */
function module_name_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  $form['created']['min']['#title'] = t('From');
  $form['created']['max']['#title'] = t('To');
}


How do you get the options from a select form?

$form is the array build on server side, and it is not modified from JavaScript code executed from the browser, as that array is never passed to the browser. That is the reason why $form['list']['#options'] contains only the values set from the form builder.

The code that retrieves the value of $form is the following one, contained in drupal_build_form():

  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

When the form is submitted, that code retrieves the value of $form used to build the form.


If you want to display a common piece of content on all the pages, you can  create a block with the common content, and display that block in the content region of the required pages.

Just go to /admin/structure/block and position the block before or after the Main page content block, and set it to only display on the required pages.


You can make a View and use the Views Aggregator Plus or Views Calc.

From Views Calc module page:

  This module adds simple calculations to a views table.

  You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).

You can found some screenshots here: How can I show average votes of fivestar nodes?


How to safely remove drush via pear and then install via composer?

Uninstalling Drush using Pear

If Drush has been installed using Pear, it can be removed using the following command.

pear uninstall drush/drush

Installing Drush via Composer

For the most current install instructions, refer to the Drush GitHub page.

1) Add Composer's global bin directory to the system PATH (recommended):

sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

2) Install Drush

composer global require drush/drush


Edit content created by users with the same role

I would approach this by grouping users with organic groups module instead of by role. Roles are only for defining access level, not for making groups of users.


Can I remove the "summary" from the "Text (formatted, long, with summary)" widget?

Well, that was easy.  On admin/structure/types/manage/page/fields/mycontenttype, you just have to uncheck the box for "Summary input."


Try some thing like this and see if it helps

function views_pag_views_pre_build(&$view) {
    if ($view->name == "pagination") {
            $view->init_pager();
            $view->set_items_per_page('10');

    }
}


Drupal 7 js compression generating 6 files

Surprisingly, the larger number of files can actually save bandwidth on subsequent requests, something that YSlow doesn't take into account.  Aggregating everything into a single giant file is really only optimal for visitors that load a single page and no others.

I wrote an article explaining the details in Drupal 7: Taking control of CSS and JS aggregation.

To reduce the number of files, you can try the Core Library module. The article above also has some example code that will group the files together using hook_css_alter() and hook_js_alter().


Prepare name and address for use with drupal_mail()

All credit to @deceze

Original Solution

In short:

mb_internal_encoding('UTF-8');

$name  = '山本';
$email = 'yamamoto@example.com';
$addr  = mb_encode_mimeheader($name, 'UTF-8', 'Q') . " <$email>";


If you're looking for scrolling similar to Twitter, try the Views Infinite Scroll module.

If you're looking for something more like this site, try the Geared Scrolling module (DISCLAIMER: which I maintain).


What to do when a theme doesn't show up in the enabled or disabled themes?

I would double check that all the theme files crossed over. As long as there is a .info file in the theme folder, it should show up in your drupal site.


Module:

The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.
The Panels module allows a site administrator to create customized layouts for multiple uses.
Context allows you to manage contextual conditions and reactions for different portions of your site. For each context, you can choose what blocks to show.

Theming:

Template suggestions are alternate templates based on existing .tpl.php files. You can write in preprocess_page , where put condition and if true, assign page template to page--empty.tpl.php - here you should remove all regions printing except content - so you will get empty page.


How to add js in view created by interface

If you are following that 4th comment exactly the problem is probably that it is a hook for viewing a node, not for a 'view'. Ambiguous to be sure.

The accepted answer here should be helpful: How do I add JavaScript specific for a view?.

EDIT

Okay, this may be more helpful. The trick here is finding a place to hook in to check to the page before it is rendered to add the javascript to the render array. The assumption this code makes (which may not be accurate) is that you are looking at a views page. If the view is nested in a block or a panels pane this may not work as well.  Here goes:

/**
 * Implements hook_page_alter().
 */
function food_truck_form_page_alter(&$page) {
  $views_page = views_get_page_view();

  if ($views_page->name == 'marqueurs_admin') {
    $path = drupal_get_path('module', 'food_truck_form' );
    $page['#attached']['js'][] = array(
      'type'=>'file',
      'data' => $path . 'js/food_truck_form.js'
    );
  }
}

This also assumes that you are implementing it in a module called food_truck_form and your view is named 'marqueurs_admin'.

Also, as a side-note, it often works better formatting-wise to edit your post to add the additional info there rather than in the comments.


Expose some administrative functions on the front-end

Your question is a little broad -- anything is possible given time, effort and perseverance!

I find the Role Delegation module and similar modules help to give out permissions to trusted users.

I also have been creating an Administrative Panel page using the Panels module with embedded Views and Blocks for centralized site admin options for users. I usually call this page the staff dashboard for my admin-type users.

Without specific problems you're having, these general tips are all I can provide. Happy coding!


How to translate a panel page title and a pane title

Latest version of Panels module (7.x-3.4 as today) includes Panels translation module (i18n_panels), which provides a fix for this issue.


How can I dynamically disable a single required field from validation in a form?

Why dont you use conditional field module?

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

By this module you can disable the requirement of fields when something happens to another field. you can also implement your form as a content type so its node/add page will be your form. Then by using the different hooks you can add autocomplete field or do any thing else


Translating custom database table fields

The first argument of t() is a literal string, not a dynamic string. If you use a dynamic string, that will be translated only if it matched a literal string another module passes to t().

For example, if I use the following code, the string will be shown translated (when a translation for the currently enabled language exists), as 'E-mail address' is used as argument of t() from user_account_form().

  $label = 'E-mail address';

  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t($label),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#required' => TRUE,
    '#default_value' => '',
  );

If the values contained in that database field are limited to specific values, then you can add the following code to the module you are using.

function mymodule_translated_strings() {
  $strings = array(
    t('first value used for the database field'),
    t('second value used for the database field'),
    t('third value used for the database field'),
  );
}

The function doesn't need to be called; it is required only to have a call to t() for each literal strings that contain one possible value of that database field. Clearly, this is convenient if the database field can assume values which are restricted to a small set of values. If the values assigned to the database field are input from users, then this approach is not possible, since the users can (theoretically) enter any value.

For the other cases, the Internationalization module could be helpful. As described in Translating user-defined strings (module developers), i18nstrings() is the function that should be used in this case.


Add a caption to an image field that allows multiple images

I believe what you are looking for is the Field Collection module.  It allows you to group fields together and repeat the group many times.  The following article gives a good description of what the module does: Create Multigroups in Drupal 7 using Field Collections

From the Field Collection project page:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.


Menu add item or edit item not available for users with admin rights

Do you have any custom/forked modules installed on the site? Themes?

Try changing the theme; if it works with another theme (let's say Bartik) then the problem is somewhere in your theme.

If the above doesn't work, clone the site and start disabling the modules one by one; eventually you will find the one which is causing the problem.


How to set value to login form's submit via themename_form_alter

Buttons and Submits (yes, they are different things in Form API) does not have default value. All you can set for submit is: #access, #after_build, #ajax, #attributes, #button_type (default: 'submit'), #disabled, #element_validate, #executes_submit_callback (default: TRUE), #limit_validation_errors, #name (default: 'op'), #parents, #post_render, #prefix, #pre_render, #process, #submit, #states, #suffix, #theme, #theme_wrappers, #tree, #type, #validate, #value, #weight

As you can see, no #default_value. As user is not supposed to be able to change that value, it's simply #value - no need for defaults.

Read more on Form API Reference.


Drupal 7 - Profiles 2 Module - Share profile data or migration

I think you can use a hook_form_alter() to add visibility conditions on your user_profile_form elements :

Add these kind of attributes on field you want to hide for free users :

'#states' => array(
   'visible' => array(
      ':input[name="field_1"]' => array(
         array('value' => 'paid'),
     ),
   ),
),


Aegir tasks not running, after accidentally upgrading drush

I found the solution. The problem occurred due to incomplete barracuda + octopus upgrade. One has to run the following commands to finish update

 barracuda up-stable
 octopus up-stable all


Custom ckeditor.styles.js possible to specify for any/all elements?

I also searched for a way to specify multiple elements for one style - and it doesn't seem to be documented anywhere. I was successful with specifying multiple elements as an array:

{ name: 'Red', element : ['h1', 'h2', 'p'], attributes: { 'class': 'red' } }

This works for me in CKEditor 4.2.1.


Avoid caching pages for authenticated users with Varnish

In your settings.php are you using $conf['omit_vary_cookie'] = TRUE; ?

If so, logged in users who have previous viewed a page when logged out will be served the varnish cached version of their page until they manually refresh their browser.

The solution is to simply comment out $conf['omit_vary_cookie'] = TRUE; in your settings.php.

This is explained in default.settings.php (drupal 7.34):

 /**
 * Page caching:
 *
 * By default, Drupal sends a "Vary: Cookie" HTTP header for anonymous page
 * views. This tells a HTTP proxy that it may return a page from its local
 * cache without contacting the web server, if the user sends the same Cookie
 * header as the user who originally requested the cached page. Without "Vary:
 * Cookie", authenticated users would also be served the anonymous page from
 * the cache. If the site has mostly anonymous users except a few known
 * editors/administrators, the Vary header can be omitted. This allows for
 * better caching in HTTP proxies (including reverse proxies), i.e. even if
 * clients send different cookies, they still get content served from the cache.
 * However, authenticated users should access the site directly (i.e. not use an
 * HTTP proxy, and bypass the reverse proxy if one is used) in order to avoid
 * getting cached pages from the proxy.
 */
# $conf['omit_vary_cookie'] = TRUE;

This DA question answers this issue too: What does the "Vary: Cookie" header actually do for serving pages from Varnish?


How to alter the query that selects node in the admin/content page

I had this issue in Drupal 6 just now, on the "/admin/content/node" overview page.  I wanted to hide certain content types -- and you can't do that with views per se because the admin page is a form, where you can easily bulk update.  Sorry that I'm not putting a D7 answer -- this may not be exactly what you are looking for, but it works for me in 6, and maybe others will find it helpful:

/**
 * hide child content types from /admin/content/node overview
 */
function [your module]_db_rewrite_sql($query, $primary_table, $primary_field, $args){
    if(arg(0)=='admin'&&arg(1)=='content'&&arg(2)=='node'){ // /admin/content/node page
        if($primary_table=='n' && $primary_field == 'nid'){
            if(!user_access("[your access callback for viewing this type]")){
                  $return['where'] = 'type != "[type to hide machine name]"'; // or you could use type == type_name
                  return $return;
            }
        }
    }
}

again.. that's D6, so I'm sorry but hopefully that will get you started


Get node path for Entity Referenced in Views

You already have the Entity Reference module installed and that is sufficient.

Create a view with base table Offer. Then add a relationship as follows: Click on add relationship, select filter by Entity Reference which will only show the entity referenced endpoints. It will show the field in question from two directions. You are working from the entity that contains a reference to another entity. You therefore select the 'A bridge to the Content entity that is referenced via field_whatver.

This pulls in the related entity. Now you just have to add the new field (URL) to your view and make sure that you set the relationship when you add it to the relationship you defined.


Override Entire Module Page using Template

You want to override the deliver callback for the menu route.
https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_deliver_page/7

But notice this might be very invasive and cause you issues later on.


Limit number of upload in Imagefield depending on a specific field

This will need customising to your specific situation, but the basic idea is to add a validation handler to the node form and perform a check in there, e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_id') {
    $form['#validate'][] = 'MYMODULE_images_validate_limit';
  }
}

function MYMODULE_images_validate_limit($form, &$form_state) {
  $images_submitted = count($form_state['values']['field_image'][LANGUAGE_NONE]);

  if ($images_submitted > function_to_get_limit()) {
    form_set_error('field_image', t('Too many images'));
  }
}


Access front page node only by front page link

Assuming you want http://example.com/node/6 to redirect to http://example.com/, I'd take a look at the global redirect module: http://drupal.org/project/globalredirect


Auto-complete show everything by default

Mabye you can use the Chosen module :

Install, enable and configure the Chosen module
change the widget type of your field to "Select list"
in the field settings screen, check "apply chosen on this field" :

Now in your content edit form, you should see something like this, where the entire list appears in the dropdown, but where you can also type an autocomplete request :


Javascript variable value in page source for seo from Drupal.settings

I think you're over-estimating the potential SEO value of making such a change, but if you don't want to use Drupal settings you can just interpolate the value into a static string and use that:

$var = variable_get('my-variable');
$js = <<<EOF
function() {
  window['my-val'] = '{$var}';
}
EOF;
drupal_add_js($js, 'inline');

I'll leave data-sanitising up to you, how far you need to go will depend on the source of the variable.


Not directly, but you could do that in your own custom form validation.  For example:

function YOURMODULE_form_alter(&$form, $form_state, $form_id) {

  switch ($form_id) {

    case 'YOUR_CONTENT_TYPE_node_form':

      $form['#validate'][]='YOURMODULE_valid_extensions';
      break;

    // any other forms here

  }

  // any other form alters here

}

function YOURMODULE_valid_extensions($form, &$form_state) {

  // $whitelist=array('txt', 'doc', 'pdf');
  $blacklist=array('xxx', 'exe', 'php');

  /* I am assuming that this is a single value field ([0] below) */
  $extension=pathinfo($form_state['values']['field_YOURFIELD'][0]['filename'], PATHINFO_EXTENSION);

  // if (in_array($extension, $whitelist)) {
  //   return;
  // }

  if (in_array($extension, $blacklist)) {
    form_set_error('field_YOURFIELD', t('Invalid file extension'));
  }

}

and if you leave the extensions field blank, filefield won't do any validation, but you will in the second function above.  I've also put in //'s basically what filefield is doing if you wanted to incorporate both.  If you do go this route, you will have to put some verbiage in your help section as the widget will most probably say all extensions are valid :)


Drupal 7 contexual filter display block based on node reference

Here is what I would do if I am understanding this correctly:

Create a new view block

1.) Create a view with Filter critera:  Content type is book
2.) Then I would create a Relationship to: Content Reader
3.) Add all the fields and add a relationship to the Reader content type (whatever you want displayed from the reader content)
4.) Add a contextual filer with: Content NID, where it says WHEN THE FILTER VALUE IS NOT AVAILABLE click on the Provide default value radio and select Content ID from URL
5.)  Add that block to the story display page wherever needed


Webform component weight within a Fieldset

Ok, there is a column pid in webform_components for individual components. This value correlates with the cid of the fieldset. A LEFT OUTER JOIN between the cid and pid columns, filtered by the webform node id - nid, then ordered by the fieldset weight followed by the select option weight returns the components in the correct order as they appear on the node form. Here is the db_query statement.

db_query('SELECT *
FROM webform_component AS f
LEFT OUTER JOIN webform_component AS s ON f.cid = s.pid
WHERE f.nid = 123 AND s.nid = 123 AND f.type = "fieldset" AND s.type = "select"
ORDER BY f.weight, s.weight');

This works. Any advice on optimizing this query is appreciated.


Views contextual filter on just ONE of the listed contenttypes

That really depends on your specific view configuration. Generally speaking, you can add validation (e.g. what content type to accept as contextual filter) and a fallback behavior (e.g. ignore argument vs. show 404), see screenshot. With these instruments you can achieve pretty much.


How to redirect to content if view have 1 result?

In your theme's themename.theme file add:

At the very top add:

use Drupal\views\ViewExecutable;
use Symfony\Component\HttpFoundation\RedirectResponse;

Then add:

/*
 * Implements hook_views_pre_render()
 */
function THEMENAME_views_pre_render(ViewExecutable $view) {
    if($view->id() == "view_name" && $view->current_display == 'view_machine_name') {
      if (!empty($view->result) && count($view->result) == 1) {
        $url = $view->result[0]->_entity->toUrl()->toString();
        $response = new RedirectResponse($url);
        $response->send();
      }
    }
}

Clear the cache so changes kick in.

my_module/src/Controller/ViewPageController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Cache\CacheableRedirectResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Defines HelloController class.
 */
class ViewPageController extends ControllerBase {

  public function content() {

    $view = Views::getView('view_name');
    $view->setDisplay('view_machine_name');
    $view->execute();

    if (!empty($view->result) && count($view->result) == 1) {

      $url = $view->result[0]->_entity->toUrl()->toString(TRUE);
      $response = new CacheableRedirectResponse($url->getGeneratedUrl());
      $response->getCacheableMetadata()->addCacheTags($view->getCacheTags());
      $response->addCacheableDependency($url);
      return $response;

    }
    else {

      return [
        '#type' => 'view',
        '#name' => 'view_name',
        '#view' => $view,
        '#display_id' => 'view_machine_name',
        '#embed' => TRUE,
        '#cache' => $view->getCacheTags(),
      ];

    }

  }

}

This is the view_machine_name.


How can I tell Guzzle to safely ignore ssl.certificate_authority in Behat testing? (Development server)

After reading on https://github.com/Behat/MinkExtension/blob/master/doc/index.rst#drivers, I tried the following in the behat.yml file.

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte:
        guzzle_parameters:
          verify: false
      selenium2: ~
      base_url: http://localhost
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/var/www/html'

It worked.

I needed to find out how to tell Guzzle/cURL to not worry about validating any CERT. Again, I would not do this under a production server, but for the sake of a local development environment, I'd give it a go.


How i can show the value of submitted form

First of all the validation should not be done in the form submit function. It should be done in a validate function.

For example in your case there would be an additional function which would look like

 function parkingcalulator_form_validate($form, &$form_state)
 {
    $from = strtotime($form_state['values']['from_date']);
    $to = strtotime($form_state['values']['from_time']);

    $difference = $to - $from;
    $timeInHours = floatval($difference) / floatval(60*60);
    if ($timeInHours <= 0 )
        {
            form_set_error('from_time',t('Time inserted error'));
        }
    }

If you want to display the result with in the form, after submitting then you would add a value to the form_state with in your form_submit function such as

$form_state['total_cost'] = $totalCost;

And then tell the form to rebuild by adding this code again in the form_submit function

$form_state['rebuild'] = TRUE;

Now with in the function you create the form the variable $form_state['total_cost'] would be available. you place that in a form element of the type markup. something like this

if(isset($form_state['total_cost']))
{
$form['total_cost'] = array(

  '#markup' => t('Total Cost is : ') . $form_state['total_cost'],

);
}

The if condition is used so that it is not executed in the first stage when the form is not submitted as the value is not yet there in the variable. The above code should go in the form function in your case parkingcalulator_form($form, &$form_state)

For more details examples you should refer the Examples Module which has a submodule called Form Examples.


Why I'm not able to debug twig templates? sites/default/files/php directory is empty

Probably the directory sites/default/files/php/twig is empty because the container parameter twig.config.cache is set to false.

The approach used in the linked article is arguable.. put a breakpoint in every twig compiled template is not a viable solution. For debugging twig templates with xdebug there are better alternatives:

use the devel module + this patch (Committed)
use the twig_xdebug module


Mobile browser to be assigned different background

I use Omega for that.

It's based on CSS media queries.


How can I create a Feature and have it saved under 'features manage' tab?

You can use the "Direct save" feature of the Features Tools module if you want to do this from the UI instead of the command line with Drush.


How to create tabbed menu consisting of views and a contact form while having unique paths for each tab?

If your "Contact us" page is not the default Drupal contact page, but a webform (i.e. a node), you could use views to create tabs (see this tutorial, for example). In that case you would create a view that shows just the one webform node and configure it the way that it is displayed as a tab - and the FAQ view as default tab.

I suppose that there is also a workaround embedding the contact form instead of using a webform node.


How could I do a FULL OUTER JOIN in drupal?

Dynamically it would look like this:

$q = db_select('table1')
  ->fields('table1', array('column_name'));

$q->addJoin('FULL OUTER', 'table2', NULL, 'table1.column_name = table2.column_name');

Which will give you

SELECT table1.column_name AS column_name
FROM
{table1} table1
FULL OUTER JOIN {table2} table2 ON table1.column_name = table2.column_name

Or you can run any SQL string with db_query():

$sql = <<<SQL
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
SQL;

$result = db_query($sql);


Checkbox to make billing information same as shipping information does not work for Anonymous users

Turns out I was kicking myself on this one. I forgot I had some custom hook_js_alter code in my template.php that removes unnecessary js from the page for anonymous users. This was done to improve site speed and because my custom theme didn't require these default Drupal js libraries.

function theme_js_alter(&$javascript) {
  $logged_in_user = user_uid_optional_load();
  if(!in_array("authenticated user", $logged_in_user->roles)) {
    foreach($javascript as $key => $value) {
      unset($javascript[$key]);
    }
  }
}

However I do need these javascripts on commerce checkout pages apparently, so I added a request_path() check for checkout and cart pages so the js would not be unset.

I confirmed the My Shipping information is the same as my Billing information checkbox now works for anonymous users.


'hook_field_widget_form_alter' but for markup

Attributes on the option tags aren't themeable unfortunately, many of the standard form elements in Drupal are this way. You can theme the wrappers to your hearts content, but the elements themselves are quite locked down.

If it is absolutely necessary to do this you may need to find a way of doing it outside the form API.

You could use the #post_render on the FAPI options for it to do some manual rewriting of the output markup using regex and whatnot. Not very efficient but probably quicker than writing something from scratch!

The function that handles this is in the includes/form.inc file form_select_options. I really wouldn't condone editing it, but it is handy for reference.


Is there any way to disabling caching for a single field for anonymous users?

Just an idea - in this case a workaround might be to hook a function after an order has been placed and then clean the cache programmatically.

You can use the hook_commerce_checkout_complete() and there call the cache_clear_all() function.


Drush enable module | not working | Drupal 7 on WAMP with PostgreSQL

I'm not on Windows or using postgres today, but I can suggest how to debug:

What you've got right now is that your cli environment seems to be failing to connect to the database correctly.
Checking your database-level access from drush, using verbose (-v) debug (-d) feedback may provide clues.

For instance, given your current failure, I would run

  drush -v -d sql-cli

that will, among other things, show you the exact database connection command being attempted that is failing.

You can then copy that yourself, run it again,  and see what variations of that
   command will and will not work. One of the more common issues seems
   to already be covered (the difference between 'localhost' and
   '127.0.0.1' depending on installation and version issues. There may
   be other issues such as 'cannot locate postgres.exe in the current
   $PATH' or whatever.

This is not an answer to the question, but a suggestion on how to get clueful when a (any) drush command just doesn't work. You can also use the -vd flags on your 'en' command, though I don't know how conclusive the feedback you get there will be.


Path to inline image  inside page.tpl.php to theme/images/ dir?

The following code will get you the path to your theme, together with your site's base path:

<?php print base_path() . path_to_theme(); ?>

Meaning that you should use something like this:

<img src="<?php print base_path() . path_to_theme(); ?>/images/your-image.jpg">

Note: the path_to_theme() will not have the trailing slash, so you have to add it yourself if your image is in a subfolder.


Image widget crop not returning multiple derivatives in JSON API

You can try the code

use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;

$filed_images = $paragraphs->get('field_image')->getValue();
 $images =[];
 foreach ($filed_images as $image) {
            $images[] = ImageStyle::load('273x273')
              ->buildUrl(File::load($image['target_id'])
                ->getFileUri());
          }


I still don't think I'm understanding the symptom.

If something shows up in one theme and not the other I would check if you have anything wierd in your template.php or if you have overridden any of the content-field.tpl.php files


Can I hide date field if older than a certian time using Rules?

Use the Conditional Fields  module.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


Use Tokens and/or Replacement Patterns in Shortcodes

Ok, seems there are some limited ways to do this, using available replacement patterns that are not contained within square brackets. i.e. %1 and !1, but not [replacement pattern]

Luck would have it, the replacements I need are the %1 and !1 values.

Still - would be great if anyone had any ideas how to use square bracketed replacement patterns in shortcodes without closing the shortcode (which is what appears to happen).


Display add to cart form / +product from node template

Since views seem to be the easiest way to display product offerings, the way I solved this was to create views for the products. The views are configured as blocks. Then I use:

$block = module_invoke('views', 'block_view', $block_name);
print render($block['content']);

to display the block.

I used content type fields to specify the block names I want to display within certain areas so it isn't hard-coded. It isn't terribly elegant, but sometimes programming is that way since there isn't an infinite amount of time to solve problems!


Get users by custom field and field type

You'll need an EntityFieldQuery for that:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_id', 'value', $field_id);

There's no native way to query by type of field. To do that you'll need to use the EntityFieldQuery::addTag() method to add a custom tag to the query, and then use hook_query_TAG_alter() to manually join the field_config table into the query before it's run.


How to hide paragraph items based on permission

Field permissions is not what you want, that only does permissions for fields, not for the entire entity like you want.

There's a hook called hook_ENTITY_TYPE_access, you can use it as hook_paragraphs_item_access(), that would let you alter permissions (Look at the paragraph_bundle_permissions submodule for an example).

As others have said paragraph items don't actually have the owner on them - neither does field collection. They aren't really mean't to be separated like this. You can add the property yourself if you want to.

I recommend changing the Paragraphs to not be paragraphs and be something like Nodes instead. If they have permissions and are owned by someone, paragraphs aren't really the right thing. You can use Inline Entity Form if you want to embed a form for it. Since they are nodes you should be able to have more control on permissions.


clone of drupal project failing: operation timed out

Try disconnecting your wifi and then connecting again. Used to resolve the issue before, when i got "some broken pipe error". This generally happen iF your wifi network keep switching to different connection to balance the load. Just a suggestion.


How do I change position of a "fixed" element/header to go below Admin toolbar when in Admin view?

In drupal you need to use jquery like this

(function ($) {
 $( document ).ready(function() {

      // custom code here

     });
  });
}(jQuery));

So try:

(function ($) {
  $( document ).ready(function() {
      Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
        attach: function(context, settings) {
          if ($('body').hasClass('toolbar')) {
            $(window, context).resize(function() {
              var toolbarHeight = $('div#toolbar').height();
              $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
            });
          }
        }
      }
    });
  });
}(jQuery));

If that doesn't work, all you have to do is check if the toolbar div class or id exists.

if ($('#toolbar').length > 0) {
    // dostuff
}

So if there is a wrapper that wraps everything on your site except the admin toolbar. that would be more ideal to use. So all you do is move everything down by 10 or so pixels

Using CSS with jQuery

(function ($) {
 $( document ).ready(function() {
          if ($('#toolbar').length > 0) {
           $('.zone-user-wrapper').css({"position": "relative", "top": "10px"})
           }
     });
  });
}(jQuery));


Getting the user ID of the user who created a taxonomy term

try to do this:

Add a field called 'Author' like a entity reference
alter the form to prepopulate this field

function customodule_form_alter(&$form, &$form_state, $form_id){
print_r($form_id);
if( $form_id == 'taxonomy-form-term' && isset($form['field_author']) ){

  print_r($form['field_author']['nid']['nid']['#value']);
  global $user;
  $form['field_author']['nid']['nid']['#value'] == $user->uid;

  }
}

I put some print_r so you can debug this code fast.


Set data value of entity reference field with rules

If you can't work out how to do it with Rules, maybe try a custom module. It's been suggested to me that you could use hook_node_update(), or hook_node_insert() to populate that field.

Check http://drupal.org/node/1388924.


In simple terms, CCK is yet another module that alters the forms. When your form_alter function is used, even if you disable the field, it will not work. That's because the CCK forms are built after those form alter functions.
Note that this limitation is only for Drupal 6. In Drupal 7, it should work with regular form_alter functions.

I had to do this on a client site. This page from Drupal docs helped me a lot.

See Clive's answer. It's how we do it on regular forms.
But don't forget that you always can use field permissions which is much more robust than form alters.

Also, note that setting the field's disabled attribute means this field will not be submitted by browser. If you want to get the value back to your site, use read only attribute with some fancy css to make it look like disabled (browser will take care to not allow editing). Chuck Norris can hack the page using Firebug or something to change the content though.


dynamically populate a select field based on the selection in another field works only the first time

It is hard to say without seeing your JavaScript, but what you describe fits perfectly with the following scenario:

When your page loads initially loads, the LoadDiv JavaScript event is bound to #DivSelect, but when that #DivSelect element is overwritten by the Drupal AJAX api, the event is no longer bound.

The solution is to use Drupal.behaviors - there is a good, short explanation at http://www.amazeelabs.com/en/blog/drupal-behaviors-quick-how.

Wrap your LoadDiv javascript in the drupal behaviors code, and it will be added for every request, including AJAX requests:

Drupal.behaviors.myModuleDoSomethingCool = {
  attach: function (context, settings) {
    $('#DivSelect').change(function() {
      // Loaddiv etc etc
    });
  }
};

I agree with comments suggesting that this is a good use case for hierarchical select - but the above is the likely explanation for why your AJAX works the first time and not the second time.


It looks like you're building a so-called "jump menu", is that correct?

It's not considered good practice to code a menu into a template like you're doing in your example. Try to build the functionality of your site with modules (existing ones, or custom) and use the theme (template.php, CSS files, template files) for appearance only.

If you need a jump menu, have a look at the Jump module. It provides a block for every top-level menu and every vocabulary, so it could get you exactly what you need without writing one line of code.


Using multiple AND/OR operators in contextual filters

As a workaround I have second contextual filter configured and arguments are separated with "/". In this case your /21+27/19+20 should work fine.

Still searching for the real solution.


How to migrate files into a field with unlimited values (D6 -> D7)

Finally figured it out. The image field with unlimited values needs a default value with file paths presented as an array. As the array in $filepath was 2 dimensional (an array in an array), I needed two foreach loops to get down to the simple array needed. This is now a working example, I publish it here in case somebody have the same question:

$i = 2;
$filepath = array();
if($row->field_productimages[$i] != ''){
    while($row->field_productimages[$i] != ''){
        $fid = $row->field_productimages[$i];
        $filepath[] = Database::getConnection($target='default', $key='legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',
        array(':fid' => $fid))->fetchAssoc();
        $i++;
    }
    foreach ($filepath as $value1){
        foreach ($value1 as $value){
          $files[] = $value;
        }
    }
    $this->addFieldMapping('field_bildspel_instrument')->defaultValue($files);
    $this->addFieldMapping('field_bildspel_instrument:source_dir')->defaultValue('http://www.myoldsite.se/');
    $this->addFieldMapping('destination_dir')->defaultValue('public://product/slideshow');
    $this->addFieldMapping('field_bildspel_instrument:file_replace')->defaultValue('FILE_EXISTS_REUSE');
    $this->addFieldMapping('field_bildspel_instrument:file_class')->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_bildspel_instrument:title', 'field_productimages:title');
    $this->addFieldMapping('field_bildspel_instrument:preserve_files')->defaultValue(1);
    $this->addFieldMapping('field_bildspel_instrument:urlencode')->defaultValue(1);
}


How to change timezone format for user/site settings?

Yes, you're close. The problem with the above code is that it doesn't set the correct key values in #options; thus upon saving, the date_default_timezone variable will be set to some numeric key instead of an accepted PHP timezone string that is expected for the variable.

Do something like this to set the correct key:

function token_form_system_regional_settings_alter(&$form, &$form_state, $form_id) {
  $options = array();
  foreach(timezone_identifiers_list() as $timezone) {
    //$options[$timezone] sets the value for date_default_timezone select
    //$timezone set the display for select
    $options[$timezone] = $timezone;
  }
  $form['timezone']['date_default_timezone']['#options'] = $options;
}


AJAX callback fails using form_alter on two fields

the solution is to return the target field in the ajax callback
so the code is :

function ajax_callback($form,$form_state) {
        return $form['field_campagne']['und']['0']['value'];
    }


Below is how I resolved this before, for a multilingual D7 site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.

Step 1

Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only (e.g) FR menu items.

Step 2

Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be admin/structure/menu/manage/main-menu/edit.

For "Translation Mode", use the option "Translate and Localize". So that
menu items with language will allow translations, and menu items without language will be localized.

Step 3

Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for all languages, make sure such link is marked as "Language Neutral".

Summary

For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language.

Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...


Drupal 8 REST - How to export Drupal 8 Main navigation menu with REST service (JSON)

I ended up creating a module that does the basics for getting a menu via rest. I can just put the menus machine name in the URL and it will give me the title, url and weight in JSON format. I uploaded it to github so you can test it out. It is by no means ready for productions web sites. I was just messing around with angular and REST in D8.

Using angular, I would get the menu using the new URL resource after enabling the module and route resource 'entity/restmenu/{menu-name}?_format=hal_json in your case entity/restmenu/main?_format=hal_json

app.controller('MainController', function($scope, $http) {
  $http.defaults.headers.common.Authorization = 'Basic YWRtaW46YWRtaW4=';
  $scope.menuData = $http.get('entity/restmenu/main?_format=hal_json').then(function(response) {
    $scope.menuData = JSON.parse(JSON.parse(response.data));
  });
});

https://github.com/rondog/rest-menu

<?php

/**
 * @file
 * Contains \Drupal\rest_menu\Plugin\rest\resource\rest_menu.
 */

namespace Drupal\rest_menu\Plugin\rest\resource;

use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Menu;
use Drupal\Core\MenuTreeParameters;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "restmenu_resource",
 *   label = @Translation("REST Menu Resource"),
 *   uri_paths = {
 *     "canonical" = "/entity/restmenu/{menu}"
 *   }
 * )
 */
class RESTMenuResource extends ResourceBase {
  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }
  /**
   * Responds to GET requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get($entity) {
    $menu_name = $entity;
    $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
    $result = array();

    foreach ($tree as $element) {
      $link = $element->link;
      array_push($result, array(
          'title' => $link->getTitle(),
          'url' => $link->getUrlObject()->getInternalPath(),
          'weight' => $link->getWeight()
        )
      );
    }
    return new ResourceResponse(json_encode($result));
  }
}


scheduled site backup at specific time / hour

Try Elysia Cron, in addition to Backup and Migrate, you can set the time of day to run as well as many other things.

Don't forget to read the documentation.

It is also worth noting that in the default configuration of Drupal 7 cron is triggered by users hitting your site.  If the site is not used exactly at the time indicated in Elysia Cron it will be run as soon as someone loads something on your site.  Therefore, it is impossible to get this to execute exactly when you want, but it should be close.


Simplenews + Mime Mail + SMTP = occasional blank email

First step. Have you combed your logs in Drupal for errors?  And have your also looked at your web server PHP error logs?

With this random problem you are having I would expect to see something going on in the logs.

I have never used the Simplenews module or reviewed it's code so I cannot say how well the authors of the module addressed error handling the module.

Clearly you have a problem and it's been reported by other people. If you find no error in the logs then I would say that potentially the module does not have enough error handling written into it to diagnose the problem.

For what it's worth (purely for your own information), I will say that attempting to do an email newsletter from a a web server is not the preferred method. An email service provider should be used for that functionality if you have any concern for deliver-ability of your newsletter.


Trying to access PHP library from within another namespace

When you use use you need to provide namespace + classname. This is what you are doing already, so

use ilib\lms;

Should be replaced with

use ilib\lms\AddLMSActivity;

If you want to use the AddLMSActivity class.


How to map ubercart attributes to CCK fields?

If you really want fields and do not want to use your price in your views (though Ubercart is really compatible with views), you can use Rules to fill the value of a "hidden" (I recommend you use field permission for that) CCK numeric field.

Once you've created the field for your product content type, set the rule like this :

Event : Content is created
Condition : Is of type your product content type
Condition : Entity has field your numeric hidden field
Action : Add a variable : get your price value
Action : Convert data type : make it numeric
Action : Set a data value : set your hidden field value.

(Maybe this 3 last actions can be done in only 1 with "set a data value", it's worth trying it)


full html and ckeditor strip some meta tags

Please add following code in Ckeditor Javascript Settings,

config.allowedContent = true

Thanks


Can I combine multiple "no results behavior" to avoid repetition?

I solved it myself (that's a first and probably a last)!

I'm sure this isn't the best code but it works and I don't know enough PHP to clean it up.

I disabled all "No Results Behaviors" in the view settings. I'm using the hook_preprocess_views_view hook to count the number of results for each of my attachments. Only if all 4 === 0 will it print the correct empty message.

function MYTHEMENAME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'search_results') {
    $view1 = $view2 = $view3 = $view4 = $view;

    if (is_object($view1) && is_object($view2) && is_object($view3) && is_object($view4)) {
      $view1->setDisplay('page_1');
      $view2->setDisplay('attachment_1');
      $view3->setDisplay('attachment_2');
      $view4->setDisplay('attachment_3');

      $view1->execute();
      $view2->execute();
      $view3->execute();
      $view4->execute();

      if (count($view1->result) === 0 && count($view2->result) === 0 && count($view3->result === 0 && count($view4->result) === 0)) {
        $variables['empty'] = "Sorry, but we couldn't find any results for your query. Try broadening your search terms.";
      }
    }
  }
}


Parameter upcasting in Forms: buildForm works, submitForm doesn't

Yes, this is intentational. submit and validate callbacks aren't tied to the request, they only receive exactly those two arguments.

As mentioned in the comments, you can store the information either on the object, with $form_state->get()/set() or a form elemnt of #type value, doesn't make a big difference which you chose.

You could also store only the ID instead of the whole object but actually, I believe it is stored anyway in form_state somewhere when you pass it as an argument to the form (pretty well hidden though, so better to store & access it in a more explicit place)


Try using:
Views Templates

Creates the views templates functionality which was removed in D8
views.

(have not used this myself, as I haven't made the jump to D8 yet).


How to allow visitors add option in poll?

Advanced Poll

Advanced Poll is a replacement to Drupal's poll module and provides
multiple voting systems, decision-making tools, and management
options.

Then in permissions (/admin/people/permissions), allow anonymous and authenticated users to vote and add write in votes.


How to show upcoming events in the current month with calendar module?

Try paginating the view by Date,I guess should get the month options in the pagination as well.I do not have a drupal set up with calendar so can not confirm, you have to give a try.


D7: How to loop an array as form elements?

For those of you who face the same issue: I found the answer:

foreach($jcartItemName as $key => $value) {
$form['jcartItemName'][$key] = array(
'#type' => 'textfield',
'#value' => isset($value) ? $value : '',
);


Using Drush without typing drush every time

This functionality was added in 2010 and removed in 2012. "By the book" way is to use bash with bash completion and optionally bash aliases. Or you can wrap it into a simple php / bash / c program that will automatically prepend drush -l $yoursitename to everything you write and execute the result, and use that as your small simple shell. But you would give up bash completion then.


Changing default domain in domain access causes 'access denied' for admin

Caching would be my first thought, make sure to clear cache (through drush since you can't log in). Also if you have any heavy caching like Varnish - clear that too. You may have an active session still in Drupal for the admin account, try removing that via - drush sql-query 'TRUNCATE TABLE sessions;'


Views query alter or condition not works

Ok, both solutions are work. The problem is in query fields that not exist because need add field tables. I didn't unserstand this because of this:

    catch (Exception $e) {
        $view->result = array();
        if (!empty($view->live_preview)) {
          drupal_set_message($e->getMessage(), 'error');
        }
        else {
          vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
        }
      }

Views didn't show me error.


How to limit adding content of a specific content type to paid memberships only?

Assuming that your "Add blog post" matches with an URL like node/add/blog, you can use the Rules module to stop any user who is trying to use that URL, if that user does not have access to the role "Paid membership" that you have in place. Here is the actual rule to do so (in Rules export format, just import it in your own site and enable it there to see it at work):

{ "rules_limit_access_to_node_add_blog" : {
    "LABEL" : "Limit access to node\/add\/blog",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "node\/add\/blog" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Adding content for selected content types (such as for \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022) triggers some extra (Rules) logic, as you can see here. I.e. for anyone who does not have the role to do so.",
          "type" : "error"
        }
      }
    ]
  }
}

The assumption in this rule is that your role "Paid membership" has a role-id of "4" (if not just adapt the role after you imported the rule to make it fit, or change the value of "4" before importing the rule). And if your URL is different from node/add/blog, then adapt that also to make it fit for your case. Obviously, the actual error message being shown may need tuning also. And if the machine name of your content type is not "blog", but "whatever", just change all blog occurrences to "whatever" before importing this rule.

Happy Rules-ing!


You can find some well written answers on using cookies in Drupal here.


How authenticated users can choose favorite products and show them in their profile?

This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.
Refer to Flag's Community documentation for (way) more details.
And to show this in their user's profile, could be implemented via an appropriate view (using Views), in the format of a block display, whereas you adapt the block visibility settings to only show such block for an URL that corresponds with the user's profile.


add code automatically for any article/post

The easiest way is to create a block and add your code to it if it's html or javascript code. Then for Show block on specific pages select only on the listed pages and add articles/* This will affect all the pages that have articles in their url.

If it's php, you will need to create a custom page tpl file.

go to drupal/sites/all/themes/mythemename/templates and add page--articles.tpl.php This will affect all the pages that have articles in their url.


How to create View with Full Content and Teaser

First, list only the full node in a Views display, then add a second display of type "Attachment". This attachment view will then list all the teasers, and can be configured so that it always "attaches" to the bottom of the primary one.

This way you can get both Views, but they always render together.


How do I remove a system CSS file in a theme?

You can try with the unset method that drupal provides for css alter hook. Try the following code in your custom module

function hook_css_alter(&$css) {
unset($css[drupal_get_path('module','system').'/system.theme.css']);}


I'm making a few assumptions, the main one being that you're using Drupal 6...

Basically your PHP error reporting settings include E_STRICT compliance, and the code in the version of Views you've got installed isn't compatible with it. D6, and subsequently the associated version of Views, was written for PHP4 and PHP5, and as such isn't compatible with E_STRICT.

You can either

Disable E_STRICT error reporting in your php.ini/other php conf file (if you're not sure how to do this, get whoever administers your server to do it - it'll make sense to them). Or
Apply the patch in this issue (comment #11) which will remove the problems for PHP5.3. If you have PHP5.4 installed, there's another patch in #26 to apply too.


When should field_attach_load be called manually?

api.drupal.org says:

  field_attach_load() is automatically called by the default entity
  controller class, and thus, in most cases, doesn't need to be
  explicitly called by the entity type module.

Basically only call it if you're implementing an entity type and don't want to use the default entity controller. I'm pretty sure ClosedQuestion is in the wrong, since it's only making a node type. All fields should be attached by the time hook_load() comes along.


128 character limit in Drupal text fields

Maybe my brain isn't in gear, but in your code you have '#maxlength' => 128, everywhere...  Changing that to 4096 worked here and allowed a really long message. Changing textfield to textarea and removing #size and #maxlength worked as well.


Install profile with variable default language messes up translations

Turns out to be a simple solution: the variable i18n_string_source_language can be used to specify the source language of all strings, instead of the current site language.

I ended up setting

$conf['i18n_string_source_language'] = 'en';

in my settings.php. This worked.


I believe Rules lets you write custom php. Relation has an API. You can query for a relation directly using relation_load and giving it a relation_id. You can also search for a relation by supplying 1 endpoint and the type of relation you are looking for (or empty to return all relations of that endpoint, using the relation_query() function.

/**
 * Returns a query object to find related entities.
 *
 * @param $entity_type
 *   (optional) The entity type of one of the endpoints.
 * @param $entity_id
 *   (optional) The entity id of one of the endpoints. Can also be an array of
 *   entity IDs.
 * @param $r_index
 *   (optional) The index of the search entity in the relation to be found
 *   (0 = source, 1 = target).
 *
 * @return RelationQuery
 *   The query object itself.
 */
function relation_query($entity_type = NULL, $entity_id = NULL, $r_index = NULL) {
  return new RelationQuery($entity_type, $entity_id, $r_index);
}

The RelationQuery is simply a small custom extension of the core EntityFieldQuery. You can use relation_query() and pass it a UID and a NID as the endpoints -- relation_query will return the Relation ids (RIDs) for those objects. You can inspect the relations further by calling relation_load($rid).

You can then do whatever you need to with the relation(s). A small example. In my app students have surveys assigned to them to complete; using Relations. When they're done with a survey I want to change a flag on the Relation that the survey is completed ...

function _mark_student_survey_as_completed($user_id, $survey_id) {
  // using relation query we want to search for a $user and a
  // specific survey they should have been assigned. Many arguments
  // to relation_query are optional, you can more results; like
  // if you just supply a UID, you'll get all relations that use
  // that UID as an endpoint.
  $relation_ids = relation_query('user', $user_id)
      ->related('custom_survey',$survey_id)
      ->execute();
  $relations = entity_load('relation', array_keys($relation_ids));
  if (count($relations) == 1) {
    $relation = reset($relations);
    // survey_is_completed is an attached field, to the Relation;
    // not an endpoint.
    $relation->survey_is_completed[LANGUAGE_NONE][0]['value'] = 1;
    // Save our field change on the parent relation.
    relation_save($relation);
  } else {
    watchdog('survey_check', 'Duplicate Survey!'.$user_id.'::'.$survey_id.'::'.print_r(array_keys($relation_ids), TRUE), WATCHDOG_ERROR);
 }

Lastly, since RelationQuery is just a class ... I've seen people extend it to make custom "relation logic" more easy, or even Views-like listing easily. Look at this blog post for such ideas (not my blog post):
http://www.phase2technology.com/blog/building-energy-gov-without-views/


Advantages of using context for sitewide blocks?

Yes you should. It is worth while to switch to Contexts (Irrespective of your case about site wide context blocks)

Reasons

When you have blocks which appear only on a certain pages, the time taken for loading the block is saved.
In one page you can have a block in region A and on other page you can have the same block in region B.
When you change your themes you need not worry a lot about changing all the settings. You just need to make sure that they have common regions.
You can think on a page by page and then assign blocks.
Context has a simple and clean UI of its own, including drag and drop facility.
It is not path dependent. It means you can use conditions other than the path to set a context.
Can be extended with Context UI which can be a replacement for Panels and light weight too :)
In addition to placing Blocks there are many more reactions as well.
Contexts can be stacked meaning there can be multiple contexts for a single page. So you can have a site-wide context to place the headers and footers, then a node context which will perform something only on node pages and then one more context which will be active only on say node/33.
In short think of it like Rules module for the Layouts.


Drupal automagically changing password hash

The issue was with my own code.

I would load the user object every day to perform operations and change some fields value.

Instead of just passing the new fields as the second argument of user_save(), I would pass the newly changed user object cast as an array, which was causing my password hash to be re-hashed on every call of this function.


How to switch back and logout of masquerade user back to admin?

Looking at the module code, I notice the module defines a block with links for the masquerading operations. If that block is visible for the user account to which you switched, you should see a link to go back to your original account.

This is the code used from the module to show the block.

/**
 * Implements hook_block_view().
 */
function masquerade_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'masquerade':
      if (isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'))) {
        $block['subject'] = t('Masquerade');
        $block['content'] = drupal_get_form('masquerade_block_1');
      }
      break;
  }
  return $block;
}

/**
 * Masquerade block form.
 */
function masquerade_block_1() {
  global $user;
  $quick_switch_links = array();
  $markup_value = '';
  if (isset($_SESSION['masquerading'])) {
    $quick_switch_links[] = l(t('Switch back'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
    if ($user->uid > 0) {
      $markup_value = t('You are masquerading as %masq_as.', array('@user-url' => url('user/' . $user->uid), '%masq_as' => $user->name));
    }
    else {
      $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous'))));
    }
  }
  else {
    $quick_switches = variable_get('masquerade_quick_switches', array());

    // Add in user-specific switches, and prevent duplicates.
    $user_switches = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchCol();
    $masquerade_switches = array_unique(array_merge($quick_switches, $user_switches));

    foreach ($masquerade_switches as $switch_user) {
      if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
        $account = user_load($switch_user);
        if (isset($account->uid)) {
          $switch_link = 'masquerade/switch/' . $account->uid;
          if ($account->uid) {
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
          if ($switch_user == 0) {
            $account->name = variable_get('anonymous', t('Anonymous'));
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
        }
      }
    }

    if (masquerade_menu_access('autocomplete')) {
      $markup_value .= t('Enter the username to masquerade as.');
      $form['masquerade_user_field'] = array(
        '#prefix' => '
',
        '#type' => 'textfield',
        '#size' => '18',
        '#default_value' => '',
        '#autocomplete_path' => 'masquerade/autocomplete',
        '#required' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Go'),
        '#suffix' => '
',
      );
    }

  }
  if ($quick_switch_links) {
    $markup_value .= '
' . t('Quick switches:') . theme('item_list', array('items' => $quick_switch_links)) . '
';
  }
  $form['masquerade_desc'] = array(
    '#prefix' => '

',
    '#markup' => $markup_value,
    '#suffix' => '

',
  );
  return $form;
}

Reading it, I see the same block shows you a Switch back link in the case you are masquerading as another user.
Assuming the block is enabled for all the roles in the site, and it is assigned to a region the currently-set theme uses, one of the reasons for the Switch back link not appearing could be an issue with the user session; in that case isset($_SESSION['masquerading']) could return FALSE.

There is also a bug report about switching back: masquerade/unswitch throws a no acccess error. In that issue is clearly stated you need to use the block to switch back; it also seems there are some issues when the clear URLs aren't enabled.


In hook_form_alter(), how can I access the entity that is being flagged?

Ok, thanks to leymannx and No Sssweat, I think I finally understand how to get the entity from a form.
To get the entity being flagged inside a flag, this is what I had to do:
function MYMODULE_form_flagging_MYFLAG_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $flagging_entity = $form_state->getFormObject()->getEntity();
      $flagged_entity_id = $flagging_entity->get('entity_id')->value;
}


Not sure where/when this function is called, but here's your code with some fixes:

function bartik_links__system_main_menu($variables) {
    $output = '';
    $prefix = drupal_is_front_page() ? '' : '<h2>';
    $suffix = drupal_is_front_page() ? '' : '</h2>';

    foreach ($variables['links'] as $link) {
        $output .= l($prefix.check_plain($link['title']).$suffix, $link['href'], $link);
    }
    return $output;
}


How do I call an implementation of hook_form_alter()?

hook_form_alter comes in two variants:

hook_form_alter
hook_form_FORM_ID_alter

Both are called when a form is retrieved using drupal_get_form or one of the other form builder functions, but the latter is only invoked for the form with the specific form_id. Unless you are doing the same alterations to multiple forms, it's a good idea to use the hook_form_FORM_ID_alter variation, as it will create less overhead.

All hooks are called by Drupal when certain events happen. For form_alter, that is when the form is being built. So all you need to do, using the example in your question, is to do a check on the $form_id and do the alterations you want.

Notice $form_state should be passed by reference using the &$form_state notation. Sometimes you need to not only change $form but also $form_state to be able to modify the form like you want.


How to tell if the current language is written RTL or LTR

After looking more closely into $GLOBALS['language'] I found it actually has the language direction, so the answer is:

global $language;
if($language->direction == 1)
    echo 'RTL';
else /* $language->direction == 0 */
    echo 'LTR';

Better yet — thank you MPD, I can use the Drupal constants LANGUAGE_LTR and LANGUAGE_RTL instead of 0 and 1 respectively, just like this:

global $language;
if($language->direction == LANGUAGE_RTL)
    echo 'RTL';
else /* $language->direction == LANGUAGE_LTR */
    echo 'LTR';

For reference this is what $GLOBALS['language'] looks like:

stdClass Object
(
    [language] => ar
    [name] => Arabic
    [native] => 'Arabic' [it was in arabic letters but SE refused it]
    [direction] => 1
    [enabled] => 1
    [plurals] => 0
    [formula] =>
    [domain] =>
    [prefix] => ar
    [weight] => 0
    [javascript] =>
    [provider] => language-default
)


Reflection error on my first module development

a) in the route definition the path to the controller should start with backslash
b) in the route only one permission will work
c) you do not need to define type markup, just use #markup alone


Cannot see Display Suite menu under Administration

Try clearing your drupal cache, or alternatively try visiting the URL directly under admin/structure/ds


Cron job to transfer files to remote server

If you absolutely need it, Drupal has hook_cron() for regular task running:

function MYMODULE_cron() {
  // Copy your files here using standard php FTP functions
}

But it would be considerably more efficient to leave Drupal out of this altogether, and set it up with a basic rsync/FTP cron job executed on the server.

Alternatively, Backup and Migrate can both take a dump of the public/private file system and transfer it to an FTP target. Again, a solution outside Drupal will always be more efficient as it won't bootstrap the application.


How to trigger a rules action only for a specific value of a user profile field?

Make sure to add a Rules condition Entity has field (related to your additional site:current-user-field in your Rules condition). And make sure to add that Entity has field condition BEFORE the condition you already have.

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


How can I display content from one node to another?

I think after some research I found the solution. Again Thanks to @Niall Murphy and
@drupality For their input.

I think for my purpose Field Reference will be the right module. As it not only allows to choose the particular node, but which field you want to choose from that particulate node.

Although any suggestion is appreciated.


Which modules help with loading of large images in a nice transition?

Take a look at JAIL. You will also need the jquery jail plugin.


Changes in test version applied in live version as well

Of course i have to ask the obvious here, did you check out multi-site install


Seems like you do not have .htaccess file in you website directory. Place it over there any check :)


"message": "X-CSRF-Token request header is missing"

This is not recommend to remove the X-CSRF-Token. Instead you should get the token from  /rest/session/token and add this token in your header with this value.

But if you want to disable it you can write this below line to your settings.php file  $conf['services_csrf_token_check_disabled'] = TRUE;


Alter Entity Reference View Widget available options

Ending up using hook_views_pre_render(&$view). So I did something like this

function contractor_programs_views_pre_render(&$view) {
  if ($view->name == 'location_services' && $view->current_display == 'entityreference_view_widget_1') {
    // added my logic to get the service options
    if (!empty($services_options)) {
        $services_options = array_keys($services_options);
        if (!empty($view->result)) {
          foreach($view->result as $key => $value) {
            if (!in_array($value->nid, $services_options)) {
              unset($view->result[$key]);
            }
          }
        }
      }
  }
}


Changing the $from email in D6 contact_mail_user_submit()

You can implement hook_mail_alter() to do that, e.g.:

function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'contact_user_mail') {
    $message['from'] = 'do-not-reply@domain.com';
  }
}


How can I e-mail the content of a view to myself with Rules?

You can use php code in the body of emails sent using Rules, so ultimately anything can be included. The easiest method, however, would be to use the Insert View module.


Duplicate paragraphs from node type FOO to node type BAR

EDIT: You can now find a better explanation with the code here.
I know this is old but maybe someone comes here looking for an answer like me, this is tested on Drupal 8.
I found this issue and after looking at last patch, I implemented :
$nodeDuplicate = $node->createDuplicate();

foreach($nodeDuplicate->field_paragraphs as $field){
    $field->entity = $field->entity->createDuplicate();
}

$nodeDuplicate->save();

And I got a duplicate node with duplicated paragraphs fields. If you look at the patch you will see how to add a button to Drupal etc.
Just a note field_paragraphs is the name of my field in the content type, change it with your own.
I didn't have any problem doing it this way, maybe someone has a better way but I did not find it, also at the time of writing this there is still no ported modules for cloning nodes in Drupal 8.


I did clear the drupal caches using the interface (admin/config/development/performance), it seems like drush is not clearing ALL caches. It does work now and i guess it was a caching issue. Thanks anyways!


The Create & Register module does this for you if you don't mind using a contrib module. From the project page...

  This module creates a "lazy registration" which means that the user
  creates the content first and after this logs in or registers to the
  site.

  Process

  anonymous user creates a content
  the user will be redirected to the login page (if you set it on the settings form) after he finished the node creation
  the user registers or logs in
  the created node(s) will be assigned to the user after logging in


I guess you need to enable Count content views in the same configuration page and don't need to enable access log.


Cache a block by a custom entity rendered within

By any reason I do not really get the block rendering to respect my cache keys set wherever. It only respects set cache contexts so I create a custom cache context:

In pw_basic.services.yml (pw_basic is the name ofthe module)

  cache_context.politician:
    class: Drupal\pw_basic\Cache\PoliticianCacheContext
    arguments: ['@current_route_match']
    tags:
      - { name: cache.context }

The politician cache context class:

class PoliticianCacheContext implements CacheContextInterface {

  use GetPoliticianFromUrlTrait;

  /**
   * @var \Drupal\pw_basic\Entity\Politician
   */
  protected $politician;

  public function __construct(CurrentRouteMatch $current_route_match) {
    $this->politician = $this->getPoliticianFromUrl();
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Politician');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    $cache_context = '';
    if ($this->politician !== NULL) {
      $cache_context = $this->politician->id();
    }
    return $cache_context;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

Then I cleared the block plugin class from any cache logic and just added the following in template_preprocess_politician_header(), the preprocess function of the template rendered within the block:

$variables["#cache"]["contexts"][] = 'politician';

What I do not really like is the service character of the cache context classes. Why is it only possible to set the context in such a global way? Do I miss somethin? I need to use this global workaround and check for the politician from URL which makes this context not as flexible as I want it to be. Is there a way to give a variable to a cache context directly when defining it in a render array?


Install Better Exposed Filters and if you want to have a filter as a rendered block you can edit view and see Exposed form in block: option under EXPOSED FORM. Enable it as Yes and place block in any page as you like.


How to Filter view by comparing 2 fields. If field-a < field-b

What you're looking for is the filter criteria Global: Fields comparison:)


How to simulate radio button functionality within a form

you should study the Ajax examples module you can follow the examples estructures to build you own code.
 After doing that your code should look somethink like this:

function test_code_radios_callback($form, $form_state) {
  return $form['radios_fieldset'];
}

function test_code_form($form, &$form_state) {

    $options = array(
        'Name'=>t('Name'),
        'Nickname'=>t('Nickname'),
        'Lastname'=>t('Lastname')
        );

    $form['alias'] = array(
    '#type' => 'radios',
    '#title' => 'Choose your alias',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['alias']) ? $form_state['values']['alias'] : '',
    '#ajax' => array(
      'callback' => 'test_code_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
        ),
  );

    $form['textfields'] = array(
    '#title' => t("Your Alias"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('Write your alias here'),
  );

    if (!empty($form_state['values']['alias']) && $form_state['values']['alias']) {
    $value = array();
    $value = $form_state['values']['alias'];

    foreach($value as $item) {
    $name = $item;
    }

      $form['textfields']['$value'] = array(
      '#type' => 'textfield',
      '#title' => $value,
      );

  }

  return $form;
}
function test_code_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

I tested and it's working as i understood you need it. Tell us how it went. Have a good coding!.


How to make sure no emails go out after importing users?

You can use the Development Environment module for this. Some more details about it (from the project page):

When developing Drupal sites, we are often working in a development environment in which we want behaviors different than we would like on a production environment. An example of this is sending emails - it's often preferable to not send emails from a development environment, as they can end up in our client's email boxes. This is particularly true when there is a production (live) version of the site on the web, as users may receive emails from your development environment, which will be both confusing, and any links to the site within the emails will be unusable by anyone without access to that development environment.
This module aims to provide various settings which are specific to development environments only.

Disclosure: I developed this module.


How to create a button on module configuration page that calls a custom php function?

You should use the Drupal Form API for it.

Please, check it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit (it is about adding button).

And it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property (it is about run custom function).


Feed import many fields into single content type

You are in the correct path, the Feeds module will allow you to import into the a content type data from a CSV file. You should install the feeds module first, create the content type after and last map the columns of data on your CSV file to the content type fields.

If you want to manipulate the data first before creating the node the Feeds Tamper module will help you do that.

Note: On the feed module page that are a couple of links to help you with the setup. Also Mustard Seed Media released a new podcast about the feed module as well.


For the roles in question, remove their ability to edit webform content types and make sure they don't have something like administer nodes checked off. It sounds like they may have too many permissions assigned to the role(s) that would cause the edit tab to appear. Also uncheck permissions pertaining to 'submissions' other than administrative roles.


Maintenance mode says it's on, but site is still available

Have you checked the permission "use the site in maintenance mode" to see whether it is enabled for other users?


How can i integrate java application with drupal?

This is a very broad question so the answer can only be a broad one...

You can use the Services module to expose resources from your site to interested consumers:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

There's an Example of Java XML-RPC client with Drupal7 and Services 3.x, which (trust me) is the best documentation you'll be able to find.


Overwrite a specific field on a specific node

As I understand, you want a to display the same block which lists some node information in different pages and want to avoide listing some specific nodes in some specific pages. You can make use of views filter with 'Global: PHP' and have code similar to as below :

if (arg(0) == 'node') {// Set your condition here.
  if ($data->nid == NID_YOU_WANT_TO_RESTRICT) {// Set the NID you want to restrict
    return TRUE;
  }
}

Note : To consider multiple job postings in future, you just need to set the path condition accordingly.

Hope it helps


Yes finally i am able to solve this one.

Using

function utility_views_query_alter(&$view, &$query) {

  if ($view->name == 'Viewname') {

    //dpm($view->query->orderby[0]);
 $view->query->orderby[0]['field'] = "CASE  field_data_field_bid_test_field_bid_test_value WHEN 'Pass' THEN 1 WHEN 'Fail' THEN 2 WHEN 'Waiting' THEN 3 ELSE 4 END";
  }
}


How can I extract and print specific field values from $page['content'] in page.tpl.php (vocabulary page)

There are a few things here:

Taxonomy term pages are not nodes, and on a taxonomy term page you are going to have the following args:

arg(0) ~ taxonomy
arg(1) ~ term
arg(2) ~ tid (taxonomy term ID)

To override term pages copy site_root/modules/taxonomy/taxonomy-term.tpl.php into your theme templates folder to override all taxonomy term pages. You will also find really helpful instructions in that template file.


How to enable maintenance mode only when there are no active users?

Solution 1 - Going Down:

Using the Going Down module (credits: J. Reynolds) could be a valid compromise (and maybe help to create a custom work around). Some more details about this module (from its project page):

  ... warns site visitors that the web site will be going down for maintenance at a specified time. The default configuration displays a fixed position red overlay message at the bottom of the browser window with text in the format 'Drupal is going offline for maintenance at Tue Feb 21 14:41:08 2012 -0800'. Module configuration is added to the Site Maintenance administration page (admin/settings/site-maintenance).

Here is a screenprint about it (also from its project page):

Only using this module will only reduce the risk of active users when you want to enable maintenance mode (though not completely reduce it).

However, by using that module, you may be able to use the Rules module to build some custom rule(s), in which you add your own custom Rules Conditions to go check if the time left for scheduled maintenance date/time is still sufficient.

Such Rules Condition would be to perform some custom PHP code, to retrieve the date/time set via the Going Down module. And then add this Rules Condition when visiting pages where you want to avoid your issue.

Solution 2 - Rules (and Message) is your friend:

Use the Rules module to create a custom rule that uses Rules Event "Drupal is initializing". Add whatever Rules Conditions you want, if any (eg: not for users with role admin). And add the appropriate Rules Action(s) to perform some type of special logging, e.g. using the Message module to create custom log data. Such log data should include things like timestamp, user id, current path, etc. If you'd use the Message module, you could create a (rather basic) view (using the Views module) to list the relevant log records that got created by this custom rule.

Enable this custom rule only X minutes (pick whatever value that fits for X) before you plan to enable maintenance mode. From then on just browse the views results to get an idea about how long ago which user/visitor has been visiting which path. For any events (log records) longer then Y minutes ago, just assume that user/session is not really doing anything on the site anymore at the moment you're browsing your Views result.


Content type defines kind of information, different content types means different structure and different nature of content. Taxonomy is for categorisation. They can be interchangeable to some extent, but it's really up to how you want your data defined.

If all nodes we are talking about perform the same function in the system and are supposed to have the same fields, keep them categorised by taxonomy. If their function should be different, make content types - it does not mean you need to give up taxonomy then (but you may if it's no longer needed).


Does superfish module support multiple languages?

Heh, it looks like they've released a version of Superfish with what was supposed to be just a temporarily disabled support for translations.

You can either

apply patch found at http://drupal.org/node/1112928 or
use an older version of Superfish


Programmatically created revision set as the main node instead of revision

You're looking for \Drupal\Core\Entity\RevisionableInterface::isDefaultRevision(), set that to false if you want to save a revision that is not the default revision.


Custom form using custom template, submit the form don't call its validate and submit handlers

You need "base hook" in there, I believe.

Here's an example:

/**
 * Implements hook_theme().
 */
function formcustomtemplate_theme() {
  return array(
    'form__my_form_test' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
      'base hook' => 'form',
    ),
  );
}

If you are using a custom theme, and you don't need the template in your module, the approach of creating a new theme hook for your custom form is unnecessary.
Rather than create a new theme hook, use hook_theme_suggestions_alter in your theme:

/**
 * Implements hook_theme_suggestions_alter().
 */
function mytheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#theme'])) {
    $suggestions[] = 'form__' . $variables['element']['#theme'][0];
  }

}

then create the appopriate template in your theme.

then to see the theme suggestions output to the page, turn on twig debugging:

https://drupalize.me/blog/201405/lets-debug-twig-drupal-8

You'll see template suggestions in the markup:

<!-- FILE NAME SUGGESTIONS:
   * form--myformtest-form.html.twig
   x form.html.twig
-->

You can see that it's not yet picking up your template, so create a template file by copying the form.html.twig and renaming it.

To check where Drupal is looking for templates using the "form" hook, you can print out the theme registry from hook_theme_registry_alter:

 "form" => array:6 [▼
    "template" => "form"
    "path" => "themes/custom/mycustomtheme/templates/form"
    "type" => "theme_engine"
    "theme path" => "themes/custom/mycustomtheme”
    "render element" => "element"
    "preprocess functions" => array:4 [ …4]

This lets you know that you need to put the template in that directory.


Group content by taxonomy term, but then also list all terms in each row

I figured it out!

Instead of just adding Category as a single field in the View and trying to figure out how to configure that to show each Category for a Thing row but only one Category header per group, I have the Category field on there twice - one that does not display multiple in one row (for the headers), and one that does display them all within one row (to list out all Categories for a Thing).

I hope this possibly helps someone else!


add title to front page teaser news feed

If you look at the page.tpl.php template file used by the Bartik module, you will notice it uses code like the following to render a region.

  <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

      <?php print render($page['triptych_first']); ?>
      <?php print render($page['triptych_middle']); ?>
      <?php print render($page['triptych_last']); ?>

  <?php endif; ?>

node--teaser.tpl.php is not used to render a page, but a node into a page. It is hierarchic, someway: html.tpl.php wraps the content of page.tpl.php, which wraps the content of node.tpl.php.
Regions are part of a page, not a node; therefore, the template file where to render the regions is page.tpl.php or any suggested templates used instead of that one.


This is a known issue with CKEditor.

In your case, the ampersand character & is being escaped as &amp; which is causing the HTML entity for your apostrophe to appear as &amp;#039;.

The entity for the ampersand is well-formed, so the ampersand appears in your rendered output. But this causes the entity for the apostrophe to be malformed, so it appears as a literal string.

There's a CKEditor config that you can do to force a simple ampersand, but I'm not sure how it will affect other text fields site-wide (which will no longer have their ampersands escaped), so proceed with caution.

Perhaps someone with more CKEditor experience can tell us if there's a way to configure this more narrowly.


How to resolve Catchable fatal error in entity.inc?

In case anyone else has a similar problem, here is how I solved it. I began by using Drush to disable the commerce modules one after another (in the correct order) to detect which module caused the error. I got so far that in the end I had disabled all the commerce modules, plus Rules and Entity token. And still the same error message was showing (the first one in my question).

I suspected that I really needed to flush all cache, but I could not reach any page in the site, and still it was not enough to truncate all the cache tables in the db and to run Drush cc all. So what to do? I finally found a way to flush all caches with this snippet (https://www.drupal.org/docs/7/administering-drupal-7-site/clearing-or-rebuilding-drupals-cache) in a file named for example clear.php in the web root:

<?php
// Define static var.
define('DRUPAL_ROOT', getcwd());
// Include bootstrap.
include_once('./includes/bootstrap.inc');
// Initialize stuff.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

After saving the above file in the web root, you can just navigate to it whith the browser. In my case I also had to comment out all the memcached rows in settings.php in order for this to work (I got a "Cannot redeclare ..." error message).

When I finally managed to flush all caches this way, the site began to work. I still don't know how I would have done this otherwise. And "Flush all caches" obviously does somehting more than what is accomplished by executing drush cc all + manually truncating all the cache tables in the database.

So if anyone else has a similar problem with white screens and error messages, first try to flush all caches with the method above. And if you use memcached, you will have to comment out everything that regards memchached in settings.php in order to do this.


How to set a different theme when the site is on maintenaince mode?

I think there is no way to set active theme while on maintenance mode, but you can change the way site looks.

For that to happen in your local site there is /modules/system/maintenance-page.tpl.php available.

You can overwrite as you need by pasting this into your theme directory.

Then in settings.php you need to set

$conf['maintenance_theme'] = 'ThemeName'


I got caught out in Drupal 7 by the fact that you don't need to call drupal_install_schema.  Also, hook_install should now be used to perform actions on your tables, rather than set them up.

Drupal 7 sees your schema and installs it automatically when your module is activated, so because you're calling it manually, it's trying to install the schema twice.

This might help explain it a bit.

Also, try checking in your database to see if the tables already exist.  If it's installed incorrectly, Drupal might be seeing the tables and thinking they're correct when actually they're not.


Those vertical items are internally called "operations" and are implemented by task_handlers plugins although some of them are hardcoded in page_manager. You can see some examples in:

ctools/page_manager/plugins/task_handlers/http_response.inc
panels/plugins/task_handlers/panel_context.inc

You may also find more info in page_manager_render_operations()  docstrings.


How do I render a custom form in page--front.tpl.php?

It might be because of variables being passed by reference. Try this instead:

$form = drupal_get_form('mymodule_get_subscribed_form');
print drupal_render($form);


Use a database specific function in dbtng (e.g. uuid in db_insert)

Here's what I ultimately did:

db_query("INSERT INTO {mytable} (uid, event_guid) VALUES (:uid, uuid())",
array(':uid' => $uid));

And that works to use the mysql uuid() function in an insert.

I've created an issue to add this to Drupal 8 http://drupal.org/node/1858188


The X-Drupal-Cache-Tags header should help with this.  Here's how to enable it from this doc:

  You can debug cacheable responses (responses that implement this
  interface, which may be cached by Page Cache or Dynamic Page Cache) by
  setting the http.response.debug_cacheability_headers container
  parameter to true, in your services.yml. Followed by a container
  rebuild, which is necessary when changing a container parameter.

  That will cause Drupal to send X-Drupal-Cache-Tags and
  X-Drupal-Cache-Contexts headers.


You can do that by setting a variable in your controller or in template_preprocess_teacher in your .theme file, like:

function template_preprocess_teacher(array &$variables) {
  $classrooms = $variables['elements'][0]->get('field_classrooms')->referencedEntities(); //probably a bit different for paragraphs ..

  foreach($classrooms as $classroom) {
    $variables['classrooms'][] = \Drupal::entityTypeManager()->getViewBuilder($classroom->getEntityTypeId())->view($classroom, 'optional-view-mode');
  }
}

And then access it in twig like this:

{{ classrooms }}

If you're looking for a twig only solution use the twig_tweak module, then it comes down to this:

{% for field_in_paragraph in teacher.field_classrooms.entity %}
  {{ drupal_entity('classroom', field_in_paragraph.value, 'optional-view-mode') }}
{% endfor %}