There are a couple of options for this.
To get profile fields the most common solution is the profile module included in Drupal core. Go to Administer > Site building > Modules and enable it under core-optional.  Then you can configure the Profile module at Administer > User settings > Profile and in the settings you can say whether the fields will show during registration or not.
To get a captcha during registration you will need one of a couple of modules:
I prefer HCaptcha because it works very well and even can earn you some money, but it sends your content to an external site to do some verification.
There is also Captcha which provides integration with other options.


Strip HTML from trimmed body before it is trimmed

You might want to take a look at the Smart Trim module. It gives all sorts of options for customizing trim functionality, including stripping HTML.


Setting custom key names for exported JSON view fields

From views you can configure the custom name/alias for fields from Fields | Settings option under Format.
Check the screenshot for reference


How do I add different URL to the HOME link in the breadcrumb for the authenticated user

You could use the theme_breadcrumb hook and change the link for the home breadcrumb by checking the role of the currently logged in user.

I've put some sample code in below, but I am assuming that your breadcrumbs array will always have the 'Home' breadcrumb as the first element.

This code should go in template.php

function yourtheme_breadcrumb($variables) {
  global $user;
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {

    // Check if the user has the right role.
    if(in_array('your_role', $user->roles)) {
      $breadcrumb[0] = l('Home', 'path-to-role-homepage');
    }

    $output = '
' . t('You are here') . '
';
    $output .= '
' . implode(' » ', $breadcrumb) .'
';
    return $output;
  }
}

Hope that helps out.


You can use the Entity Module which will allow you to add an image field to the taxonomy.

Then instead of displaying the term->name you'll be able to display your image.

You can create a field image field_brand_logo and get it this way :

$term = taxonomy_term_load($tid);
$brand_logo = field_get_items('taxonomy_term', $term, 'field_brand_logo');
if (!empty($brand_logo)) {
   $brand_logo_img = field_view_value('taxonomy_term', $term, 'field_brand_logo', $brand_logo[0], array('type' => 'image'));
}

print render($brand_logo_img);


How do you disable modules in bulk via Drush matching a specific pattern?

Here's the drush recipe combined with a few other commands to disable modules in bulk:

drush pm-list | ack uc_ | ack Enabled | grep "\((.*)\)" | awk -F'(' '{print $2}' | awk -F')' '{print $1}' | xargs -i drush dis '{}' -y

Broken down:

drush pm-list lists out all of your modules
ack uc_ returns only the lines matching "uc_"
ack Enabled returns only the enabled modules
grep "\((.*)\)" matches the words in parentheses
awk -F'(' '{print $2}' breaks up the line starting with the ( character
awk -F')' '{print $1}' breaks up the line starting with the ) character
xargs -i drush dis '{}' -y runs the returned result into drush disable command with the -y parameter for yes to all.

Thanks to greg_1_anderson, I updated it to be a bit shorter.

drush pm-list --status=enabled --pipe | grep 'uc_' | xargs -i drush pm-disable '{}' -y


integer field select list with min and max value

It may not be the best way to do this, but it might work for you... you can set up the field as a list and leave it empty, then use a PHP script to populate it, EXAMPLE being your field name:

for ($i=0; $i<100000; $i++) {
      // Get the field info
      $info = field_info_field('field_EXAMPLE');
      // Get a reference to the values
      $values = &$info['settings']['allowed_values'];
      // Manipulate the values in some way, e.g.
      $values[$i] =  $i;
      // Save the field
      field_update_field($info);
}

Then you should be able to see the value listed under your field's values (under admin/structure/content/types/YOURAPGETYPE/fields). You can also use this in the future if you need to add more values, just remove/modify the for loop. I can't take credit for this code, I found it here on SE but just can't remember where.


Alter Ubercart Billing/Delivery Panes with User Profile Info

The billing/delivery address panes are driven by a custom uc_address form field. You need to alter it's #default_value object to alter the fields.

For example:

$form['panes']['delivery']['address']['#default_value']->delivery_first_name = $user_fields->field_name['und']['0']['value'];
$form['panes']['billing']['address']['#default_value']->billing_first_name = $user_fields->field_name['und']['0']['value'];


How do I get Views content items in "my language" but fall back to "default" if the content isn't translated?

I think your requirements can be restructured into the following:

Show all content once.
Show the content in the current language, fall back to the other.

Then it becomes pretty easy:

Add the "Default Translation" filter to a view. That basically ensures that all your nodes are shown once because each node can only have one default translation.
Select "Interface text language selected for page" for "Rendering" language. That will attempt to display the site in the current language and fall back if that's not available. (Interface text sounds a bit misleading, but unless you explicitly enabled separate content language negotiation, that's the same as the content language).


field_get_items() will do the trick:

if ( ($items = field_get_items('entityform', $entityform, 'field_team_name')) ) {
  $values = array_map($items, function($x) { return $x['safe_value']; });
  $comma_separated = implode(', ', $values);
}


Single document, multiple filetypes for download: how to manage?

node-[type].tpl.php

$fields = array('field_reports', 'field_agreements'); // you should to create 2 fields for different filenames
$items = array();
foreach($fields AS $field){
  $exts = array();
  foreach($node->{$field} AS $file){
    // delete real extension from file name
    $filename = explode('.', $file['filename']);
    $ext = array_pop($filename);
    $exts[$ext] = l($ext, $file['filepath']);
    $filename = implode('.', $filename);
  }
  ksort($exts);
  $items[] = t('!filename - download as: !links', array('!filename' => $filename, '!links' => implode(', ', $exts)));
}
print theme_item_list($items);

Hovewer, this code must be in template.php in phptemplate_preprocess_node function.


How to unset _none option inside field collection?

You're modifying a local variable. You need

$field_collection = &$form['field_field_collection'][LANGUAGE_NONE];

or

unset($form['field_field_collection'][LANGUAGE_NONE][$delta]['field_name'][LANGUAGE_NONE]['#options']['_none']);


Create a custom block to only show on that page in full html with links to that content... should work.


ajax callback on form element checkboxes

When you use a callback $forms and $form_state is available for use in your callback. But you should call them as parameters in your callback definition.
So:

public function ajax_option_callback(array $form, FormStateInterface $form_state) {
  // get the id of the form
  $value = $form_state->getFormObject()->getFormId();
  // create a response object and return it
}

public function ajax_option_callback() {
  // $form and $form_state not available
}

Note that &form_state->getTriggeringElement() contains nothing as the form is not submitted.

I realize now the question is for D7. Maybe my answer is usefull for someone within the D8 context.


You need to, and should, use CSS to style this.

.buttonize {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  padding: .5em;
  /* whatever other styles you want */
}

I added a jsfiddle.

You can look this up, but I'll note that appearance is different on OS's


user warning messages keep popping up even after uninstall

Most probably the disabling and uninstalling process of the modules didn't went smoothly. According to this help page on Drupal.org:

  Restore the module and actually disable and uninstall it (recommended if possible): First, restore the module to its original location in the file system. Then either go to the Modules page and disable/uninstall it from there, or use Drush (drush dis module_name && drush pm-uninstall module_name, where module_name should be replaced with the name of the module).

Don't forget to also clear the caches, that "magic" feature also resolves a lot of problems ;)

You could also disable the specific message by using the Disable Messages module. However, I would recommend to try cleaning up your Drupal configuration that are causing the messages.


How to create test users on the localhost?

To add new user you can go to admin/people/create (localhost/YOUR-SITE/admin/people/create) and create the user, you don't need to enter a real email. And if you want to test the site with different users you can use the Masquerade module.

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

  This is helpful for site developers when trying to determine what a
  client, logged in as themselves, might see when logged into the site.


How can I redirect node page for a content type to custom URL?

Here is how I managed to solve this issue, based on the example in drupal.org/node/2013014:

I registered Event Subscriber in my_redirect_module.services.yml file:

   services:
     my_redirect_module_event_subscriber:
     class: Drupal\hbmsu_redirect\EventSubscriber\MyRedirectModuleSubscriber
     tags:
       - {name: event_subscriber}

and then in the file my_redirect_module/src/EventSubscriber/MyRedirectModuleSubscriber.php

I added this code:

  namespace Drupal\my_redirect_module\EventSubscriber;

  use Symfony\Component\HttpFoundation\RedirectResponse;
  use Symfony\Component\HttpKernel\KernelEvents;
  use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class MyRedirectModuleSubscriber implements EventSubscriberInterface {

      public function checkForRedirection(GetResponseEvent $event) {

          $baseUrl = $event->getRequest()->getBaseUrl();
          $attr = $event->getRequest()->attributes;
          if(null !== $attr &&
             null !== $attr->get('node') &&
             $attr->get('node')->get('type')->getString() == 'my_content_type') {
              $event->setResponse(new RedirectResponse($baseUrl.'/some_internal_url_path'));
          }
      }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {
          $events[KernelEvents::REQUEST][] = array('checkForRedirection');
          return $events;
      }

  }

in checkForRedirection function, I'm checking if the page is for a node with the content type my_content_type, then redirect to the page mywebsite.com/some_internal_url_path


Administration Structure to list menu items fails to display

If you want to modify only breadcrumb, then you can use one of below module.

custom breadcrumbs:

  Allows administrators to set up parametrized breadcrumb trails for any
  node type, Views, Panels, Taxonomy vocabularies and terms, paths . This allows node types to have "Home > User
  Blog > 2005 > January" style breadcrumbs on the node view page
  itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.

path breadcrumbs

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!


Check if user_picture value is changed or compare with old value

Perhaps you should use hook_entity_presave that keeps the old (original) value

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if($entity->getEntityTypeId() == "file"){

    $filename = $entity->getFilename();

    $file_old = $entity->original;

    if($file_old != null){
      $filename_old = $file_old->getFilename();

      if($filename_old !== $filename){
        $entity->setFilename('newfile.jpg');
      }
    }
  }
}

The function above changes the filename if its not the same as old filename.

Depending on your use case you might want to apply the above logic when user is presaved

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity)
  if($entity->getEntityTypeId() == "user"){

    // get specific field by field machine name
    $file = $entity->get('field_file');

    // or get the user_picture field
    $picture = $entity->get('user_picture');

    $user_old = $entity->original;
    // drill down in the old user object to see values changes
    // and do appropriate changes
  }
}


how to publish a node content to the walll of a Facebook account?

check Fridge for a fast solution. wont post the whole content, though. (and i wonder how that would be done)


Unable to uninstall an incompatible module

Install drush, and type

drush cc all

to clear the cache, then

drush en quicktags

to enable the module; sometimes drush saves my day, when the admin>>modules throws errors.


Ubercart/Securepages site breaks overnight!? Can't POST (login/add to cart)

I had a similar issue. You can look at this and this to get a bit more insight as to what my problem ended up being. Here are somethings you may want to try;

Enable your cookies via your settings.php file. (This is something that helps with securepages).
Enable secure pages across all your pages. This will test if its the issue with securepages losing its session values. If it works, then you need to wait till secure pages gets fixed OR just make every page on your site HTTPS.
Turn caching off. For some reason, this was conflicting with my current setup. It wasn't until I did this that ALL my problems went away.

Good luck and I hope this helps.


Quickly build a Drupal website from another Drupal website

There are several tools available to make this easier. Some benefit greatly from being applied, while some can be added in hindsight without issues.

Drush make, allows you keep a file with the definition of which modules, their versions, any patches etc, you need to build your site. This then makes it easy to quickly pull in all the modules again when you need to set up a new site. It also happens to be very useful whenever you need a workflow that includes patched modules.
Features on the other hand, allows you to take the configuration you make with your modules, such as Views, Panel Pages, Contexts and more, and export it to a module. To some extent, this module requires you to have thought about features from the beginning. Some things, blocks and their settings for example, cannot readily be exported this way, meaning that those will either need to be manually configured after the new site is setup, or be replaced by something. I use Panels content panes in place of blocks, largely for this reason.
An Install profile finally allows you to tie number one and two together.
In the install profile, you first define dependencies on a few core modules, then on all your features, and finally on any other modules you need, that aren't pulled in by features. Then when you run the install, all of your modules will be enabled automatically. This part can easily be done in hindsight, but then you always end up with some amount of custom work that depends entirely on your site, and can't quite be captured in another way, and needs custom code to run during install. This step has proven to require quite a bit of work when colleagues of mine have attempted this after the site is already built.

This approach can readily be, and should IMO be, applied already when building the site initially, but can also be used afterwards to help cloning a website. Realistically, the second will require more work than the first. It is left as an exercise to the reader to discover other cool benefits of this approach, such as how one can automatically generate demo content and more.


How to search more fields using single text field textbox

It's Global: Combine fields filter.

Follow Up:-

process No 1:-

  Add fields to filter criteria

  Add Global: Combine fields filter to filter criteria

  Check fields you want to combine in filter's settings

Process No 2:-

  Add Fields

  Install  Views filters populate module.

  Add Global:Populate filters  to filter criteria

  Check fields you want to combine in filter's settings

I think this answers are resolved your problem.


I ended up with decreasing Token's limit (see images below)


To do this for custom blocks, you will need to enable translations for blocks and custom blocks in the settings.  Then you will need to create translations (with the correct links) for each language.

Details:

Go to /admin/config/regional/content-language
Make sure custom blocks is selected at the top.
Save
Scroll down to Custom Block section
Make sure the basic block and at least the title and body fields are translatable.

To Edit the block.

Go to the Custom Block library
The Edit drop down should have a translate option
Select this and in the translate screen, create a translation.
Edit for the needed language.

Result is that if you are looking at a page for lang X and there is a lang X block translation.  You will see this block.


It looks like the javascript file WERE included before, but they were in the footer. When jQuery code is placed in a basic page, that appears to not work. However, forcing the js files in the header allows everything to run.

I changed my module file to be:

<?php
function flot_d8_page_attachments(array &$page) {

 $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/core/assets/vendor/jquery/jquery.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'jquery-define'
  ];

  // Attach the flot asset on every page.
  $page['#attached']['html_head'][] = [
    // The data.
    [
      // The HTML tag to add, in this case a <script> tag.
      '#tag' => 'script',
      '#attributes' => array(
        'language' => "javascript",
        'type' => "text/javascript",
        'src' => "http://test.mysite.com/modules/flot_d8/flot/jquery.flot.js",
      ),
      '#value' => '',
    ],
    // A key, to make it possible to recognize this HTML <HEAD> element when altering.
    'flot-define'
  ];

}

And my Basic-Page javascript now works.


Add the next code to you template.php

/**
 * Implement hook_preprocess_page().
 */
function THEME_NAME_preprocess_page(&$variables) {
  global $user;

  if (in_array('DESIRED_ROLE', $user->roles)) {
    drupal_add_css(drupal_get_path('theme', 'THEME_NAME') . '/YOUR_CSS_NAME.css');
  }
}


How to prevent admin role from changing "Updated date" of content

You can't really, it's hard coded into the node_save() function with this bit of code:

$time = time();
if (empty($node->created)) {
  $node->created = $time;
}

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

Short of implementing your own node form which bypasses node_save() there's not really much you can do (except hacking the core node.module file which is never advised).


I would implement this in the following manner:

Two content types: Job opening & Job application
Job openings to have fields like : Job description, current CTC, expected CTC, etc.
Job application to have fields like : Cover letter, experience, resume (file upload), etc.
Important: In job application content type, add an entityreference field that refers to Job openings.
Give permission to company user to create job opening; and normal user to create job application.

With this architecture, you should easily be able to build the views as entityreference module provides two very powerful relationships:

Entity reference: Referenced entity (Job opening)
Entity reference: Referencing entity (Job application)


You have many ways of achieving this:

You can either preprocess it inside template.php file. The title has a #prefix and a #suffix theme key when preprocessing it with hook_preprocess_node().
Install delta blocks and turn convert the page into block and place the block accordingly.


Commerce - selecting attribute results in ajax error when product has many attributes

Experienced the same issue. Apache error log "PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini."

Editing php.ini and setting max_input_vars to a suitable figure fixes this.


Checkboxes options with class in form api

To modify how drupal outputs checkboxes, override the default theme_checkbox function found in includes/form.inc. This allow to you add classes and all other stuff. I simply copied the function and changed the last 8 lines:

/* Override theme_checkbox to display titles as facebook-style beautytips  */
function MYTHEME_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  if (substr($element['#name'],0, 13) == "field_MYFIELD") :
    $element['#attributes']['class'][] = 'beautytips';
    return
      '<input title="' . $element['#title'] .'" ' .
      drupal_attributes($element['#attributes']) . ' />';
  else: // Return the regular value
    return '<input ' . drupal_attributes($element['#attributes']) . ' />';
  endif;
}

Thanks @clive for the inspirtation.


You might want to take a look at Workspace, which which was added to Drupal core (8.6.0) just a month ago. It's mainly about content moderation and let's you prepare content on one site that then can be published to another site.

So maybe, if you wanna stick to your setup of one live (master) site and multiple dev (slave) sites, then you could let Workspace push just the content from live to dev – if it works this way.

Unfortunately, I can't find any really good documentation about Workspace. And yes, it has been added to core as an experimental module. But I'd say, you should give it try and can maybe contribute your experiences back :)


Search results are not displaying on top by relevancy

Sorry I got the answer.
Add the sort criteria relevance.

It's working fine. Cheers!!


How to allow for redirecting on same URL with different query strings?

Using the Rules module you can implement a rule that looks like so:
{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "blog\/about-author?page",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "blog\/about-author" } }
    ]
  }
}

It will redirect any path starting with blog\/about-author?page to a path named blog/about-author. So this will "redirect any such paths but with different query strings/parameters to the same url" (as in your question ...).
To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if you have the Rules UI enabled).
But wait, there is more ...
You could also check if page was specified as an URL argument. And make the actual value specified for such argument (like in your question: the 1, 2 or 3 after page=) available as a new variable to Rules. To do so, use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rules configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Approach to adapting a traditional PHP solution into a Drupal module

Here is what I would do (Drupal 7 assumed):

Look into http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_schema/7 for defining your tables. You don't need to do anything special to reference node and user; Drupal doesn't make heavy use of foreign keys. Look into the database abstraction layer to get an idea of the functions you can use to interact with the database. db_select is particularly cool and naturally supports joins.
You may also want to look into Data and Views. Through the use of these modules, you may be able to cut down on the amount of custom code you have to write.
For the blocks, it depends on if they have dynamic or static content. If dynamic, look into Example: Block. If static, check out the Boxes module. Also look into Context as an alternative for placing the blocks instead of using the block visibility settings. This is assuming I understood your use of terminology when you said blocks.
For the pages, look into hook_menu. You can define your own this way; of course, you can also just create pages through the interface...so it depends again on what you meant.
Your development environment sounds fine. You'll find the tools you like as you go along.
There'll be a learning curve, but what you learn will be extremely reusable across future sites you build. It's worth it.


You don't need to modify your .tpl, you only need the Field Group module to group your fields together. With this module you 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.

You can read the documentation where you will find some examples.


add a field to registeration to subscribe to newsletter module

in /admin/config/services/simplenews/add add multiple category you want,
by adding any category here, add term to newsletter category and you can do any thing with its taxonomy


Is learning Drupal 7 a bad option now after release of Drupal 8

Well, firstly learning never gets wasted. Whatever you learn will some day in some moment help you.

Yes, Drupal 8 is going to be released and not yet released. No one knows when it gets released and even people are skeptic about the features that vary with Drupal 7. Definitely, Drupal 8 is going to set a new standard in development and usage. But, till then we shouldn't avoid Drupal 7.

Previously, we developed a website in Drupal 6 as soon as we deployed the site Drupal 7 was released. Then the features provided by Drupal 7 attracted us and we started migrating to 7 and it took most of our time in migrating. But our knowledge and work in drupal 6 didn't go into vain. Infact, we just learnt the new features added/upgraded. It took us only 1-2 days to know about Drupal 7, as we know the core concepts.

So, I suggest you to start learning drupal 7 don't bother about the things that are yet to come. You can easily manage things even drupal 8 gets released.


Load Multiple Arguments to a View with PHP Code

Okay...Here's the right way to do it. I was running into a problem with empty key values. I had to create the array out of the user reference fields I wanted, scrape any of the empty array keys

$node = node_load(arg(1));

if($node ) {
$user_args = array(
$node->uid,
$node->field_am_reference[0]['uid'],
$node->field_realtor_reference[0]['uid'],
$node->field_title_rep_reference[0]['uid']

);
//Remove empty array values and thier respective keys
  $clean_args = array_filter($user_args, 'strlen');

//Take all of the array values and put them into a single key
  $safe_args = implode(',' , $clean_args);

return $safe_args;
}

else  {

return FALSE;

}


Views filter that alternates content types?

Not automatically. You could custom code such a solution, maybe an advanced Pager for showing different number of results for each CT.
The usual way to solve this problem is to create different Attachment or Block Displays, each for a different Content Type, show them in the same Region and adjust the CSS styles to make them look like they are part of the same "box".


Is it possible to custom Event Date format?

You can add a new date/time format by going to Administration > Configuration > Regional and Language > Date and Time. In the upper right corner of the screen you see two tabs: Types & Formats. First go to Formats and add your desired date format there (according to PHP date formatting). In your case, this will probably be something like

D, M j, Y - g:i a

Next, you go to Types and create a new date type. You can assign your custom date format to this new date type.


Can I sort a view by a custom date field without the date module?

Using date field gives you more flexibility, but year made with text field would work also.

But in my opinion after your site grow larger you will probably say to yourself: "Gosh, now I wish to order with moths and days..." and you'll regret not using date field at the beginning.


You need to run drush updb, not drush pm-update. And you don't specify the module name.  So just:

drush updb


Set a default font family and size in ckeditor

Assuming you are using the CKEditor module you will need to override it using CSS. You can either create a ckeditor.css file to override it or edit it in your theme file.

Or you can add

config.extraCss += "body{font-family:Arial, serif;}";

To your extra javascript section in the settings text format.


Redirect only after inserting a new node?

You could use hook_node_insert() under this hook should use drupal_goto() for redirect. The hook_node_insert() only trigger when a new node inserted. If you also want to update. You could use hook_node_update().


How do I create an "About us" page and make it appear in the main menu?

I think there are some confusions here.

First: Custom.tpl.php-files are not custom pages.  They are custom templates for pages, and unless you need to have a different style or layout on your "about" page, there is no need for it.

Second: The hook_menu function has nothing to do with this, it is (mostly) for setting up callback functions for forms and hooking those forms up to the menu router system.

To create an "about" page for your site and make it appear in your site's main menu is much simpler.  Do as follows.

First create your "About" page as a "Basic page" on your site.  To do so, navigate to Home » Add content » Create Basic page and just create the page.  When done, press "Save".
Make a note of the node path of this page.  Let's say it is node/69.
Navigate to Administration » Structure » Menus. To the right of "Main menu", click "add link".
In the field "Menu link title", fill in the desired title (e.g. "About us").
In the field "Path", fill in the node path (e.g.  node/69 if that was the path you made of note of in step 2).
Click "Save".
Clear all caches (you always do this after changing the appearance of a Drupal site).

After going through the steps above, a tab linking to the "About us" page shall appear in the main menu.

If you want a custom layout for this page, you can create this as a template file.  If the node path to the page is node/69, the file should be named page--node--69.tpl.php.


Get url of referenced entity in twig based on target_id

What they've done on this post should do the trick How do I get the node URL in a Twig template?

So in your case this should work:

{{ path('entity.node.canonical', {'node': node.field_suggestion_articles[key].entity.id}) }}


Email notification via private message module

Part 1:

The answer to the question "What is the settings to send mail to user using private message?" is like so: these settings can be used to finetune the eMail to the user who received a "Private message", whereas such eMails are like a "notification" that there is a new Private message waiting on the site (and for which that user must head over to the site to actually read/see the private message).

Compare it so the various eMails a newly registered user may receive after a registration request got approved, which also requires such new user to go visit the site to actually start using the user id (to set a new password, etc).

Part 2:

Below is a suggestion to address the 2nd part of your question, which you wrote in these 2 comments:

But when i am creating message "To" I have specified their user name to send mail,instead of that i want to give "ROLE OF USERS" it is possible to send mail by using user role ? ...
I have posted in above pic in place "To" i want to specify my user roles ...in under one role i have 10 users i want sent a mail for all of that users.

The Privatemsg Bulkmail module (for D6) would possibly address your question ... Provided "sending a private message" (instead of "sending an eMail") would be OK for your case. If that's not what you want, then you should not be using the Private message module (that's not what it is for). The rest of my answer below assumes that "sending a private message" would be OK.

There are currently no plans for a D7 version of that module. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted (in this case a list of users that corresponds to your ROLE OF USERS).
use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module.


logged in users only for /user in user menu

I suppose since /user is open to both authenticated and non authenticated users the other /user is somehow specially defined.

For others looking for a quick fix, I solved this with menu item visibility module.


Compute values to display on the user profile page based on other user profile field values

You can make use of hook_entity_extra_field_info() . Below is the following code snippet which you can use in your module:

/**
 * Implements hook_entity_extra_field_info().
 */
function my_module_entity_extra_field_info() {
  $extra = array();

    $extra['your_entity']['your_content_type']['display']['my_own_pseudo_field'] = array(
      'label' => t('My own field'),
      'description' => t('This is my own pseudo-field'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}
And you can use hook_ENTITY_TYPE_view
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function my_module_your_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('my_own_pseudo_field')) {
      $build['my_own_pseudo_field'] = [
        '#type' => 'markup',
        '#markup' => 'This is my custom content',
    ];
  }
}

Please replace the entity and entity type with your requirement. Since it is only for the display this code snippet will work . Clear the cache you will find this field in manage display section .


Is there any other way to store values in DB other than 'system_settings_form'?

You can store your data wherever you like, in whatever format you like, and you can manage it in any way that php allows; Drupal doesn't have an opinion on the matter.

If you're asking whether Drupal has another variable API you can use for this slightly different requirement, then no it doesn't.

So to answer your question directly

  Is there any other way to store values in DB other than 'system_settings_form'

Yes, just use the database API in whatever way you think is appropriate for the data you're storing/retrieving. Various modules provide data layers, e.g. ctools has a data API as Jimmy mentioned in the comments. There's also the core entity API, but that's going to be overkill for your needs.

All that said, you might want to actually profile your code to see if 20 values serialised into a single row is going to cause you any real problems. Yours and MySQL's definition of "huge" might be quite different.


Generate price from item selected in drop down

You can do this using the Rules module: http://drupal.org/project/rules/.  That should already be up and running if you're using Drupal Commerce.

So just go to admin/config/workflow/rules and add a new rule that looks something like this:

Event: Calculating the sell price of a product
Condition: Entity has field: [commerce-line-item], Field:
Action: Set the unit price to a specific amount; Parameter: [commerce_line_item]; Value:  can either select another field to base this on or do a hard-coded value; Leave Price component type and Price rounding mode to their defaults
Test!

Let me know if this ends up working for you


Silly me. I copied some lines from D6 settings.php. After adding an extra ['default'] here: $databases['default']['default'] = array(... things are working fine again.

Note 1: Probably good to not delete this question as someone else might run into something similar at some point.

Note 2: Will be nice if Drupal 8+ will have a more informative way of error reporting.


How do you sql-sync a site with multiple databases?

drush sql-sync @prod @dev --source-database=my_other_db --target-database=my_other_db


How to create a node with mulitple field-collection items?

Try This:
Example for field1 and repeat it with other fields.

$entity_fc_val = entity_metadata_wrapper('field_collection_item', $fc_val);
$entity_fc_val->field_field1->set(array('value' => $val1));


Recoverable fatal error after form submission in drupal7

Here is an example of a file upload with some validation, hope it helps

function file_upload_form_validate($form, &$form_state) {

  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('txt csv'),
    'file_validate_size' => array(10000000),
  ));
  // If the file passed validation:
  if ($file) {
    // Move the file, into the Drupal file system
    if ($file = file_move($file, 'public://')) {
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', 'there was an error uploading the file');
    }
  }
  else {
    form_set_error('file', 'No file uploaded');
  }
}

function file_upload_form_submit($form, &$form_state) {
  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  $file->status = FILE_STATUS_PERMANENT;
  // Save file status.
  file_save($file);
  // here you can save your data
  $firstname = $form_state['values']['name'];
  $username = $form_state['values']['username'];
  $password = $form_state['values']['password'];
  $year_of_birth = $form_state['values']['year_of_birth'];
  $email = $form_state['values']['email'];

  db_insert('registration')->fields(array(
    'firstname' => $firstname,
    'username' => $username,
    'password' => $password,
    'yearofbirth' =>$year_of_birth,
    'email' => $email,
    'file' => $file->uri,))
  ->execute();

}


Creating a related content view in Drupal 7:

Show related content based on shared Term-pages (from any given vocabularies).

Each term page will be recognized by the term ID (TID) hidden in the pages’ URL.

The process:

Basic stages:

Create a “Content” view-block.
Add a contextual filter: “Has taxonomy term ID”.
Choose “provide a fixed value”.
(From type): “Taxonomy term ID from URL“.

Checking:

•   Uncheck “Load default filter from the term page”.
•   Check “Load default filter from node page, that’s good for related taxonomy blocks”.

•   Check “Limit terms by a vocabulary”.
•   Check your desired vocabulary.

Select “Filter to items that share any term”.
Go down and check “Reduce duplicates”: This will several terms that relate to the same page – To appear. Only one will of them will.

https://www.daymuse.com/blogs/drupal-guide-related-content-term-views

Optional:

If you would like that the current node won’t appear in the list:

Go to the view and add another, extra Contexutal filter.
Give it content: NID.
Select “Provide default value”.
Set the “Type” to “Content ID from URL”.
Go down in that window, click on “More”, and there check “Exclude”.

Note that this will exclude the current node in which the related is shown – From that very list.

It will do so by using the content ID which is a (hidden) part of the URL.


Administrative page still accessible by anonymous users?

The problem is you are setting
'access callback' => TRUE
this gives access to all.
I also to sure that administer is a valid permission in 'access arguments' => array('administer'), instead try 'access arguments' => array('administer site configuration'),.


Rules condition if user has certain roles not working at all?

Sorry, ignore my last comment.

You need a condition of "user as role" set to "site:current-user".
Then select the role that is required which is "moderator".
Leave everything else unchanged and save.

You need an action of "add role"
This action defaults to "account" so leave it as is.
Select the role you want to add, and save.


How to display Facebook friend count on your Drupal site

Mind you I have the Drupal for Facebook module installed. So this is what I did:

function facebook_count($username) {
$url = "https://graph.facebook.com/".$username;
$fbData = json_decode( file_get_contents( $url, 0, null, null ), true );
return intval($fbData['likes']);
}

I then displayed it via:

<?php echo number_format(facebook_count('Fan_Page_ID') ); ?>

Hope this helps!


Does performing $entity->save() on field collection programmatically clears the page cache of it's node host?

I know that node_form_submit will clear ALL page caches. Sounds like what you're looking for is something like the expire module.


How to override page title by content type

As mentioned by Ivan Jaros You can use hook_preprocess_page_title.

You just have to load the node from the route first, to get some context.

function yourtheme_preprocess_page_title(&$variables) {

  // Load the node entity from current route
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Load the label of the bundle
    $bundle_label = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($node->bundle())
      ->label();

    // Set the page title
    $variables['title'] = $bundle_label;
  }
}

If you just want to use this with certain content types, you can use $node->bundle() to get the machine-readable name and check against it.


Adding markup to fields in block plugins

You can configure a custom view mode with the two fields image and body and then use a twig file:

node--blog-post--my-view-mode.html.twig

And build the node:

$build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'my_view_mode');

Alternatively your task could be easily solved in Views, but maybe this is only an simplified example and you need to do more things in code.


Redirect to a view with contextual filters

You have to use the route parameter names defined in the route.

You can check the route definition of this view display with Drupal Console:

drupal router:debug view.search.page_1

When you define contextual filters the route parameter names are usually {arg_0}, {arg_1} ...

So this could work:

$form_state->setRedirect('view.search.page_1', ['arg_0' => $value]);


How to include "Page Updated" in the footer of my drupal 7 site?

There is no module specifically to do that. Its very easy todo as you just put the message variable in the bottom of your footer. Just find the message variable in your page.tpl.php file. search for message and copy that $variable to the bottom of the page.


Why are these file errors show up on the site - I have "none" selected in admin

The "Error messages to display" setting only controls whether or not PHP errors/warnings/notices/etc are shown - that particular message is a 'standard' message displayed using drupal_set_message(), with error as the second parameter.

This happens in includes/file.inc, line 891.

drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $original_source)), 'error');

Since there's nothing actually throwing an exception the PHP error handling never comes into it, and the message is displayed as normal.


Problem creating nodes from XML using Feeds/ Feed XPath Parser

Have you tried turning on debugging in the Xpath Parser? It can give you an idea of what is going into the field before any interference like the formatting of the field itself.

I also use Firepath which is an add-on for Firefox for use with Firebug.
I don't use Xpath very often- kind of a quick means to an end- and the two of these tools have been invaluable. Firepath will help you find out if your Xpath is correct.


What to set up in a Kernel test to get custom content type to be available

For kernel tests you need to specify which configurations you want installed. For instance, you'll need something like this in your test's setUp() method:

$this->installConfig(['my_custom_module']);

That takes an array of modules, so you'll probably need to specify additional modules (like filter, node, and field potentially).

This assumes your field configurations are bundled in your module's config/install directory.


if I change site with local devdesktop it will not change anything with my live site?

Normally there is nothing to worry about. Some advices:

make sure that you are working on a local database and not producction.
Sanitize your database (users + passwords) or use reroute email to ensure that your site does not send emails from your local environment.

drush sanitize

  Reroute email: This module intercepts all outgoing emails from a Drupal site and
  reroutes them to a predefined configurable email address.

  This is useful in case where you do not want email sent from a Drupal
  site to reach the users. For example, if you copy a live site to a
  test site for the purpose of development, and you do not want any
  email sent to real users of the original site. Or you want to check
  the emails sent for uniform formatting, footers, ...etc.


Redirect users from authentication URLs to signup page

There is no dedicated hook for things like this, but you can implement hook_init() and then do the redirect there. Something like this:

function yourmodule_init() {
  global $user;
  if (in_array($_GET['q'], array('user', 'user/login', 'user/register') && !$user->uid) {
    drupal_goto('sign-up');
  }
}


Using twig inside theme folder rather than twig from modules

Create templates folder inside your theme and enable Twig debugging, check here for how to enable twig debugging.

Once twig debugging enable look for theme suggestions and name the templates accordingly.


How do I place a multigroup in another multigroup?

In Drupal 7, CCK Multigroup is succeeded by Field Collection, which can be used to nest collections within collections.

In Drupal 6 however, you already have your answer. You cannot place any kind of group inside a multigroup, due to the way the information is stored in the database.


How to change "to" to "-" while displaying start and end date in views?

My answers assume I have a field called "field_event_date" which shows as Content: Event Date in my view.

Answer #1 - Use View Template

Under the Advanced Section of the view, under the Other section, open Theme Information
Copy the filename of the last theme option for Field Content: Event Date, in my case it will be views-view-field--VIEWMACHINENAME--BLOCKMACHINENAME--field-event-date.tpl.php
Copy the following into it:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value"])); ?>
 -
<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value2"])); ?>

This will output something like 2014-08-09 20:15:00 -
2014-08-12 20:15:00, format using the date() format string.

Answer #2 - Use View Fields

Under Fields, add Content: Event Date and set the Display to "Start Date Only"
Under Fields, add Global: Custom Text and set Text to  -
Under Fields, add Content: Event Date and set the Display to "End Date Only"
Under Field Settings, Set the three fields above as Inline.

This will output something like Sunday, December 1, 2013 - 12:00 - Sunday, December 1, 2013 - 12:00, based on the format you have chosen.


Save content with current user roles and add filter to show only content with current user role

You don't have to add author's role to a node directly.
You can add user's role based Exposed Filter option in a view by using relationship. To do this please follow steps of below:

Create your view as usual (like configure view name, display type
etc)
From Fields section add all desire fields.
From Filter Criteria choose appropriate node type.
Click on the Advanced button (indicated by an arrow on right side of the view).
Click on the Add button of the Relationship section and add Content: Author as a relationship.
Now Click on the Add button of the Filter Criteria section and add User: Roles as a filter. In this filter settings pop-up form, enable or check Expose this filter to visitors, to allow them to change it option then choose Is one of option as an operator.

Output/result:


drupal_render() renders an item. Rendering it contains theming it. Look into function's code, there is this line:

// Call the element's #theme function if it is set

So placing render inside theming function is bound to make a loop. drupal_render_children() exist to break this loop - it renders element's children only, so you can print element itself in theming function and still have children themed by their own proper functions.


What's the alternative for my failing PHP code about block visibility based on user?

You could perhaps just set the "Roles" options under the block visibility settings.

Alternatively, something like:

global $user;
return in_array('administrator', $user->roles) ? FALSE : TRUE;


Flags: get Action after a user flagged a specific number of nodes?

You can able to detect limit has reached using hook_flag_flag hook exposed by flag module..

Flag Limiter module uses the same logic to detect the limit as you can see the below code

function flag_limiter_flag_flag($flag, $entity_id, $account, $flagging) {
  // Get the flag limits.
  $flag_limit = variable_get('flag_limiter_' . $flag->name . '_value', 0);
  $peritem_limit = variable_get('flag_limiter_' . $flag->name . '_peritem_value', 0);

  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) > $flag_limit) {
      $unflag = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag) {
        drupal_set_message(t("You've already signed up @num times", array('@num' => $flag_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }

  if ($peritem_limit) {
    $flagging_data = flag_get_counts($flag->entity_type, $entity_id, TRUE);
    if ($flagging_data[$flagging->flag_name] > $peritem_limit) {
      $unflag_item = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag_item) {
        drupal_set_message(t("The event already signed up @num times", array('@num' => $peritem_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }
}

You can implement same hook in your custom module to redirect user to the page you want.. You can use drupal_goto function to redirect user..

function YOURMODULENAME_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}

writing custom module instructions ..

Create a folder called "custom" inside sites/all/modules
Create a folder called "myflaglimit" inside sites/all/modules/custom/
Create a file called "myflaglimit.info" inside "myflaglimit" folder create above.
Put in below code and save file

Below code goes into myflaglimit.info file..

name = My Flag Limit
description = Provides a redirect on reaching limit.
core = 7.x
package = Custom
dependencies[] = flag_limiter

Your logic goes into .module file

Create a file called myflaglimit.module file inside myflaglimit folder you have create with below code
You extend drupal function using hooks which are nothing but functions which starts with modulename_hook

use below code inside module file

<?php
function myflaglimit_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}


Restricted access on reference field type?

The reason you see that is that you don't have view access to field storages.

In Drupal Core, there is no access control handler for them because they're managed behind the scenes and never really edited/viewed/deleted. That happens automatically through field configs.

You can add implement hook_field_storage_config_access() (look for hook_ENTITY_TYPE_access() for documentation) and allow view access to your users. But....

  I'm trying to find a way to create an index for a content type based off of several of the fields found on each page.

I don't understand that. I'm not sure you're on the right track and before spending time to implement access control, I'd try to confirm that.


Multiple forms and required fields affecting hook_form_FORM_ID_alter()

To do form validation use the form API validation capabilities:

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#validation

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#validate


Views duplicate result if multiple entity reference

I figured out good solution which is as follow:
-A is the content type & B is the second content type
-A is field entity reference in the content type of A with multiple values.
-in the views in creating view of content type B just render the field of entity reverence A normally, by default it will render the title whether its 1 value or more.
-now the views for this field in formatter option choose Rendered Entity.
-and in view mode we can choose Tokens.
-now we got to the content type A and then go to manage display tab.
-at the bottom left in the menu click on Custom display settings and then check the option Tokens and click save.
-now in the top right tab "Tokens" display will appear, click on it.
-now we choose which field we want to appear in the view & we can control the label, value, the format. for my case i just showed 1 field without the label and with plain text format and thats was great enough with out making relation and duplicate the content.


There are many ways to do this. A simple way would be to create a view for each content type and then create menu items for each of them.


Blank spaces opening RSS XML file - How to solve?

Some more troubleshooting ideas:

Do the spaces only appear on the RSS page, or also on other pages? That could tell you whether the problem is in a central place or a template/include-file that is only loaded for the RSS feed.
You can use var_dump(get_included_files()) (ideally in the template, just before the XML is generated) to see a list of all PHP files that have been included so far. This might help with investigating - look for closing PHP tags at the end of the files, print statements, etc.

Also, an idea for a dirty workaround (may cause other problems, but could be worth a try if it's urgent): ob_start() buffers all output, while ob_end_clean() deletes it. So if you put an ob_start() in the top of your index.php and an ob_end_clean() at the start of the RSS template, this might let you discard the spaces. (It shouldn't affect anything else, because the buffer is flushed automatically if it's still open when the script ends.)


can needs-data be an array in drupal hook_token_info?

There is no type limit on needs-data. It all depends on how do you want to call token_replace(). On the other hand, it might be wise to use 'node' approach - when you provide node, you provide also user object of node's author, even if it is never provided or mentioned in needs-data explicitly.


if (arg(0) == 'node' && is_numeric(arg(1))) {
  $active_trail = menu_get_active_trail();
  end($active_trail);
  $nid = 1; // change to nid of parent node you want to check
  if ($active_trail[1] && $active_trail[1]['link_path'] == 'node/'.$nid) {
    return true;
  } else {
    return false;
  }
}

You can use the above code to achieve it in Drupal 7.


How to create a view based on taxonomy term of a node reference

OK. I've solved it myself!

I had to set up a relationship with "Team".

Then I added in a  "Content: Has taxonomy term ID" contextual filter. Within the settings there is a relationship option which I set to the one I set above.

Works as I expected!


Problem In Adding Flexslider To Slideshow

Make sure you use the flexslider module with views integration, views slideshow and flexslider views style are different modules. They each provide a different style for your view!


Any performance impact or reason to delete unused views?

If they are never loaded/rendered, there should be no performance hit, except for the admin viewing the /admin/structure/views page since they get listed there.

Ok, maybe a slight performance hit, since the view table ID's in your DB is bigger, so it would take longer to find an ID, but if you're caching your Views you will be fine.


Better is later than never :)

Try to use "dependencies" from context menu of facet block.


Relationships between content types and views

I don't think you need to create content types to do what you need.

You have a content type of car and then I would use taxonomy to select the series and models.  You can add fields/images etc to taxonomy and pull those into your view if you need to.


How can I keep a long-running Drush script from gradually exhausting available RAM?

You could use the Drupal batch API and call it from Drush.  You could use the Drush batchTest unit test as another reference on how to use the batch API from Drush.


Trying to get fullPage.js implemented, but how to add data-attributes?

Now there is contributed module that will let you add custom attributes per menu item, you can find it here: Menu Links Attributes


give the module hierarchical_select or it's simpler approach a try.

or see here how to programmatically play with the exposed filter(s): https://drupal.stackexchange.com/a/96769/3218


Can I run Drush in a situation where the database is on one server and the remainder of the Drupal installation is on another?

I've never run a Drupal site like this, but Drush should take your database settings from your settings.php file; if the database is remote for Drupal, then it should be remote for Drush as well.  Note that most Drush commands (with the notable exception of the sql-* commands, which you will not be able to use without a local mysql installation) just call through to the corresponding Drupal code, after first bootstrapping.  If your bootstrapping is failing, check to see if there is anything in your settings.php that depends on the site's URI to select the database.  If so, make sure that you use the --uri= flag, or set the 'uri' element in your Drush site alias when using Drush.  If that doesn't get you going, post the output of a failing Drush command with the --debug flag specified.


You can look at deploying a site and scrubbing it of files like CHANGELOG.txt/INSTALL.txt automatically. Other things, like removing the meta generator tag in the head also can hide that it is Drupal, but nothing is bulletproof. For example, typing 'Drupal' in the browser devtools window is another way to tell if a site is Drupal or not (in most cases). You could also try banning requests originating from that domain/service at the server level.


How to set Rules event for "Content is viewed" from excluding Teaser view?

In your rule add a data comparison called "view-mode" and set it to "Full content".


Persistent variable (`variable_set()`) name restrictions

Until Drupal 7, the main storage for the variables is the variable table in the same database Drupal uses.

The name column is a varchar(128) so that requires the variable names to have equal or fewer characters than 128.

Prefixing the variable names is purely by convention. Drupal Form API can handle spaces in machine names too, but you will almost never see a form array item key with spaces in it.

There are workarounds, but it's easier if there are no spaces, for example when you use drush, export settings, etc.


Trigger Drupal Rule Based on Taxonomy Term

When you say the content "matches" the term, do you mean the content has a field to select that term, and you want the email to send when the content has been tagged with that term?

If thats the case...

Create a new condition "Entity Has Field"
Choose the taxonomy field.
Create a new condition "if taxonomy field == taxonomy name"
Create action to send mail to user of a role.


Syncing Development Site with Production Site

You simply need to sync the database and the whole complete Drupal folder. Every single file except for .htaccess and settings.php as they may be different in every environment.

And from now on you start to do things just the other way around.

git init a Git repo on your local machine. Then you do every update, every UI change, every site building task on your local machine first.

When you are done locally you do drush cex to export the new configuration into YAML files. I think you can do that from the UI as well.

Then you deploy (upload) these YAML files to your live site and start the configuration import, drush cim or UI.

Similar with updating Drupal. Wether Composer or manually, you do that on your local machine first. Then deploy the resulting composer.lock file or the updated files to your live site and start the database updates once again, drush updb or from the UI.

From now and then you get a database dump from your live site and import that locally. Maybe you download or rsync the whole sites/default/files folder to your local machine as well. This one and your settings.php are going to be ignored from Git.

That's how things are supposed to go. File changes always upstream, database dumps downstream.

After you've set up Git correctly you may start to use Git Flow. Which expects you to work in different Git branches, master and develop. And feature/* branches when developing new features locally.

Basically when you're done with a feature you merge the feature branch into the develop branch and push the changes to your Dev server. Once in a while you start a new release where the develop branch gets merged into the master branch. And the master branch would be the one that pushes stuff to the Live server.


Programmatically modifying global custom text field in view

have you tried to use a custom handler? This way you don't need to override nothing.

Related to: Move php in views to module


Need to add custom element in sitemap.xml file

If you don't mind a programmatic approach, then follow these steps:

Ensure that XML Sitemap module is installed & enabled
Create/use a custom module (say, MYMODULE) & use the following hook:

  function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
    // Some logic to generate datetime
    // or hardcoded value
    $element['expires'] = '2010-10-10';
  }

Go to admin/config/search/xmlsitemap/batch-generate & click on 'Run'
Go to admin/config/search/xmlsitemap/rebuild & click on 'Rebuild sitemap'
Go to sitemap.xml, inspect element or view page source & verify that 'expires' tag is included

Hope this helps.


Get a list of all users and into an array

In Drupal 7 you can fetch all the users using entity_load like following,

$users = entity_load('user');

and array_keys($users) will gives you the array of uid's


Multiple aliases, context and menu items (Drupal 7)

I was able to create an acceptable solution by adding a query string to my menu links and adding an additional test to my PHP conditions. Now I've got something like:

return $_SERVER["QUERY_STRING"] == 's=pt';

and I get the context I'm looking for. The actual implementation is a little more complicated (due to having taxonomy also defining context, but needing to override it when a query string is passed so as to avoid ending up displaying both menus) but that should give you the idea in case anyone else is looking to solve the same problem.

I'd like to see the patch in http://drupal.org/node/904416 make it's way into the official context release. For me, maintaining a custom PHP condition is much easier than remembering I need to patch a module every time I update it if it doesn't get in there.


Run lazy-builders of sub-keys in the render array

This seems like an anti-pattern. Normally you would configure and theme separate instances of the block for the fields you want to display in each region.

If you need block fields in the page template, get the fields directly from the custom block content and put them in variables in page preprocess, see Programmatically accessing block content, or use the module Twig Tweak:

{{ drupal_field('field_example', 'block_content', 1) }}


Views UI doesn't provide links to expand fieldsets anymore

This probably means that there is something wrong with JS making collapsible not work.

Is there anything in the JS error log? Check if all JS files are moved and that they are complete. Also check for error 404 for JS files.


Want to use exposed filters to pass arguments to a view

In your view on right hand side there is "Advance" toggle under that "Expose form" is there click on Exposed form in block "No" to "Yes". Now you can find that expose filter in system block. You can place that block anywhere you want you will redirect to that main view.


How to find the path of the feed for content type in drupal 7?

You can use the Views module to create feeds. Simply add a new display of type "Feed" and customize the view to contain only the content you want. You have to set the path in Feed Settings(enter your own path for example: type feed or any path you want).

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "Displays" heading with an "+ Add" button. Click that and select "Feed" . You will then have a Feed display that is using the Default Display's settings.


Can't add iframe to paragraph - iframe is stripped for attributes

If this is your output:

It's likely you need to specify the allowed attributes as well under Limit allowed HTML-tags. e.g.


/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new RedirectCommand(Url::fromRoute('<front>')->toString());
    // $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}


how to put "add friend" link with flag friend with views

In views you have to go to advanced setting and in relationship you can add your flag.

After that you will be able to add your field.


In the form submit handler, you can modify the $form['action'] value.

// Get the routename
$routename = 'My-Route';
  $url = \Drupal\Core\Url::fromRoute($routename);
  // make the redirection
  $form['#action'] = $url->toString();


Show node field as a carousel using jCarousel module programmatically?

Have you try with this module: http://drupal.org/project/field_slideshow It will help you to build a carousel with the content of a field.

As field slideshow is not the best options, because you need field collection.

Another option is this other.

Use a normal image field.
Build a block view with the images from the node.
With Display suit, you can choose what fields you can show or hidden, you can hidden the imagefield. And also use Display Suit (admin/structure/ds/fields) to become the views block as a field for the content type.

The last step is to enable the new field.


Alter the path of the more link from Views

If I have understood your question, I have been needing the same thing.
I solved it by means of:

1) add the field 'link to taxonomy term' and exclude it from visualization

2) format the description field as 'clipped version' (I am using right now a Spanish version of Drupal 8, not sure what the English option name is called)

3) rewrite the output for the description field as '{{ description__format }} {{ view_taxonomy_term }}'

That did the trick.

I hope that that's what you had asked, and that someone can take advantage of it.

EDIT: After re-reading your question, I realize that what I was trying to solve is different: a taxonomy terms view, which returns a list of terms, the description shortened to 160 chars, with a 'read more' link based in the taxonomy term's custom path (/path instead of /taxonomy/term/2).

Since I haven't been able to find an online answer to that, and given that google drove me to this question while trying to find an answer to mine, I think I could still leave this answer here. However, if the OP or some mod tell me to remove this answer, I gladly will.


You can do this by hook_preprocess_node(&$vars) function. By this function you can check the Node ID then if it is some custom IDs, fetch the appropriate data and assign them in $vars array.

In the aggregate we have

function THEME_preprocess_node(&$vars){
    if(drupal_is_front_page() == true){
         if($vars['node']->nid == 44){
             $newNode = node_load(45);
             $wrapper = entity_metadata_wrapper('node',$newNode);
             $image = $wrapper->field_home_section_photo->value();
 //here use kpr($vars) to get the correct syntax of  field_home_section_photo in $vars
// suppose it is $var['fields']['field_home_section_photo']->value
              $var['fields']['field_home_section_photo']->value = $image;
           }
      }
}

don't forget to install entity module.


Run the cron manually it will update this.If you have more translations for NL it will get update there.

cheers!


How to hide selected term values in Views?

Use the views feature "rewrite result", combined with a logic similar to the pseudo code that is below to implement the desired functionality:

if Price Term = 'Costs Money' then write the image tag related to 'Costs Money'
else write &nbsp;

Not sure if you'd actually need the else clause ...

Note: This requires the Views PHP module , as described in https://www.drupal.org/node/482752#comment-4841554 also. Attention: this module only has an alfa version as of today, but it's used in over 71K sites anyway.


Problems with Search API and Entity Translation

Make sure to enable the "title_field" field in the Fields tab of the index instead of "title", as well as any other translatable fields you want indexed.  Then, make sure to re-index everything.

By default, custom fields aren't enabled there, and neither is "title_field" which provides translations of titles via the Title module.


Drush doesn't download module version specified as dependency

The Drush download code actually pre-dates this feature; as you have observed, it is not supported.

I have posted a feature request in the Drush issue queue, here:

https://github.com/drush-ops/drush/issues/1285


How to change label pass field on registration form

Here is the soluition (need to clear the caches):

function MYMODULE_element_info_alter(&$type)
{
    // dpm($type);
    // assuming it's a password_confirm type
    $type['password_confirm']['#process'][] = 'custom_pass';
}

function custom_pass($element)
{
    $element['pass1']['#title'] = 'Пароль / Password';
    ...

    return $element;
}


Ubercart: Change the product display form label "SKU"


Especially in templates files, dpm() doesn't show up, I'm not sure about the cause but I guess it's because the drupal_set_message() function is called earlier. So while working on templates I prefer using kpr(), it works the same way but print directly the krumo message into the page instead of using drupal_set_message.


Creating a slideshow with images and text overlays

I don't believe that there's a module that supports the dynamic placing of text on top of an image in a wysiwyg editor. However, you should be able to use the imagecache_actions module to superimpose a text field onto an image field; IOW, you'd need to have separate fields (or a field collection) for the image and text. It also supports custom actions which should allow you to exploit the imageapi and GD as per your requirements.


How to have a combined search view that shows both users and content on search terms?

Haven't tried it, but I believe you could use Apache Solr with the http://drupal.org/project/search_api, http://drupal.org/project/search_api_solr, and http://drupal.org/project/search_api_multi

Create two indexes, one for nodes and one for users.  Then create a view that uses both indexes.


How can I make Search API search field collections?

You shouldn't use the field collection module in D8 to begin with, as the project page says

and it also says

Drupal 8
Use Paragraphs and Entity Reference Revisions instead of field collection for Drupal 8 projects.

If you don't make the change now you will have to, in the future, whenever you migrate to D9 as there won't be any D9 version.


No "body" when creating a node programatically, with Internationalization

If your site is multi-lingual then 'en' would contain the English-language translations of your original node (I think that's right).

Going out on a limb, I'd say you're not running a multilingual site and instead want to use the LANGUAGE_NONE constant, e.g.

$node->language = LANGUAGE_NONE;

If your site isn't multi-lingual, using 'en' would probably explain why you're not seeing the body value saved. It might even be there in the database, but because the field system is looking for fields with a LANGUAGE_NONE when it's attaching data to a language-neutral node, nothing gets found.

That might be a load of nonsense though ;)


Add a node as a select list in Webforms Drupal 6?

If you are using D6 then consider the Webform View Reference Component module. Here is a quote about it (from the module's project page):

  ... adds a webform component where you could use a View as a datasource for your normal webform select component. Instead of hardcoding all the selectable values in the component values field you just select a reference to a View similar to the CCK nodereference. The selectlist/radiobuttons/checkbox then automatically gets filled with all the nodes from the View.


Entity "changed" timestamp is not incremented on $entity->save() only on a form submit; feature or bug?

Pretty sure it is being updated, but it is updated to the REQUEST_TIME timestamp. If you have a long-running process or so, that will not work as expected.


How do I set up multiple sites with one database or multisite Apache configuration?

The new site vhost should be pointing to the drupal root installation where the index file lives and the entry point for all your sites, not to the site1 folder.
"DocumentRoot /var/www/multisite" this should be the same for all your sites.

With multi-site a approach you can shared modules between sites (those in all folder), have different modules per site, you can have different databases per site and share tables between them.

Your drupal sites are going to share the same code base, One drupal core for everyone.

This can be useful https://drupal.org/documentation/install/multi-site


User rights: Only create, edit and publish articles

There is no specific module for that, and it is well known problem. But if you want them to only create one content type, like Article, you don't need a module for that. You can simply go to /admin/structure/menu and add links like /node/add/page to a menu they can access.

For node listings for such users, create a view with table of titles and edit links.


Create custom block module with sorting of block content

You can do it with views + some minimal coding in your module: Make the view as you need, use a custom block to put 4 link with 4 different query arg: mysite.com/node/1?no_files=1, mysite.com/node/1?post_date=1 etc.
For the dropdown you can use ctools jump menu feature, it's a simple drupal_get_form with this parameters.

If the dropdown is ok, let's modify the view's result based on query_arg: See hook_views_query_alter.

To get how do you need to change the query, I'm used to create the same view with all different filter what I need, and put file_put_contents('/tmp/log', var_export($query)); into your _view_query_alter implementation. If all different query of views are in log, it's easy to figure out, what do you need to modify in $query.

To order your views by file attachment exists, just add a filter named Field: Your
File Attachment to the view, and use the operator Is Not Empty (NOT NULL). (As I understand, in this one case, you want to filter the query, not to sort.)

Most comment sorting need the sort criteria: Content: Comment count, Most viewed is not so exact, it depends, what do you use to tracking content viewing.


How to ajaxify webform submit in Drupal 7?

The Ajax Module works for me in Drupal 6.

For Drupal 7:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
      // see if webform_client_form_ is in the form_id
      if(strstr($form_id, 'webform_client_form_')) {
        // get the nid so we can use it in the wrapper value
        $nid = $form['#node']->nid;
        // add the ajax properties to the submit button
        $form['actions']['submit']['#ajax'] = array(
          'callback' => 'mymodule_webform_js_submit',
          'wrapper' => 'webform-client-form-' . $nid,
          'method' => 'replace',
          'effect' => 'fade',
        );
      }
    }

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {
        // first we have to load up the webform node object
        $node = node_load($form_state['values']['details']['nid']);
        // create an array up with the confirmation message, retreived from the webform node
        $confirmation = array(
          '#type' => 'markup',
          '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }


How we can have layout options at time of node creation just like we select in panels and display suite

It sounds like what you really want is something like the Paragraphs module:

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

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/

EDIT: It's not a video, but here's a good place to start with Paragraphs for Drupal 7:

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

And since you are familiar with Display Suite, you might find this to be helpful:

https://stackoverflow.com/a/40479965


How to import Image alt, titles or File description?

One way to deal with this issue is to use the ImageField Tokens module:

  The ImageField Tokens module extends the default functionality of
  Image fields adding the ability to specify default values and use node
  tokens in the Alt and Title text.

The module Token is required. After you install and enable the modules, you configure its settings in the field properties for each individual content type.


Media Wysiwyg + CKeditor. Replace inline images with custom images programmatically

The purpose of this question was to replace old node images with a default image so as to reduce disk space usage, as old nodes are not frequently visited by users.

To achieve this first you load the node using node_load function, and grab the body field:

$node = node_load($nodeID);
$body = isset($node->body[$node->language][0]) ?$node->body[$node->language][0] : array();

$text = isset($body['value']) ?  $body['value'] : $body['safe_value'];

After this you create DOMDocument object:

$doc = new DOMDocument(null, 'UTF-8');

Here, UTF-8 is for languages that are not Latin/Plain English.

$doc->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8'));

Convert your text to HTML entities following UTF-8 format.

$tags = $doc->getElementsByTagName('img');

You grab all your image tag from body.

Next, Loop through those tags:

foreach ($tags as $tag) {
// Get default Image.
$file_temp = file_get_contents($urlToDefaultImage);
// Get Image information.
$info = pathinfo($urlToDefaultImage);
// Replace if it exists.
$file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);
// Get old image fid.
$oldImage = $tag->getAttribute('data-fid');
// Remove the file info from db and server if not used by any.
$status = file_delete(file_load($oldImage)),
$tag->setAttribute('src', file_create_url($file->uri));
$tag->setAttribute('data-fid', $file->fid);
}

After looping through each img tags save the newly generated HTML.

$replacedBody = $doc->saveHTML();

Remove extra html, body and Doctype from the new body using str_replace:

$replacedBody = str_replace('', '', $replacedBody);
$replacedBody = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', '', $replacedBody);
$replacedBody = str_replace('', '', $replacedBody);

Next update the newly formated body to node object:

$node->body[$node->language][0]['value'] = html_entity_decode($replacedBody);
$node->body[$node->language][0]['safe_value'] = html_entity_decode($replacedBody);

Save the node

node_save($node);

Bonus: Updating images in node image field.

Grab the field data.

$field = !empty($node->field_{machine_name}[$node->language]) ?  $node->field_{machine_name}[$node->language] : array();

Here, {machine_name} represents the name for image field you created using Content UI.

// Loop through old images.
foreach($field as $key => $row) {

    // Check if the image
    if($row['type'] == 'image') {

        // Get default Image.
        $file_temp = file_get_contents($urlToDefaultImage);

        // Get Image information.
        $info = pathinfo($urlToDefaultImage);

        // Replace if it exists.
        $file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);

        // Change the current image with default.
        $node->field_{machine_name}[$node->language][$key] = array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uid' => $file->uid,
        'uri' => $file->uri,
        'status' => $file->status,
        'display' => 1,
        );
    }
}

Performing these operation will remove default image from your db and server and will save disk space. While we need to use file_delete function when removing files from body, it is not needed when when perform this operation while we replace on an image/media field. file_delete function will safely delete the files from server if that file is not used by any other nodes in website, if second parameter is not set to TRUE. While file_manage_delete does the same thing, though it will not lookup for database and check for its existing usage, it will simply release your disk space from that file, result in 404 not found image on other reused nodes.


Is it possible to create an installation pack in Drush make?

I have code to generate an installation profile from an existing site; it is still a work-in-progress in the issue queue here: http://drupal.org/node/1368242.  Presently it works with D7, but does not yet generate the necessary installation scripts for D6.  It still does a lot of useful work for you, though, and is a good place to start.

However, if your goal is to upgrade your D6 site to D7, what you are really looking for is Drush Site Upgrade.


How to change the query for content type in d6 to d7?

You should add a new view by the UI. Then, you can display the generated SQL query, by activating the sql display below the views UI:

admin/build/views/tools (D6)
admin/structure/views/settings (D7)

You'll see live, what the sql query is :

Copy/Paste the sql and rearrange it


Calling two namespaces for formbuilder and controller in d8

A class can only be in one namespace. There's never a scenario when a class being in two namespaces could be useful, and the language doesn't allow it.

I have no idea what you're trying to achieve, there's no mention of that in your question, so again I'll just reiterate (3rd time now!) that you should learn what namespaces are, what autoloading is, what PSR4 is, and how to use them. Otherwise you're just going to spend your time banging your head against these trivial PHP language issues, and get very little done.


Saving custom fields for nodes and users

I haven't done this with user_save() before but if it follows convention from the rest of the system (which is likely) it'll be like this:

$values = array(
  'name' => $name,
  'pass' => $password,
  'mail' => $email,
  'status'=>1,
  'field_foobar' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $field_value
      )
    )
  )
);

$newUser = user_save('', $values);

In fact there are a few examples further down the page in the user_save() docs confirming this method is the right one.


"Preview before submitting" based on user role

You have to unset the button:

unset($form['actions']['submit']);

This will delete the submit button from the array, thus it won't show up. Be carefull bacause above code will hide your submit button. You will have to check the key for the "preview" button.


Calendar Module Styling of upcoming events

In the View of the Upcoming Events, i changed the view option from HTML List to Unformatted List and the problem went away. See attached pic.


Converting Term names with special characters to Term ID's in Views

You can use pathauto to set up automatic aliases for your taxonomy terms. Pathauto will take care of invalid url characters for you when it creates the automatic aliases. Then in your view use term id as the argument. The path of your view can either be taxonomy/term/% or the autoalias you set up/%


Can I create a view that combines multiple images from single node with images from other nodes that entity reference the original node?

if you can't get it to work any other way, you could try using Views Field View to combine the two:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


How to write page.tpl.php file for bootstrap site

Use .image-responsive class in your tpl.php file on your image or link tag like that

Image

The .img-responsive class makes the image scale nicely to the parent element (resize the browser window to see the effect):

image-responsive in bootstrap


Line 693 of locale.inc is

$fd = fopen($file->uri, 'rb');

So you need to provide your file path on the uri member of the file object, instead of/in addition to filepath.

There are a bunch of different things done with that file object throughout the process you're calling, so there may be more you need to add as well.


Is it possible to exclude module settings when migrating database?

It probably is possible, but not with Backup and Migrate. BaM only enables you to exclude whole tables, and enabled / disabled status is a row.

Worse, your devel environment contains different set of scripts than production one. This may have various side effects, bugs you will only see after migrating your changes to production. That's exactly what you want to avoid, so consider other options:

Test site in environment that can connect to WWW, either by switching your dev server, or by creating dev/staging machine connected to www-enabled testers' workstations. In this latter case, you will catch if you forgot to enable something.
Store GA JavaScripts on some local place, and use hosts file or local DNS to fake traffic. It would be pretty safe to just make needed JS files available, I nothing changed recently you don't need to care about actually doing anything with data GA is trying to send to Google.


Are updates applied across multiple sites?

You need to run updatedb on each site individually.  Note that as soon as you update the shared code, any site that has not had updatedb run could show errors or otherwise fail to function.  You should therefore take all of the sites offline prior to updating the code, and bring each site back online again after updatedb completes.


I edited the database but the site's showing old content no longer in it

Have you refreshed your caches?
Configuration -> Development -> Performance -> Clear all caches


Your site doesn't look like it is bootstrapping completely. So I would suggest that you see if drush status will complete in the sites/default or sites/sitename folder. It should look something like the full output below.

A full drush status output

Drupal version                  :  7.38
Site URI                        :  sitename.com // could be http://default if you have not set your site url
Database driver                 :  mysql
Database username               :  db_user
Database name                   :  db_name
Drupal bootstrap                :  Successful
Drupal user                     :
Default theme                   :  default_theme
Administration theme            :  admin_theme
PHP executable                  :  /usr/bin/php
PHP configuration               :  /etc/php5/cli/php.ini
PHP OS                          :  Linux
Drush script                    :  /usr/local/bin/drush-master/drush.php
Drush version                   :  8.0-dev
Drush temp directory            :  /tmp
Drush configuration             :  /usr/local/bin/drush-master/drushrc.php
Drush alias files               :  /usr/local/bin/drush-master/includes/../aliases.drushrc.php
Install profile                 :  install_profile
Drupal root                     :  /var/www/html/docroot
Site path                       :  sites/default // Could be sites/sitename.com
File directory path             :  sites/default/files // Same thing here could be sites/sitename.com/files
Private file directory path     :  /vagrant/private
Temporary file directory path   :  /tmp

To help this is my alias setup I usually use

This is what I usually use to setup my complete drush alias, it has options that most do not need but it may help someone in the future setup their drush alias that they may have not known existed. If you don't use the "path-aliases" below then you need to use "default" or whatever the "sites/sitename" folder name is named. You can see this in the example alias file from drush.

$remote_sites = '/path/to/site'; // usually /var/www/drupal-root-name
$aliases['site.dev'] = array(
  'uri' => 'sitename.com',
  'remote-host' => '{ip to remote}',
  'remote-user' => '{remote ssh user}',
  'root' => $remote_sites,
  'ssh-options' => '-p {if you ssh in on another port like 2222}',
  'path-aliases' => array(
    '%drush-script' => '/root/.composer/vendor/bin/drush', // This is so you can have multiple drush installs and use different ones on different sites.
    'php'=> '/usr/local/bin/php', // Again if you have different php's for different sites.
    '%site' => 'sites/default/', // This is the important part here, it will ensure the proper bootstrap
    '%dump-dir' => '/path/to/drush.dbdumps', // This is where you want to dump your databases, normally /tmp folder I think.
    '%files' => $remote_sites . '/files' // Your sites file folder, incase it is somewhere else.
  ),
  // You may actually need this, especially if you are running D7 since I haven't ever tested the db-url thing on D7 or above.
  'databases' => array (
    'default' => array (
      'default' => array (
        'driver' => 'mysql',
        'database' => '{db_name}',
        'username' => '{db_user}',
        'password' => '{db_pass}',
      ),
    ),
  ),
);

After writing the answer I was thinking that this may be a D6 question but I answered assuming the opposite. If that is the case please let me know and I will try to answer for D6 also if there are in fact any differences. Hope this helps, thanks!


Selectively clear cache, without AdminMenu

After going through 19 pages of search results I don't think what you want exists. I'd say you need to write one yourself.

I also checked GitHub Several modules to easily clear everything...


Programmtically add image to custom image field User

In Drupal 7 you can use system_retrieve_file()

  system_retrieve_file : This function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to
  the file_managed table if you want it to be managed.

  $usr_info = user_load(334); //load user object
  if (!empty($usr_info)) {//assign only if user exist
    $image_url = 'http://g-raph.be/sites/all/themes/g_raph_/images/image03.jpg'; //image URL to save. If image already saved in the drupal system then get the file ID(fid)
    //I have used picture folder to store images using image field settings
    $file_info = system_retrieve_file($image_url, 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$usr_info->picture = file_load($file_info->fid); //for default profile pic
      $usr_info->field_profile_picture[LANGUAGE_NONE][0]['fid'] = $file_info->fid; //for custom profile pic
    }
    user_save($usr_info);
  }


Files inside the CSS folder gets automatically deleted when I clear the cache

What you are doing is dangerous. It opens a security hole in your installation. But that's your problem.

Drupal caches pre-combined css and js files in, respectively:

public://css
public://js

It's hardcoded, and you can do nothing about it. This means that if you will set public to mean your ../, Drupal will use ../css and ../js for CSS and JS caching purposes - all purposes even cache clear. For performance reasons Drupal does not care if it was this installation that created cache item when you tell it to clear it all. Why should it? Clear is clear after all.

Long story short: Don't set drupal's public:// to anything you don't want Drupal to manage. If you really have to, symlink specific directories, or write custom module to manage such uploads.


Change order (weight) of blocks before page load programatically

You can use hook_block_list_alter to achieve this. Be aware that the $block->weight attribute won't be affected at this point in the proceedings, but there are solutions in the comments to this problem.


The thing is, every Drupal site has a variable, in {variable} table, called update_last_check that stores the last time the site had a update check. This variable is mostly update by Drupal cron. It happens that, in some of my sites, this date is too small to need a new check, so Drush skipped it and considered the site up to date. So, in other words, if you want to ensure there's a new update, you should first run a drush cron and then run a drush pm-update.


Pass parameter to node twig template via url

try this in twig:

{% set url =  url('<current>')['#markup'] %}
{% set urllast =   url|split('/')|last %}
{{ urllast }}  // 3