This line:

$form['actions']['submit']['#weight'] = 0;

only sets a submit's weight inside actions container.

To push actions to the top of the page, you need to affect it's own weigh:

$form['actions']['#weight'] = 0;

and if you want to move only one button, you can restructure your form by moving this button outside actions container:

$form['submit'] = $form['actions']['submit'];
$form['submit']['#weight'] = 0;
unset($form['actions']['submit']);

Note that this may break some forms that expect submit button in it's exact original place in form structure.


Sure therefore add a date: filter not a node: post date.

On the date filter configuration form you can select the node: post date field and that's all you need.


What module would give an image thumbnail list in a slider format?

I used jCarousel for views: --- its a bit outdated so you need the updated patch.

You have to apply the following patch: https://drupal.org/node/1548484#comment-8260283 to make it responsive.

If you have a better solution. Do let us know! :)


On node edit form, how to edit field from a referenced entity?

You can use https://www.drupal.org/project/references_dialog or https://www.drupal.org/project/inline_entity_form.

The first one will load the referenced entity in a popup, the other will show it as part of the original form.


Drupal Commerce Hook - Extra validation before adding to cart

Seems like hook_commerce_cart_product_add is what you're after. I couldn't find any examples for preventing the line item being added to the cart but at the very least you should be able to use drupal_goto to interupt the process. You might also want to look at the Rules events\actions provided by Commerce.


What's the easiest way to create CRUD interface for custom entities?

The Entity Construction Kit (ECK) module allows you to create and manage entities through admin.
Here is a quote about it (from the module's project page):

...  builds upon the entity system to create a flexible and extensible data modeling system both with a UI for site builders, and with useful abstractions (classes, plugins, etc) to help developers use entities with ease.
ECK allows the creation and management of entity types with custom properties; adding bundles to entity types; and fields to bundles, with the help of the Field UI module.


How to get jquery switchClass working in Drupal 7

switchclass() isn't a library, it's a function that's part of UI Effects. So...

drupal_add_library('system', 'effects');

Should then let you use:

$('.foo').switchClass('foo', 'bar', 1000);


Show a Custom Block on Homepage in Drupal 6

If you have a suitable region to display the block, why not set it to display in that region and in the Block Visibility settings configuration under Show block on specific pages select Only the listed pages. Then in the text area type <front> to display it only on the front page.


How do I output a list of PDF files set up via a custom content type

Change the Formatter to be URL to file

Rewrite the field as attached image using the title to display link to file with the title as link text


How to abort the ajax request and redirect in the ajax callback of form element

If you've got ctools installed (nearly all Drupal sites do), you can make use of ctools_ajax_command_redirect() in your AJAX callback, e.g.

ctools_include('ajax');
$commands[] = ctools_ajax_command_redirect('path/to/redirect');
return array('#type' => 'ajax', '#commands' => $commands);


These comments should be filed as a code task in the Drupal Commerce issue queue: https://www.drupal.org/project/issues/commerce


Highlight current user in multiple user reference field on /user page

This was actually much easier than I anticipated.

Of course, by default, every user name is a link, and for the user name to be highlighted on each users page, it meant that the link could automatically be given an active class as the current page.

Problem solved.


Problem with the schema structure produced by Schema module

Drupal doesn't have a boolean type for DB schema, and there's no automatic fallback for a type it doesn't know about, so you end up with the invalid portrait NOT NULL instead of portrait boolean NOT NULL in the create statement.

To fix, just add a pgsql_type to the column. DatabaseSchema_pgsql::processField() knows what to do with it.

'portrait' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'int', // Keep it portable
  'pgsql_type' => 'boolean',
  'not null' => TRUE,
),


You are probably just missing the build() call.

$menu_name = 'my-custom-menu';
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
print \Drupal::service('renderer')->render($renderable);

Core is the best example for these kinds of things. I pulled the above from SystemMenuBlock::build().


how to override the timeline-twitter css

In order to be able to style it, you'll need to stop using the standard twitter embed code and use another solution.

I suggest using the Twitter (https://www.drupal.org/project/twitter) and Oauth (https://www.drupal.org/project/oauth) modules for this.

This will allow you to create a view of your feed which you will be able to style easily.

There looks to be a pretty good recipe here: http://polso.info/integrating-twitter-feed-your-drupal-site

Good luck!
Anne


How do I control the "more" link from a views content pane to point to a biblio filtered page

A simpler solution for this is to edit the display footer, set its input format to PHP and print the link yourself like:

<?php

  $term_name = 'TERM_NAME'; // set term name depending on how you filter for it
  print l('Read more', 'biblio/term/'. $term_name);

?>

if you are using arguments to filter the terms, then you can access the argument(s) like so:

<?php
  $view = views_get_current_view();
  $arg0 = $view->args[0]; // or whatever index the term name has
?>

Otherwise you need to use a custom module and figure out one of the hooks Views implements (e.g. hook_views_pre_view())


Is it possible to use random submission number for webform?

You are probably looking for something like Webform Submission UUID module:

  This module provides a UUID integration for Webform Submissions

UUIDs are hashes that looks random and are not based on submission order, so they would meet your need. Note that this module is in dev version only, so you can expect errors. On the other hand it's GPL, so you can use it as an example how to interact with submission IDs.


How can I remove zombie Panel menu item links caused by Features?

To fix this, disable and then re-enable each Panel one-by-one on the production server.  Hope someone finds this useful!


file upload works with only one specified extension but not more than one

Don't use a comma separation, separate extensions just with space

'file_validate_extensions' => array('jpg jpeg png gif txt doc docx ab1 seq')));


Check the module called OG Forum D7. This module allow to make some forum and their topics owned by an Organic group, just like any other group content.


Programmatically get field definition for custom user profile fields

Yes you can get field definition programmatically with field name and entity name, by using EntityFieldManager::getFieldDefinitions.
For your select list how to get allowed values check this example

 $options_array = [];
    $field_name = 'field_country_list';
    $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('custom_entity_name', 'bundle');

    if (isset($definitions[$field_name])) {
      $options_array = $definitions[$field_name]->getSetting('allowed_values');
    }

source : https://api.drupal.org/comment/63953#comment-63953


How to allow access to create terms in a specific vocabulary?

You can create a custom permission: "Create new authors" in mymodule.permissions.yml:

create new authors:
  title: 'Create New Authors'
  description: 'Create New Author Taxonomy Terms'
  restrict access: true

Assign the new permission to the roles you want.

Then using hook__access_entity_create_access():

function mymodule__access_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
  if ($entity_bundle == 'author' && $account->hasPermission('create new authors')) {
    return AccessResult::allowed();
  }
  // No opinion.
  return AccessResult::neutral();
}

This will give explicit access to roles with your custom permission, and in other cases it will defer to the default drupal permissions.


DRUPAL_ROOT undefined on module installation

The error about the undefined constant DRUPAL_ROOT could be caused from the index.php file that is corrupted, or that is returned corrupted from APC, or similar extension. DRUPAL_ROOT is always defined when Drupal bootstraps.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

As for why the error message is reported for that module when a function that doesn't contain any reference to the constant is executed, I think that is caused from the autoload function Drupal registers, drupal_autoload_class(), which is trying to load the file containing the class.


Drupal navigation always returns a 404 error

Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing ?q=user or ?q=admin. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about RewriteRule) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning RewriteBase in your .htaccess.

Option 2 - Admin option 'Clean URLs'

I you can use the ?q=adminURL, then try to navigate to /index.php?q=admin/config/search/clean-urls to check the current status of clean urls (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

Option 3 - base_url

Make sure the value of "base_url" is set correctly (in your settings.php).

Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.

Note (about your "The ?q=admin URL didn't ask me to log in" comment to this answer) Check if you get the same problem using another browser. If with another browser it works, then that part might be a cookie problem (delete the cookie in the browser where you have the problem, and try again).


Mollom and Spamicide are not slowing down spam registrations

You can still try to use CloudFlare service, coupling with Mollom it's very effective.

Also, I'm not sure that they (bots I mean) are creating account e-mail to validate their account. The problem with Drupal 6, its has an algorithm to create the validation link that it's easier to reproduce (much harder with Drupal 7 as its has a secret key when you install).

Well, if with CloudFlare it doesn't slow down your spam problem, you can either change the validation algorithm or upgrade to Drupal 7.


How to disable all commerce modules from Commerce Kickstart using Drush?

Note that by disabling all of the Kickstart specific modules (which is practically required to uninstall Commerce due to dependencies) may cause your site to become unusable. If you're using the image rotator or the Kickstart specific content types things could get really crazy. You've been warned. Go slowly.

I know you want to know how to do it in drush, but using the UI will likely be easier given the amount of time it will take to do this:

Uninstall the Kickstart specific modules. These will be all of the modules whose Package is Commerce Kickstart. There should be 18 of these. Disable one or two at a time. You have to do these first.
Once those are done, then you'll need to go through and disable all of the Commerce Contrib modules. These would be modules found under Commerce (Contrib), Commerce (whatever), etc.
Once those are done, then you should be able to disable the Commerce core modules.


Set the allowed options of a selectlist CCK field?

check this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields when form is loaded, and his relation with the function to alter forms, called hook_form_alter(). In few words, you must also use an after_build() function.


Change the subtotal amount in commerce_email_order_items

Well, after re-examining the code of the commerce_email.module, I had an epiphany, and finally get it.

Here is the code before my change (starting line 169) :

$data = $wrapper->commerce_order_total->data->value();
  if (!empty($data['components'])) {

foreach ($data['components'] as $key => &$component) {

  if ($data['components'][$key]['name'] == 'base_price') {
    $rows[] = array(
      'data' => array(
        ' ',
        array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
        array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
      )
    );
  }

And now with my change :

$data = $wrapper->commerce_order_total->data->value();
 if (!empty($data['components'])) {
  foreach ($data['components'] as $key => &$component) {
         if ($data['components'][$key]['name'] == 'flat_rate_expedition_internationale' || $data['components'][$key]['name'] == 'flat_rate_expedition_outremerre' ) {
            $amount_expedition = $data['components'][$key]['price']['amount'];
          }

  }
  foreach ($data['components'] as $key => &$component) {
      if ($data['components'][$key]['name'] == 'base_price') {

          $amount_base_price = $data['components'][$key]['price']['amount'];
            if (isset($amount_expedition)) {
                $amount_base_price += $amount_expedition;
            }
          $rows[] = array(
              'data' => array(
                  ' ',
                  array('data' => t('Prix HT :'), 'style' => array('font-weight: bold; text-align: right; margin-top: 10px')),
                  array('data' => number_format(commerce_currency_amount_to_decimal($amount_base_price, $currency_code), 2), 'style' => array('font-weight: bold; text-align: right;')),
              )
          );
      }

It's not a great solution, and I will try to make a full module, to select dynamically the components to add to the base_price.
Until then, this will do the job.


How To Calculate Sum() of a field in a view using use aggregation=Yes option

I am not sure if you have already found the answer. I found this question from Google, so I am answering this so that somebody else might benefit.

When you are using Aggregation = Yes, remember one rule of thumb : All the fields that you are selecting must either use GROUP BY that field or some aggregation function on that field.

In your case you have two fields, User Name and Payment value. Once you enable the Aggregation, you will find Aggregation settings beside your fields in Fields, Filter and Sort groups.

For User Name - click on Aggregation settings and select "Group Results together".
For Payment Value - click on Aggregation settings and select Aggregation type as SUM.

Check List

In-spite of the above if your view is not using, then the culprits are sort and filters. Be careful about them. Removing them and adding them back one by one may be a easier solution.
Remember that sorting is not necessary as GROUP BY does default sorting of groups. And more over if you add a sort it might add an additional GROUP BY, if your settings are not right.


How to add a title text input to an image field node form widget

You have to enable the title field on your image field in the manage field tabs, at the bottom of the field form. for example at
example.comadmin/structure/types/manage/example_content_type/fields/node.example_content_type.field_example_field

Found the answer after landing here: https://www.drupal.org/project/drupal/issues/2303765


For current version of drupal 8.x:

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
        array(
          'type' => "article",
          'title'=> "test entity",
          'body' => "body body body",
        ));

$entity->save();


$_SESSION vars created outside of Drupal lost when navigating to a Drupal served page

A really good source related to your question from drupal.org's forum:
Struggling with Session Variables (the $_SESSION array) when redirecting to external php scripts

The key for codes outside Drupal's full control to work is to save PHP's current working directory, change it to Drupal's, requiring the needed file to bootstrap Drupal (includes/bootstrap.inc), pass the appropriate $cookie_domain variable ("the domain to be used for session cookies"!), bootstrapping Drupal, and then change the current working directory back to the original. After this, you can write your own codes and use Drupal's functions, mess with its session variables, etc. - of course, depending on the bootstrapping mode of Drupal.

The code to achieve it looks like this (you have to change $your_drupal_directory variable to yours, usually this is in the root, but its path can be different [e.g. if it's in a subdirectory]):

// ...

/**
 * @see http://drupal.org/node/575002
 */

// store current working directory
$currdir=getcwd();
// which is your Drupal directory? (usually it's in the root, but can be different)
$your_drupal_directory = $_SERVER['DOCUMENT_ROOT'];
// change PHP's current directory to Drupal's
chdir($your_drupal_directory);
// including bootstrap file...
require_once("./includes/bootstrap.inc");

// The domain to be used for session cookies. (see: http://api.drupal.org/api/drupal/developer!globals.php/global/cookie_domain/7)
$cookie_domain = $_SERVER['HTTP_HOST'];

// DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

// the code above should be enough for your task, but if you want Drupal to be "fully loaded, validate and fix input data", you could try the following too (see: http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_bootstrap/7)
// drupal_bootstrap( DRUPAL_BOOTSTRAP_FULL );

// change PHP's current directory BACK to the original
chdir($currdir);

// ...
// YOUR OWN CODE COMES HERE
// ...


Taxonomy autocomplete is empty because of access control for anonymous users

Changing the access settings didn't help because Drupal filters out items that are not accessible by the user currently viewing the view.  There are a number of ways you can deal with this:

Use Vocabulary Permissions Per Role which gives finer grained control of taxonomies
Use Page Manager (part of ctools) to override the taxonomy page either by redirecting somewhere else or making your own page in Page Manager using Panels.
As you suggest, use a redirection module (or Rules perhaps) to redirect users away from the page.  The data will be safe as long as the rule or redirection fires before anything is rendered.


Javascript & Ajax failed to load on many pages like field editing & views editing pages.

Jquery Update module is very helpful but new jquery versions can cause issues with other dependent modules. The module is important not only to keep your site up to date but also allow for theme-specific control to ensure compatibility. So the module's settings page is something you might want to visit and test when a new jquery version is released.

Also, the CDN option can cause load issues if the provider you choose is offline for some reason or overloaded. From the jquery update settings warning:

  "NOTE: Using one of the "CDN Provider" options below is the preferred
  method for loading Bootstrap CSS and JS on simpler sites that do not
  use a site-wide CDN. Using a "CDN Provider" for loading Bootstrap,
  however, does mean that it depends on a third-party service."

So use this option with caution.


How to find orphaned files and images which are not linked from any css stylesheet or from any node?

You can find orphaned files by running the following MySQL query:

SELECT fm.*
FROM file_managed AS fm
LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
WHERE fu.type = 'node' AND n.nid IS NULL

This returns all files which have no associated node. I'm not sure if it's safe to delete the returned rows and files, probably also depends on your module setup. Only use at your own risk!

Source: http://drupal.org/node/733258#comment-5582764


Best practice for using location names as part of taxonomy?

It depends of your goal:

If you want to cover large areas like cities, it's better to use Taxonomy as it will be easier to build (for example) a view (or map) of all node from this city.
If you want very precise geolocation (like the position of a store in a map), then go for location. Regarding Location module, it may be overkill for simple Lat./Long. positioning and a simple CCK field for each should be enough.
You can of course have both Taxonomy and Lat./Long. for your nodes and use the one appropriates regarding your context.

If you have time, I'll recommend the listening of Acquia Podcast 22: DevSeed On Mapping in Drupal.

  Being able to display maps in Drupal is a powerful feature, and can
  also be confusing to implement. Join us as we talk with Ian Cairns,
  Tom MacWright, and Robert Soden from Development Seed about how it is
  done and the different options available for displaying great maps.


Filter the products by selecting the checkbox

If what you are looking is filtering and not just displaying the products according to their taxonomy terms, then maybe you are looking for the facet api module with apachesolr


menu_tree_output() not returning full menu array

From what I understand about menu_tree_all_data() you need to supply it a link and depth to give it context (where in the menu tree am I at & how far do I go?). Also drupal_render() expects an argument passed by reference, so there will problems passing the output of function.

// Default to root link w/ a depth 5.
$link = menu_get_item();
$tree = menu_tree_all_data("devel-frus", $link, 5);
$tree_output = menu_tree_output($tree);

// Supply a variable for drupal_render to reference.
$menu = drupal_render($tree_output);

$nocss = preg_replace('/class=".*?"/', '', $menu);
echo($nocss);


How can authors choose a different display name?

While this doesn't allow for someone to choose their name per post, it does allow for someone to have a username and a "realname" http://drupal.org/project/realname

You could also just add a text field to nodes where they can fill out any name they want. Then plug that field into your theme instead of the username.


how to solve Notice: Undefined offset: 1?

This line of code will split arg(3) into an array of strings using _ as the delimiter.

  $tesr = explode('_', arg(3));

Assuming that in this case arg(3) is never empty, it is still possible that there are no underscores in arg(3), in which case you will have an array of 1 item.

Since arrays are zero based, this will give you something like

Array
(
    [0] => 'somestring'
)

In that case, your next piece of code

  if ($tesr[1] == $account_id) {

will throw the Undefined offset: 1 notice because there is no array element with the key 1.

If you want to safely use $tesr[1] you have to do something like

  if (isset($tesr[1]) && $tesr[1] == $account_id) {

Additional unsolicited feedback:

Don't name your module 'custom'. Name it something more descriptive of its purpose. If it has many distinct purposes split it into multiple modules. It will be easier to maintain in future if you can easily tell what different modules do.
Always prefix your function names with the name of the module. _term_account() might clash with another module's function. Prefixing with your module's name helps avoid that.
You have global $base_url; and global $user; but then you never use them.
Consider using a variable name that is more descriptive than $tesr, so you can easily tell what it means if you come back to the code in future.
Code is easier to work on if it uses consistent formatting standards. Check out Drupal's at https://www.drupal.org/docs/develop/standards


How to not index comments in search_index?

There doesn't seem to be an easy way to do this in drupal 6.

It gets added in hook_nodeapi() but the comment module, so comment_nodeapi().

There is no way to override what gets added in this manner.

So you would have to hack the comment module to make it no longer do that by removing the 'update index' part.

Hacks
A note on hacks:
In cases where you really do have to hack core, I recommend creating a patch file for the change and give it an informative name.
Then commit to your version control the change and the patch.
Keep a list of any hacks you might have, along with their purpose, which files have been changed, and their relevant patch file, in your developer documentation.

Then when you go to upgrade drupal next time you have the patch file, so you can update, then apply the patch (if the patch doesn't apply cleanly you can re-roll it).
Easy.

This way if you ever hand over the project the next person will have it easier too.


How to create a scheduled mailing list using Rules?

This can be accomplished by using Views, Ultimate Cron, and a custom module:

1) Create a view with the list of emails that you want to send.

2) Create a custom module to loop through the view results and send the emails.

3) Use Ultimate Cron to schedule it to run once a week.


Sounds like you are looking for something like https://www.drupal.org/project/file_entity_inline


Render alternative content if user is logged in instead of redirecting to user/uid

function custom_render_register_profile() {
global $user;
global $base_url;
$uid=$user->uid;
if($uid)
{
drupal_goto('url where you want to take login user..like $base_url./node/1');
}
else
{
  $user_register_form = drupal_get_form('user_registration_form');
  $markup =drupal_render($user_register_form);
  $output = array( '#markup' => $markup);
  return $output;
}
}


How to check whether a username is in use?

Drupal 7 has a function to return a user object by username:

$user = user_load_by_name($name);
if(!$user){
    // User doesn't exist
}
else {
    // User exists
}

function user_load_by_name

And a function to return a user object by email:

function user_load_by_mail


$result = $query->entityCondition('entity_type', 'node')

        ->entityCondition('bundle', 'mypage')
        ->fieldCondition('field_mymodule_module','tid', 123,'=')
        ->execute();

    $nids = array_keys($result['node']);
    $array=array();

    foreach($nids as $nid)

{
    $query2 = db_select('metatag', 'm')

    ->fields('m', array('entity_id', 'revision_id', 'language', 'data')) ->condition('m.entity_type', 'node')

->condition('m.entity_id', $nid, '=')
->orderBy('entity_id')
->execute()->fetchAssoc();

$array[]=$query2

        }

$array contains all fields value.traverese this array.
Hope this will give you result.


config-import error: These entities need to be deleted before importing

For:

  Entities exist of type Shortcut link and Default. These entities need
  to be deleted before importing.

You need delete the entities of type short-cut, you can do with drush:

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'


How can I specify where an image is uploaded

In your site log in as adminstrator and go to

'/admin/config/media/file-system'

and you can find the place where you can define your path to save any uploaded files.

for Example your siteis example.com you have to access

"**example.com//admin/config/media/file-system**"  as Drupal Administrator and you can change the path there.

image URLs messing up

possibly this will give you a answer


No. Smart IP is solely for IP geolocation, it doesn't not touch storage of user location addresses.

Depending on your needs, Location (with the User Location submodule) or a combination of GeoField/Address Field on your a profile (you might want to guess the location while letting the user determine what his address) will get your location storage needs.

None of those modules have Smart IP integration so you'll have to build some custom code to add IP geolocation to either of those storage options.


Programmatically render a panels page variant

Here is how :

$page = \Drupal\page_manager\Entity\Page::load('featured_content');
//all variants ids, for the example
$variants = $page->getVariants();
$variantIds = array_keys($variants);
// last variant... could have been $page->getVariant('{VARIANT_ID}');
$pageVariant = end($variants);
$viewer = new \Drupal\page_manager\Entity\PageVariantViewBuilder();
$arr = $viewer->view($pageVariant);
\Drupal::service('renderer')->render($arr);


Creating a drupal-composer/drupal-project gave me an outdated version of core

Installed Drupal using this instead: composer create-project Drupal/recommended-project mysite and everything is current and correct.


Linux distribution suited for a clean and easy Drupal 8 install

Now that is released, Ubuntu 16.04 LTS with php 7.0, perfect for drupal 8.


Check that you have the .htaccess file present in your Drupal root folder.


Try drush pm-refresh, and then run drush pm-updatecode again.


How to duplicate a node into an external database in Drupal 8

This seems similar to Database::setActiveConnection not working as expected?. Perhaps the Node object you've instantiated before switching the connection is still going to hold on to the old db settings as the source to save.

The DatabaseSwitcher class (found in the above posted question, just under the accepted answer by the original poster) may be an effective way for you to switch the container context in a way that will allow your already instantiated Node object to save in your external DB:

//... mymodule_node_insert

$node = Node::load($id);
$db_switcher = new DatabaseSwitcher();
$db_switcher->changeToDifferentDb('external');

// save the node in the shared database
// Create node object with attached file.
$sharedNode = Node::create([
    'type'        => $node->getType();,
    'title'       => $node->getTitle();,
    'body_text'   => $node->get('body')->value,
]);
$sharedNode->save();

$db_switcher->changeToDefaultDb();

Hope this works for you!


Edit tabs and configure gears are missing on all content types in my drupal 7 website

page.tpl.php needs $title_prefix too. Add  before the main  (and the suffix after if you need to)


I'm looking for a similar solution, I work on a site with thousands of fieldable panel panes and need to find all the nodes that contain a certain fpid. The most promising lead I've found is: Find node programmatically by field value so if you've found a better solution (maybe using views) I'd like to hear about it.


Drupal 7 View - How to show content based on conditions

I think it would be easier to use hierarchical taxonomy tree, this would definitely make your life much easier when creating views listing child taxonomy terms or content tagged with child terms...


I've used the 2.x version of Similar by Terms in the past, and it is very good, with nice views integration. A D7 version of the 2.x branch is in development at http://drupal.org/node/1270244.

The Apache Solr module can also supply a block of nodes that have similar taxonomy terms based on a Solr database: http://drupal.org/project/apachesolr. Very fast, but not trivial to set up.

Finally, here's a comparison of similar/relevant content block modules: http://drupal.org/node/323329.


Field Collection with Date for Calendar View

I couldn't get Calendar to play nice with Field Collections.  It seems like I needed to somehow provide for the custom calendar row plugin or calendar items within the field collection view (it's too complicated).

Ultimately, I went with the FullCalendar module, which is built on the FullCalendar jQuery plugin.

It's very clean, simple to setup, and it plays very nicely with everything I'm throwing at it.  If Calendar and Field Collections make any further progress with their development, I might revisit them, but for now this fits the bill.


How do I hide the core version to the outside world?

If you want to hide the Drupal version then you can use the following module:
https://www.drupal.org/project/remove_http_headers


Not able to find login form anymore on Drupal

Maybe a problem of clean urls?

Try site.com/?q=user


Number of users currently checking a node

viewers ,though this module is in drupal 6 but it can give you a good start.


hook_field_widget_form_alter - modify specified field only

So it's actually to be found in $context['items']

if (($context['items']->getName() != 'field_myfield')) {
  return;
}

// if still here, our field matches. do something

Also note you can be more efficient by using the WIDGET_TYPE hook, e.g. for my "Check boxes/radio buttons" widget:

function hook_field_widget_options_buttons_form_alter(...)


To remove modules, you have to remove them from your server's modules directory (usually sites/all/modules/). Uninstalling through the interface runs the uninstall code provided in the module, typically to remove custom database data and tables that the module may have created.


Display solr result by specific field order

I am resolve my problem by using edismax of solr.

Ref Link: https://cwiki.apache.org/confluence/display/solr/The+DisMax+Query+Parser

http://localhost:8983/solr/collection1/select?q=search_word&wt=json&indent=true
&defType=edismax&qf=field_1^20+field_2^19+field_3^18+field_4^17&pf=field_1+field_2+field_3+field_4


Add a youtube video in the template file using url

<?php print render($content['field_video_url]']);?>

try this


Views tagging question (bulk update tags)

Found a solution, via the editablefields module!! Here is a quote about it (from the module's project page):

  ... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).


entity Reference with select list doesn't show results

Ok, the problem was due to the fact that the site has two languages. had to enable the second language in order to make the it work properly.


You have taken the wrong approach. It's not as simple thing to do as you would like.

What's needed depends on your Drupal version 6 or 7. The columns in the table for the field is created though the field definition that defines which columns are needed. It's not possible to alter this without hacking the module that provides the field. This is not the approach you want to take.

Instead you need to create your own version of the field definition. You should be able to copy most of the code and alter the bits needed for the table definition. Only field or cck knows that the table contains the column for SEO it will also save and load values for that column. If you are not familiar with CCK/Fields it might take a little while to get things working. Also a down side is that you most likely will create your own version of the image field that you will have to maintain.

An alternate solution is to not store the values in the field table, but create your own table and handle saving and loading the data yourself. If you don't need integration with Views, this would probably end up as a cleaner solution.


Is it possible to combine contextual filters with regular filters?

You can add "or" conditions to filters -- either regular or exposed -- using Views in Drupal 7 or 8 (in Drupal 6 you need to use the Views Or module).

Add the filters you want -- in your example, a "Has taxonomy term" filter for "meta" and a "Has taxonomy term" exposed filter. Then click the arrow next to the "Add" link to expand the options and select "And/Or, Rearrange".

From there you can add a new group and drag both the "Has taxonomy term" filters into that group and set the operator to "or". (You can also set the operator between groups to "or" for more complicated scenarios.)

To add OR clauses to contextual filters, tick the "Allow multiple values" option and use the "+" or "," characters in the URL to indicate an OR or AND of values.

That should get you what you want.


How do I programatically add a Node to an Organic Group in Drupal 7?

Try og_set_association() its listed under their API section of og.module

I have done this in the past with D7, but I believe the API I used has changed since then.


CPU spike during image multiupload — how to optimize performance?

More than likely, the CPU spike is actually happening after the upload and the new gallery is being viewed.

When this happens, each of the new images will be loaded by the browser.  Drupal will detect that these images don't exist on the filesystem, and punt to Image module to render out the derivatives that you defined (ie, the images in each style).  If the user bulk uploaded a bunch of images, then the server may be rendering out a lot of new images in parallel.

To combat the CPU, you can try enforcing smaller max image dimensions.  Smaller images take less CPU to crop/scale/etc.

You can look through the MPM configuration options and see if there is anything you cal tweak.  ServerLimit may be your only option here; I don't recall per-client option in Apache for maximum parallel connections.

Otherwise, I think you may be better served on ServerFault for this issue.


In cases like this, I usually use:

https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7

For pre-processing the views render array.


Removing div wrapper of textfield element in webform

You would do this by overriding theme_form_element() in your theme, eg, something along the lines of:

function YOURTHEME_form_element($variables) {

  $element=&$variables['element'];

  if ( /* this is a webform textfield */ ) {

    // create the html without the div wrapper

  } else {

    // do it the standard way

  }

  return /* the html */;

}

A look into includes/form.inc will show you the full theme_form_element() code that you could copy into your function above where necessary.


Can a theme leverage block config Yaml files when installed for the first time?

It turns out tim-plunkett was correct in his comment above. I used the config export function at /config/development/configuration/full/export to export all the block settings for my theme.

I then took all the generated YAML files and placed them in a new folder within my theme at /config/install. I then uninstalled the theme and then reinstalled it as the default. Voila, all my blocks, i.e., menu, help etc... were in their designated regions according to what had been exported in the YAML files.

Some examples of the file names are:

block.block.gratis_help.yml
block.block.gratis_main_menu.yml
block.block.gratis_branding.yml


Create a new personal page instance for each user

You can create new Views page like this:

Let me explain underlined options:

Path: personal/% - let you to create dynamic path. In addition "%" sign is a wildcard used by contextual filter;

Relationships > Content:author - this relationship is required by filters to show only nodes created by its author. Without this we would be able to filter only by user ID.

Contextual Filters > User:name - this is value of URL wildcard. It allow you to filter nodes by put any user name instead of % sign.
For example: www.mywebsite.com/personal/john

Filter Criteria > Current User (Yes) - It shows only nodes created by current logged in user. Without this filter anyone can put any user name in url and see content created by this user.

Let me know if something is not clear to you.


How can I write an input selector for the states API?

drupal_process_states() has a great set of information on handling inputs for different types of input elements.

You have checkboxes, so you have to use checked assertion.

case 'my_form':
    $form['revision_information']['#access'] = FALSE;
    $form['field_guide_link_hosting']['#states'] = array(
      'visible' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE),
      ),
      'required' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE
      ),
    );

Notice I replaced the value assertion with a checked, and also changed the jQuery selector to use the full name attribute of the checkbox.


Saving a unpublished node without validation

Another option here is to add a custom validation function to force validation to run, and then also have a custom submit handler to clear any errors produces and save the node.

The code here is mostly taken from this question but this question and this post have also helped.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'my_form_id':

            $form['actions']['draft'] = array(
                '#type' => 'submit',
                '#value' => t('Save draft'),
                '#weight' => '9',
                '#submit' => array('save_draft_submit'),
                '#validate' => array('save_draft_validate'),
                '#attributes' => array(
                    'class' => array('cancel'), // add the class cancel will skip any clientside validation
                ),
                //'limit_validation_errors' => array(), // this should be enough to skip validation however does not work for me
            );

            break;
    }
}

function save_draft_validate($form, &$form_state) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;
    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);

}

function save_draft_submit($form, &$form_state) {
    // clear error messsages
    drupal_get_messages();
    // save the node
    node_form_submit($form, $form_state);
    $form_state['redirect'] = 'node/'.$form_state['nid'].'/edit';
}


How to run a Drush command in interactive mode

The 'interactive' flag in Drush backend invoke is only used when Drush is going to programatically call another Drush command.  In this instance, the interactive flag tells Drush to call the subcommand in a way that will allow user input.

The issue you reference above (drupal.org/node/1058874) is now standard in Drush 5. If you upgrade, you should find that Drush does a better job at showing incremental progress in some situations. Of course, there are also still some commands where Drush must first compose all of the output, then format it in a table, then output it.  In these cases, the output will always be buffered.


If you just need to apply CSS styling, then if you view the source of the webforms you will see they have container divs with classes that contain an ID number. This ID will allow you to directly target a specific webform.

If you mean you want to add your own divs etc. and template different webforms, then the best way to do this is by creating a specific template file for it.

In your theme folder you can add a template file such as:
webform-form-[nid].tpl.php you can get the ID by viewing the source of your form, it displays in one of the forms parent divs.

As your base you can use the default template from the webforms module. Goto (or other location where you have installed the webforms module):

/sites/all/modules/webform/templates/webform-form.tpl.php

and make a copy of this.

I have themed webforms that appear in blocks in the following way too:

block--webform--client-block-112.tpl.php


Add HTML to Page Title for Entity (Profile2)

I solved this by adding the HTML to a custom page template based on the user role and profile. I used the following code to create the template suggestion in the template.php file:

function MYTHEME_preprocess_page(&$variables) {
  global $user;
    if(arg(0) == 'profile-carer' && in_array('my custom role', $user->roles)) :
      $variables['theme_hook_suggestion'] = 'page__profile_carer_my_custom_role';
    endif;
}

I was then able to use the custom template page--profile-carer-my-custom-role.tpl.php based on the page.tpl.php


How do I add the "- Any -" option for the published status on exposed filters?

As the screenshot shows, the filter is set as Required. This means the users need to select a value for that filter that, being a filter for the published status, can only get Yes and No as values.

If you want to allow users to select - Any - as value for that filter (which isn't really a value for the published status, but a value that tells the view not to filter the nodes basing on their published status), you need to deselect the checkbox that is shown to the left of Required.


To put a JavaScript in your theme you must do the following steps:

Assuming that your sub-theme name is example.

Update your example/example.info to have this scripts[] = js/custom.js. That means the custom.js path is example/js/custom.js.
Clear the cache.

Troubleshooting:

If your code in custom.js is not working then there is something wrong. First, check if there is a js error using browser console. Second, check the http response code make sure that there is no permission issue.

Alternative way to add Javascript.

Another way of adding Javascript is by using drupal_add_js. With this API you can control which page the js is going to load.


You can use the webform validation   to create a rule that compares the e-mailaddress with all e-mailaddresses in the table where the webform data is stored (you will have to look it up but I believe it is the email field in the webform_emails table).
Or you can create a custom module depending on webform_validation to compare data, there is a similar issue in the issues..


Public and temporary files error in my "Status Report"

The easiest method is in the fine print.  If you haven't edited these files, then

browse to admin/config/media/file-system
delete sites/default/files/.htaccess
delete wherever/your/private/files/are/.htaccess as indicated on the page you just browsed to
delete wherever/your/tmp/files/are/.htaccess as indicated on the page you just browsed to
click SAVE

This will recreate the two .htaccess files.  Then visit the status report and double check things.

Otherwise, edit sites/default/files/.htaccess to be

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

and wherever/your/private/files/are/.htaccess and wherever/your/tmp/files/are/.htaccess to be

Deny from all

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Note the difference on line 1 for the private files.  This is what prevents files from being browsed to from the outside world.  It is also beneficial to place your private and tmp file directories outside your DOCROOT if you can, as an added precaution.


In Views admin, is there a section to insert CSS to style the view? i.e. how to style view without editing theme code or other drupal PHP?

Actually, the latest views does allow all kinds of CSSing, both from the easiest, such as adding CSS classes to the view Style Settings section, to embedding custom css and fields wrappers in the fields output when you click on their configuration and edit Style Settings there.

But I think the question here is, after you do all that, where do you put the CSS itself.

And that would be in one of your theme's css files, which are defined in your themename.info file (which is located in your theme's toplevel directory) like:

stylesheets[all][] = myfilename.css

So, you could ADD a css file to your theme with your customized CSS without touching anything else in there.


Allow anonymous users to post content but require login/register before it is saved

This module might be worth looking at as well: Create and Register. Below are some more details about this module, and how it works (summary from the module's project page).

  This module allows an anonymous user to create the content. After
  doing so the user must login (or registers to the site). Here are some
  more details about the process to do so:

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


In your AJAX callback, use $form_state['rebuild'] = TRUE; (drupal_rebuild_form).

$form_state['rebuild'] is very useful in multistep forms, but it can also be handy in Ajax callbacks.

I recommend checking out the Examples project as well.  Both the Form examples and the AJAX examples.

If you will add the relevant snippets of your code I will try to add more details.


I've recently built a subscriber module with a small piece of custom code. I prefer working with webform handlers instead of the Mailchimp module.
In a custom module add a folder src/Plugin/WebformHandler and create a file newsletterSubscription.php. Add the following code:

<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "newslettersubscription",
 *   label = @Translation("Newsletter subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions in Mailchimp"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class newsletterSubscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const MAILCHIMP_API_KEY = 'x'; // see https://mailchimp.com/help/about-api-keys
  const LIST_ID = 'x'; // see https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // The data to send to the API
    $postData = array(
      "email_address" => "$email",
      "status" => "subscribed",
      "merge_fields" => array(
        "FNAME" => "$first_name",
        "LNAME" => "$last_name"
      )
    );

    // Setup cURL
    // To get the correct dataserver, see the url of your mailchimp back-end, mine is https://us20.admin.mailchimp.com/account/api/
    $ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.self::LIST_ID.'/members/');
    curl_setopt_array($ch, array(
      CURLOPT_POST => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.self::MAILCHIMP_API_KEY,
        'Content-Type: application/json'
      ),
      CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);
    $readable_response = json_decode($response);
    if($readable_response->status == 403) {
      \Drupal::logger('Mailchimp_subscriber')->error($readable_response->title.': '.$readable_response->detail .'. Raw values:'.print_r($values));
      \Drupal::messenger()->addError('Something went wrong. Please contact your webmaster.');
    }
    if($readable_response->status == 'subscribed') {
      \Drupal::messenger()->addStatus('You are now successfully subscribed.');
    }
    if($readable_response->status == 400) {
      if($readable_response->title == 'Member Exists') {
        \Drupal::messenger()->addWarning('You are already subscribed to this mailing list.');
      }
    }

    return true;
  }
}

Read more on how to enable and use the handler here: How to create a mailchimp subscription with drupal 8 webform and custom handlers (Video)


How to upload multiple files and predefine filetypes?

Also i would like to know how i can predefine the filetypes users can
  upload?

Specify the file types restriction on the file field with 'file_validate_extensions' in the #upload_validators array in the file field.
See the form api for reference. See the file_managed field.


If you have already created a view which shows nodes you want to display, in the view settings select Format > Grid, and Show > Fields in the Format area; select the fields you want to display in the Fields area.

If you want other than default sorting options use modules such as the following ones:

the Weight module (It allows you to assign weight to nodes and then sort them by that weight.)
the Menu Node Views module (If you have added your nodes to some menus, then this module allows to sort nodes in the view by that order.)

Note

The Menu Node Views module starts producing duplicate results, if the content of the node is translated to other languages (translated using the Entity translation module).


You could try out this Article..

The contextual filter should be "content:nid"

The options should be set as follows...

The Relationship should be your "Entity Reference: Referenced Entity" relationship
Under "When the filter value is NOT available" check "provide default value" and select "Content ID from URL"
Apply changes and save view.


Ok I found what was wrong :
I needed to register the function in the template.php :

function business_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu_tree__menu_block__menu_navbar']['function'] = 'business_menu_link__menu_block__menu_navbar';
}
function business_menu_link__menu_block__menu_navbar($variables) {

}


How Do I Replicate Computed Field Functionality In Drupal 8?

There you are:

https://drupal.org/node/2112677

Basically you have to write a plugin and store your calculations in the getValue() function.


How to trace Drupal 7 Core Logic Using Netbeans with xdebug?

In my opinion, studying drupal core using netbeans and xdebug is somewhat too overwhelming. Starting in index.php will lead you through the whole bootstrap and other parts which do not need to be studied by someone who is starting to understand drupal. The most important parts to be familiar with are menu system and node system. These two parts are the basic building blocks on which you can build further (entities, taxonomy etc.). To study these, I would recommend the combination of 3 approaches:

Study the documentation

menu - you can start with hook_menu (https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7)
node api hooks (https://api.drupal.org/api/drupal/modules!node!node.api.php/group/node_api_hooks/7)

Study the examples module (https://drupal.org/project/examples) - it provides a lot of very well documented code which you can see in action (by turning on the module and its submodules)
Playing around with your own code snippets (=trying out what you learned)

I think xdebug comes later into this mix because it is a debugging tool (by definition) and even though jumping from function to function, from module to module can give you some understading of the flow of things, it is usually easier to just check it out in the documentation.


Views pager not rendered for teasers with comments

Have you tried to give your pager another "Pager ID" (in the pager options on the view). Try to enter a number bigger than 0.


Displaying commerce product with all product variations and attributes

If you're insistent on not using Views, you might pull it off like this:

Create a new node type and then add an entity reference field that will reference the product displays for each of your products. Set the values to unlimited.
For each of your individual products, create a product display.
Set the renderer of the entity reference field on the new node you created to "rendered entity"
Theme the product display nodes that are linked to the entity reference field accordingly

  +------+     +------------------+     +----------+
  | Node |1---M| Product Displays |1---1| Products |
  +------+     +------------------+     +----------+
            ^     ^
            |     | Theme this entity appropriately.
            |
            | Set this display rendered to "Rendered entities"

At that point, you should have a list of rendered node entities that would each have their own add to cart form. You could also add a new view mode (using Display Suite) and use that view mode specifically if you still wanted to use the other view modes.

But honestly, this is an extreme amount of work for something that you could accomplish in 30 minutes with Commerce Add to Cart Extras and Views. And regardless of what I said above, that's still my recommendation.

Edit: You're on the right track with Views Field View. If you're worried about performance (how many products do you have?) then you can also:

Use Views cache. It's configurable under Advanced in the right-most column of the view configuration screen.
Enable Views Content Cache.
Implement Redis and perhaps Entity Cache.


You can override existing twig file in preprocess hook. You may check the link https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates.


How do I create a route that opens an external file?

Is there a way to achieve this without calling a controller from the route file?

No, a route needs a controller, no exceptions. If you can find an existing controller/method that does what you need, reliably, then you should use that. If not, you'll need your own controller and method.


Unable to override views-view-unformatted.tpl.php

In the "Advanced" section of the views configuration, click in "Theme:informaction" and you will see all the possible templates

Regards


Unable to add a submit button to a drupal Block

A small change needed as below

  Key was to chnage the type from button to submit
  But I guess making a separate function to get the form will be better

function block_content() {

  //calling the form in the block
  $block_contents = drupal_get_form('_cacheclearbutton_clear_cache_form');

  return $block_contents;
}

// A separate function to return the form to clear the cache
function _cacheclearbutton_clear_cache_form() {
  $form = array();
  $form['clearbutton'] = array(
    '#type' => 'submit',
    '#value' => 'Clear Cache by Module Test',
    '#submit' => array('clearbutton_submit'),
  );
  return $form;
}

function clearbutton_submit($form, &$form_state) {
  cache_clear_all();
  drupal_set_message(t('Setting a message from the submit handler'));
}


Part of the problem here is that there's no standard specification for CSV.

Added to that, Microsoft does not have much incentive to ensure interoperability between their version of CSV and Drupal's version, and so it is not surprising that they do not offer any (direct) way to encapsulate the contents of cells with single quotes within double quotes, so you've got to do something a bit more complicated if you want Excel to output Drupal-friendly CSV files.

Or, since Drupal is telling you where the problem is, you can do it manually.  If you only have a few rows with apostrophes, then that may not be a big deal.  If you have a lot of rows in your CSV with apostrophes or single quotes, then you've got a bit of pain.

Alternately, if you've got Python on your machine, or are willing to install it, this python script to add double-quotes to CSVs may work for you, and may be much easier than dealing with Excel macros.  It all depends on the languages and language environments you're comfortable with, however.

One might argue that Drupal (or more specifically the Feeds module) should support Microsoft's CSV, and thus handle apostrophes gracefully when not wrapped in double quotes.  If you are of this opinion, you may want to file a request with the Feeds project.  Since there is no (standard) CSV spec, this can't be considered a bug (AFAIK), but it does seem like a useful feature that they might want to add.


Can I setup a backup migrate schedule from settings.php

According to this thread (the first part is about the Environment Indicator module but the last part is about Backup and Migrate), Pantheon forbids the use of the Backup and Migrate module on their platform.  While it is possible to make Backup and Migrate settings exportable, including for use in settings.php, it's probably best not to violate your web host's policies.

That said, Pantheon should really start writing their rules down clearly somewhere.


Since you're using Views, you've got everything you need.  You just need to set the Display Format to Grid, and set it to Show Fields, as in the following example from editing a view.

And to display more than one field in each Grid "cell", you will need to add a Global: Custom Text field to combine the fields for display. (Change the Content: Title and Content: Link fields used in these example to your fields.)

See the Image of Custom Text Settings (below) for an example of how to combine the fields. The Replacement patterns shows the fields available to be combined.

In the settings for each field, set Content: Title and Content: Link fields to be excluded from display, and set the Global: Custom text to NOT be excluded.

Oh, yeah... these images are from Views 3.x.

View settings:

Click the Settings link next to 'Grid' to set the 'Number of columns'. You can also set the display Alignment to Horizontal or Vertical.

Grid settings:

Global Custom Text selection:

Custom Text Settings:


I don't think you can do it that way. You can always do it quick and dirty, depending on how it's written.

If it's your own code, wrap it in the following and throw it in a block:

(function ($) {
    // in this function, you can use the $ which refers to the jQuery object
}(jQuery));

Or you can try creating a generic file content type with a file attachment, upload the .js into the public directory, then make a new block with a PHP filter and use drupal_add_js() and load in that file.


Individually Print Exposed Filter Elements/Options

I found a fairly reasonable solution to this - there may be better ways, but so far it works without any performance hit that I have been able to detect.

It seems as it's a fairly complex multidimensional array, you can only render an entire widget or not. So to do this you need to create different versions of the widget, with different options inside them, and render them in their entirety.

Step 1: Copy the form array (the widget) into a new array and create another array containing just the options

$formArray = $form['colours'];
$allColours = $form['colours']['#options'];

Step 2: Unset all the options from the new array, which is now just a shell, then create a few copies of it

unset($formArray['#options']);
$justColours = $formArray;
$justShades = $formArray;

Step 3: Cycle through your array containing just the options, and distribute them back into the shells you created

foreach ($allColours as $id => $result) {
    if ($id >= 0 && $id <= 2):
          $justColours['#options'][$id] = $result;
    elseif ($id >= 3 && $id <= 4):
          justShades['#options'][$id] = $result;
    endif;
}

Step 4: Render your new arrays where you need 'em

print render($justColours);
print render($justShades);

Snap!


Can I allow a user to add additional tabs in quicktabs?

Well, this is not so much about quicktabs, but I did find a work around. I ended up using plain old field groups. This module has logic in it where if containing fields have no content, don't display that tab (or "horizontal item" in this case).


Checkout a specific dev version of module using git

This is more a git question than Drupal, but you can use rev-list command to retrieve a list of commit hashes since the 7.x-2.0-alpha8 tag. Using the tail command you can reverse the list to show the first 100 commits (I think the +XX- scheme is an offset from the first commit) then filter that down to the last result (which should be +99-dev commit).

git rev-list 7.x-2.0-alpha8^..HEAD  | tail -r -n 100 | tail -n -1


How do I migrate the file attachments field from a content type?

In Drupal 6, file attachments are considered enabled if the upload-module is enabled, and the variable 'upload_[content_type]' is true or not set. The latter could be the cause that your attachment fields are not being migrated.

There is an open bug report for this scenario, including a patch, at https://www.drupal.org/node/2829274


book_delete module will address your issue !

  Book Delete adds the ability to delete entire books to the book
  administration page (admin/content/book). It uses a batch operation to
  allow deletion of large books.

Take a backup of database before doing any delete actions :-)

It just worked as expected !! Follow below steps.

Install module
Clear Drupal Cache
Go to admin/content/book
Select the book you want to delete and click on delete book link next to it.
Confirm delete !

That's it :-)


Node "add" with already set paragraph fields

Actually it is pretty simple. I have written a module with the following hook:

Hope that helps somebody. Pretty handy and user friendly when it comes to content that is mainly created through paragraphs elements.

You attach the field widgets to the node when the add form is opened.

function xxx_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {

    if("article" === $entity->bundle()){
        $bundles = ['article_navigation_banner', 'call_to_action_banner', 'author_information'];
        $entity_manager = \Drupal::entityManager();
        $langcode = $form_state->get('langcode');

        $field = $entity->get('field_ui_elements');

        $target_type = $field->getSetting('target_type');

        foreach ($bundles as $bundle_name) {
            // Create paragraph and display.
            $entity_type = $entity_manager->getDefinition($target_type);
            $bundle_key = $entity_type->getKey('bundle');

            $options = array(
                $bundle_key => $bundle_name,
                'langcode' => $langcode,
            );

            if("call_to_action_banner" === $bundle_name){

            }

            /** @var FieldableEntityInterface $paragraphs_entity */
            $paragraphs_entity = $entity_manager->getStorage($target_type)->create($options);

            // Field values.
            $field->appendItem($paragraphs_entity);
        }

    }

}


Permission tmp problem: Change of tmp directory

You can edit the relevant setting in Configuration > Media > File system > Temporary directory (/admin/config/media/file-system).

You can choose any directory in your document root skipping the forward slash. I would recommend you to specify tmp. Take care of the permissions.


Display Suite Extras, shipped with Display Suite, lets you choose a different build mode for every row in the View. You might look its code to see how it's done and then hook into it to switch based on the value of a node field. Shouldn't be hard.


Browsing private and public files in IMCE

While writing this question I found it:

You can access the public files like this:
mydomain.com/imce/public

and the private files:
mydomain.com/imce/private


Add mail to user register with user_external_login_register

The function user_save is called in user_external_login_register, so you could just use hook_user_insert to add the info you need.


Multi-site, multiple database and 1 shared database

If your need is

  each site must use same content types, views, rules but different contents

Domain Access is simplest answer:

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

Of course it uses one database, but end-user experience you need is covered.


Multiple problems after updating to 7.54

Try to apply the patches that commerce kickstart uses .. https://www.drupal.org/project/commerce_kickstart/releases/7.x-2.45

where

http://drupal.org/files/drupal-865536-204.patch

is form related

the others may not be needed:

http://drupal.org/files/1275902-15-entity_uri_callback-D7.patch
http://drupal.org/files/drupal-1470656-14.patch
http://drupal.org/files/issues/drupal-7.x-allow_profile_change_sys_req-1772316-28.patch
http://drupal.org/files/issues/install-redirect-on-empty-database-728702-36.patch


Why is submit handler not called if $state['rebuild'] == true?

When form validation fails submit handler should not be executed because there are errors in the form.

In a similar way, when a form is mark as rebuild in the validation phase submit handlers should not be executed because the form is going to be rebuilt. This means that form is going to change and the user interaction with the form is not finished.

You can check the (complex) workflow of FAPI in this illustration:

(Illustration from https://www.drupal.org/node/165104)


How to show a string once you submit a form in a page reloading the page?

Add the code to calculate and display the result in the form build

  public function buildForm(array $form, FormStateInterface $form_state) {
     $form['number1'] = array(
      '#type' => 'textfield',
    );
    $form['number2'] = array(
      '#type' => 'textfield',
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Sum'),
    );

    $values = $form_state->getValues();
    if (!empty($values)) {
      $result = $values['number1'] + $values['number2'];
      $form['result'] = ['#markup' => '<p>' . $result . '</p>'];
    }

    return $form;
  }

So that the result can be included in the form rebuild when the input values are filled in.

In submit request a rebuild:

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }


How would I use the Field Validation module with Addressfield to make just city and province/state required?

On your node type field administration page, click the validate for your address field. Click the Required field validator link. On the validator form you want to:

Add your arbitrary Rule name (e.g. Address State)
In Column, select locality or administrative_area for City & State respectively.
Add your custom error message in the Custom error message field.
Click Add rule to add the validator.

Once added for both city/state this will force the address field's city/state to be entered.


Obfuscation or e-mail spam protection for content displayed through Views module

SpamSpan can do that for views too. You need to select te SpamSpan formatter on your display settings of the field.


Following rule should help you

{ "rules_send_email" : {
    "LABEL" : "Send Email After Save",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--send_email" : { "bundle" : "send_email" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "Subject Test",
          "message" : "submittted value for Result field is [node:field-result]"
        }
      }
    ]
  }
}

The above rule will trigger email when a new content will be added For update also clone this rule and change the event to "After updating existing content"


What do array keys in the database definition array mean?

Here is the explanation from the setting.php file:

  For each database, you may optionally specify multiple "target" databases.
  A target database allows Drupal to try to send certain queries to a different database if it can but fall back to the default connection if not. That is useful for master/slave replication, as Drupal may try to connect to a slave server when appropriate and if one is not available will simply fall back to the single master server.

  The general format for the $databases array is as follows:

$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;

  In the above example, $info_array is an array of settings described above. The first line sets a "default" database that has one master database (the second level default). The second and third lines create an array of potential slave databases. Drupal will select one at random for a given request as needed.  The fourth line creates a new database with a name of "extra".

I hope this will give you clear idea about default2 and default3.


How do I fix a "Mismatched entity and/or field definitions" error on my configuration?

You can solve this issue by two ways
If you have Drush -

drush entity-updates

If you don't use Drush add following script before $response->send(); in index.php file(located in Drupal root folder) and reload the web page.

try {
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}
catch (EntityStorageException $e) {
  print_r($e);
}

Then remove this code from index.php file.


User Login with Email Address - Services

You can do this in a custom module:

/**
 * Implements hook_services_resources_alter().
 */
function my_module_services_resources_alter(&$resources, &$endpoint) {
  // Override the normal user login callback.
  if (isset($resources['user']['actions']['login']['callback'])) {
    $resources['user']['actions']['login']['callback'] = 'my_module_services_login';
  }
}

/**
 * Replacement callback for the Services user login resource. Optionally use the email address to login.
 *
 * @see _user_resource_login().
 * @see https://drupal.org/node/1431724
 */
function my_module_services_login($username, $password) {
  $result = db_query(
    "SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:username)",
    array(':username' => $username)
  )->fetch();
  if (!empty($result->name)) { $username = $result->name; }
  return _user_resource_login($username, $password);
}

Using this technique, you don't need to patch the Services module.

This solution is borrowed from DrupalGap:

http://cgit.drupalcode.org/drupalgap/tree/modules/drupalgap_logintoboggan/drupalgap_logintoboggan.module


How to override path of specific page using views

Just set the path of the view to the same as the path of the page you want to override.

That's all you need to do, paths that Views takes care of "win" over paths provided by core and other modules. The most famous example of this is probably the taxonomy/term/% page View that comes with the module. Once enabled, term pages aren't handled by core any more, the View takes their place.


Media Title appearing in View when HTML is stripped

This ended up being a media field label and not the media type name, like I originally thought it to be.

This was happening due to the media label being set to "Visually Hidden" instead of "Hidden"

This setting can be found at
Administration > Structure > Media types > [your media type] > Manage Display

Now that it's set to "Hidden" it no longer shows in the label in the view or the WYSIWYG


Host blocked website due to sending spam from website

Your hosting provided blocked your website, because it was used for sending the spam from using PHP scripts which were suspiciously uploaded to your Drupal installation folder (by using some vulnerabilities).

Why this happened?

There could be many issues, including contrib modules or Drupal core vulnerabilities.

Please follow Drupal Security advisories to be up-to-date.

If your Drupal version is 7.32 or below, there is Highly Critical issue (SA-CORE-2014-005) which people call Drupalgeddon. See FAQ and Drupalgeddon project for more details. Also my GitHub repo (drupageddon) for educational purposes (to understand how it works).

What to do

To prevent that from happening, first of all, check Status/Reports in Administer page to see if you've any Security warnings and your site needs some upgrades.

Then you may consider to log-in to the website (ssh) and scan for suspicious files.

You should look into these tools to help you with restoring your Drupal security:

Security Review
Site Audit
Hacked!

  If you use drush (and you've alias set-up to your environment), check for Hacked! module. It can find which core files or modules were hacked, but it could find only modified one, not the one which are extra.

If you're using drush, other trick can be to generate your make file (drush generate-makefile) from your current Drupal site (however this is probably not necessary, but it keeps track of your old version of modules), then run drush up. This will upgrade your Drupal core and all contrib projects and apply any pending database updates. How would that help? It'll actually upgrade all core/module files by replacing old directories with fresh version of stable release files (so any extra files which aren't part of the module would be automatically removed).

Finding suspicious files

To fix your infected website installation, you need to find files which were hacked and malware files in your Drupal installation folder.

You actually found one at (which is a good start):

  /var/www/vhosts/site domain/httpdocs/sites/all/themes/chaymae/css/mailer.php.php

which needs to be removed as soon as possible. Probably you have more of them.

If there is no access to shell, transferring over FTP (ncftpget -R) and checking locally would help. Or find other way to backup your whole site and test it locally for any extra files or hacked files.

If you don't use git, I would suggest you to download your Drupal site into folder and create git repository, so you can track the changes.

For example:

git init
git add -A .
git commit -m 'My original files.' -a

Then upgrade all your core and modules and review the changes (git diff), and commit all again.

Here are few commands which can be useful to find suspicious files (in your webroot):

grep -R return.*base64_decode  .
grep --include=\*.php -rn 'return.*base64_decode($v.\{6\})' .
find . -name \*.php

Above results doesn't mean necessary suspicious files, but you need to use your common sense to identify which files aren't Drupal. Usually these files are obfuscated.

Please find the following repository with common php-exploit-scripts to give you some idea what you could deal with. See also: What does this malicious PHP script do?

Unblocking your site

Once you find your problem and identified malware files, then remove these files from the server and upgrade your core and modules to the recent secure version and inform your hosting provider that you've removed malware so they can unblock your site.


Redirect all subpages back to the front page

I assume "pictures", is a content type. If that's not the case, this may not work. Please provide more details about your setup in that case.

Install the Chaos tool suite (ctools) module, and enable the Page Manager module
Enable the node template
Create a variant of type "HTTP response code".
Set the response code to 301.
Set the path to <front>
Go to "Selection rules" in the left menu
Add "Node:type == 'pictures'"
Save


Have you tried the Feeds module?

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files


What is the difference between KPR() and DSM()

In Devel there are various formatters you can use to dump variables. But the main difference of dsm() is, that it uses drupal_set_message(), which displays the output in the message array via a session, so that the information is preserved between different requests of the same user. This is helpful for debugging code, which doesn't result in a html page to display a normal var dump, for example a form submit. The disadvantage is, that dsm() sometimes produces the output asynchron, not when you expect it, which can lead to false conclusions.


How can multiple sites use a common default theme with site specific customizations?

Consider starting from a Base theme, such as Omega, Zen, Bootstrap, etc. Or build your own (custom) theme that you can use as a Base theme (that would be youru "core theme".

And then create Sub-themes (that would be what you named "their custom themes").

Note: the question about "Right way to start with a Bootstrap subtheme?" contains a lot of details to get started with such sub-theme ...


How to fix "Unable to save a field collection item without a valid reference to a host entity" error?

Sorry for the late reply but your question is a bit confusing and I would like to clarify the mentioned issue (message). Did you use ->setHostEntity($obj) at creation of the FieldCollection? I think that you created "ghost" fieldCollections. Have a look in DB if they was added there and you don't see the new FieldCollection at HostEntity in back end.

In my case, i was loading a FieldCollection Item which also did not have the HostEntity set and was struggling with the same Error Message (therefor the explanation). Later I figured out that the following procedure is correct - mention the saving of the HostEntity of the FieldCollection:

use Drupal\field_collection\Entity\FieldCollectionItem;

$fieldCollectionObj = FieldCollectionItem::load($fcId);
if($fieldCollectionObj->hasField('field_my_user_fc_field')) {
    $userObj = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $fieldCollectionObj->set('field_my_user_fc_field', 'my new value');
    $userObj->save();
}


db_query('SELECT nid FROM uc_products'); doesn't give any results! Why?

I think it is likely because your first result is a "0" and php will evaluate that as a False, which stops your while loop from running.


In Drupal 7 you need to use drupal_render_children() instead of drupal_render() for the $form. Otherwise, if the form has the #theme property set you will get an infinite loop (as your theme function will invoke the form builder to run your theme function again, and the cycle will continue).


How to override an existing theme without subtheming it?

You can call for your css

<?php
function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=News+Cycle', array('type' => 'external'));
}
?>

and for your tpl file

<?php
/**
 * Implements hook_theme_registry_alter().
 */
function my_module_theme_registry_alter(&$theme_registry) {
    // Defined path to the current module.
    $module_path = drupal_get_path('module', 'my_module');
    // Find all .tpl.php files in this module's folder recursively.
    $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
    // Iterate through all found template file objects.
    foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
            // Alter the theme path and template elements.
            $theme_registry[$key]['theme path'] = $module_path;
            $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
            $theme_registry[$key]['type'] = 'module';
        }
    }
}
?>


Drupal site communication with other site

This is a fairly complicated thing to do, but the "go to" module for handling integration with third-party sites is the services module.


How to log the history of nodes viewed by a user, and report about them?

You can try using Recently Read module...

  Recently read allows site administrators to enable blocks displaying a
  history of recently read content (nodes) both to anonymous and
  authenticated users. For logged in users, each user has its own
  history. For anonymous users, the history is based on sessions. This
  module may be useful i.e. for displaying recently viewed products on
  the e-commerce site.


How to prevent the addition of HTML in "Full HTML" text format?

Ok, I think I've found the answer:

This is a "feature" of the Full HTML mode.

  Full HTML:

  Web page addresses and e-mail addresses turn into links automatically.
  Lines and paragraphs are automatically recognized. The  line break,  paragraph and  close paragraph tags are inserted
  automatically. If paragraphs are not recognized simply add a couple
  blank lines.

You can disable it in You are here Administration » Configuration » Content authoring » Text formats by unchecking Convert line breaks into HTML (i.e. <br> and <p>).

Source: http://drupal.org/node/503754


Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment)

I have not found a better alternative to migrate module till date and I have done lots of migration including ubercart order migration. It has served me well for:

ASP.Net (MSSQL server) -> Drupal migration
D6 -> D7 Migration
Rails (MySQL) -> Drupal Migration

There are tons of other modules like node_export, views bonus pack, uuid features, deploy that will let you export content out of drupal site but nothing scales better than migrate module. Having said that, its some effort as you need to write your migration classes, but it comes with excellent features like:

Incremental Migration ( you can test your migration class, with small subset of content)
Rollback ( In case you realize you missed something )
Solid drush interface.

Also, once you get a hang of it you keep appreciating the fact that it always work. It knows what has been imported, it reports on warnings during migration, gives you a status update on your migration. Can't recommend it enough!! and the best part is minimum downtime, you keep syncing content till the last moment.


Reinstall a patch with composer - update one module only

Yes, use the following:

composer update --prefer-source drupal/menu_block


Trying to turn on theme debug, but getting an error: Drush command terminated abnormally due to an unrecoverable error

Update drush

composer require drush/drush:9.0.0-alpha1


Change name of a tab for a specific content type

You can use hook_menu_alter() to change the name of tabs for a specific content type. For example:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  unset($items['node/%node/view']['title']);
  $items['node/%node/view']['title callback'] = 'MYMODULE_view_tab_title';
  $items['node/%node/view']['title arguments'] = array(1);
}

function MYMODULE_view_tab_title($node) {
  if ($node->type == 'organization') {
    return t('Organization Home');
  }
  return t('View');
}

Remember clear Drupal cache.


Drush commands to control theme debugging:

Drupal 7

To turn it on: drush variable-set theme_debug 1
To turn it off: drush variable-set theme_debug 0

Drupal 8

To turn it on: drush state-set theme.debug 1
To turn it off: drush state-set theme.debug 0


unsetting field via view hooks no effect on aggregation results

with pre_build worked fine and the aggregation disappears.

function views_test_views_pre_build(&$view) { unset($view->field['my_field']); }


How to flag if a 'webform' exists on a page?

This appears to be a preprocess function. If it's hook_preprocess_page(), you can do this:

function hook_preprocess_page(&$variables)
{
  if(isset($variables['node']) && $variables['node']->type == 'webform')
  {
    $variables['s.event4'] = "event4";
  }
}


How to call jQuery functions from my form with Ajax?

You need to read the documentation as you are conflating the idea of ajax and what the AJAX capability of Form API is. A form item needs to add an #ajax item to perform ajax callbacks (php), and those functions can trigger AJAX commands some of which can trigger external JS functions.

On top of that, your actual JS code needs to conform to Drupal JS / behavior format so that it is leveraged by Drupal properly. The minimum here is it at least has to be enclosed in an anonymous function to prevent a jQuery conflict:

/**
 * @file
 */
(function ($) {

  "use strict";

  // All the JavaScript for this file.
  $("#ajax-wrapper").show();
  // other code or behaviors

})(jQuery);

Plus, if you have form fields that are dependent on other fields as far as being visible, you might be able to just use #states.

Here are resources:

https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
Behaviors
AJAX API
Ajax Forms in Drupal 8
AJAX command usage example
InvokeCommand
Form API #states
Using InvokeCommand


How to print the Addthis block code into a template

did you enable the Display Setting in your addthis block configuration because code is good go it working for me, so go and configure the display setting surely it will work.. its under admin/structure/block/manage/addthis/addthis_block/configure enable it as you need by "Basic button or Basic Toolbar"...


There is an apachesolr field collection module available, which makes me think that field collection support is probably not out of the box with the apachesolr stuff.

As a matter of fact, if you look at the issue queue for the apachesolr module you can find this ticket #1810228 : Process Field Collection Items. It confirms that field collections are not supported out of the box, and the comments point to the apachesolr field collection module, and indicate that the module may be buggy...

I'd say try it, but test your integration thouroughly. And do try both available versions (alpha and dev), and see how it goes.


why does drush tag 8.0.0-beta14 returns all zero for config core.extensions

The numeric values in core.extension are the module weight; if a module is disabled, then it does not appear in the list at all.


How to enable Views caching for all pages instead of only the first page?

While I haven't used a search view, I ran into a similar problem with pagers. Views caching has two parts out of the box, query and render. The render cache was interfering with the pager. I think setting the Views caching to Search Specific is setting both query and render in one swoop.

I would try changing it to Time Based and caching the query, but not the render. Varnish will then be able to correctly cache the various pages of the view.


How to programmatically clear/refresh module file cache?

Add a MYMODULE.install file to your module. In there implement hook_update_N to flush all caches. When others update your module, and then do database updates, Drupal will pick up this hook and flushes the cache and your new files will be recognized.

/**
 * Pick up new files.
 */
function MYMODULE_update_7100(&$sandbox) {
  drupal_flush_all_caches();
}


Is there a way to add variants to a mini panel?

Minipanels don't support variants, however, you can achieve a similar result by adding visibility rules to show/hide minipanel panes on certain pages, according to specified conditions.

Though more simple options are possible, an example using PHP for a visibility check is here


How to overwrite modules by default with DRUSH?

Overwrite
Allows the project to be installed in a directory that is not empty. If not specified this is treated as FALSE, Drush make sets an error when the directory is not empty. If specified TRUE, Drush make will continue and use the existing directory. Useful when adding extra files and folders to existing folders in libraries or module extensions.

projects:
  myproject:
    overwrite: TRUE


How to create a view grid that changes content type per row

sounds doable with Views Field View, I have done something a bit similar using Views Field View with Contextual filters. if it did't work the way you want, so you need to code it checkout this answer


How to check if a link field uses  in template

Assuming your link field only allows 1 value.

{% if content.field_link.0['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
{% endif %}

If your field allows multiple link values then loop:

{% for link in content.field_link %}
  {% if link['#url'].toString() is empty %} # or use "is not empty" if you're checking if there is a url.
    # your code goes here
  {% endif %}
{% endfor %}


How do I use entity_metadata_wrapper to create a node and at the same time multiple node references?

You should probably look at Migrate module. IT has support to import xml data into nodes.


Where to add my merchant gateway using ubercart?

There are lots of modules that actually does this. You will need to do some custom coding and integrating with Ubercart. It's been a while since I did this and it also depends on your Ubercart/Drupal version. But you can checkout the quickpay module for drupal 6 integration example.

The typical way of doing these kinds of things, is to create a form and auto post it with javascript to the payment gateway url with all the params needed. It's up to you to send the correct params along and up to the gateway to redirect back. But answering those questions won't be drupal or ubercart related.


How can you alter the display of Flag confirmation dialog messages?

I figured this out.

When you create a new Flag, at the very bottom of the Flag set up screen is the option to choose if a dialog confirmation box is required for selecting your flag.

If you choose yes, an additional option box becomes available below this were you can set the message to be displayed when a user is either Flagging or Unflagging content with this dialog box.

If you don't enter any values (text string) in these fields, it seems the default text input by the system is "Flag confirm".


You need to use the Name (Translated) handler provided by i18nviews.


How to automate the replacement of special characters in URLs?

Have a look at the Transliteration module. Here is a quote from its project page:

  ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydoamin/poslednie-novosti-v-Ukraine-i-mire.

However, to actually make this work, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". Attention: this does not "fix" already created aliases (those need to be deleted and recreated).


How to add region just above title for omega theme?

In case you're using Omega 4 you need to include your regions in two files, instead of only the .info file.

You also need to include them in your layout.inc file, which is located in the theme's folder at:

  layouts/yourlayout/yourlayout.layout.inc

and then print them at the desired spot in your HTML markup in your layout.tpl.php file, which is in the same folder.

Hope this helps.


Inline class annotation with /** @var or just comments?

I checked more about annotations and it doesnt makes sense to have them in places other then outside the class, as stated on d.org, so this is just plain comment for IDE's to connect what is used there.

  In addition, there is a performance bonus as it makes Drupal use less
  memory when discovering plugins. The original implementation had a
  getInfo() method on each class, similar to Drupal 7 test classes. This
  meant each class had to be loaded into memory to get its information
  and the memory was not freed until the end of the request, thus
  greatly increasing the peak memory requirement for PHP. Instead, the
  implementation used by Drupal to parse the annotation simply tokenizes
  the text of the file without including it as a PHP file, so memory use
  is minimized.


If you are using Entity reference has the option to sort. I will give you three choices.

1. Manually:

Go to the /node/nodenumber/edit and you can specify the order that you want  Manually seems to be your best choice because it is your user who decides the order

2. Programatically

If want to order by descending (Ascending is the default). The only it worked for me was to use array_reverse:

$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
$value -> field_reference_field_to_reference['und'][]['target_id'] = $node -> nid;
$value -> field_reference_field_to_reference['und']=array_reverse($value -> field_reference_field_to_reference['und']);
node_save($value);

3. Fields settigs in the entity reference

There is another option of sorting in your content type field settings:

/admin/structure/types/manage/volunteer-profile/fields/field_reference

and then you can tell it to sort by

However, to be honest the last method  number 3 has not worked for me for some reason. If you made it work. Please let me know your solution. I would love to know what am I doing wrong. :)