When should the second drupal_bootstrap() parameter be used?

Without looking more closely, I can't say why statistics_exit() doesn't use the second parameter, but to answer your question...

The drupal_bootstrap() function only ever needs to be called with $new_phase = FALSE to prevent an infinite loop inside the core bootstrap code. Unless you're modifying core, you'll always want to leave the second parameter at its default value (TRUE).

The key is in this part of drupal_bootstrap():

// When not recursing, store the phase name so it's not forgotten while
// recursing.
if ($new_phase) {
  $final_phase = $phase;
}

Calls to drupal_bootstrap() outside the bootstrap process always specify the final phase to bootstrap to (or only get the current phase, in which case, the second parameter doesn't matter). When you call drupal_boostrap(), you'll be initiating the bootstrap process and setting the static $final_phase variable, so you'll need $new_phase = TRUE.


Have a look at YOUR_SITE_ROOT/includes/pager.inc

I think you are looking for the theme_pager_previous() and theme_pager_next() functions.


custom field in product type not showing in line item drupal

You added the fields to the commerce product entity (commerce_product), not the line item entity (commerce_line_item).

That is why the fields don't show on your line item entity.

The line item entity contains a product reference field (commerce_product) referencing the associated product, you will need to inspect that to get the fields from the product.

e.g:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Get product field value from line item
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  // If line item is a commerce product type
  if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
    // Fetch duration value on product.
    $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->value();
    // Get raw values
    // $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->raw();
    drupal_set_message($duration);
  }
}


if term reference is value X in tpl.php file

The above use of field_get_items('node', $node, 'field_page_type'); is going to return an array that looks like:

Array
(
    [0] => Array
        (
            [tid] => 549
        )

)

But what you want is the value of the term so you'll need to do the following:

<?php $page_type = field_view_field('node', $node, 'field_search_type');
if ($page_type['#items'][0]['taxonomy_term']->name == 'Standard') {
    print "worked";
} ?>


As an alternative to the module you are using, try the PHPExcel module. Some details about it (from its project page):

The PHPExcel module allows developers to export/import data to/from real Excel files.
The idea behind this module is to have a single module for handling the export or import of Excel files, instead of multiple modules handling specific cases.
The module provides no functionality as-is (the .module file is as good as empty). The phpexcel.inc file must be included to use the export or import functions in your own module.


How can I capture Watchdog output during a functional test?

The Watchdog to File module is handy for this use case. You can initialize it in a test setup, like so:
<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * My browser tests.
 */
class MyBrowserTest extends BrowserTestBase {

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

    $this->enableFileLogging();
  }

  /**
   * Enables logging of ALL watchdog events to a file.
   */
  protected function enableFileLogging() {
    $installer = \Drupal::service('module_installer');

    $installer->install([
      'watchdog_file',
    ]);

    $config_factory = \Drupal::configFactory();
    $config         = $config_factory->getEditable('watchdog_file.settings');

    $log_path =
      sprintf(
        '%s/artifacts/watchdog-%s.log',
        dirname(DRUPAL_ROOT),
        $this->databasePrefix
      );

    $config->set('log_filename', $log_path);
    $config->save(TRUE);
  }

}

Then, just configure GitLab CI to capture the test artifacts folder:
  artifacts:
    when: always
    reports:
      junit: artifacts/junit/*.xml
    paths:
      - artifacts/*
      - web/sites/simpletest/*

As a bonus, the above snippet also captures browser output produced by browser tests, in case you need to review them as well.
Each watchdog log will be named according to the Simple Test database ID that is used for the corresponding test run. For example, if you have five cases in your test, you should end up with five watchdog file logs.


The hook page comes from a hook_theme implementation in system.module:

/**
 * Implements hook_theme().
 */
function system_theme() {
  return array_merge(drupal_common_theme(), [
    ...

which calls the function drupal_common_theme() in theme.inc:

function drupal_common_theme() {
  return [
    // From theme.inc.
    'html' => [
      'render element' => 'html',
    ],
    'page' => [
      'render element' => 'page',
    ],
    ...

The hook name is the top key of the array in hook_theme. See the documentation in D8 Theme API. The theme suggestions are built in core the same way as in custom code.


Add something like this to your hook_form_alter() or hook_form_FORM_ID_alter():

  $form['field_address'][LANGUAGE_NONE][0]['#address']['country'] = 'US';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = 'Livermore';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = 'CA';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = '94551';


Set the menu link as disabled by default

Have a look at this module, I guess that is what you want.
http://drupal.org/project/default_menu_link
Some details from the module's project page:

Provides the user with a check box on all content types to set the "provide a menu link" value to true by default.
This is basically a nice way to ensure the menu system is adhered to by all content authors.
There is a similar module called menu_force that does just that. Whereas Menu Force mandates menu assignment, Default Menu Link merely changes the status of "Provide a Menu Link" to true. The user can still create content and choose to un-check this box. However, the default state (on node creation) will be true, and as long as you've set a default menu parent item, all content will be filed under that parent.


If you don't need to update the link tag, then just use the download attribute, it should do the trick.

I've wrote a tiny Fiddle for you https://jsfiddle.net/45ug9p7t/1/

Keep in mind that not every browser has implemented this, check it out


I have logged out and the login block is missing,how do I login back?

You can get the one time login url with drush command: drush uli;


The combination of Rules module and Cache Actions module should solve your issue.


restrict visiting user/1 path for all users except admin

You can do this in page.tpl.php

global $user;
global $base_url;
$uid=$user->uid;
if(agr(0)=='user' && arg(1)==1)
{
if($uid!=1)
{
drupal_goto($base_url);
}
}

OR

function YOURTHEMENAME_preprocess_page($vars) {
  if ($_GET['q'] == "user/1")
  {
    $usr = user_load(arg(1));
    if(!in_array('administrator',$usr->roles) ){
         drupal_goto("ANY PAGE"); //Example <front> for the homepage
    }
  }
 }

Hope this will work


How to add css using the Preprocess_image function?

Try this.

function mytheme_preprocess_image(&$variables) {
   if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'image_style') // this is an image style used in drupal's image styles {
     $variables['class']['img-responsive'][] = "true";
  }
 }
}


blocked due to MIME type (“application/octet-stream”) mismatch

Pretty sure that the scss files should be in a scss folder, and not the css folder.
/sites/all/themes/mbm/css/style.scss?qktcrf


How to access a table I inserted manually into Drupal 7 db

You shouldn't do  a query from a .tpl.php or include any php logic there. If you have to do it in the theme (this would be better in a small custom module), do it in the template.php in a preprocess function (node or page preprocess, depending on what template you want your variable available).

So you do your query in the template.php file and then through a preprocess function send the variable to your .tpl.php files.

I also don't recommend writing MySQL queries in Drupal, you should use the Drupal API for this. Drupal has a database abstraction layer that gives you lots of handy function you can use.


How to create a select list of which the selected item is used as parameter in VBO rules component?

VBO uses the core 'actions'. You can create new actions with hook_action_info.

The https://www.drupal.org/project/examples module has a good action example.


My best guess is that you haven't configured the contextual filter on author_id in views. and take it for logged users. In that case it will show the other users pages aswell


How to host and play videos in a drupal site?

Something along the lines of the Video module?

  Video module allows you to upload video in any format, play video in
  any format, transcode video to H.246, Theora, VP8 using Zencoder or
  FFMPEG automatically creates video thumbnails, stream videos from
  cloud, HTML5 videos with mobile device playback compatibility. Very
  reliable API for converting videos and auto thumbnail, embed video to
  node body using WYSIWYG module (D7 only) and many more.


views_embed_view($view_name, 'default');
// does not work because you need to print/echo the result. eg.
print views_embed_view($view_name, 'default');

views_get_view_result($view_name, 'block');
//does not work because the function returns an array (and you aren't even trying to print the array anyway)

echo views_embed_view('woensdag', $display_id = 'block')
// Trying to set a variable in a function call? It probably would have worked like this:
echo views_embed_view('woensdag', 'block')


Updating / Pushing Changes to a Views from Local to Staging Server?

If your working on an existing View and not a new one, you can just use the import View option on your server. Once you click into that page just check off the following:

Replace an existing view if one exists with the same name

It will update the existing view with what you have done on the local. On your local desktop just click on export on the view and copy and paste the code given to the server Views import page.


Exporting results with Views Data Export not working as intended

A possible alternative to consider for the fix you are looking for, is to consider an alternative module that can possibly address all of your requirements, such as the Forena module. Here are a few features of it, which seem to be part of your requirements:

Support for exposed filters (via report "parameters").
Save reports (= query results) in CSV format (CSV is one of the supported document types).
Create export view (= Write a report, e.g using the WYSIWYG report writer).
Yes or no include a pager (using the dataTables plugin via report "skins", which also implements the search box feature that dataTables offers ...).

There are many more features that come with Forena, as detailed also in its Community documentation. Refer to the demo site for some sample reports (shipped with the module), or the documentation included with the module (such as the supported document types, of which CSV is just one of them).

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


Download file from field instead of going to node page

You could make a custom module and put this function in it

/**
 * Implements hook_node_view().
 */
function custom_tweaks_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'arquivo' && $view_mode == 'full') {
    $file = $node->field_file[$langcode][0]['uri'];
    if ($file) {
      $file_uri = file_create_url($file);
      drupal_goto($file_uri);
    }
  }
}


How can I add the Schema.org type 'BreadcrumbList'?

function yourtheme_breadcrumb($variables) {
  $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']);
  }
  else {
    return t("Home");
  }
}


Facet pages bring site down because of bots

For example, my facet page path starts with /library.  I created a Firewall rule in Cloudflare to block anyone visiting a page that contains /library/ so a facet result page like /library/xxx/bbb/ccc and is a known bot will be blocked.


I would suggest you to use Panels and Views modules and optionally Profile2.

You will add some fields to user account or to the user profile if you installed Profile2. Then enable the 'User profile template' page under admin/structure/pages and add a panel variant, select a layout and place the content or fields. If you have Profile2, then you need to add it as a relationship 'Profile2 from user' under the 'Contexts' menu of the panel page. I'm not going into details about how to use panels.

To display the summary of user's recent activity, you should setup a view with a contextual filter of user id, preferably a 'Content pane' display, then you need to place this content pane into you user panel.

It is not a great secret how to build a user profile page, but it's completely dependent of what you want to have. If you have any difficulties implementing the steps I wrote, you can update your question or post another more specific question.


How can I avoid this markup is filtered out from my block?

I've had the same issue with CKEditor removing classes in the past, Full HTML is not the issue.

Add the below code to the end of your CKEditors config.js file, which is found within the CKEditor library code.

CKEDITOR.config.allowedContent = true;

You might find that the file is called ckeditor.config.js and that this is the file that needs to be changed rather than the default config.js. This file can be found in the root of the CKEditor module.


Add fix amount to all orders as packaging price

I think you should check this module commerce fees maybe help you


Possible to manage display of Profile2 profile fieldset on user registration

It's a while since I used panels for this, but I'm quite sure you can use panels, and enable the panels page for the user/%user/edit page. Then create a new variant for this page and rearrange the elements through the content section as you would for a front-end panel. If you're not already using panels for other aspects of your site, you may want to try Display Suite, which I've never tried out. Choose the one that works best for your needs and stick with it to avoid module bloat.


Should we use a separated database for our data set?

Talk to your hosting provider. If they can't answer these questions, get a new hosting provider.

These really are concerns you should bring to your hosting provider. A quality hosting provider will be able to meet these needs and tailor a solution that ensures smooth operation of a site as a whole and within the individual components: Solr, MySQL, Apache/Nginx/Litespeed/etc.

How will they do this?

Benchmarking - Before launch, they'll launch a version of the site and then work to ensure that certain performance criteria are met. They'll tweak and scale to meet these numbers.
Infrastructure - Just having a master/slave DB isn't necessarily a solution. You have to have good infrastructure and equipment backing it up. It also has to be architected well. Good providers will have this.
Multiple Layers of Scalability - Having multiple strategies to handle load or large sites is key. This means not just having a huge DB but also effective content distribution (CDN) and internal Drupal caching (Redis) in addition to strong infrastructure.


This module Code Per Node will make things alot easier for you.

Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.


How can I limit and show only the first referenced node per node in a view?

I can suggest you one solution which will probably help you with performance.

You can make use of views field view module.

You can use the view which you have created to render the fields of content type A and now create a separate view (as block) of content type B with current node ID as contextual filter and required relationship for the reference field and set limit to 1 or use delta as filter and call this view as field in the view in which you have rendered content type A fields.

EDIT: Second view can be called conditionaly wherever required, so is more handy if you require it only once in the parent view (by result count or once in header) OR get rendered it with every result of parent view.


Why can't I access my custom fields in Rules?

You're not looking for the field on the entity you've added it. You added it to the product, so in addition to your "Entity is of type" on the line item, then you need to check the type of the commerce-line-item:commerce-product for whatever product type you're expecting to find the weight field on. Only then will Rules know that that product has that field.


How to conditionally send emails Drupal 8 Webform

The latest dev release of Webform 8.x-5.x supports conditional emails and handlers.


Way to show changes to a particular node to users

You could try Revisioning (integrates with Diff) for both Drupal 7, and Drupal 6.

  Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You use it in scenario's like this:

  Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
  We shouldn't have to grant these roles “god-like” powers (e.g. Drupal 6's "administer nodes" permission) to implement this.


Perform a query with an entity field condition with multiple values

Use two separate andConditionGroup():

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'custom_type');
$and = $query->andConditionGroup();
$and->condition('custom_taxonomy', 2);
$query->condition($and);
$and = $query->andConditionGroup();
$and->condition('custom_taxonomy', 8);
$query->condition($and);
$result = $query->execute();

This works no matter how many terms are in the field or in which delta they are.

Edit

This results in this SQL:

SELECT base_table.vid AS vid, base_table.nid AS nid
FROM
{node} base_table
INNER JOIN {node_field_data} node_field_data ON node_field_data.nid = base_table.nid
INNER JOIN {node__custom_taxonomy} node__custom_taxonomy ON node__custom_taxonomy.entity_id = base_table.nid
INNER JOIN {node__custom_taxonomy} node__custom_taxonomy_2 ON node__custom_taxonomy_2.entity_id = base_table.nid
WHERE  (node_field_data.status = '1') AND (node_field_data.type = 'custom_type') AND( (node__custom_taxonomy.custom_taxonomy_target_id = '2') )AND( (node__custom_taxonomy_2.custom_taxonomy_target_id = '8') )


Can you tag individual searches per search in order to apply different filters to each?

I found a solution that worked for me. Here it is in case anyone else wants to do something similar, or in case someone wants to suggest a better way of doing it!

So the situation is that for a single page, I need to run a handful of SOLR queries to determine what should show up and what should not. Each of those queries works on different fields, so we need to be able to add a different 'qf' parameter to each of them. This gets harder however, when all hook_apachesolr_query_alter calls trigger on all searches! (See the related issue about enabling 'qf' #1659184: Allow apachesolr_search_search_results() to accept 'qf' (query fields) parameter)

After a lot of experimentation I found that the only field I could manipulate when starting a query and fetch and act on in hook_apachesolr_query_alter was using the search path value in a custom $search_page. This is how I did it:

<?php
$search_page = array(
        'env_id'   => 'solr_server',
        'settings' => array(
          'apachesolr_search_per_page' => 25,
          'spellcheck' => FALSE,
        ),
        'search_path' => 'ducks-BiGhE3Nxv34lyTKVoka74WI3r9yjJyc5ohiuJkeCiqp8gJunyWk3gXMDK8W',
      );

      $search_terms = array('"duck"', '"cheese sauce"');

      // Only run if the solr is enabled server environment is detected.
      if (module_exists('apachesolr') && apachesolr_environment_load($search_page['env_id'])) {
        $results = apachesolr_search_search_results('"' . implode(' ', $search_terms). '"', NULL, $search_page);
?>

Then, in hook_apachesolr_query_alter for this particular module/query:

<?php
function pet_or_dinner_apachesolr_query_alter($query) {
  /* test that this is a 'ducks' query */
  if (stristr($query->getPath(), 'ducks')){
    /* now apply different settings depending on the current page */
    $node = menu_get_object();
    if (isset($node->type) && $node->type == 'pets') {
      //Search only the Pet field
      $query->replaceParam('qf', 'sm_vid_pet');
    } elseif (isset($node->type) && $node->type == 'meals') {
      //Search only the Meal field
      $query->replaceParam('qf', 'sm_vid_meal');
    }
  }
}
?>

I don't know if it's necessary, but I put the extra long random string in the 'search_path' so that I didn't have any site visitors accidentally tripping over it. I don't think it is publicly accessible though. Someone else can confirm or debunk that concept!

But there we go, a hook to be able to perform custom modifications on concurrent queries. Definitely not clean but it gets us over the line!

I'll leave this question open in case someone has a better answer.


How can we manually enter a payment using their credit card information for a customer in Commerce?

Create the order in the admin UI and add the user as the first step of creating the order.
Save the order.
Go to People and then edit the user you just created.  Add payment info.
Then add shipping info in the orders > shipments tab (if you have a shippable product).
Then go to Orders > Payments and you should be able to add the payment that you just added and make the charge (if cc).
Then edit the order and place the order.

Maybe there is an easier way to do this but so far these are the bizarre steps I am going through.


Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column

On Drupal 6 running CCK, the database field names are different from the CCK field names.

In my test site running Drupal 6, I created the following CCK fields:

field_code_page (text)
field_co_author (user reference)
field_book_list (node reference)

The database table created from CCK for the content type containing those fields has the following database fields:

field_code_page_value
field_co_author_uid
field_book_list_nid

It is rather probable the database field is named ctp.field_titul_pred_jmenem_value. To be sure, you should check the database table, as the database field could have a different name, basing on the type of the CCK field.


New Relic: "Application Code (in /theme)"

New Relic offers Drupal monitoring as part of their paid Standard plan to collect metrics for Modules, Hooks, and Views.

  The collection of Drupal-specific metrics can be
  controlled by the ini setting newrelic.framework.drupal.modules. It is
  enabled by default (in versions 3.0 and higher), and can be disabled
  with:

  newrelic.framework.drupal.modules = 0 Though this setting uses the
  word "modules", it controls the collection of all Drupal metrics:
  modules, views, and hooks.

  The PHP agent collects metrics for the following:

  Modules: Versions 2.5+. These metrics indicate time spent within each
  Drupal module. In versions 3.5+, time is calculated from the hook
  dispatch functions module_invoke and module_invoke_all. In previous
  versions, time was calculated from functions from a file with the
  ".module" extension where the file name and function prefix were a
  match.
  Hooks: Versions 3.5+. These metrics indicate time spent within
  each Drupal hook. Time is calculated from the hook dispatch functions
  module_invoke and module_invoke_all.
  Views: Versions 3.5+. These
  metrics indicate time spent within a view's view::execute method.

You are correct that New Relic: “Application Code (in /theme)” refers to the execution of the theme() function.  Given the throughput you referenced, this seems to be a minor issue, though there is definitely room for optimization if you're seeing ~7000ms response time.  I typically see around 400-500ms with similar throughput.


Loading css style present in DOM of another node

I have a related content section on my page through views in which i
want one field to be a div with a background-image.

Ok, then you can use Image URL Formatter. Which will output your image as a url instead of the actual image.
Then add the image field, which contains the image you want to use as background

Hide it from display.
Select image url as your formatter

Add a custom field OR Rewrite the result of an existing field and use the image replacement pattern.
ex
OR if you create a .html.twig template file for your view, then you can use

Another option
In Style settings you can add a class to your fields.
[
Then with css give it a z-index: 0; and give everything else z-index: 1; and move img around by giving it position: absolute; top: -100px; etc..


Is it possible to make a custom facet that behaves like a Views grouped filter?

Based on this article, I was able to do this with the following code:

/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_nat'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Nationality'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_nat_getter_callback',
  );
}

/*
 * Getter callback for agg nationality property.
 */
function MYMODULE_search_agg_nat_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  $nationality = $account->field_gen_nationality['und'][0]['iso2'];
  switch ($nationality) {
    case 'JP':
      return 'ja';
    break;
    default:
      return 'en';
    break;
  }
}


Problem with Three hierarchical dropdown for country, state city

I was facing the similar issue in my drupal site.
The other issue was the performance especially for IE where it took too much time in rendering the new item.

After some experiments, I made the following module that can help in making three hierarchical dropdown for country state and city. Its developed in a generic way that it can be used for n number of dependent dropdowns and can be used for other dependent data as well.

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


How to programmatically set a value to a node attribute

Actually very straight forward, here is how i have done it:

$group = node_load ( $nid );
$group-> foo = 'bar';
node_save ($group);

That's it.

Hope that' ll help anyone.


Custom content entity: can't hide translation details in edit form

The translation field that you try to disable is not the one containing the metadata.

The translation metadata is generated in Drupal\content_translation\ContentTranslationHandler and is automatically applied if following access check is true:

'#access' => $this->getTranslationAccess($entity, $new_translation ? 'create' : 'update')->isAllowed(),

To solve this problem you can add a checkbox to your entity settings form that allows you to disable the translation.

You will also need to create a custom TranslationHandler for you entity.

In the annotations of your entity add this under handlers:

"translation" = "Drupal\MY_MODULE\MyEntityTranslationHandler",

Your custom translation handler can then be something like this:

namespace Drupal\MY_MODULE;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

class MyEntityTranslationHandler extends ContentTranslationHandler {

  public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
    $form = parent::entityFormAlter($form, $form_state, $entity);
    if (// Some condition...) {
      $form['content_translation']['#access'] = FALSE;
    }
  }

}

Hope it makes sense.


If you know any php I recommend the Migrate module to easily write a SELECT title, body FROM old_content and map them to Title and Body fields of a Drupal Page type. You would do this with a Migration class. See documentation on the project page.

You could also try the Feeds project.

There are modules for Migrate to migrate from Wordpress or older Drupal sites. You could use that as example migrations to move content, menus, etc into a new drupal site.

I've migrated pages, and custom Joomla content for courses and instructor content into Drupal content types .... but every migration use-case is always unique; I'm just recommending tools I've used.


How to send one time login url with Rules?

Try out Login one time module

  The use case for this is where your users can't figure out how to use
  a username and password - so they request an email link to what they
  need.


Drupal javascript file loading and jQuery

By the docs You should wrap your code that way:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery);

What's wrong with other methods? Nothing fundamental, only Drupal's own scripts are not tested to work with them, and redefining $ globally may interfere with non-jQuery libraries some modules use, rendering either their or yours code not working.

For "jQuery is not defined", there are couple of possible problems. My surest bet was to skip drupal_add_js() altogether. Unconditional module (or theme) scripts can be added in info files:

scripts[] = somescript.js

and form related ones can be added directly to a form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/js/a.js',
  drupal_get_path('module', 'mymodule') . '/js/b.js',
);

I prefer to leave conditions in javascript itself, it means I only need one aggregated file for all pages on my site (plus one per form), so this is a performance boost in addition to problem prevention.


How to display a node field value in a template file?

Duplicate node.tpl.php and rename it node--article.tpl.php and then it's just:

print render($content['field_custom_field']);

If you really want to stay on the page level you better use page--node--article.php and then you need to get hold of the $node object first somehow. Maybe take a look at Clive's answer here: https://drupal.stackexchange.com/a/32310/15055


Views are available through configuration in Drupal 8, and can be exported via the Configuration Management interface.

In the admin menu select "Configuration" in the DEVELOPMENT section, select "Configuration synchronization":

In that menu area, the Export tab leads to the path:
http://sitename/admin/config/development/configuration/single/export

In that area, a single view can be exported or imported, and the steps are about the same so I'll include Export here to help explain.

Select 'Export' menu tab.
Select 'Single item' sub menu tab.
From the first item drop down 'Configuration type' select 'View'.
From the second item drop down 'Configuration name' select the name of your view.

The result is a views.view.view_machine_name.yml "YAML" file that can be copy pasted into the 'Import' area.


How can I insert into table a row which contains an auto incremented field?

The problem is you are using the keyword GROUP as a column name. Drupal's PDO code doesn't always escape column names, so you should avoid using MySQL keywords.

See the MySQL documentation.

  Most of the reserved words in the table are forbidden by standard SQL as column or table names (for example, GROUP).


Drupal can handle multiple sites very well. In a raw way without any modules you can use the multisite features of drupal. This can be done by creating submodules under sites for each of the sites.

When it comes to modules there are couple of them that deals with subdomains and multiple sites.

Virtual Sites
This kind of automates the Multisite configuration for drupal. You can create additional domains and subdomains.
Subdomain
This one is mainly used to create a subdomain and place contents under that subdomains. For example all contents of a group can be placed under the groups subdomain.
Domain Access
Domain access is used in scenarios where you want to share contents between your domains and subdomains. You can assign contents specific to a domain or have the same content appear in multiple domains. Assign admins per domain etc. This is used for affiliates sites. A use case would be a main rental site with subdomains for each city.
Aegir
This is not a module. This is a complete hosting solution build for drupal. This is a hosting profile. You would install it on a dedicated or virtual servers. You can create multiple sites from with in Aegir some thing similar to what you do on a reseller control panel. If you want to restrict the subdomains to a single domain then you can use the module Hosting Subdomains

So it ultimately depends on your use case.


You define an entity type in a class. Either a content or a config entity. Content entities can have bundles. These are defined in config entities (you need a separate class for this). Like all config entities bundles
can be exported and imported in yaml files.

An example for a content entity type is Node. The node bundle is called Content Type. Internally Drupal uses node_type as machine name, which makes it clear that this is only used for nodes.


Thanks everyone.

What I was able to do was build a Rule with Form Events that sets the 'Post to Facebook' checkbox (and one for Twitter) if the current page URL matches the node edit URL.  This way only the creation of a node, and not subsequent edits, are posted to FB...

I was initially going to do a hook_form_alter, but once the initial Rules test worked I figured I would go with it.

Rule Export >>

{ "rules_form_alter_post_to_fb" : {
    "LABEL" : "Form Alter - Article Post to FB and Twitter",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_forms" ],
    "ON" : { "rules_forms_article_node_form_form_built" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "http:\/\/www.example.com\/node\/add\/article"
        }
      }
    ],
    "DO" : [
      { "rules_forms_set_default" : {
          "form" : [ "form" ],
          "element" : "checkbox:fb_stream:fb_stream_do_post",
          "value" : 1
        }
      },
      { "rules_forms_set_default" : { "form" : [ "form" ], "element" : "checkbox:twitter:post", "value" : 1 } }
    ]
  }
}


Most drupal pagers work by setting a ?page=XX in the url. So a simple solution would be to set the url to mimic that, entering the number entered by the user in the url.

This might break if the pager argument in the url changes (like if you have multiple pagers on a single page etc), but this might cover your needs.


The internationalization collection will allow you to offer full language support for the user in the form of variables and all sorts so it is more feature full than the solution you linked.


You need to add an exposed filter to the view for the category field. Under the advanced settings in views you can select to display filters as a block so that you can place it above the search block.


You likely need to save the line item before adding it to the order. The order total should be recomputed for you automatically on save.


Drupal Commerce: IPN received - When order paid in full not triggered

It randomly started working. Here's what I did to debug in-case it helps someone else:

IPN only works on a live server not a localhost. Paypal can't talk to localhost.

Debug on Drupal Side - In Payment Rules

Enable Log notifications with the full IPN during validation and processing (used for debugging).

It'll get stored at example.com/admin/reports/dblogs. You can see a sample IPN in my post.

I was originally getting the IPN in a log that looked like:

commerce_paypal_wps  |  1 Oct 2013 - 12:48am  | Customer returned from PayPal with the following POST...  |   username

That log contained the IPN in my original post.

Paypal Settings

You don't need to enable IPN notifications because the module does it automatically when it needs to. But if you do then you can view your history and see if they were getting sent. (I put example.com in the PayPal URL field.)

The only thing I did here was try re-sending an IPN.

What you should have

When it works your log should have something like this in it

commerce_paypal      |  1 Oct 2013 - 11:46am  |  Attempting to process IPN 7Y390707M1183591C. Array...   |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN validated for Order 21 with ID 7Y390707M1183591C...  |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN processed for Order 21 with ID 7Y390707M1183591C.    |  Anonymous (not verified)


Creating a view of relation fields limited to the relations that a currently viewed node is an endpoint of

Instead of creating a view of relations, you should create a view of candidate nodes. Then you can use a contextual filter to limit the results of the view to the candidate node you are currently viewing. The fields of the relation can then be added via a relationship.

Create a view of content of type candidate, for example located at node/%/info; then under the Advanced settings of the view add a contextual filter with Provide a default value: Content ID from URL (i.e. the candidate node id) as the argument. You can use the same setting when the argument is provided by EVA instead of via the URL, with the default configuration of Use the ID of the entity the view is attached to (but the first example is useful to understand where the argument comes from).

Now in order to get the relevant Relation fields displayed, under Advanced add a relationship using Content: Relation: <your relation label> (node → relation).

Under Fields you can now add the desired Relation fields, specifying that it should use the relationship you just added.

Note the difference between relationship (≈ SQL table join) and relation.


How do I create a route to a raw text file

There might be a clever solution for this, but a simple straight forward solution would be to:

Make a Controller and use that in your routes.
In the method on the controller, load the contents of the file (or just hardcopy it into your controller method)
Return a JSON response in your controller.

I haven't gone into details on how to code this, there are plenty of code examples and documentation on this on drupal.org


It is coming from includes/bootstrap.inc:

/**
 * Indicates that the item should be removed at the next general cache wipe.
 */
define('CACHE_TEMPORARY', -1);

Which is also defined in the docblock for cache_set($cid, $data, $bin, $expire):

  $expire: One of the following values:
   - CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
   - CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
   - A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.


The feed was expecting a node id and I was delivering a text value. I replaced the text value for node id corresponding in the CSV file and it works. I had to looking for node id value using phpmyadmin.


What happens when two files with the same name are uploaded?

It will rename the second file for you. If dogs.png exists, Drupal will try dogs_0.png, dogs_1.png and so on, until it finds an unused filename.

The behaviour comes from the $replace parameter to file_save_data(), which can be one of the following:

FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with the destination name exists then its database entry will be updated. If no database entry is found then a new one will be created.
FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique.
FILE_EXISTS_ERROR - Do nothing and return FALSE.

The default is FILE_EXISTS_RENAME, which is used for managed file form elements like the user profile picture, and file field widgets too.


Autocomplete on multiple fields Entity Reference

You can use the functionality Views: Filter by an entity reference view that comes with the Entity Reference module to search on more fields.

To use this functionality you need to change Entity selection mode to Views: Filter by an entity reference view instead of Simple (with optional filter by bundle) on the settings for your entity reference field.

First off you need to setup a View that lists your product nodes. Then add a display of the type Entity Reference.

You can exclude the field cnk from display but add it as a search field to the settings for the Format "Entity Reference List". If you don't exclude the field cnk from display it will show content from the field in the autocomplete widget.

No go back to the entity reference field and choose the view you just created under the settings for Views: Filter by an entity reference view.


Displaying all the entity reference entities in a view

I think you will need to create a view of image entities, rather than nodes. The use a reverse relationship with the node that references it as a filter.


How to use fields of a flag instead of only toggling the flag?

When configuring flag(s) (using the Flag module), you can indeed attach fields to them. However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.


How do I use an OR condition in an exposed filter?

You can make view filter with OR condition by clicking on And/Or, Rearrange link.


Mismatched entity and/or field definitions for comment field

drush entity-updates (aka drush entup) has been deprecated as of Drupal 8.7.0. You either need to write an update script using hook_update_N(), or you can use the Devel Entity Updates module, which does the same thing as drush entup did previous to 8.7.0.


Trying to add CSS to certain pages using a custom module in 7.x

To add CSS to node edit pages you can use hook_form_alter. Then check the $form_id to localize changes to desired node form(s) and add your call to drupal_add_css().

Example:

function admincss_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "xxx") {
    drupal_add_css(drupal_get_path('module', 'admincss') . '/css/admincss.css');
  }
}

hook_preprocess_html() Is used to preprocess variables for the html.tpl.php file.


retrieving values from a database in drupal 7

$select = db_select('registered_users', 'c')
->condition('c.fieldname', $id)  //try the condition if u have anything
->fields('c');

$result = $select->execute();
if($result->rowCount() == 0) return false;

$val = $result->fetch();

for sorting try asc or desc followed by the condition
you can get the answer in google itself


Checkbox value always 0 in custom submit handler

try this, it is work with me just change name to item_specifics
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['item_specifics'] = [
      '#type' => 'checkbox',
      '#title' => t('Sync item specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        // 'id' => 'select-colour',
        'name' => 'item_specifics',
      ]
    ];

    $form['fieldset_item_specifics'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Item Specifics'),
      '#attributes' => [
        //define static name and id so we can easier select it
        'class' => ['form-wrapper', 'js-form-wrapper'],
      ],
      '#states' => [
        //show this textfield only if the radio 'other' is selected above
        'visible' => [
          //don't mistake :input for the type of field. You'll always use
          //:input here, no matter whether your source is a select, radio or checkbox element.
          ':input[name="item_specifics"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Sync'),
    ];

    return $form;
  }

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

    dpm($form_state->getValue('item_specifics'));

  }

}


How can get access to field's data of plugin block in twig template?

you can use markup render arrays like this:

 public function build() {
    $build = [];

    $build['LinkA_url'] = ['#markup' => $this->configuration['LinkA_url']];
    $build['LinkB_url'] = ['#markup' => $this->configuration['LinkB_url']];

    return $build;
  }

Then in your twig:

link 1

link 2

then add hook_theme in your .module file:

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return array(
    'block__my_module' => array(
      'base hook' => 'block'
    ),
  );
}

Otherwise, it won't look in your module's templates folder.


How to create a form, using a function, located inside a class

You can use the form callbacks provided by the entity module. So for your example (assuming your entity_type is named 'transaction') you would call drupal_get_form like so:

drupal_get_form('entity_ui_overview_form', 'transaction');

You can find other Entity UI form related functions here.


In simple words please, what is the "Rendered file" image-format?

Since Drupal 7 Images can be rendered the same way as any other entity. Images are a special case of a file and file is a fieldable entity.

Fields can be added to the entity and how the fields are displayed can be configured here:

admin/structure/file-types/manage/image/display

But most times you don't want a rendered file, but a resized image. That is provided by the module "image" in core and if enabled you can configure image styles and use this in node displays and views.


How to migrate user passwords from D6 to D7 site using salt module?

It is not possible - both Drupal version stores user passwords in a way that was considered pretty secure when the major version was released. But these ways are incompatible. And by design you cannot recover passwords - it's a one way algorithm. Well, there are ways to hack passwords from D6 now (that's why it was changed in D7) but they are CPU-intensive, and in some countries attempts are outright illegal.

The best you can do is to use _user_mail_notify($op, $account, $language = NULL) - Set $op to 'password_reset' and call it inside foreach over all accounts after migration. That way all users will get an email saying they need to reset their password, with one-time link to do that. Probably there is already a module for that, too, but I couldn't find it.


Make sure you're installing a current version of Drupal 7, that error appears to have been fixed in an earlier version.

https://drupal.org/node/1622886


So I found a solution that works...of course if there's another or better way, I'd love to know.

I added this to my form:

  if (!empty($form_state['nnjob_mtbf']['mtbf_results'])) {
    $form['result'] = array(
      '#markup' => $form_state['nnjob_mtbf']['mtbf_results'],
    );
  }

And then to my form submit handler:

  $form_state['nnjob_mtbf']['mtbf_results'] = theme('nnreport_client_perf_report', array('parameters' => $submission));
  $form_state['rebuild']=TRUE;

And voila, template loads like a champ.


How to print multi-value link image CCK field in template?

You should be able to use the l() function (link function) to print out your link.

Typically, l() is used with the arguments l("My link text", $path), however, the first argument doesn't have to be text and can be just html.  You just have to specify that with the optional $options array argument at the end if you're including html.  :-)

Here is more documentation on using l(): http://api.drupal.org/api/drupal/includes!common.inc/function/l/7  The 6 & 7 versions should work similarly.

In your case, you can build your link like this:

Your first argument will be an image, rather than text as the link
Your second argument will be the path you want the image to link to, which should be $image['filepath']
Your third argument should specify that the first argument is html, and not just text

So, try something like:

<?php
print l(
    theme_imagecache('my image cache preset name', $image['filepath']),
    $image['data']['url'],
    array(
          'attributes' => array(   // Sample attributes you can apply to your anchor tag
            'id' => 'your-link-id',
            'class' => 'your-link-class',
            'target' => '_blank',  // open link in new window.
          ),
        'html' => true,
    )
);
?>

I haven't tested this yet, as I don't have a Drupal 6 site handy, but this should work.  Let us know if it works or if it needs some tweaking...


Ability for user to flag or select multiple nodes from view listing

Here is a solution with webform and flags:

1. Create a small module.
You can create a very simple module for it - an info file and a module file with your functions. https://drupal.org/node/1074360

2. Implement hook_webform_submission_presave().
This will intercept the form data on the webform submission form submission form before it gets saved in the database.

3. Get the flags that the current user flagged with flag_get_user_flags().
You will receive an array of flags, that you can process as you like, add to form results array for later use, or, if you have a hidden text area called 'flags' in your form, insert that data there as a formatted text.

So, in totality, it will be something like this:

function leadflag_webform_submission_presave($node, &$submission) {
  $nodes_list = '';
  $title = '';
  // Get the flags.
  $flags = flag_get_user_flags('node');
  // Get the nodes.
  if (!empty($flags)) {
    $flags = $flags['flag_name'];
    foreach ($flags as $flag) {
        $nid = $flag->entity_id;
      // Get node data. Delete to not get node titles.
      $node = node_load($nid);
      $title = $node->title;
      // Combine data.
      $nodes_list .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = $nodes_list;
}

This function gets flagged nodes and populates the webform component 4 with node/nids and titles, like this:

node/10 Node Title of node 10,
node/21 Node Title of node 21, etc

The function gets the flags and puts them in form component 4. You need to hover your mouse over your textarea component edit link on the webform components edit page to see what component number it actually is, in the edit link url. Replace the component number in code with your actual component number.

There is a section (lines 13-15), that loads nodes to get their titles. Doing node loads is somewhat an expensive function. It's Ok unless you expect dozens of submissions per minute though. But to not have node_loads, and to only have a list like 'node/10, node/15' without titles, you can delete these lines.


How can I hide the authoring information?

Try to disable this information in content type settings.


Dependency injection not working custom form

I accidentally declared the $custom_manager property of my class as private instead of protected, and that's why I was unable to access the custom manager object in the form submission method. Whoops!

MPD's answer is theoretically correct though, as class requiring to access services do need to implement the ContainerInjectionInterface class.

Worth noting though that the class FormBase which we're extending, already implements ContainerInjectionInterface, so we don't need to explicitly do so when creating a custom form.


Mathjax module does not render on edit ckeditor

Assuming you are using D7, it seems like the solution is in this MathJax issue.  Requires some patching / adding plug-ins to ckeditor.


how to pass the query parameters as default values in buildForm?

there might be a better method as suggested in the comments.
I replaced

    $params = drupal_get_query_parameters();

by

    $params=\Drupal::request()->query->all();


Image style scale and crop not formatting right

In addition to this code. Try using this

function mymodule_image_default_styles() {
  $styles = array();

  $styles['mymodule_thumb'] = array(
    'label' => 'MyModule Thumbnail',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 200,
          'upscale' => 1,
          'height' => 200,
        ),
        'weight' => 0,
      ),
      array(
        'name' => 'image_crop',
        'data' => array(
          'width' => 210,
          'height' => 210
        ),
      )
    ),
    'name' => 'mymodule_thumb',
    'storage' => IMAGE_STORAGE_NORMAL
  );
  return $styles;
}

Hope it works!


White screen after installing on Ubuntu 15.04

I think that this error is recoverable if you drop the cache_config table because cache tables are created dynamically at run time if they do not exist when using a database backend.

Like Brady suggested there may be a bug in the Drupal installer where that table was not created correctly. To dig more into this bug, if you're interested, you would need to look at the MySQL log to see what happened and try to reproduce it.


Cell Phone Validation field using sms message

You don't want to create this yourself. You want to use the relatively new Two-Factor Authentication Module and it's plugins -- or create your own plugin.

  Second-factor authentication for Drupal sites. Drupal provides
  authentication via something you know -- a username and password while
  TFA module adds a second step of authentication with a check for
  something you have -- such as a code sent to (or generated by) your
  mobile phone.

  TFA is a base module for providing two-factor authentication for your
  Drupal site. As a base module, TFA handles the work of integrating
  with Drupal, providing flexible and well tested interfaces to enable
  your choice of various two-factor authentication solutions like
  Time-based One Time Passwords (TOTP), SMS-delivered codes,
  pre-generated codes, or integrations with third-party services like
  Authy, Duo and others.

  Features

  Pluggable - Supports multiple methods of 2nd factor verification and
  can work with any number of 3rd party systems
  Configurable - Supports fallback methods and context-specific exceptions
  Flood control and even secures one-time logins
  Tested - Over 100 tests

  TFA module is recommended as a full suite solution to 2nd factor authentication and Drupal.

  See the TFA basic plugins for a TOTP plugin that works with FreeOTP,
  Google Authenticator, Authy, and any other app that works with TOTP
  tokens.

  This module stores some sensitive data which it encrypts using the php
  mcrypt library. You will need to have the mcrypt extension installed
  to use the module.

This module is designed to allow you to meet your use-case (some custom code may be required). It's also designed with fallbacks and edge-cases taken into consideration which you may not have thought of -- and it has a zillion tests.


Custom content entity field widget. This value should not be null

I managed to get it working by extending the OptionsButtonsWidget class instead of OptionsWidgetBase. I've also added the multiple_values annotation which I was missing and also removed the validation callback I was supplying, so now the validateElement method from OptionsWidgetBase is the validation handler used. My widget class just extends OptionsButtonsWidget and works fine. I think the missing annotation was the main reason it wouldn't validate.


You did not specify if this is a block view or a page view.

If it's a page view, you have to use /something/% as your path.

1) Add your field in question as a contextual filter. (I used title as an example)

2) Use Provide a default value

Raw Value from URL
Path is 1 assuming its yourwebsite.com/####. Path is 2 if yourwebsite.com/something/####


Why don't links use https:// when I access the site using that protocol?

I had a similar problem and ended up using $base_url = ''. It fixes the problem with static content. Drupal will generate relative URLs instead of absolute which is the right thing to do anyway. However, this breaks update.php for some reasons (running 7.38).


How big is the file? The error msg says you likely exceeded the 64MB limit. Can you upload a 1MB file?

If you can upload a 1MB file, then your solution is going to be to increase the server limits on max upload size (see your php.ini file) to allow files of the required size to be uploaded.


Should I call a function to query the database in a custom content type template?

I believe that depends on what you're doing with your query. According to this Drupal.org community doc you should "refrain from having complex logic in" .tpl files and "for all the conditional logic and data processing of the output, there is the template.php file". IOW template files are for theming/output manipulation while other functions or logic should go into your custom module. So if your query is part of a theming process, yes it should be in your template file. Otherwise in your custom module.

AFAIK other developers will not be looking for a non-theming function in a template, which is why I think the senior dev suggested that.


How can I re-Install a site I pulled in from a git repo?

If you see "it works", Apache hasn't recognised index.php - either you are being served files from the wrong directory, or Apache isn't configured to use index.php as the default file in a directory. You can test the latter readily: http://dev.foo.com/index.php will show the correct page while http://dev.foo.com/ will display "It works".
mysqldump, backup and restore, PHPMyAdmin ... whatever tools you have available.
Yes, you need a working DB locally to install Drupal. And you need the values in settings.php to work to load your existing DB.


When you define a widget form, you can change it from another module with hook_field_widget_form_alter(), which requires Drupal 7.8 or higher.

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}


The main functionality of maintenance mode is that it allows the site to use the theme system without requiring the database.

It does almost exactly what you had guessed, it locks out all users that do not have the 'use site in maintenance mode' permissions or administrator roles.  A site in maintenance mode will use a different template file than the live site, normally maintenance-page.tpl.php.

Maintenance mode also kicks in in other situations:

Site installation
Updates
Any time the database fails


It is very easy! where do you want to display the field?

If it is a view, then you can use template_preprocess_views_view if it is a node, you can use hook_preprocess_node function to alter the values. where your content is going to be displayed?


Commerce Node Checkout free option skip cart/checkout/payment

You can write a custom module that implements hook_node_submit() and that sets

$form_state['values']['commerce_node_checkout_skip'] = True;

if the free version is selected.


Create a non admin area form to update user form

Look at the Drupal core user module, is generates the forms for account editing. Specifically, user_profile_form(), user_account_form(), & user_profile_form_submit() will give you an example of an user-accessible form that updates a user account.


How can I add JavaScript only on the front page?

One way, in your mytheme.theme file:

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(&$attachments) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $attachments['#attached']['library'][] = 'mytheme/library-name';
  }
}

This points to an entry in your mytheme.libraries.yml file which list out what file(s) to load.


Difficulties with the #ajax form item attribute

Since 'foo-wrapper' is replaced at the first call, it doesn't exist in the second call, and therefore, the callback doesn't know where to put the return value.

A simple solution would be to include a wrapper in the return value, with the same id as 'foo-wrapper'.

function foo_get_js($form, $form_state) {
  return '
' . mktime() . '<xmp>' . print_r($form_state['values'], true) . '</xmp>
';
}

Please note that this is untested.


How to generate different image styles at upload?

Ah yes, you are right.

  Image derivatives will be automatically generated once requested and not-yet existing.

That's a quote from my own answer to a similar question. I guess you could try to hook into the upload somehow like Image Style Warmer does it, or simply try that module out yourself.

  Synopsis

  The Image Style Warmer module provides options to create image styles
  during upload or via queue worker. So configured image derivates
  already exists when they are requested.


To process uploaded file for certain content type, how to?

Use the Exif module to grab your exif data from the uploaded image:

Use some simple theming (eg: create node-photo.tpl.php if you are using d6 and content type is called 'photo') - there do some simple jquery show / hide type stuff with a div wrapped around your exif data.


You'll need to fork the module. This is more of a pain than patching but it's much better now that you can make issue forks on drupal.org.
Here's a detailed tutorial.
The basic workflow is this:

Make an issue fork on drupal.org that updates the version requirement.
Add the forked repo to your composer.json and update your site that way.
When the module gets a real Drupal 9 release, switch your composer.json back to the release.


What will happen if I delete 'page.tpl.php file'? Is there any alternative for this file?

page.tpl.php file is used to render your page body content (i.e. content inside <body> tag). Below is one line description of file on api.drupal.org.

  Default theme implementation to display a single Drupal page.

If Drupal is not able to find page.tpl.php file inside your theme, then it will use one of the following file:

If your theme has Parent theme, then Parent theme page.tpl.php file.
If no, file provided by system module.

If you're using version control system like GIT, Bitbucket, etc. you can revert your file from last commit. If not you will need to create new file and do necessary changes


Update fields to use a different FieldFormatter during an update hook

The plugin definitions you've posted are for new fields to build the options when configuring a field formatter in UI. For existing fields you have to update the field formatter in config.

For example:

use Drupal\Core\Entity\Entity\EntityViewDisplay;

function mymodule_update_8001() {
  foreach (EntityViewDisplay::loadMultiple() as $display) {
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['type']) && $options['type'] == 'old_formatter') {
        $options['type'] = 'new_formatter';
        $display->setComponent($name, $options)
          ->save();
      }
    }
  }
}


xbbcode maintainer here.

It seems that the module uses a Regex syntax that was introduced in PHP 5.2.2: http://php.net/manual/de/regexp.reference.subpatterns.php

I'll release a fix when I can; it's a pretty small code change: For each occurrence of (?<...> in the pattern, insert a P to make it (?P<...>.

Alternatively, you can fix it by upgrading to PHP 5.2.2 or later.

Edit: In fact, Drupal 7's minimum requirements mention PHP 5.2.5 (https://www.drupal.org/docs/7/system-requirements/overview).


Change default language from the database?

In the setting.php file used by your site, add the following lines:

$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

This will force Drupal to use English as default language. Once you removed the language files for that language, remove those lines from the settings.php file, or Drupal will always use English as default language, indifferently from what you set from the setting page.

The same trick works also for Drupal 6.


How to add integer field to content type?

You could use the Date Module

Then when you add a new field, select Date as your Field Type.

When you configure it use something like this


Just to be sure, navigate to admin/structure/views within your site. Then perform an "edit" of your view. On the next screen, select the "views display" for which you're having this issue. Then verify if all the "fields" that you want to be shown in your view are actually included.

E.g: if you'd only have field "Title" shown in the list of fields (and "Content: Body" is not in the list of fields to be shown), then that would explain your issue. In that case, use the "Add" button next to "fields" to add the fields you want to be added.

Curious to hear if this is the "... small setting somewhere ..." that you were looking for.


How do I theme (add extra markup to) menu links in Drupal 7?

It calls theme('links__system_secondary_menu'). By default, there is no theme_links__system_secondary_menu, so I guess it is calling theme_links. Looking at the function, all you have to do is copy it to your theme as THEMENAME_links__system_secondary_menu, then change the call to l() to something like:

$link['html'] = TRUE;
$output .= l('' . $link['title'] . '', $link['href'], $link);

The html => true is required or l() will strip the html out of its first parameter.


Try This

$nice_menus_block =_block_get_renderable_array(_block_render_blocks(array(block_load('nice_menus', '1' /*1,2,3 more,  this is get nice_menus_2 block*/))));
print render($nice_menus_block);


Instead of creating new content types. You can create fields and use FieldCollection module to group as many field as you like.

and show (Display) it using FieldCollection Views module.

Find demo here,

FieldCollection Demo

FieldCollection Views  Demo


Construct a View-Grid from fields of the same node?

You could use a combination of Display Suite and Views. This is not a perfect grid... but it's close. These are the steps I followed. I created a Content Type with 6 Long text fields.

Install Display Suite and enable Display Suite and Display Suite UI
Go to Manage Display of your Content type, click on Custom display settings and enable Full content

Click on the Layout tab and select a layout. I selected a Three column stacked - equal with layout.

I distributed the fields into the three columns (Left, Middle, Right), and added the node Title in the Header area
Create a View of Content. In display format be sure to select Unformatted list of full posts
Click on the Content link under Format. Be sure to select Display Suite. Select Full Content

Visit your View. This is what it looks like (I am showing two nodes, with 6 fields each):

Now, if you want to make it look nice (e.g. more space between columns), you will have to use css - no way around it.


How to drop tables shown as Missing in Schema Report

Check out the db_drop_table function.

You could use it on the mysite.com/devel/php page which runs arbitrary php for you, but be ultra careful with it and always have backups, because if you get it wrong you could completely kill your site.


Sort a related products view based on product features

If you want to display those product first that matches the current product features, include all those fields in view accordingly and then apply views_query_alter function to override the order and sort according to current product.

For example, If you want to sort according to product color taxonomy term, Include the field (Products referenced) Commerce Product: color (desc) in sort criteria of view. Then write following code in module file

function MYMODULE_views_query_alter(&$view, &$query) {
  // condition for current view
  if($view->name == 'related_products') {
    //Get current node product color tid & override order query to sort according to that id
    $node = node_load(arg(1));
    $product_id = $node->field_product_reference[LANGUAGE_NONE]['0']['product_id'];
    $product = commerce_product_load($product_id);
    $query->orderby[0]['field'] = "commerce_product_field_data_field_product_reference__field_data_field_product_color.field_product_color_tid = '".$product->field_product_color[LANGUAGE_NONE]['0']['tid']."'";
  }
}

Let me know if you face any query regarding this.

Thanks!


How to make custom taxonomy pages per term based on fields?

I solved this with Panelizer and a custom block made in Views.

View of taxonomy terms, custom block
Contextual filter- taxonomy term: term ID
Provide default value: Term ID from URL

Pathauto pattern for taxonomy terms:
[term:tid]/mylinkpath/[term:name]

Go to taxonomy term display and add panelizer, then add custom views block.


Multilingual Taxonomy Views - Entity Translation

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

The above may turn out to NOT be the complete answer. Since you use the Entity Translation module, this option isn't there if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.

Note: The Internationalizations Views module only has a DEV version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +31K users can't be wrong, right?


I think your hosting provides default cpanel url is /admin

In that case you need Rename Admin Paths module.

The purpose of this module is to secure drupal backend by overriding admin path.

Overview

This module allows you to:

rename path like '/admin/...' to '/something/...'

rename path like '/user/..' to '/something else/..'


When you're using mocks in unit tests (see https://stackoverflow.com/questions/2665812/what-is-mocking), you yourself specify all the interaction that happens with the mocked object. In the simplest example, you can just specify exactly what the mock expects to receive, and what it will return:

$connection = $this->getMock('\Drupal\Core\Database\Connection', []);
$connection->method('query')
  ->with('SHOW TABLES LIKE {does_my_table_exist}') // expect this query
  ->willReturn(
    $this->getMock('\Drupal\Core\Database\StatementInterface')
      ->method('rowCount') // expect the ->rowCount() to be called.
      ->willReturn(1) // pretend that there is exactly one result.
  );

$result = $connection->query('SHOW TABLES LIKE {does_my_table_exist}')->rowCount();
$this->assertEquals(1, $result); // PASS
$result = $connection->query('SHOW TABLES'); // FAIL; unexpected argument.

Note that you shouldn't normally be mocking the StubPDO class; it's only for Drupal's internal DB driver tests. When your code interacts with the database, it does so via the database (\Drupal::database()) service, which you can replace with a mock of \Drupal\Core\Database\Connection.

Edit: A good example of a core unit test that mocks the database and actually simulates interaction is core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php. An excerpt of the setUp() function:

$this->statement = $this->getMockBuilder('Drupal\Core\Database\Driver\sqlite\Statement')
  ->disableOriginalConstructor()
  ->getMock();

$this->statement->expects($this->any())
  ->method('fetchObject')
  ->will($this->returnCallback([$this, 'fetchObjectCallback']));

$this->select = $this->getMockBuilder('Drupal\Core\Database\Query\Select')
  ->disableOriginalConstructor()
  ->getMock();

$this->select->expects($this->any())
  ->method('fields')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('condition')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('execute')
  ->will($this->returnValue($this->statement));

$this->database = $this->getMockBuilder('Drupal\Core\Database\Connection')
  ->disableOriginalConstructor()
  ->getMock();

$this->database->expects($this->once())
  ->method('select')
  ->will($this->returnValue($this->select));


Allow users to edit own unpublished content

I am not sure about your exact requirement. If you want to list all contents created by current user with an edit link, my suggestion to make try with views.

Give Edit Own Content permission to your needed roles for all content types in Home » Administration » People » Permissions.
Create a view with content of all.
Add title in fields (or the fields you want).
If you want to give an edit link , add Content:Edit Link.
In views contextual filter add Content:Author uid = User ID from logged in user (Refer here).
Change format to Table (Only title and edit link is there this gives a nice formatting).

Hope this will help you.


Check if theme is enabled programmatically

Use list_themes

Parameters

$refresh:
Whether to reload the list of themes from the database. Defaults to FALSE.

Return value

An associative array of the currently available themes. The keys are the
themes' machine names and the values are objects having the following
properties:

filename: The filepath and name of the .info file.
name: The machine name of the theme.
status: 1 for enabled, 0 for disabled themes.
info: The contents of the .info file.
stylesheets: A two dimensional array, using the first key for the
media attribute (e.g. 'all'), the second for the name of the file
(e.g. style.css). The value is a complete filepath (e.g.
themes/bartik/style.css). Not set if no stylesheets are defined in the
.info file.
scripts: An associative array of JavaScripts, using the filename as key
and the complete filepath as value. Not set if no scripts are defined in
the .info file.
prefix: The base theme engine prefix.
engine: The machine name of the theme engine.
base_theme: If this is a sub-theme, the machine name of the base theme
defined in the .info file. Otherwise, the element is not set.
base_themes: If this is a sub-theme, an associative array of the
base-theme ancestors of this theme, starting with this theme's base
theme, then the base theme's own base theme, etc. Each entry has an
array key equal to the theme's machine name, and a value equal to the
human-readable theme name; if a theme with matching machine name does
not exist in the system, the value will instead be NULL (and since the
system would not know whether that theme itself has a base theme, that
will end the array of base themes). This is not set if the theme is not
a sub-theme.
sub_themes: An associative array of themes on the system that are
either direct sub-themes (that is, they declare this theme to be
their base theme), direct sub-themes of sub-themes, etc. The keys are
the themes' machine names, and the values are the themes' human-readable
names. This element is not set if there are no themes on the system that
declare this theme as their base theme.

Use path_to_theme to get active theme..

  It can point to the active theme or the module handling a themed
  implementation. For example, when invoked within the scope of a
  theming call it will depend on where the theming function is handled.
  If implemented from a module, it will point to the module. If
  implemented from the active theme, it will point to the active theme.
  When called outside the scope of a theming call, it will always point
  to the active theme.


You need to add items to your queue. You have created a queue, but haven't added anything to it, so nothing is being done.

$queue->createItem($item);

$item will get passed to the queue callback function (_import_all_jobs).

I would suggest modifying _import_all_jobs to import an individual job (_import_job). Then $item would be a job added to the queue and you let DrupalQueue do its thing.

This article may be helpful: Cron Queues: Processing large amounts of data in cron

And here is some relevant Drupal documentation: Queue operations


Module not returning echoing or printing variable

fixed it I had to add an $orderidentifier = intval($orderidentifier); to convert it to an integer so the hook I was calling could understand it


Failed to load popup dialog with in views

After further Google search I found this Webform issue.

Solution:

You have to use the Footable dev version and not the alpha2 version.


How to display data export icon on top of an admin view without views-view.tpl.php in admin theme?

You can create

function MODULE_preprocess_views_view_NAMEOFMYVIEW(&$variables) {
  $variables['title_suffix'] = array(
    /* Renderable data or just string instead of array */
  );
}

it will render you content between view title and view content.


getID3 can be used to calculate the size of the file.

$fileinfo = getID3_analyze(drupal_realpath($name2));
$playtime_sec = round($fileinfo['playtime_seconds'] / 60);

//Generate playtime in minutes (for display only), @type String
$playtime_mins = $fileinfo['playtime_string'];

use the following modules to integrate with views.
https://www.drupal.org/project/computed_field
https://www.drupal.org/project/getid3


Use Rules to Change Field Value By Clicking URL

I'm not sure I understand exactly what you need, but the great module Rules Link (https://www.drupal.org/project/rules_link) provides a link that can be attached to any content type or entity, and can also be accessed in Views as a special Rules Link field. When you click the link a preset Rule is triggered. The link passes the node or entity as a parameter to the Rule. There is also the option of using a "Javascript" link that invokes the Rule via AJAX (without reloading the whole node) - I've never used that option, but I suspect that it may help your needs.


How to hide the "Add to cart message" on mobile site"?

One way to do it would be to use hook_node_submit to override the submit handler for commerce_cart_line_item_views_form_submit. Check for your theme and apply messages appropriately. However, that will only work for this single message. You would have to rewrite all of the cart functions that have messages.

Another way: I know you can do this with CSS. You just need to target the product pages only. I don't know your CSS structure, but if you look at the classes in the <body> element, you should see classes that you can use to cascade down and set display: none; to the message region. I don't know what other messages will show up that you care about on the product pages. If you do have some, then the first option is your only option. (Or the non-recommended option below.)

You could also edit the cart source but that is not a good option because it breaks your upgrade path.

If you are using Kickstart, I can find the function to override there as well. (I have sites running both.)


The controller from your question runs without exception:
public function demo() {
  $build = [
    '#cache' => [
      'contexts' => ['ip'],
    ],
  ];
  return (new CacheableJsonResponse(['test'], 200))->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
}

Result:

["test"]

To produce the exception you need a controller like this:
public function demo() {

  $build = ['#markup' => 'early rendering'];
  $markup = \Drupal::service('renderer')->render($build);

  $build = [
    '#cache' => [
      'contexts' => ['ip'],
    ],
  ];
  return (new CacheableJsonResponse(['test'], 200))->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
}

Result:

LogicException: The controller result claims to be providing relevant
cache metadata, but leaked metadata was detected. Please ensure you
are not rendering content too early.

This may not always be that obvious. Another example is when you try to get an url from an url object, see this answer https://drupal.stackexchange.com/a/187094/47547

Add an URL with cacheable metadata to a response
This is how you avoid the exception, when you render an url for a json response, and at the same time add the correct cache metadata to the response:
  $generated_url = $url->toString(TRUE);
  $response = new CacheableJsonResponse(['url' => $generated_url->getGeneratedUrl()], 200);
  $response->addCacheableDependency($generated_url);
  return $response;


How to display a timetable for reservable resources?

Try to use any of below modules :

Field TimeTable

  A Fields module that creates a timetable field that can be display
  through an nice weekly grid. Can be use to display opening hours or
  working hours in a very neat way.

  If you need to display office hours in a graphical way you have now a
  proper solution !

Grid Field Formatter

  the Grid Field Formatter module provides a simple way to overridde the
  display of multi-value fields to show as a grid/table with a certain
  number of columns.


Clickable preview of a youtube video in a Lightbox?

Well! Thanks to this answer, I just found a workaround. I had to install the Video Embed Field module, and now I can display YouTube videos in a Colorbox popup window perfeclty fine. And Colorbox only, because Lightbox2 is still not supported by Video Embed Field.


Views: showing similar terms on term page by another term reference field

Assuming that you have a term reference field attached to the Artist vocabulary showing terms from the Styles vocabulary, and assuming that you wish to display a list of other Artists with the same Styles in a block ...

Create a block view showing taxonomy terms from the Artist vocabulary.

Set a Conceptual filter on Taxonomy term: Tid and provide a default value of Term ID from URL.

Add a relationship on Taxonomy term:Styles (field_styles) and check Require this relationship.

Add a second relationship to Taxonomy term: Taxonomy term using Styles. Configure it to use the relationship *term from field_styles* and check it as required.

Go to your view fields and edit the Taxonomy term: Name field. Configure it to use the *field_styles* relationship.

Go to Advanced > Other > Query options and select Distinct. This type of query can produce duplicates.

Place the block on your taxonomy pages and it will give you a list of Artists with the same Style(s) as the current Artist.


What are the major differences between Views Datasource and Views data export?

Views Datasource can be thought as providing a view format that takes over the whole page; each submodule you enabled (JSON/RDF/XHTML/XML) provides a format that it outputs the view as a specified document type without your site theme.

Views Data Export can be thought of providing an attached exportable format of some complementary view format (e.g. a Page view formatted as a table that as an exportable CSV file); when enabled, it provides a new view display that you can make available at a specified path and attached to existing view as a button which can be configured to be a downloadable attachment.

There is some overlap (e.g. both could be used to produce an XML-producing custom path), but only Views Datasource provides a JSON (unless you use some other contrib module), while Views Data Export has other options (e.g. batching support) that make it better suited for large data exports.


Is your external database provided by another authentication mechanism? There are mature modules for Active Directory, Social Network login, and many others besides.

If your database for authentication is totally custom, then you will need to write some custom code.

Drupal users generally login using the user_login form. When users login, a particular function, user_login_authenticate_validate, is called by the user_login form's submit hook. This function validates user credentials against the local database.

user_login_authenticate_validate can be replaced with another function by using hook_form_alter on the user_login_form. You will need to create a new module, and implement code something like the following...

/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_user_login_alter(&$form, &$form_state, $form_id) {
  // Add your own validators to the form.
  $form['#validate'] = mymodule_validators();
}

/**
* Returns an array of user validation function callables.
*
* @see user_login_default_validators().
*/
function mymodule_validators() {
  return array('user_login_name_validate', 'mymodule_authenticate_validate', 'user_login_final_validate');
}

/**
* Validation function, validates users against foo database.
*
* @see user_login_authenticate_validate()
*/
function mymodule_authenticate_validate($form, &$form_state) {
  // Use the password and username from the form, and make sure you set
  // $form_state['uid'] to the correct uid for the auth user.
  $password = trim($form_state['values']['pass']);
  $username = $form_state['values']['name'];

 // Authenticate them against your database, and find their drupal uid....
 $form_state['uid'] = mydatabase_auth_function_that_returns_a_drupal_uid($username, $password);
}

Implementing your own authentication is a decision that you should not take lightly. Personally, I would never go down this path. There are serious security concerns when rolling your own authentication mechanism. Wherever possible, you should leverage mature and well-tested solutions.


Rules reaction: "After updating an existing user account" reacts on user login

What event are you using to trigger the node creation? It sounds like maybe there's a "User has logged in" event somewhere in the chain.

The Rules module can be flakey. (I love it but it drives me crazy sometimes.) If you can't figure it out, you could try to preempt the problem by adding a check to the event where you create the group node to see if a group node already exists before adding one.


Gather arbitrary data in feeds xpathparser without mapping it to a field?

As per this issue: Map "Temporary target" to a property of an entity, Feeds tamper seems to be the way to do this.


You can go to admin/build/translate and translate your defined words, it's search is case sensitive


drupal_add_js() 'setting' not being set on form submit

it might be something with the form redirecting during the submission process and the JS is getting lost?

Yes, you are absolutely right! Normaly, after form submitting user is redirected with drupal_goto() function. Messages which set with drupal_set_message() are stored in $_SESSION so they are not lost, but drupal_add_js() doesn't use session.
You can prevent redirect in your submit function:

// In this case your form hanler will be able to see flag $form_state['submitted'] and
// other data from previous form processing to indicate that form was submitted.
$form_state['rebuild'] = TRUE;
// Will work.
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

Or with:

$form_state['redirect'] = FALSE;
// Will work, too
drupal_add_js(array('myModule' => array('test' => 'test-value')), 'setting');

But I would have used $_SESSION as it is more flexible.

$_SESSION['js_settings'] = array('myModule' => array('test' => 'test-value'), 'setting');

Then you have to process $_SESSION yourself in accordance with your site logic.


How to configure or style an Openlayers source?

You won't find any options in Views to customize the display.
Have a look under "admin/structure/openlayers".
Markers are defined under "styles" -> admin/structure/openlayers/styles.


Migrate a CSV into two entities with reference

It's fundamental to how the migration process works that it processes one item being written at a time. In this case, since it's sentence entities that are being updated, it needs a migration that processes one sentence at a time. The layout of your CSV here is not well-suited for that, and to work directly from that CSV would require significant hackery. The best approach would be to either generate your CSV in this format in the first place, or have a preprocessing step to put the data in this form:

chapter,sentence,headings
1,1,heading one
1,2,heading one
1,3,heading one
1,4,heading one
1,5,heading one
1,6,heading one
1,7,heading one
2,1,heading two
2,2,heading two
2,3,heading two
2,4,heading two
2,5,heading two
2,6,heading three
2,7,heading three
2,8,heading three

Then, you'd have a migration with source IDs chapter and sentence, setting the heading for each sentence from the headings column.


Module that provides Rules action to create node?

In Rules 2.x on Drupal 7, there is a "Create entity" action built-in to the Rules module itself.  You can use this action to create a node (Content), which is one type of entity.


In D8 the module File Entity provides this feature, same as in D7. It was required by Media, so you probably installed it without noticing in D7.

The new Media package for D8 doesn't use this anymore. Instead it uses a new media entity for the extra information. There is work going on to put the media entity in core for 8.3:

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


Adding JS and CSS Dynamically to Override Theme

If the style sheet is used on all your pages, there's no need to load it dynamically with drupal_add_js(). Just put your style sheet into the .info file of your theme. The Writing theme .info files guide has detailed descriptions and links to more docs about this.
Your JS script looks fundamentaly wrong to me. Remove the script tag alltogether.
To add the JS script just add scripts[] = foo.js to your theme .info file. Look at the above mentionded guide, or here to get more detials.
What do you mean with basic content page.


Two options: node_load_multiple() function (deprecated) or EntityFieldQuery Class (preferred).

Example node_load_multiple():

$nodes = node_load_multiple(array(), array('type' => 'us_states'));

  The second argument ($conditions) is marked as deprecated; and you can see that in the Drupal 8 documentation for the same function, it has been removed. I only included this example because I'm sure someone else would have pointed it out had I not and the fact that you specifically asked for a function.

Example EntityFieldQuery (Use this):

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'us_states');
$nodes = $query->execute();

In both examples, $nodes will be an array containing all nodes of the content type 'us_states'. (Note that the nodes within the array will be objects per usual.)

If you really need to use a function (that won't be deprecated in Drupal 8), you can pass an array of Node IDs as the first param to node_load_multiple() that contains the Node IDs of all of the 'us_states'.


The way to do this is by overriding variables in the template. Put the following code in your themes 'template.php' file, replacing YOURTHEME, YOURBLOCK, YOURCLASS with the obvious.

/**
 * Override or insert variables into the block template
 */
function YOURTHEME_preprocess_block(&$vars) {

  // var_dump($vars);

  $block = $vars['block'];

  if ($block->delta == 'YOURBLOCK') {
    $vars['title_attributes_array']['class'][] = 'YOURCLASS';
  }

}

You can determine what the $block->delta is for example by doing a var_dump($vars) in the function. If you have the DEVEL module installed you can use dsm($vars) which gives the dump some presentation.


After registration password : Your password is not correct

Try this module : Registration Password Token. It will provide the user register password as a token.

  This small module provides token [user:password] during user registration. Site administrator allowed to customize the text of the e-mail that is sent to the user after registration.


What are the key differences between Drupal 7 and Pressflow 7?

I dug in to find all of the differences and looked them up on GitHub and this is what I found:

Pressflow Smart Start will forward you to the install page if the database is set up in settings.php but the database is empty, disabled by default.

Files: includes/bootstrap.inc and sites/default/default.settings.php
Commits: https://github.com/pressflow/7/commit/fa91b2fc80741cb8c42c2db618f0ef0ad890f4cc

Allow for environmental PRESSFLOW_SETTINGS to override settings.php; settings must be entered as a JSON array.

Files: includes/bootstrap.inc
Commits: https://github.com/pressflow/7/commit/673fb0bdab618f8989365012149c76b8397f95d6 (Pull request: https://github.com/pressflow/7/pull/7), and https://github.com/pressflow/7/commit/953e6608b34975eaa0c8abed8a90f80d22f1b967

APC CSS and JS check; to prevent Drupal from constantly checking the file system for core-aggregated CSS and JS files, use APC as a key:value store instead. This is very helpful for networked file systems (and therefore very relevant to Pantheon, who happens to be the primary driver behind Pressflow since version 7).

Files: includes/common.inc (also see lines 3558 and 4949)
Commits: https://github.com/pressflow/7/commit/e2f9d2b10b4f0c5f61f120be145621913c6794a4 (Pull request: https://github.com/pressflow/7/pull/16/files, original pull request: https://github.com/pantheon-systems/drops-7/pull/4)

Allow modules to act on the js_cache before writing to disk, add a new hook called hook_js_cache_alter, and, if you use the new hook, add a note to the aggregated JavaScript that it was built with PressFlow

Files: includes/common.inc and modules/system/system.api.php
Commits: https://github.com/pressflow/7/commit/53098cf059236110716ca97c18565a178c458b43

Allow sub-second delays for lock_wait(). The calculation Drupal currently does will allow a value of 0 for the lock wait time, effectively skipping it. When PHP converts to an integer, a float will always round down. For example, as Drupal performs the operation: php -r "echo (int) 0.25 * 2;" would return 0. The Pressflow change corrects this, for example: php -r "echo (int) (0.25 * 2);" would return 5, allowing for sub-second delays to be used as an input to the function.

Files: includes/lock.inc
Commits: https://github.com/pressflow/7/commit/2cd4323946987608a660694df2c02f3cb4cce6c3

Here's a full diff as of October 2013: https://gist.github.com/alanthing/6064500


Is it possible to set Cookie Session ID from a REST Service?

You cant save off the JSESSIONID into the user attributes, eg data column, in D6 or D7. You simply do this in your code with:

$_SESSION['JSESSIONID'] = /* some value here */;

or wherever you call user_save() in your custom login you can pass $edit['data'] = array('jsessionid' => 12341234); from the user_save documentation:

  $edit: An array of fields and values to save. For example array('name'
  => 'My name'). Key / value pairs added to the $edit['data'] will be serialized and saved in the {users.data} column.

it then becomes accessible from a fully loaded $user object as simply a field of the user ... $jsessionid = $user->jsessionid; and you can use it as needed.


Does install.php open a connection with ANSI ON?

If you look in database.inc for your database driver you can see what parameters are passed from drupal on the default connection. If you apply this patch to drupal8 you can set additional PDO options supported by the driver https://www.drupal.org/node/1926284


Simply use the quick tab module. It exactly do same thing.


How can i create a view of all drupal commerce products with the orders they appear in?

Drupal Commerce does support some reverse reference relationships, but currently there is only a reverse relationship from products to nodes that reference them, not from products to line items that reference them. If I were you, I'd instead make the base table orders, because you can more easily establish relationships from orders to line items to products and get at the same fields that way. We use commerce_order as the base table for shopping cart Views, for example.


403 forbidden for all css files located in /modules

That extra query string are used to control caching. That will change everytime the cached files expired.

As per Dave Reid:

  It's to prevent browsers from caching those files when they change.

See these threads:

https://www.drupal.org/node/346711
https://stackoverflow.com/questions/11362261/appending-query-string-to-all-js-and-css-files-to-prevent-caching


How to save POST variables securely using entity api

It really depends on how ShipWorks works. If it lets you specify a URL when it downloads the order data, you could use a secret key appended to the URL that you can use to authenticate a request as Ayeshk mentions. If it allows the merchant to specify a URL in a configuration form, at least you can set the secret key once and have the merchant copy it, kind of like how Drupal appends a secret key to the cron URL.

I also have a project upcoming that requires ShipWorks. Are you sharing the code publicly anywhere?