Drupal 7: adding an image and a link to a user page

For images, just enable the Image module and add an Image field to your users just like you already did with other fields.

For a link, assuming you want that to actually display it as a link and not just as text, I really suggest you have a look at http://drupal.org/project/link. I know you said you don't want any contrib modules but again, there is no reason to not do that. Drupal only really gets it's power from contributed modules. Upgrading minor versions is pretty much always trivial and Drupal 8 is most likely still years away and Drupal 7 will be supported until Drupal 9 is released, so you don't have to worry about that for quite some time. Using link.module will certainly be better than trying to develop your own module. link.module has already been tested on 2000 other D7 sites (and 70k D6 sites..).

The Tab question is something completely different, so I suggest you create a new question for that. For a start, you will need to implement hook_menu() and add a 'user/%user/something' menu item of type MENU_LOCAL_TASK.


Varnish problem, user logged out for a HIT page

Maybe too late, but I had exactly the same problem, I spent two days looking for what is wrong, then I read in settings.php:

  Without "Vary:Cookie", authenticated users would also be served the
  anonymous page from the cache.

So change 'ommit_vary_cookies' from TRUE to FALSE in settings.php solved the problem.

$conf['omit_vary_cookie'] = FALSE;


An entity autocomplete widget with opportunity to save its text content

There is no need to create a custom table or a second field. While editing your entity reference field, in the "Reference type" section, you could check the "Create referenced entities if they don't already exist" option. If for instance, your field is referencing taxonomy terms, a new term for the referenced vocabulaty will be created. I hope that this helps.


If you're POSTing a JSON string, it won't be available as key/value pairs in Symfony's request object.

You could parse it yourself:

$json_string = \Drupal::request()->getContent();
$decoded = \Drupal\Component\Serialization\Json::decode($json_string);
$name = $decoded['name'];


How to boost relevance of Search API solr with creation date?

To do this (Drupal 7), one needs to implement the below hook:

hook_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query)

This hook can go in the theme or module layer.

Example code could be:

/**
 * Implements hook_search_api_solr_query_alter().
 *
 * @see https://www.drupal.org/node/2009760#find-out-field-id
 * @see https://www.drupal.org/project/search_api_solr/issues/2194055
 * @see https://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results
 * @see https://www.drupal.org/forum/support/module-development-and-code-questions/2014-12-18/extending-search-api-solr-search-with
 * @see https://www.drupal.org/project/search_api_solr/issues/2392499
 * @see https://www.drupal.org/project/search_api/issues/1694698
 * @see https://books.google.com.au/books?id=othpBgAAQBAJ&pg=PA157&lpg=PA157&dq=3.16e-11+solr
 */
function mytheme_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query) {
  // Boost more recently created content. This is taken directly from an
  // apachesolr query with +1 boost (+1 for every 100).
  $fields_names = $query->getIndex()->server()->getFieldNames($query->getIndex());
  if (isset($fields_names['created'])) {
    // If using node property 'created', get solr name of it  e.g. 'dm_created'.
    $created_field_name = $fields_names['created'];
    // @codingStandardsIgnoreStart
    // Field name version.
    // $created_field_name = $fields_names['field_date'];
    // @codingStandardsIgnoreEnd
    // Ensure '$call_args['params']['bf']' exists.
    if (!isset($call_args['params']['bf'])) {
      $call_args['params']['bf'] = [];
    }
    $call_args['params']['bf'][] = "recip(ms(NOW,{$created_field_name}),3.16e-11,0.5,0.5)^100.0";
  }
}


Add CSS class to fieldset div element without extending the template

Under a fieldsets 'Advanced' settings tab, you can add custom attributes to the fieldset.


The answer lies here:

$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL'))

The code that comes after the call to $.once() will only be executed once. However, $.once() can and will be executed multiple times. That's why you are seeing your calls to the console being called multiple times. If you change this:

$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
  // Do some stuff.
});

To this:

$('#portfolioModal', context).once('bootstrap-modal-shown').each(function () {
  console.log('*** REGISTER SHOWN.BS.MODAL');
  // Do some stuff.
});

You will see that your call to the console is only shown a single time.
Note that you also will not use $.on() here, as the Drupal behaviors API replaces any necessity of it. Each time Drupal.behaviors are executed, a context argument is passed to it. This will be either the full DOM, or any HTML being newly inserted into the DOM. So where in normal jQuery you might do this:

$(".some_selector").on(someCallbackFunction);

In Drupal, you would do this:

Drupal.behaviors.someArbitraryKey = {
  attach: function(context) {
    $(context).find(".some_selector").once("some-arbitrary-key").each(someCallbackFunction);
  }
};

This is the Drupal way of achieving the same goals as using $.on() in normal jQuery, while tying in with the Drupal APIs.

---- Edit ----

Original answer below, which turned out to not answer the question. Left for posterity's sake, and because it actually adds on well to the end of the above answer.

Drupal behaviors are called on page load. It is also called upon AJAX load. You need to wrap code in $.once() if it should only be executed a single time:

function someElementListener(context) {
  // Call to $.once():
  $(context).find(".some_selector").once("arbitrary-key").each(function () {
    // Code here will only be executed a single time on
    // each .some_selector element found
    $(this).click(function() {alert("clicked");});
  });
}

Drupal.behaviors.someModule = {
  attach: function (context) {
    someElementListener(context);
  }
};

If you wrap your code in $.once(), your console calls will only be logged a single time.


Check out this documentation: https://www.drupal.org/docs/7/creating-custom-modules/creating-drupal-7-hooks

For your case, the simplest may work

So lets say your hook you want to be hook_pdf_generated()

module_invoke_all('pdf_generated');

in your custom module, have a function YOURMODULE_pdf_generated()

If you wanted to be able to alter the $pdf variable, use a _alter() hook

So in that code you posted, add:

drupal_alter('pdf_generated', $pdf);

and in your custom module you'd have YOURMODULE_pdf_generated_alter(&$pdf)


I guess you have a solution available in the following bug report filed at http://drupal.org/node/1904006

You have two possible options available.
1. There is a patch available in that post, use that.
2. Download development release, which already has that path applied in it.


Show commenter IP address to admins (Drupal 7 / AdaptiveTheme)

It looks like you're adding your code within the adaptivetheme_preprocess_node function but you should be working within the adaptivetheme_preprocess_comment function (a little further down the page).

Specifically the following could be modified with your code above as a starting point (starting at line 835 in preprocess.inc for AdaptiveTheme 3.2):

  $vars['submitted'] = t('Submitted by !username on !datetime',
array(
  '!username' => $vars['author'],
  '!datetime' => '<time datetime="' . $vars['datetime'] . '" pubdate="pubdate">' . $vars['created'] . '</time>',
)
);


Entity Query using conditions that ignore special characters

Drupal does not supply a solution to your problem out of the box.
However you can create a list of all the permutations and create a condition for each of them.

Code snippet

$searchterm = 'test-1_2 3';

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED);

// permutation generator function.
$permutations = function($source_term) {
  $result = [$source_term];
  $unprocessed_terms = [$source_term];
  $regex = '/[\W_]/'; // Selects all the non-alphanumeric characters and _

  while (!empty($unprocessed_terms)) {
    $unprocessed_term = array_pop($unprocessed_terms);
    $matches = [[]];

    // By using PREG_OFFSET_CAPTURE we get the position of the match.
    preg_match_all($regex, $unprocessed_term, $matches, PREG_OFFSET_CAPTURE);
    foreach($matches[0] as list($match, $pos)) {
      $result[] = $unprocessed_terms[] = substr_replace($unprocessed_term, '', $pos, 1);
    }
  }

  // the above algorithm will create duplicates.
  return array_unique($result);
};

// Create an OR condition group that contains a
// condition for each permutation term.
$query->condition($or = $query->orConditionGroup());
foreach ($permutations($searchterm) as $term) {
  $or->condition('body', $term, 'CONTAINS');
}

$nids = $query->execute();


Which statistics like page visitors or most visited pages are tracked automatically, or do I need extra modules for that?

Everything in Drupal is provided by a module (core, contrib or custom), so one way or another you'll need to enable one to get extra functionality.

Drupal core comes with a Statistics module, you can enable that and see if it has what you want easily. If not, just search around for the different statistics modules there are out there, and install and try them.

If you stick to stable releases, you shouldn't have any trouble removing a module that you find doesn't do what you need, so there's no downside to trying.


why do my cache entries all double up with a #cache_redirect item?

It's still a bit unclear what you are asking, but to be more precise about my comment. The bubbled up cache contexts depend initially on the content of the render array, but this content can be dependend on other things. For example a rendered link can depend on a configured language negiotiator which provides a path processors rendering links differently dependend on the language and so bubbles up the cache context you have identified.


How to handle the 'Save and edit' form action?

The way I do it is to add extra parameters, like:

$form['actions']['save']['#machine_name'] = 'save';
$form['actions']['save_edit']['#machine_name'] = 'save_edit';

Button position in $form found here.

Then in submit handler I can use:

switch($form_state['triggering_element']['#machine_name']) {
  case 'save_edit':
    // some code
  case 'save':
  default:
    // come other code
}

Alternative method:

Note that both buttons have submit handlers attached directly to them:

$form['actions']['save'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save'),
);
$form['actions']['save_edit'] = array(
  '#type' => 'submit',
  '#validate' => array('apachesolr_environment_edit_validate'),
  '#submit' => array('apachesolr_environment_edit_submit'),
  '#value' => t('Save and edit'),
);

So, in your own code you can append submit functions separately. Assuming you wish to keep original ones executed, in your form alter use something like:

$form['actions']['save']['#submit'][] = 'x_environment_edit_save_submit';
$form['actions']['save_edit']['#submit'][] = 'x_environment_edit_save_edit_submit';

and of course create these functions.


The template file you're looking for is field.tpl.php. The naming suggestions for this template are explained fairly well here and here - although they aren't in the documentation and I haven't tested them. So the steps you need to take are:

Copy the .tpl.php file from modules/field/theme
Rename it so it
targets only the field type you wan't ('list_text' I think in your
case).
Change the divs into ul/ol and li as required.


I want to get the real password(not md5 encryption) when edit the account profile via user profile form and save. how to do that?

You cannot decrypt the password due to security reasons. Drupal 7 uses SHA512 by default with a salt. It will perform multiple hashes on the password. It's highly impossible to decrypt password.

See the better explanation provided here.

To reset the password see the solution provided here.


How do you add a prefix to an existing drupal database for single site use?

If you have phpMyAdmin the simplest way is to:

go to the "Structure" tab (where there is the list of tables).
select all the tables (with the "Check All" checkbox at the end of the list)
in the dropdown list close to the "Check All" select the action "Add table prefix" (or "Replace table prefix" if that is the case)
insert the prefix, press the button and let it do all the work.

After that remember to specify the prefix in the site\default\settings.php

array (
  'database' => 'sample_drupal_db',
  'username' => 'sample_drupal_usr',
  'password' => 'sample_drupal_pwd',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => 'prefix_', // <<== prefix here
),


Drupal commerce: Save into a customer profile field

ok i got it:

$annotations = $form_state['values']['annotations'];
global $user;

// load oder
$order = commerce_cart_order_load($user->uid);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

// get profile id
$profile_id = $order_wrapper->commerce_customer_billing->profile_id->value();

// load customer profile
$profile = commerce_customer_profile_load($profile_id);
if ($profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile)) {

       // set the value of the field and save the profile
       $profile_wrapper->field_shop_annotations->set($annotations);
       $profile_wrapper->save();

}


I researched this for a while, then I found a sample implementation in modules/views/tests/modules/views_test_data/src/Form/ViewsTestDataElementEmbedForm.php:

$form['view'] = [
  '#type' => 'view',
  '#name' => 'test_view_embed',
  '#display_id' => 'embed_1',
  '#arguments' => [25],
  '#embed' => TRUE,
];

In that file it is used in FormBase::buildForm, but it works nicely also in hook_form_FORM_ID_alter(); I reported another example in this comment to a similar post.


In your submit handler of your form, you should be able to retrieve the fid of the uploaded file / image. By using this fid, you can load the file and work with that object.

function YOUR_MODULE_FORM_NAME_submit($form, &$form_state)
{
    $fid = $form_state['values']['Background_image'];

    if ($fid !== 0) {
        // Retrieve image URL
        $image_url = YOUR_MODULE_get_file_url(file_load($fid));
    }
}

function YOUR_MODULE_get_file_url($file)
{
    if (!$file) {
        // File not found
        return false;
    }

    // Return URL from a give file URI
    return file_create_url($file->uri);
}


How to edit the id of a form element of a content type?

I figured it out by digging through the kint() statement. Turns out the id is buried deeper in the $form array. Here is what worked for me:

function hook_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_element_name']['widget']['0']['value']['#id'] = 'element_name_id';
}


You should pass the context in and use the once() function to make sure your events are only bound once, and in the right context. Something like:

(function($, Drupal) {
  Drupal.behaviors.ukgproducts = {
    attach: function(context, settings) {
      $('h2', context).once('myaccordian').click(function(e) {
        e.preventDefault();
        $(this).closest('.binder').find('.product-list').toggle('slow');
      });
    }
  };
})(jQuery, Drupal);


Custom module hook entity presave not 'firing'

The hook_ part is for example only; it should be replaced completely by your module's name:

function update_description_entity_presave($entity, $type) {


Change title of a node programmatically before displaying it

To modify the node title while displaying, I had to do changes in the theme.

Implement the hook (don't remember if it was already there) in template.php file:

function themeName_process_page(&$variables)

And then had to add this part of custom code at the end of the function:

// Raj: To Append the scientific name and it's desciber to the title
$nodesArray = $variables['page']['content']['system_main']['nodes'];
if (!empty($nodesArray))
{
    foreach ($nodesArray as $speciesNode)
    {
        if (!empty($speciesNode['field_common_names']))
        {
            $scientificNameArray = $speciesNode['field_scientific_name_1'];
            if (!empty($scientificNameArray))
            {
                $theScientificName = '' . $scientificNameArray[0]['#item']['first'] . '';
                $theDesciber = '' . $scientificNameArray[0]['#item']['second'] . '';
                $prominentName = $variables['title'];
                $sciFiNameAndDescriber = $theScientificName . ' ' . $theDesciber;
                $variables['title'] = $prominentName. ' ' . ' ( ' . $sciFiNameAndDescriber . ' ) ';
                $variables['title'] = '
'.$variables['title'].'
';
                break;
            }
        }
    }
    unset ($speciesNode);
}

Please see that in the above code, most of it belongs to the context of my website where I had to append the scientific name of the species to the title of the species inside brackets. The point here is, you need to modify the $variables['title'] inside process_page() hook.

Also most important, to see the changes in affect, clear the cache. I had a rough time thinking that the changes are not working, only very late did I realize that I was doing everything right but did not clear cache. It's a learning experience for me.


Fatal Error: Call to undefined function in a drush backup module

The function variable_get doesn't exist in Drupal 8. I suggest just removing ~/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc or moving ~/.drush/backups to ~/.drushbackups if you can control this.

Your problem is probably caused by the fact that you are putting the backup inside the ~/.drush directory and Drush is parsing code/files in that directory.


This is the best solution for you ==> https://www.drupal.org/node/1343708

EFQ an beautifull tools for manipulate the entities in drupal.

Do not hesitate if you need precision but this doc is verry good.

In the Entity Reference case

The column name for an entity reference field is target_id, so your code should be:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node_type', '=')
  ->fieldCondition('field_reference_name', 'target_id', $id, '=');

$entities = $query->execute();

For follow the relation of your entities you need to reference the A into B or B into A with a reference field. When you use EFQ to search the relation in node A with B you need to use fieldCondition in this reference field in my example is field_reference_name. If you list the content B (ids) into an array and you user this

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'a', '=')

$entities_a = $query->execute();

For search the relation A to B into A you need to use this :

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'b', '=')
  ->fieldCondition('field_reference', 'target_id', $entities_a, 'IN');

$entities_b_refered_into_a = $query->execute();

Good chance.


If you have a look at the code for the original block.tpl.php file, $content doesn't actually get run through render(), as it's already been rendered to a string.

If you want to alter the block content while it's still in a structured array you should use a hook_block_view_alter() implementation in a custom module. This is the example from the docs page:

function hook_block_view_alter(&$data, $block) {
  // Remove the contextual links on all blocks that provide them.
  if (is_array($data['content']) && isset($data['content']['#contextual_links'])) {
    unset($data['content']['#contextual_links']);
  }
  // Add a theme wrapper function defined by the current module to all blocks
  // provided by the "somemodule" module.
  if (is_array($data['content']) && $block->module == 'somemodule') {
    $data['content']['#theme_wrappers'][] = 'mymodule_special_block';
  }
}

How successful you'll be using this method depends on how well the modules that provide the blocks respect render arrays. If an implementation of hook_block() by a particular module flattens the block content to a string before it is made alterable, then you'll have to make the changes somewhere else in the process (probably using a theme preprocess/override).


Retrieve select option value in webform-mail.tpl.php (7.x-4.x-dev)

For anyone else that runs across this:

<?php
print $node->title;
?>

<?php print ($email['html'] ? '
' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '
' : ''); ?>

<?php
foreach ($node->webform['components'] as $key => $component) {
   if (isset($submission->data[$key][0])) {
     $key_converted = ucwords(str_replace('_',' ', $node->webform['components'][$key]['form_key']));
     $submittedvalue = $submission->data[$key][0];

     if (isset($submittedvalue)) {
       print '
'. $key_converted .'	';
       if ($node->webform['components'][$key]['type'] != "select") {
           print $submittedvalue;
       }
       else {
        $selectlistitems = explode("|", $node->webform['components'][$key]['extra']['items']);
        if (is_numeric($submittedvalue)) {
                print $selectlistitems[$submittedvalue];
        }
        else {
                 print $submittedvalue;
        }
       }
       print '
';
       }
  }
}
?>


Is it possible to use a different theme for just a section on the page?

Thanks Clive and Cromian for your input. Guess its not possible to actually use 2 different themes on the same page.

The simplest solution I found is to use one theme, then add 2nd ones css using drupal_add_css function. Then hope 2 CSS don't interfere too much and it's good enough without HTML part of the theme.


How do I mass flag a node on behalf of users (possibly with VBO)?

What you could do to get this to work, is to use the integration of VBO with the Rules module, as further detailed below.

Step 1: Create a Rules Component

Create a (rather basic) Rules component to flag a node by a user. Here is such component in Rules Export format:

{ "rules_flag_node_flagged_by_a_user" : {
    "LABEL" : "Flag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "your_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node flagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

This Rules Component uses a flag with machine name your_flag. After you edit that machine name to fit the name of your flag, you should be able to import this rule in your own site (using the Rules UI, which needs to be enabled).

BTW: the Rules Action to display a message is just to see it at work while QA-testing this rule, feel free to remove that if you want.

Step 2: Let VBO do the work

This step is pretty easy ... Just use your VBO view. The clue to what you want VBO to do as an operation is ... Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 records at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Happy VBO-ing while Rules-ing!

PS: I'm assuming this question is about D7.


You could use Media (7.x-2.x branch) and some modules for managing responsive images (I use Picture).

You should enable this modules and:

add the "media" button for Wysiwyg (I've tried both Tinymce and Ckeditor)
configure media to use the "Picture" module for a custom display mode for files

So, when you add a media to a textarea you can choose the display mode for the file.
For documentation about Picture please read this.

Obviously you could use also other modules, but the logic is the same: associates a responsive style for a display mode for images.


Although it doesn't look too complicated, I'd normally use the following modules to easily add and display nodes on a map:

Leaflet;
Leaflet Views;
Leaflet More Maps;
Views;
Geofield;
Geocoder;
Geocoder Autocomplete;
GeoPHP;
Entity;
Entity Reference;
Chosen;

I don't work with Taxonomy terms. Instead, I create a node type named, let's say "Category" and add the right categories as nodes instead of terms in a vocabulary. It is easier like this and offers me more flexibility in the future.

The Category content type is based on a form that only includes Title as field. I'm adding them manually, which is not as simple as adding tags (terms) with the autocomplete options. As an alternative, I think you could use Inline Entity Form to add Categories during node add form. Not sure though.

When adding nodes, you need:

an entity reference field pointing to the Category (using Chosen could help, if you don't have 10k categories);
a textfield using Geocoder text field with autocomplete;
a Geofield using Geocode from another field.

Now, when adding nodes, you get the Google Geocoder autocomplete option and the geofield will auto-fill with the right coordinates.

Then, I'm using Views to display items on the map with Leaflet. Here you can choose displaying only first 5 items, based on whatever filter criteria and order options you'd like. The view is a block and has an Entity Reference relationship poiting from the node to the category node + a contextual filter NID type my-node-type, with content ID from URL argument that uses this relationship.

Block will show up only on Category node-type pages in the content area.

Doesn't look very simple but there are a few tutorials on how to achieve that with leaflet, geofield and entities on Youtube. There are other ways to solve your problem, like using EVA with DS, adding blocks as fields in your DS display.


How to combine Views, Rules and EVA to record submission?

I am not familiar with EVA but it looks pretty good.

I have a similar use case with entityform.

You can embed entityforms on nodes using the entityreference field.

Now entityform comes with a view already set up that displays a user's latest entityforms.

Here is a screencap of the view configuration - it displays a user's latest form submission(s).

You can then add a 'block' version of this view (the 'add' button in the top left corner.)

You can then configure your new block to only show up on the logged-in-user's /user page.

Hope that helps. Incidentally let me know if you are trying to get the form-fields to be pre-populated with user details.

Based on your comments:


How to get rid of error messages after second try where file was uploaded successfully?

There is a working patch for this issue here. (File validation error message not removed after subsequent upload of valid file - 1792032)

That patch issue is waiting on someone to write tests before it can be RTBCd. It shouldn't be hard to adapt that patch to Drupal 7 in the mean time. Just make sure you document the fact that you have patched/modified core somewhere for future developers.


Can I use another entity in the route to provide an entity to an entity form?

You can use a controller with the user as only route parameter. There you can put the code to retrieve the entity that matches the user and build the entity form:

public function myEntityForm(UserInterface $user) {

  // get $my_entity that matches $user

  $form = $this->entityFormBuilder()->getForm($my_entity);

  return $form;
}


Show 'submitted by' date in a language different from English

Month names are not added automatically.

An elegant way to do this is described here:

https://drupal.org/comment/8251325#comment-8251325

function monthname_install() {
  $months = array(
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  );

  $options['context'] = 'Long month name';

  foreach($months as $m) {
    t($m, array(), $options);
  }

  drupal_set_message(t('Month names have been made available for translation. The rest is up to the translation team :-)'));
}


Multisite - Commerce reference between sites

So I have discovered that I will need to create a Rule using the module Rules URL Argument that will take the URL /add-to-cart/[SKU] and add this to cart.

I can create a field on the main site for the SKU and this then outputs the link to the LMS website.

The source is here:
https://www.youtube.com/watch?v=6Rn7FLFytTU


Ajax pager won't work after other ajax event

Append the following line in the 'success' function

Drupal.attachBehaviors('#container');


How to set pragmatically Minimum order subtotal limit in Ubercart Drupal?

If you would like to validate minimum subtotal directly in the cart, you could use hook_form_alter.

function mymodule_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'uc_cart_view_form':
      //add own validate function
      $form['#validate'] = array('mymodule_subtotal_validate');
    break;
  }
}

Then define the content of the validation function:

function mymodule_subtotal_validate($form, &$form_state){
  //validate only if we are going to submit the cart form
  //there are others possibilites, when the validate handler is called,
  //such as quantity change, etc..)
  if(isset($_POST['op']) && $_POST['op'] == t('Checkout')){
    //access cart items and their quantity
    $sum = 0;
    foreach($form_state['values']['items'] as $key => $item){
      $product = node_load($item['nid']);
      $qty = $item['qty'];
      $sum += $product->price * $qty;
    }

    if($sum < YOUR_SUM){
      form_set_error(null, 'Your items subtotal is less than minimal subtotal.');
    }
  }
}


Unless you've hacked D6, 'inline' only works with drupal_add_js(), not drupal_add_css().  So, to do what you want, you need to put that line of css in a file and include that file instead.


How do I pass a variable via drupal_goto()?

Assume your url is like in this example:

http://example.com/somepage?param1=val1&param2=val2

In that case you can take values of param1 and param2 like so:

$param1 = $_GET['param1'];
$param2 = $_GET['param2'];

You may use this parameter for drupal_goto as

drupal_goto("path_here", array("param1" => $param1, "param2" => $param2));

For Drupal 7:

As YPCrumble says you need to use this code:

drupal_goto("path_here", array("query" => array("param1" => $param1, "param2" => $param2)));

For more details, refer to the API Documentation.


Can Profile2 present fields on registration?

I think there is a checkbox in the profile settings if it should be displayed in the user registration form. At Structure > Profile types > edit.


The file ID is the property target_id of the file field:

$fid = $entity->get('field_file')->target_id;


How to do System Tests / Functional Tests with an existing database

I have once answered this exact same question for Drupal 7. Though some things have changed, the concept remains the same; extend the test class.

The normal setup of a BrowserTest would look something like this:

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    // Create an article content type that we will use for testing.
    $type = $this->container->get('entity_type.manager')->getStorage('node_type')
      ->create([
        'type' => 'article',
        'name' => 'Article',
      ]);
    $type->save();
    $this->container->get('router.builder')->rebuild();
  }

All you need to is to remove the database definitions from parent::setUp();

So copy setUp() from core/tests/Drupal/Tests/BrowserTestBase.php and remove the database definitions. That should make the test run on the current database.

Though this is very simplistic and you might run into more problems along the way. All is in the BrowserTestBase class. Make sure to read my other answer, make sure to implement the teardown properly. And most of all, make proper backups!


drupal overlay text when you hover over the image views

This is only in part a Drupal question. The part that interests you most is the CSS styling.

As a tutorial, this could take several hours to explain, using the classes, wrappers, fields and so forth. I will jump over the styling, but I hope this will help as well.

As for the view itself, managed by Drupal, it is a little tricky. You need 2 containers in a wrapper. The first container should have the link set on the image and the second container should have the rest of the text and buttons.

Create a page or a block view listing all your nodes you need to include, printing fields.

Add the field image and set it to link to the node itself.

Add the text fields you need, one after the other, in the right order (title on top, text in the middle, button - linked to content - at the end and so forth).

Here comes the Drupal tricky part. Set everything as "exclude from display".

Now, as a last field, add a Global Text Area and print the 2 containers. Use tokens generated by Drupal and include them inside the containers.

For the first container, write down the wrapper code including the link over the image as a token generated by field no. 1.
For the second container, write the code for the wrapper and include inside every token for the hover visible content, in the proper order.

Then you need the right CSS, using position absolute, setting the view wrapper as relative and the second container as absolute.

Good luck.


Why are hook_form_alter updates being reverted?

The function seven_form_article_node_form_alterwas correctly named but not placed in the correct file in the correct folder.

The function seven_form_article_node_form_alter has to go in template.php in a (sub)theme of the administration theme seven - of course - and not in the  template.php of my "front-end" theme.

The fact that I had a function in there with a prefix other than my from-end theme's should have signalled my mistake.

What mislead me was a quirk of Drupal cache clear. It happens that  clearing the Drupal cache actually (and incorrectly) caused my form alterations to be displayed as my function must have been the last one in the chain to have taken effect. It was only after a subsequent page build / refresh that the form alter's effects (correctly) disappeared.  So this is a quirk of Drupal cache clear that needs to be taken account of in this edge case.

Consequently I have created an administration sub theme into whose template.php file the function now sits (Does it count as one line of code or two? ;-). All is now working as it should.


Views 2 - How to show exposed filters when results list is empty?

Ok. The ominous non-sound of tumbleweed lol

Well, after a bit of faffing and a >slap forehead< "D'Oh" moment I sorted it.

I added some text in the "Empty text" setting (under "Basic Settings") and the exposed filters now show when there is no result.


How to hide an empty block with no results

try restricting the block's display using "Pages on which this PHP code returns TRUE (experts only)"  and checking for the final re-written value there.


How to create unique banner for each node and views page?

I'd suggest to use core's Custom content blocks to create blocks (similar to your banner paragraph for nodes). Then you've got two options:

You can either use Block Layout to place the blocks, but limit visibility of the block to certain pages/URLs. Pro: You can directly place the block in any region. Con: It will clutter up your Block layout page if you've got a lot of views.

Or you can go to Views UI and place the block in the header of the view (middle column, below Page settings). Pro: Block and View are tied together in the same part of the Admin UI, no clutter in Block Layout. Con:The block will not be placed in your banner region


'meta' loosely means 'about', like the discussions on the meta site here. They are about the site, not drupal. Meta Tags are about the page, placing it in context. The [meta] issues are not about functionality, but rather about policy, code-cleanup, documentation, standards etc., rather than regular (functional) issues which are about achieving a result through code.


How do I get the user ID for the currently logged-in user?

$user = \Drupal::currentUser();

See the Drupal class. There are a lot of helper methods; most of them are shortcuts for services, so you don't have to call \Drupal::service() directly.

Note that the current user is not the user entity, it is just user proxy. You can get some basic information from it but fields or other entity-specific logic is not present. To access the user entity you have to load it manually:

$user = User::load(\Drupal::currentUser()->id());

Unfortunately there is no direct method like \Drupal::currentUser()->getEntity() :(


How do you make Varnish cache update when Drupal content changes?

There are many ways to achieve this. A very common way is by using the Expire module (https://www.drupal.org/project/expire).

It can easily be configure to clear specific pages, or sets of pages from varnish when they are changed. It has been well documented and is up to date, a great module and does exactly what you require.


hook_form_alter to limit user select list to those referenced in a node

I finally managed to get it working:

<?php

function my_module_form_alter(&$form, $form_state, $form_id) {
 if ($form_id == 'project_event_node_form') {
  $node = $form_state['node'];
   if (!isset($node->nid) || isset($node->is_new)) {
    /** This is a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
   }
   else {
    /** This is not a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
    /** horrible hack, but I can't get the nid to behave as an integer no matter what */
    $id_project = substr($id_project, 1, -1);
    /** no need to change the referenced project, hiding the field  */
    $form['field_projet'] = array('#type' => 'hidden');
   }
   /** common code */
   $project = node_load($id_project);
   $user_ref = array();
   foreach(field_get_items('node', $project, 'field_users') as $u){
   $usr_obj=user_load($u['target_id']);
   /** this makes the checkbox form render in a useable way */
   $user_ref[$usr_obj->uid]=$usr_obj->name;
   }
  $form['field_attendees']['und']['#options'] = $user_ref;
 }
}

Any suggestions or improvements are welcome, particularly with the dirty hack whith the nid behaving as a string in the node edit.

Although this is a rather simple module it is my first one, so I'd like to thank the patience and support of all those who helped with this, particularly Peyman and Josh at robustLINKS, bnjmnm and Michael.


How to change the label of exposed grouped Filter field in Views?

Normally you can remove field machine name from the configuration itself as shown below, but seems like those portion is hidden from your screenshot. Please check those portion, also check this troubleshoot Can't set the label for an exposed grouped filter.

If still no help you can use hook_form_alter(&$form, &$form_state, $form_id) to change the label


give value to form element after select event - value should be catched with JQuery

Use like this to get form select list element in jQuery.

$("#elementId :selected").text() //the text content of the selected option(country name)
$("#elementId").val() //the value of the selected option(country code)


Custom module implementation for menu items as JSON

You'll want to use this kind of implementation based on the Alias Manager service.

<?php
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
?>

Details and a further explanation can be found on D.O https://www.drupal.org/node/1853148

If you'd be willing, I'd also like to see the full code for that resource.


Does poll not allow multiple anonymous votes?

The problem is that the poll module only allows one vote per anonymous IP address.  In the case of your hosting provider I suspect that they are using some sort of proxy that sends all requests to Drupal from the same IP address.

The Poll Enhancements Module modifies this behavior to allow multiple anonymous votes from the same IP address.  The documentation on this module's description page also suggests the Poll Improved Module may solve this as well, but it does not have a production release at this time.


Getting error for drush site-install :Unable to find a matching SQL Class

Make sure that you execute drush from the web folder.


Redirect with POST and parameters in a controller

You can't redirect with Post properties. You can only do a request, which you've done. The $response you've created in the controller will contain the results of your HTTP request to the remote service. You'll have to retrieve the the relevant data from that object, and do something with it. You are currently returning that from your function. $response is a Psr\Http\Message\ResponseInterface object. If you just return this, your controller will not know what to do with it.


Unable to Retrieve Custom Taxonomy Fields Using PHP

Using print_r($term) (as per Mohammad's suggest) I could see the correct expression was actually another one.

$term->field_image['und'][0]['uri']


This:

function my_custom_submit()

Should be this:

function my_custom_submit($form, &$form_state)

Right now you are setting redirect on a variable that doesn't exist.


Body and Subject fields in Mail Function

The last parameter you are passing to drupal_mail() is FALSE. That parameter is telling the function if sending the mail. The documentation describes the parameter as follows:

  $send: If TRUE, drupal_mail() will call drupal_mail_system()->mail() to deliver the message, and store the result in $message['result']. Modules implementing hook_mail_alter() may cancel sending by setting $message['send'] to FALSE.

As its default value is TRUE, just leave out that parameter, and the mail will be send, if other modules don't set $message['send'] to FALSE.


Make the suggestions of an autocomplete exposed form clickable

Install Better Exposed Filters module , got to your views, in Advanced section In Exposed form style: select better exposed .

The Better Exposed Filters module replaces the Views' default single-
or multi-select boxes with radio buttons or checkboxes, respectively.
Description fields and Select All/None links can be added to exposed
filters to make for a better user experience. Views Filters is a
powerful tool to refine the results returned by a given view. When you
expose a filter, you allow the user to interact with the view making
it easy to build a customized, advanced search. For example, exposing
the node type field as a filter lets your site visitor limit their
search queries to just blog entries. Better Exposed Filters gives you
greater control over the rendering of exposed filters.
Why use this module? Because it provides a better user experience than
the default option. Try telling a client that they should click on an
option, then scroll to the next option and ctrl+click on it. Don't
just click 'cause you'll lose your first selection. Oh, and ctrl+click
again to unselect an option... Yeah, not user friendly.

additionally,

What else can you do with BEF?.
The BEF handbook page provides some basic recipes making exposed
filters a much better user experience.
Add help text for each exposed filter Tame long lists with scrollable
checkbox/radio button lists or select all/none links Provide instant
feedback by updating the View using AJAX whenever an exposed filter is
changed Use the jQuery Slider widget for greater-than, less-than or
in-between types of filters If you've got any ideas not covered on the
handbook page, add a feature request to the issue queue. You can also
rate this module on DrupalModules.


Canonical link for multidomain multisite

It is better to use Metatag module which has ability to override meta tags on each entity objects. Other tokens must be used.


This should really be pretty simple if you have created the Views properly.

You need to make the views select only the content that the user provided through an argument, fx uid = 5 would should show content user with uid 5 created.

Then it's just a matter of creating a panel page that has the uid in the url, fx user/[uid]/profile and pass the uid to the views when you insert them on the page, which then will display the correct content.


How to add javascript to theme_preprocess_user_login

A preferred solution I would use for adding/editing forms would be to use a module hook.

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

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')
  );
}


Use the following commands:

sudo rm /usr/bin/drush
sudo pear install drush/drush
sudo drush --version


Does the language filter show all languages by default?

"Switch Language" block created by "Locale" module which is the most fundamental  language handler in drupal. Its purpose it to switch user interface between languages. If translation exists for certain node it will used if not, only interface changes.

"Content Translation" module handles relations and links between translated nodes. The link you need is something like the language link/s that, by default, displayed inside node's links area.

I am not aware of existing  module that display these node links in block.
But you can display this list using code.

First, get can get an array needed links using translation_link() that supplied by "Content Translation" module

$node_translations = translation_link('node', $node_object);

Than, create HTML list out of that array, using theme_links(),

print theme('links', $node_translations, $attributes = array('class' => 'links langs more-classes-if-you-wish'));

To display this in block you can create new custom block with php input format or create template file for that block and make your code live there.
To get node object in block you can use

  if (arg(0) == 'node' && is_numeric(arg(1))) {
   $node_object = node_load(arg(1));
  }


It turned out you can do this with Views. You list all content with some category tags, then you sort them with grouping tag and remove not needed headers (duplicates).


How can I let a user select my Drupal Commerce product to either be shipped or downloaded?

Required steps

Step 1

Create a taxonomy, let's say it's called "Delivery methods", with terms "Shipable" and "Download".

Step 2

For each product type, add a field like "Delivery method", which is a field "term reference" (and refer to the "Delivery methods" taxonomy).

Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).

Step 3

Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for the Delivery methods taxonomy.

Video tutorials

For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13).

Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.

Commerce Backoffice

Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce.


Pathauto taxonomy terms in content paths

You are looking under the wrong section. You want to look at 'node paths' in the path auto settings. Under that section you need to put '/[term-raw]/[title-raw]' for content of type 'Page'.

Install token module as well


Migration Source YML File import date string into date and time field of content type

The migrate plugin that handles this is FormatDate.  It looks like you are missing the input and output date formats.  For date-only, you would do something like

process:
  field_date:
    plugin: format_date
    from_format: 'm/d/Y'
    to_format: 'Y-m-d'
    source: event_date

and for date+time, it would look something like

process:
  field_datetime:
    plugin: format_date
    from_format: 'm/d/Y H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    source: event_time

When migrating into the core datetime/daterange fields, the to_format needs to be those strings (these were written to be generic, not just for those field types).  The from_format gets adjusted to your input source.  If you look at the references below, there is also a way to specify time zone.

That plugin is unit tested, so core doesn't provide any YAML example, but you may be able to glean samples from FormatDateTest.

References:

Added FormatDate migrate process plugin
https://www.drupal.org/project/drupal/issues/2820490
FormatDate migration process plugin now supports specifying of source and destination timezones
https://www.drupal.org/project/drupal/issues/2883892


Aplying image styles to images return 404 for images

I don't know what caused the issue but at the end I solved It following this steps:

http://www.aldibier.com/blog/articulo/drupal-7-cuando-no-aparecen-las-imagenes-generadas-por-image-style

1- Adding to the Nginx():

location @rewrite {
  # Some modules enforce no slash (/) at the end of the URL
  # Else this rewrite block wouldn't be needed (GlobalRedirect)
  rewrite ^ /index.php;
}

location ~ ^/sites/.*/files/styles/ {
  try_files $uri @rewrite;
}

2- Adding to the settings.php:

$conf['image_allow_insecure_derivatives'] = TRUE;

3- Rebooting the server.

This solution may bypass the error since, for what I know, nothing in the server configuration was changed when the problem started so this shouldn't be the root of the problem.


This isn't really a Drupal or Drush question, but a Bash/shell question: How to run a script in the current directory?

The script must be executable: chmod u+x drush
The script must be in the (executable) path. Since it's not recommended to have the current directory in the path (for very good security reasons), the solutions is to call Drush as ./drush instead of just drush.


How to display menu block but deny adding a new instance?

So at the end my solution in regard to blocks was to create route access check for the block.admin_add route to prevent attaching unwanted blocks, override the controller for the block.admin_library route by extending the original one and removing unwanted blocks from the list, implementing hook_block_access to prevent certain operations on certain blocks and hook_block_filter to remove some blocks completely.


What may cause my fatal error Call to undefined function _menu_target_edit_form_extra_elements_submit()?

Hey I just had this issue this morning too. In my case it was being caused by the module menu_target I disabled it and the issue disappeared.


How to get the type of Paragraphs entity in the parent node field?

I think you can wrap each paragraphs field in any html wrapper of your choice, but you have to edit each field by modifying the appropriate field.html.twig  template file.

In the field template suggested name, for example:

FILE NAME SUGGESTIONS:
   * field--paragraph--field-text-half--text-svg.html.twig
   x field--paragraph--field-text-half.html.twig
   * field--paragraph--text-svg.html.twig
   * field--field-text-half.html.twig
   * field--text-long.html.twig
   * field.html.twig

You will then use the template suggested name to edit the html wrapper of your choice.

Like this :

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}
 --> change div to preferred  html
    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Hope this helps :)


Create renderable nested tree array like Menu Tree or Taxonomy Tree

What you are trying to solve is a recursive problem.... See below code which solves problem..

function listArrayRecursive($array_name, $ident = 0){
  if (is_array($array_name)){
    foreach ($array_name as $k => $v){
      if (is_array($v)){
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . "
";
        listArrayRecursive($v, $ident + 1);
      }else{
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . $v . "
";
      }
    }
  }else{
    echo "Variable = " . $array_name;
  }
}

$ages = array(
        "ahmed" => "25",
        "mohamed" => "35",
        "group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20")));

listArrayRecursive($ages);

Output will be


Integrating a local php script into drupal block

Sounds like your script is expecting to run index.php from the website root directory which is already used by Drupal.  You will need to re-write the script to use a different root url or set the root url for that script.


How do I set a picture as a background image/wallpaper?

Try out Live CSS module

  Edit CSS live within the page, and save the changes back to any css
  file if you have write access.


I've made a couple of TCPDF implementations myself in Drupal. As Clive suggested, you shouldn't use URIs in TCPDF's output() method, instead you'll want to provide absolute filepaths.

This code has always worked for me:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$path = drupal_realpath('public://folder/folder2/folder3');

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

EDIT: As Clive mentioned in the comment, drupal_realpath() is deprecated. Here's an alternative:

// Change the path to whatever you like, even public:// will do or you could also make use of the private file system by using private://
$uri = 'public://folder/folder2/folder3';
$stream = file_stream_wrapper_get_instance_by_uri($uri);
$path = DRUPAL_ROOT . '/' . $stream->getDirectoryPath() . '/' . file_uri_target($uri);

// Supply a filename including the .pdf extension
$filename = 'file.pdf';

// Create the full path
$full_path = $path . '/' . $filename;

// Output PDF
$pdf->Output($full_path, 'F');

Just make sure you're always providing an absolute path for TCPDF.


Drupal 8 + Twig background-color -field select

One way to do this is provide a field template for that field that just prints the value and no markup:

field--your-field-name.html.twig:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Then in the main template, wherever you want to output that field value, you would have:

Example

The result should be just the field value, with no whitespace, so "black" or "grey".


If you like you can use the CMS Updater module to enable automatic Drupal core updates. Find the module on drupal.org here: https://www.drupal.org/project/cms_updater

If you need more information about the service behind, lokk here: https://cms-updater.com

Excerpt from project page:

  CMS Updater module helps you to keep your Drupal site secure at all times.
  Right after a new Drupal core release is published, this is recognised by the CMS Updater Service, which in turn will update your Drupal system.

  There is no need for intervention on your part – just check your mailbox from time to time, read your PDF update, and see if the automated updates have been successfully completed (or not).

  The use of this module requires the purchase of a CMS Updater licence key for € 29.99 incl. VAT. This fee covers one year of updates - your subscription will not be automatically extended, although you will be reminded when your subscription is close to expiring. You can buy the licence key directly in your Drupal admin area under /admin/config/system/cms-updater. If you need a hand or more information, visit https://cms-updater.com.

Emphasis on price added for purpose of this answer.


How to select every date before now in timestamp?

You could just use strtotime() to get yesterday's date instead of using a DateTime object:

$yesterday = strtotime('-1 day');

$sql = 'SELECT * FROM {mytable} WHERE date < :timestamp';

$result = db_query($sql, array(':timestamp' => $yesterday));


How to link (a menu item) to the RSS feed?

If you're using i18n module, and after you have installed module Variable, you should enable the i18n_variable module (one of the i18n submodules that requires the Variable module, among others).

Then navigate to /admin/config/regional/i18n/variable (= the Variables tab within '
Multilingual settings'). There you'll be able to specify all sorts of variables for which you want multi language support enabled also, using an appropriate sub-tab there, such as for "Site information", "Menu settings", etc.). Within sub-tab other, there is also "RSS feed for front page" (=The RSS feed for the front page, default is rss.xml). That "other" sub-tab should be between "Menu Settings" (1st sub-tab) and "Site Information" (3rd sub-tab).

I'd be curious to hear if your issue is resolved after you enable that option (by checking the checkbox).


How to block the user after a few failed logins

Rules is what comes to mind. You can react to the user logging in I guess.


According to the jQuery blog, the function curCSS was deprecated in jQuery 1.8:

  $.curCSS: This method was simply an alias for jQuery.css() from jQuery
  1.3 onward. Although it has never been part of the documented API, some external code has been known to use it, perhaps thinking it was
  “more efficient.” Now it’s “more gone.”

but since its simply an alias its possible to patch the beauty tips plugin to fix this. There is a patch here on Drupal.org that does just this and its been committed to the dev release. Its not ideal as you have to patch the library to get this to work but its really your only strategy since the beautytips plugin hasn't been upgraded for the newer versions of jQuery.


Are there any Drupal modules that allow you to select a template to use for output or are there any modular content editing interfaces?

I think your best bet is to add an additional field to the blog post content type, which can be used in the theme layer to select the proper template. You will provide the templates in advance, which will result in an easy UI for the editor, but will not sacrifice your ability to customize and tightly control the template.

Step 1: make your new field

This new field should provide them with options for the layouts. For the purposes of this example I'll use a field called field_blog_layout that provides two options: Single Column and Staggered. Make sure you provide machine values in a format that is accepted by the theme hook system, just to make it a tad simpler for yourself in the next step. Here would be the values in your field settings:

single_column|Single Column
staggered|Staggered

Step 2: Add dynamic theme hook suggestions

Now that you have your field, add a new hook inside template.php (or a custom module, e.g. if you have a Blog Feature). My example would live inside a module file called my_feature.module:

/**
 * Implements hook_preprocess_node().
 *
 * Provides theme hook suggestions to complement the custom layout.
 */
function my_feature_preprocess_node(&$vars) {
  // Only run this code on Blog nodes.
  if ($vars['node']->type == 'blog') {
    // First, grab the value of the Layout field.
    $my_layout = field_get_items('node', $vars['node'], 'field_blog_layout');
    // Add the theme hook suggestion using the field's value
    $vars['theme_hook_suggestions'][] = 'node__blog__' . $my_layout[0]['value'];
  }
}

If you were careful about using the expected format for theme hooks within your custom field's machine values, there should be no other processing needed.

Step 3: Implement the theme hook by adding templates

With the theme hooks ready to go, you can now create templates. It's simple, just create a template using the exact format of the theme hook, except replace all underscores (_) with dashes (-):

node--blog--single-column.tpl.php
node--blog--staggered.tpl.php

For the content of these templates, just make a copy of node.tpl.php and customize it to your heart's content.

Note: you must have a file called node.tpl.php in your theme for the special templates to work. This is a known behavior of the Drupal 7 theming system.

Step 4: Clear the cache and marvel at your work

New hooks and templates both require a cache clear. Don't forget or you'll wonder why nothing is changing!


Is there a way to trigger migration imports from the admin UI?

A general migration runner in the UI is not yet implemented - the issue to add this is at https://www.drupal.org/node/2470882.


Setting node ID sequence to a particular higher value for future created records

Yes, you can set the nid to a higher value in your D8 instance, then continue to migrate D7 nodes under that.
Something like the following to set the auto_increment value.
// Set the next auto increment field value on the table
$result = db_query('ALTER TABLE {' . $connection->escapeTable($table) . '} AUTO_INCREMENT = ' . (int)$auto_increment);

e.g for node and node_revision
// Set the next auto increment field value on the node tables
$result = db_query('ALTER TABLE {node} AUTO_INCREMENT = 8000000');
$result = db_query('ALTER TABLE {node_revision} AUTO_INCREMENT = 8000000');


Calling a PHP script from Drupal retrieves different result than calling it outside Drupal

You really shouldn't use include_once, Instead you should use module_load_include.

After you've done this start putting in Debug code in your include file to make sure it's being loaded.

Also makes your your include file contains namespaces functions and no variable being used outside a function scope. To avoid any naming collisions that could happend.

Besides that, there really is not much help anyone can provide. A script will work the same way in Drupal as it would when being include in a regular php file.


How can I get the current user role in my web app?

I have just used views to get this working.

Duplicate the default people view and rename it current_user.
Add a rest export route eg. rest/users/current_user.
Add a filter for current user. (User: Current = yes)
Save all.
Retrieve the current user via http get request on example.com/rest/user/current_user?_format=hal_json

Thanks to QueenVictoria for the advice.


You can achieve it as follows:

Copy webform-confirmation.tpl.php from /webform/templates and into your theme's template folder
Rename it to webform-confirmation-{nid}.tpl.php to apply the template to a specific webform
Make sure you clear Drupal's cache after placing or renaming the template file
Add the following snippet

include_once drupal_get_path('module','webform') . '/includes/webform.submissions.inc';
$submission = webform_get_submission($node->nid, $sid);
// All the submitted values will be here, access the necessary values from this object.
// print_r($submission);

I tried this snippet, and it works. It was taken from Print submitted data on confirmation page.


How should I handle container form elements?

You should use $form_state['values'] to handle submitted user data, not $form.


The only way I can think of is as follows:

template.php

<?php

function YOURTHEME_menu_tree__YOURMENUNAME(&$variables) {
    global $cur_level;
    $cur_level++;
    return '
' . $variables['tree'] . '
';
}

?>

page.tpl.php

<?php print render(menu_tree('YOURMENUNAME')) ?>

This will give each level an unique class for it's level. Though, there is one big problem with this approach, and that is that menu_tree is working from the bottom up. So you will end up in the following level classes:

ul .level-3
li
li
    ul .level-2
    li
    li
        ul .level-1
        li
    li
li

So, you can never actually be sure about which classname the top level will have, only if you know for sure that there will always be an X count of levels.

Edit
So, just to be clear about my solution here above, this is the only way I can think of doing this programatically at theme level. If you could use a module like Nice Menu's (like suggested above) you should really be using that, since this is more a kind of workaround than a real solution to Drupal's sturdy menu system...


audiofile throwing error on file size even though settings changed

If you don't have apache access control, you can try to add the php.ini settings into

ini_set('post_max_size','16M');

and

ini_set('upload_max_filesize','16M');


Exclude first node with specific value from a view?

The easiest and fastest way I can think of is to use an offset in your pager.
If the most recent featured article is to be skipped, ensure that the list does not start with the first, but with the second result. You can do this for any pager, or even with a fixed amount of items to display.

Alternatively, but that is easier with a node and a view, you might be able to use a contextual filter to suppress a Content ID from a views listing. I have used to populate a sidebar view with all recent articles except the viewed one.
In your situation it might be an issue getting the Content ID from one view to another though


Why does core use print rather than echo?

echo is only faster in academic environments. The difference is very marginal. A quick benchmark I just did: The time fetching one row from a table with more than 2000 nodes is 1 unit.

In order to get an improvement of 1 unit, I would need to replace about 3.700.000 (over 3 milion) print statements with echo. In other words, if you want performance improvements, this is hardly the place to start.

Seen that print can be used in a much wider range of cases then echo, the first has some advantages. It leaves you three options:

Always use print
Use echo where possible and fallback on print
Use echo always and refactor your code if echo cannot be used, to use it

Drupal has defaulted on the first.

To answer your actual question as to why this was chosen: It was not. It simply grew this way.


Prior to 8.5.x, drupal_set_message is the way.
For >=8.5.0-alpha1, there's a new messenger service, with a note (and example which I won't bother copying):

The procedural functions drupal_set_message() and drupal_get_messages() have been deprecated and replaced with a dedicated Messenger service.
You should now inject this service as a dependency for your own services and controllers:


How to use contextual filters to a View for use as a sort criteria?

I am not sure how this translates to Drupal 7 and Views 3, but I have done the following with Drupal 6 and Views 2 using hook_views_query_alter

function mymodule_views_query_alter (&$view, &$query)
{
    if ($_GET["sort"]) {
        $sort = check_plain(trim(strtolower($_GET["sort"])));

        switch ($sort) {
            case "title":
                $query->orderby = array("node.title ASC");
                break;
            case "order":
                $query->orderby = array("node.nid DESC");
                break;
            case "somefield":
                $query->orderby = array("node_data_field_somefield_field_somefield_value ASC");
                break;
        }
    }
}

The trick is to make the views w/ the sorts, and look at the SQL, and use this to update your code.


Drupal not detecting the correct version number of a module?

As Jimajamma in comment #2 pointed out it is worth to check whether there are older versions in renamed directories.

I had the same problem and error message with modules - after removing the backup below "sites/all/modules/old" the dependency check error in update.php was gone.


How to add filter on node list in a custom module?

If you are using Views 3 and within CCK you have listed allowed values for the field in question, you can set it up like this.

Select the field in question with the allowed values option, eg, in Filters, select 'Content: Field Name (field_name) - ALLOWED VALUES'
Click on EXPOSE.
Click in the values and select them all.
Click Limit list to selected items.
Save it.

You should now have an exposed filter with a drop down that limits the view to that field.


Figured it out. It had to do with using MultiSite apparently when you use multisite and bootstrap it will only bootstrap to the main site. I found an article talking about it here https://drupal.org/node/2080819

Basically you need to override what the system variable is for the url so that it will bootstrap to the correct site.

define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$variables['url'] = 'http://subsite1.example.com/';
drupal_override_server_variables($variables);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


How to add the proper javascript to a page for using the Chartbeat module?

the module doesn't work for me, I ended up putting the required javascript code into the template files.


How to display the same nodes with two different themes?

Yes simplest way to do it is using Themekey module. See the demo config for article type nodes.


I've got the same problem like Jussi and i tried to set up a system with the himuesgallery module, the upload via ftp works great and you can build a folder system.
I tried to integrate the image folders in Drupals Private Dir and the result is that i can't see any picture anymore ... may i configured somehing wrong, but this seems not to be a solution.
May a module to restrict access to another folder help.
A long time ago i tried the media module and there was some other problems...
See also the Media Issues or the statement of the authors:

Known Issues
Private files: There are several issues in Media and Drupal core when the private file system is used. While these issue are being investigated and fixed, the use of the File lock module is highly recommended.

So my answer is: No, there is currently no working gallery that reachs your aims.


What rule to use to redirect users, unless already redirected?

Make a flag on users: 'flag_user_has_logged_out', you will need more than one rule, first rule: react on: user has logged out, and flag the user with this new flag, on another rule: react on logged_in: first validate your roles, then validate if user is 'flagged' if so, redirect to /whatever, and unflag user has logged out. if not, the other redirect will take control. This kind of rules i use a lot, i make many calculations on user has logged-out and i do not need to recalculate things again when user loggs in, it work both ways, maybe user just clossed browser and did not made a logged-out, so a evalutate that when loggs in and i do not duplicate my calculations. i hope you understood me and help you. is just a pointing directions on what you can do. Examples how your rules will look like:


Which hook is used to alter a field's description?

To the best of my knowledge there's no hook for that. Instead you'll want to use the following API functions in whatever context makes sense in your site:

field_info_instance()

  Returns an array of instance data for a specific field and bundle.

Use the function to load up an array of instance data/settings, which you can then alter as necessary before passing back to:
field_instance_update()

  Updates an instance of a field.

That will persist your changes to the database, and take care of clearing relevant caches.

A complete example might look like

$info = field_info_instance('node', 'body', 'article');
$info['description'] = t('New description');
field_instance_update($info);


Leave Month (Date) Field blank (Optional)

You can use Number field and do the validation if you just want to store only DD(Day).

Date picker is using to collect Day Month Year


Without seeing the error it's difficult to know, but you do at least need to extend CKEditorPluginBase rather than PluginBase:

use Drupal\ckeditor\CKEditorPluginBase;

class Scayt extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

Otherwise the required interface methods won't be satisfied.


How to create a specific menu for specific users?

This you can do easily with Roles for Menu module.

  This module allows you to restrict access to menu items based on user
  roles. It is used when you don't want to copy your whole menu just
  because for one specific role you want to hide one menu item.

Define the user role (in your case X and Y) in your site.
Then as per user role you can set the menu items, so the menu will be automatically gets display based on Role.

Other similar module is Menu item visibility

  This module exposes configurable and extendable visibility settings
  for menu links.

Both does pretty much similar activity.

Illustration for Menu item visibility module.

Steps:-

1. Module: Download and enable the module.

2. Creating User Role: Now, for example you want to set two user role X and Y. Hence, create by going at People/Permission/Roles -> add two user roles, like userX & userY as shown in following image.

3. Creating a User: Now, create two user, as shown in following image by going at People/ -> add new user, and give corresponding role which we created in step-2. You can see all specifications in the image.

4. Menu item creation: I have created a 7 Menuitems in the section  Main menu by going as Structure/Menus/Main menu.

Now, during the each Menu item creation, you will find the following option at the end of page, and from there selection, FOR WHICH USER YOU WANT TO SHOW THAT MENU-ITEM. Like in follwoing case we want to show Menuitem1 to userX and userY both.

I gave the user role visibility as below, because, I want to show first 4 item to userX Role and all other to userY Role.

Item               Roles Selection
Menuitem1     userX     userY
Menuitem2     userX     userY
Menuitem3     userX     userY
Menuitem4     userX     userY
Menuitem5               userY
Menuitem6               userY
Menuitem7               userY

5. Test: Now, if you Login using userXexample(which has useX role) you will see only four items, and for userYexample(which has userY role) you will see 7 items.


In Drupal Fullcalendar, how do I add an additional field to the calendar view?

There's no need to edit any code to add additional field to calendar view.

To add additional field, you need to install Views fields combine or Token module.

How to use Views fields combine:

Edit your calendar view
Add fields you want to display (from field)
Add Combined fields field and select which fields you want to display
Under format -> settings -> customize fields, check Use a custom title checkbox and select the combined fields you created on step 3
Apply changes and save your view then preview the results on the actual page/block.


How to modify account page adding possibility for a user to chose one of 2 roles

The drupal module Auto Assign Role allows you to do this (users can select during registration, not afterwards).

The module name is a little misleading because although one of its features is allowing for automatically assigning roles to users, another of its features is to allow users to select a role for themselves.


want to display values of content type Article in a page

Maybe you can write a custom template or a custom theme function to output the fields, you will have to play with delta. You can also create multiple content types and link them with a relation field to create the hierarchy. You can also use a specific module that handles this kind of dimensional representation like tablefield or sheetnode.


D7: How do export content types, module settings, taxonomy terms, webforms and other nodes?

It is not bad.  It is preferable to store as much configuration as possible in code, so that it can be version-controlled and deployed easily elsewhere with Git etc..  Features makes this possible somewhat, but it is not yet feature-complete.  Some work that is still on-going:

Taxonomy terms: This will be implemented with a combination of Features and Deploy, but it is not quite ready.  See http://drupal.org/node/1245582#comment-5146834 for details.
Content type settings: A fair amount of this is now working, but Strongarm needs to be set up first for these to be exported with Features.  See Features does not capture important settings while exporting a content type for details.

As there is no more CCK in Drupal 7, that content-copy feature is no longer available.  We've moved onto Fields.  If you want a quick way to get bundles exported without getting into Features, check out the Bundle copy module.


How to add section titles to group fields in content type input form used to create content?

Field Group module is best solution. It will allow you titling above the field group.

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


Boost + Expire: Front Page not expiring from cache

You may try to add the <front> page to the rules action "Clear URL(s) from the page cache":


Checkout filedepot module.

  The filedepot module is full featured Document Management module that
  has a google docs like feel. It fulfills the need for an integrated
  file management module supporting role and user based security.
  Documents can be saved outside the Drupal public directory to protect
  documents for safe access and distribution.


How do I display random nodes within a week?

You can achieve it by below steps.

Add filter criteria Content: Post date.
Follow the screenshot for Content: Post date field configurations.


You can always use the Views: Filter by an entity reference view option from Entity selection mode and then create a view and set the number of items to 3.


It looks like you want to have one more custom field formatter. In order to create a custom field formatter all we need is implementation of 2 hooks

hook_field_formatter_info() - to tell drupal about a new
formatter for a field type
hook_field_formatter_view() - this    is handler for how the field will look like.

so code will be like this

/**
 * Implements hook_field_formatter_info().
 *
 */
function mymodule_field_formatter_info() {
  // Add a setting to a formatter type.
  $formats = array(
    'email_custom' => array(
      'label' => t('Email Custom'),
      'description' => t('Display the email address as custom format.'),
      'field types' => array('email'),
    ),
  );
    return $formats;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'email_custom':
      foreach ($items as $delta => $item) {
        $output = l("email", 'mailto:' . $item['email']);
        $element[$delta] = array('#markup' => $output);
      }
      break;
  }
  return $element;
}

after adding this codes to your custom module clear the caches and you will see one more field formatter as Email Custom(you can change the labels in above code). Now your configurations in manage display for this field will be .

  Hide your field label
  Select Email Custom as field format


FAQ page access denied for anonymous users

It looks like I needed to flush my cache, the page was cached with old permissions and so anon couldn't see it last night when I made the change, but can see it now.


It may be because you are doing this:

->fieldCondition("field_ann_type", "value", array($type));

try just check it against $type like this:

->fieldCondition("field_ann_type", "value", $type);


How to correctly configure Fivestar module with a node reference?

You first need to go to path admin/structure/types/manage/product/fivestar and click the Enable Fivestar rating for the "vote" tag. For Full node display I choose Static display above node body because the voting widget will be on the Review form.

At admin/structure/types/manage/review/fields create a Node reference called Reference with a machine name field_review_reference. Add a field for Fivestar voting. Set the Voting target to Node Reference: field_review_reference. Under Reference Field Settings check the Product content type. At admin/structure/types/manage/review/fivestar the widget should NOT be enabled.

(edit: paragraph removed per suggestion of ericduran)

Now you can create another View with field to make a list of products that show fields from the product such as title, price, and image. Add the relationship Content: Vote results. Set Value type as percent, Vote tag as vote and Aggregations function as Average vote. Add the field Vote results: Value, set Relationship to Vote results, set Appearance to Fivestar Stars (display only).

That should be it.


How to fix 'Call to undefined function node_load() in menu.inc' fatal PHP error?

Problem was the file encoding from mysqldump. My solution: Downloaded the sql file to my local computer. Saved it in UTF-8 with Sublime Text 2. Run the script. And things worked fine with the original drupal files copied from web server. Did not need to run registry_rebuild etc.


How to set or change path to Drupal 8 contact form?

I also needed a page at /contact path. With a simple custom module you can change the default routing for the contact forms.

Let's assume custom module is called: example and the new default for the contact forms will be /contactform instead of /contact:

example.services.yml

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

src/Routing/RouteSubscriber.php

<?php
// Save this file as `src/Routing/RouteSubscriber.php` in your module directory.

namespace Drupal\example\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Change the core's default path for `/contact` so that we can use it as an alias.
    if ($route = $collection->get('contact.site_page')) {
      $route->setPath('/contactform');
    }
    if ($route = $collection->get('entity.contact_form.canonical')) {
      $route->setPath('/contactform/{contact_form}');
    }
  }
}


"The website encountered an unexpected error" right after login in

If you are not able to login then you can try checking the logged error directly looking into your database watchdog table.

In your case:As per our chat you were missing watchdog table so importing the database back helped you.


How to display translated term names in exposed form in block

Your best path would be to open an issue with Views after confirming that the terms don't translate correctly with BEF module disabled.

I found this issue related to translation in BEF's queue, but that looks to be slightly different or only part of your issue.

Unfortunately it can be difficult for contrib module maintainers to test their modules in multiple languages unless they happen to run their own multilingual site, so it is up to the community to make them aware of issues and help test patches.

You also might want to take a look at http://drupal.org/project/i18nviews


How to make base path available in views 3 Drupal 7?

There is something in the view core.
If youre planning to output some field with base path, follow the steps to get an absolute path.

Click on the Field
Scroll down to REWRITE RESULTS
Check Output this field as a link checkbox
Check Use absolute path checkbox

If you're looking this for just a link Views PHP is a good choice.

If youre not happy with this method take a look at How to create a custom Views handler


Add a jQuery hover effect to images in a View

I would do it with adding a custom theme to that view How to apply theme to a view drupal 7 to make the views output to match with your tutorials HTML structure and add .js files as recommended.

When it goes advanced you can try creating a views style plugin so that you can add this jQuery effect directly from your views page.

see

How to create a Views style plugin for Drupal?

How to properly implement hook_views_plugins?


Alter view with hook_views_post_render and save results to cache

Yes Clive is right use

function hook_views_pre_render(&$view) {

instead of

function hook_views_post_execute(&$view) {


Thanks to @googletorp advice the solutions is so easy and I want to share it with others.
All I need was to overwrite two Drupal autocomplete object functions: found and select.

My autocomplete works on content profile fields. I pass nid of selected profiles to JS:

PHP:

function messagi_autocomplete($string) {
  global $user;

    $cache = cache_get('messagi_auto_complete_'.$string);
    $items = array();

    if ($cache) {

        $items = $cache->data;

    } else {

        $sql = "
              SELECT
                n.nid AS id
              FROM
                node as n
              WHERE
                n.type = 'profile'
              AND
                u.status = 0
          ";
          $result = db_query($sql);
          $disabled = array();
          while($obj = db_fetch_object($result)) {
              $disabled[] = $obj->id;
          }

          $items = array();
          $sql = "
                        SELECT
                    profile.nid AS nid,
                    profile.field_profile_name_value AS name,
                    profile.field_profile_surname_value AS surname
                  FROM
                    content_type_profile AS profile
                  WHERE
                    lower(profile.field_profile_name_value) LIKE lower('%s%%')
                  OR lower(profile.field_profile_surname_value) LIKE lower('%s%%')
                  LIMIT 10
          ";
          $result = db_query($sql, $string, $string);
          $sql = NULL;
          while($obj = db_fetch_object($result)) {
            if (! in_array($obj->nid, $disabled)) {
                  $key = check_plain($obj->name).' '.check_plain($obj->surname);
                  $items['nids'][$key] = (int) $obj->nid;
                  $items[$key] = $key.', '.check_plain($obj->venue);
            }
          }
            if (! empty($items)) {

                cache_set('messagi_auto_complete_'.$string, $items, 'cache', 1000);

            }
          $disabled = NULL;

    }

  print drupal_to_js($items);
  exit();
}

JS:

$(document).ready(function() {    if
    (Drupal.jsEnabled) {
            Drupal.jsAC.prototype.found = function (matches) {
              if (!this.input.value.length) {
                return false;
              }

              var ul = document.createElement('ul');
              var ac = this;
              for (key in matches) {
                var li = document.createElement('li');
                //to avoid of showing nids object in the select list
                if (key !== 'nids') {
                    $(li)
                      .html('<div>'+ matches[key] +'</div>')
                      .mousedown(function () {
    ac.select(this); })
                      .mouseover(function () {
    ac.highlight(this); })
                      .mouseout(function () { ac.unhighlight(this); });
                    li.autocompleteValue = key;
                    $(ul).append(li);
                } else {
                 //add all nids to prototype
                    Drupal.jsAC.prototype.nids = matches[key];
                }
               }
                //rest of the code
              }
            };

            Drupal.jsAC.prototype.select = function (node) {
              //get selected value nid and put it on form hidden field
              $('#edit-nid').val(Drupal.jsAC.prototype.nids[node.autocompleteValue]);
              this.input.value = node.autocompleteValue;
            };
} })

I hope this help somebody in the future. Thanks for the others advice to this code.


I don't understand why this isn't a simple case of changing your CSS? You're adding 20px to 940px so that equals 960px. You must either use CSS3 (box-sizing: border-box;) or minus your extra 20px from 940px...which would be 920px. Standard box model stuff but maybe I'm missing something in your requirements.


Anonymous user can view unpublished content

Yes, You can enable module Workflows which is currently packed in core since 8.3 and check for permission for anonymous user

  View any unpublished content

in /admin/people/permissions

Note: Not to confuse about the permission when enable only Workflows. You need to enable module Content Moderation(Core module) to make Workflows work. Once go to /admin/config/workflow/workflows you will see the the default workflow. Here is the permission after enable Content Moderation.


How and when to use filter_xss() and check_plain()?

First, read up about these in the Drupal API:

filter_xss
check_plain

So check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. &lt; and &amp; respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. The function filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. It does four things:

Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Both functions are used to sanitize data from users to make sure that any user injection is neutralized before the data is rendered on your site.

You never pass the same string through both.

If you use check_plain() then the string passed to the function is supposed to be used as plain text (not HTML). Then filter_xss() is not needed, since check_plain() will always make the string plain text.

If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() will mess it up.

When I look at the template you use as example, it looks to me as if all three fields passed to print() comes from content that is already sanitized, and need no more sanitation.

However, if you create your own module that collects user input without passing it through a "safe" text filter such as "Filtered HTML" or "Plain", you must use these functions for sanitation purposes.


Ah I found that one needs to view the site in another language than English in order to have the strings to be registered.


The problem isn't with block_load(); you've specified the correct parameters with the function (the module is 'block' & the delta for the block is 'navigation'). The problem is your typo prevents the render array going to the print_render(). It should be:

$res_output = drupal_render($output);


Same file_temporary_path for localhost and production server?

There is more than 1 way to accomplish something like this. I am not aware of a simple "1 line universal fix" unless you try a relative path, but that assumes some consistancy between your servers which clearly by your directory paths you dont have.

Option 1:

At the bottom of you settings.php put something like:

$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

I do this programmatically in BASH with like:

#!/bin/bash

# I actually install drupal via the command line with a custom install
# profile and append on the tidbit to settings.php programmatically like
# so ...

cd $drupal_www_dir
drush site-install MY_INSTALL_PROFILE \
  --locale=en \
  --db-url="mysql://dev_user:dev@localhost:3306/demo_drupal" \
  --account-name=admin \
  --account-pass='admin' \
  --acount-mail=foo@test.com \
  --site-name=demo --verbose -y

#
# Now that drupal is built we modify the settings.php file with additional db
# and other custom configuration values by appending a child seetings file.
#
# This is in concept similar to an Apache vhost directive file.
#
echo "altering settings.php to be aware of our 3rd party remote databases."
sudo chmod -Rv a+rw "${drupal_www_dir}/sites/default"
read -r -d '' PHPCODE <<'EOF'
/*
 * For our project we provide our own localized configuration schemes.
 */
$local_settings_conf = dirname(__FILE__) . '/settings.local.php';
if (file_exists($local_settings_conf)) { include $local_settings_conf; }

EOF
echo "${PHPCODE}" >> "${WWW}/sites/default/settings.php"

Then for each server you keep a version of this file. Or in this file make an If-Else PHP block that stores the correct $conf value based on whether this configuration file is $local vs $dev or $prod. So basically you can move all your custom settings.php stuff that arent 100% stock drupal into a special appended configuration file ... this way the stock drupal settings.php stays as it is and all your custom stuff can go into its own file as-needed.

Option 2:

Use something like the Environment module and in PHP set the value for the file_temporay_path with variable_set as that is what is being called by file_directory_temp().

Those are the two options I know of that aren't brain surgery ...

EDIT 09/26/2014 by author

You can also use Drush on each server to run: drush vset file_temporary_path "to/some/path"
If you're comfortable with virtualhost settings you can also always create a aliased directory in your webserver configuration (pushing the problem up 1 level in the production stack (out of PHP))


Feeds import creating more nodes instead of replacing or updating - Drupal 7

I figured out the problem: I had not set "Guid" as unique identifier, that is the reason it was duplicating the rows in the database and why it was not replacing or updating the content. The problem now is how to reset the node->nid number to a reasonable number after all these deleted entries.


How to set the filter condition by default for specific condition in view

Use group filters, that way it will allow you to set a default.


How can I get the content type for which a certain comment belongs?

You can use Comment::getCommentedEntity() to get the entity, and if it's a node, grab the type:

$entity = $comment->getCommentedEntity();
if ($entity instanceof \Drupal\node\Entity\Node) {
  $type = $entity->getType();
}


How do I change the site name in the .theme file?

In a *.theme file this would be difficult to find all places where the site name may end up. This is much easier to do it in settings.php right at the start:

settings.php:

if ($_SERVER['REQUEST_URI'] == '/abc/def') {
  $config['system.site']['name'] = 'abc-def';
}


REST Service - 500 Internal Server Error

The problem was when I used the drush tool. It downloaded and installed the Services module, and the Rest Server module (another no necessary module).
This error was describing this conflict between modules;

[Sun Jun 23 17:11:24.136866 2013] [:error] [pid 2957] [client::1:48424] PHP
Fatal error: Call to undefined function
services_resource_uri_formatter() in
/var/www/drupal/sites/all/modules/rest_server/includes/RESTServer.inc
on line 15

I disabled the Rest Server and restarted the HTTP server.


Content profile bug - cannot edit user profile page

The Content Profile module associates a node with a user.  If the administrative user adds a profile node, then it is authored by the administrator.  Therefore, the user that the profile node was created for will not have access to edit the node since they are not the author.  As an administrator, make sure to change the "Authored by" field to be the user whose profile the node belongs to, then the user will have the ability to edit it.


Find out what time was last comment posted on a node

node_created and node_changed refers only to node itself.

In views you should be able to add relationship " Comment: Last Comment".
Then, you'll have filter and field like "Comment: comment time". You can add this field as non-display one and then use it in templates for fields after it. Will be simpler and more reliable than preprocess functions.