Depending on your requirements, Field Validation can be a good approach.  It's simple to set up, but one potential issue is that if this field is something that the user can edit, they can easily modify their birthday if the form submission is rejected.

Often this is OK, but for my site I needed to actually block users who were under 18, so I did the following.  I have a required date field, birthday, on the user registration form.

Then, I added a computed field, age, to calculate the age based on the value of the date field, birthday.  For sample PHP, you can see this Stack Overflow answer.  This is a way that you can take into account leap years, etc.

Then, I added a rule:

Event After saving a new user account

Condition Data to compare: Age less than 18.

Actions Block user

The advantage of doing it this way is that if a user registers with a birthday under 18, their e-mail address will be blocked from registering again.  Of course, this may or may not be necessary for your case, but I'm just putting it out there because other sites may have such a requirement.


Does Multiversion module need content migration if enabled on running site?

As mentioned in the Multiversion description on Drupal.org that it should be enabled on the fresh instance of the drupal. If you are planning to use multiversion on already established database then on enabling this module it will erase all the entities including the custom ones. It will delete
all Taxonomy Terms, Menu Items, Content, Config Entities. So that will require content migration on after install. But there is another way,
1. Install a fresh database
2. Enable the Multiversion
3. Sync the configuration.
Configration management comes really handy in this case.


Creating filter seems to work but doesn't "stick"

To modify the value of a view programatically you don't need to actually render the view like you do with this part:

$view->pre_execute();
$output = $view->display_handler->preview();
$view->execute();
$view->post_execute();

They are only functions involved in rendering the view output.

The part you are missing is saving the view.

You are adding things to it but because you don't save it they don't end up in the database.

You will need to use the view::save() function like this:

// Load the view.
$view = views_get_view('VIEW_NAME');
// Modify the view here.
...
// Save the view.
$view->save();

[EDIT]

As for actually adding the filter. I recommend using the view::add_item() function instead of just manually adding to the view object because it does some extra work with the handler that isn't being done by your current code.

Some examples of using add_item() are https://drupal.stackexchange.com/a/134872/10729 and https://drupal.stackexchange.com/a/70649/10729


.info file is not loading the JavaScript code

The file path should be relative to the theme directory not the root directory; try it with js/jquery.nivo.slider.pack.js instead of sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js.


Logging into Drupal 7 site with headless browser: why would it fail?

Is there some security feature built into Drupal to prevent
  submissions by scripts?

Yes, there is.

In order to prevent automated form submission by bots etc.. During form build Drupal generates a token, based on session id, and a unique id, for form cache. These are used during form validation.

See:

drupal_prepare_form
drupal_get_token
drupal_validate_form
form_get_cache

In order to successfully submit the form, you would need to retrieve it and then submit it using the same token and form_build_id values.

However, there are other ways to submit forms programmatically, such as

drupal_form_submit

As well as purely code based methods to log a user in.

e.g, in a very simple form:

// Load a user account and assign to global $user
global $user;
$account = user_load(1, TRUE); // Root user
$user = $account; // This "logs" the user in
drupal_session_regenerate();
// Invoke login event
$edit = NULL;
user_module_invoke('login', $edit, $user);


How to map uid in users table data to the entityid in feild table to retrieve data of the users in drupal7

For the field_data_* tables, when the entity_type is node, the entity_id & revision_id are the foreign keys into the node table. You can use this to JOIN into the users table.

  //@TODO: Replace field_data_* with the field table in question
  $fields = db_select('field_data_*', 'f');
  $fields->join('node', 'n', "n.nid = f.entity_id AND n.vid = f.revision_id AND f.entity_type = 'node'");
  $fields->join('users', 'u', "u.uid = n.uid");
  $new = $fields
    ->fields('f')
    ->fields('u',array('uid'))
    ->execute()->fetchAll();


Why nodes aren't always deleted on cron?

Check this "Running cron as an authenticated user" in http://drupal.org/node/23714
it might be useful for you.


Notice: Undefined index: elements in block_theme_suggestions_block()

You are not supposed to use the block template like this. This will be added automatically and it will be done so one level higher in the render array structure.

Check other block plugins, none of them use #theme like this, like SystemBrandingBlock::build()

You have two options:

Define the block template suggestions like system_theme() does it and then overidde the output there. (the first in the list is the one for the branding block linked above, so you can easily connect the two things)
Make your own template for the content within the block. It will be wrapped by a generic block template, so you don't have to worry about that at all.


How can I refresh the adjustment tax after changing the line-item price?

Order refresh is done via a service, this service is called every time an order is saved. Check the module documentation.


Issue a html.tpl.php override from a module?

According to this answer, you could simply print the page content in the menu page callback rather than returning it.

  To get data from Drupal's database and/or produced in PHP, you need a
  page callback (in a custom module) that output the data without the
  full layout rendering. This is easily doable by printing the content
  of the page directly in your page callback instead of returning it.

I guess the Print module implemented the printer-friendly page in this way. The following is the code snippet from the module.

function print_menu() {
  $items = array();

  $items[PRINT_PATH] = array(
    'title' => 'Printer-friendly',
    'page callback' => 'print_controller_html',
    'access arguments' => array('access print'),
    'type' => MENU_CALLBACK,
    'file' => 'print.pages.inc',
  );
  ........
}

/**
 * Generate an HTML version of the printer-friendly page
 *
 * @see print_controller()
 */
function print_controller_html() {
  $args = func_get_args();
  $path = filter_xss(implode('/', $args));
  $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;

  // Handle the query
  $query = $_GET;
  unset($query['q']);

  $print = print_controller($path, $query, $cid, PRINT_HTML_FORMAT);
  if ($print !== FALSE) {
    $node = $print['node'];
    $html = theme('print', array('print' => $print, 'type' => PRINT_HTML_FORMAT, 'node' => $node));
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html;
    ......
}

According to this, the module uses the custom HTML template print.tpl.php. It is a HTML-level template. The module then gets the HTML by calling theme('print',...) and render it directly to the browser using print $html;.

Here is a general idea for your purpose: mymodule.module

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['mylogin'] = array(
    'title' => 'Custom Login Page',
    'page callback' => 'mymodule_custom_login_page',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mylogin' => array(
      'variables' => array('page' => array()),
      'template' => 'mylogin', // mylogin.tpl.php in your module folder
    ),
  );
}
/**
 * Generate a custom login page
 * @see more in print_controller_html() in print.pages.inc of the Print module
 */
function mymodule_custom_login_page(){
    $page = _mymodule_login_page_prerequisite(); // get/prepare necessary variables, js, css for the page
    $page['form'] = drupal_render(drupal_get_form('user_login')); // get login form
    // prepare html in mylogin.tpl.php
    // See more in print.tpl.php() in the Print module
    $html = theme('mylogin', array('page' => $page));

    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    drupal_send_headers();
    print $html; // cease Drupal page rendering and render directly to the browser
}
/**
 * Prepare the array for the template with common details
 * @see more _print_var_generator() in print.pages.inc of the Print module
 */
function _mymodule_login_page_prerequisite(){
    global $base_url, $language;
    $page = array();
    $page['language']   = $language->language;
    $page['head']       = drupal_get_html_head();
    $page['title']      = '';
    $page['scripts']    = drupal_get_js();
    $page['favicon']    = '';
    // if there is a custom css file for this page
    // drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mylogin.css');
    $page['css'] = drupal_get_css();
    $page['message'] = drupal_get_messages();
    $page['footer_scripts'] = drupal_get_js('footer');

    return $page;
}

Template: mylogin.tpl.php

<?php
/**
 * @file
 * Custom login page template
 *
 * @ingroup page
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $page['language']; ?>" xml:lang="<?php print $page['language']; ?>">

    <?php print $page['head']; ?>
    <title><?php print $page['title']; ?></title>
    <?php print $page['scripts']; ?>
    <?php print $page['favicon']; ?>
    <?php print $page['css']; ?>

This is custom login page.

    <?php
    if (!empty($page['message'])):
        foreach($page['message'] as $type => $message):
        ?>
            <div class="messages <?php print $type; ?>">

                <?php foreach($message as $msg): ?>

<?php print $msg; ?>

                <?php endforeach; ?>

        <?php
        endforeach;
    endif; ?>

<?php print $page['form']; ?>

    <?php print $page['footer_scripts']; ?>

I hope this will customize your login page as you need.


For string changes your best bet is altering the view in a custom module. Use  hook_views_pre_render to modify the output of the fields prior to the view result being fully outputted.


Ubercart - hook for modifying the order review page

Documentation is lacking. This is the only documentation i could find and it's here: http://www.ubercart.org/docs/api

but not exactly what i want.


Manually deleting images (from db and file_usage table)

This is probably more of a comment but the code won't fit in...there should be no reason for the UI to fail on the file delete, unless the web server daemon doesn't have write permission to the files folder. That would be the first thing I'd check, then try again.

If that fails, you might want to give it a go manually:

$nids = db_query("SELECT nid FROM {node} WHERE type = 'the_type'")->fetchCol();

foreach (node_load_multiple($nids) as $node) {
  $node->field_name[LANGUAGE_NONE] = array();
  node_save($node);
}

That will take care of the whole lot (removing the data from file_managed, file_usage, and deleting the file from the disk if it exists and is writeable).


By default, Drupal assumes that any installed module or theme is hosted on drupal.org. This means that, if you are using a custom module (which is probably not hosted on drupal.org), Drupal will return the error you are seeing because it doesn't find any information about the module you are using, on drupal.org.

If you just want to stop Drupal from looking for a module updates, normally because you are using a different method to update it, or because the module is not hosted on drupal.org (for example, a custom module you have on your computer, on Git, Gitlab, or similar services) you can implement hook_update_projects_alter().

function custom_module_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['custom_module']);
}

With this example code, the custom_module module is hiding itself, but a module can hide any module. For example, if I had a custom_core module that is a dependency for every custom module I use on my site, I would implement the hook using code similar to this.

function custom_core_update_projects_alter(&$projects) {
  // Hide all the site-specific modules from the list.
  unset($projects['custom_user_data']);
  unset($projects['custom_entities']);
  unset($projects['custom_spam_prevention']);
}

If you want Drupal checks for updates on a site that is not drupal.org, then the .info.yml file for the module needs to contain the following line. (See the code of the UpdateFetcher class, which is the class that fetches project information from remote locations.)

project status url: http://example.org/project-history

In this case, for a module using my_module as machine name, Drupal will fetch the information about Drupal 8 releases of the module from http://example.org/project-history/my_module/8.x.

Notice also that:

If the .info.yml file also contains a project: my_custom_project line, Drupal will check for information about Drupal 8 releases of the module from
http://example.org/project-history/my_custom_project/8.x, not http://example.org/project-history/my_module/8.x (This is useful when a module is a sub-module of another module, and both are packaged in the same file.)
Drupal expects that http://example.org/project-history/my_module/8.x returns XML data that follows a specific format; you can see for example what drupal.org returns for the Date module (https://updates.drupal.org/release-history/date/8.x)

<?xml version="1.0" encoding="utf-8"?>
<project xmlns:dc="http://purl.org/dc/elements/1.1/">
  <title>Date</title>
  <short_name>date</short_name>
  <dc:creator>vijaycs85</dc:creator>
  <type>project_module</type>
  <api_version>8.x</api_version>
  <project_status>unsupported</project_status>
  <link>https://www.drupal.org/project/date</link>
  <terms>
    <term>
      <name>Projects</name>
      <value>Modules</value>
    </term>
    <term>
      <name>Maintenance status</name>
      <value>Actively maintained</value>
    </term>
    <term>
      <name>Development status</name>
      <value>Under active development</value>
    </term>
  </terms>
  <releases>
    <release>
      <name>date 8.x-1.x-dev</name>
      <version>8.x-1.x-dev</version>
      <tag>8.x-1.x</tag>
      <version_major>1</version_major>
      <version_extra>dev</version_extra>
      <status>published</status>
      <release_link>https://www.drupal.org/project/date/releases/8.x-1.x-dev</release_link>
      <download_link>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</download_link>
      <date>1380568703</date>
      <mdhash>f36524e70ed83fe7f2812d3768a337c0</mdhash>
     <filesize>164918</filesize>
     <files>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.tar.gz</url>
         <archive_type>tar.gz</archive_type>
         <md5>f36524e70ed83fe7f2812d3768a337c0</md5>
         <size>164918</size>
         <filedate>1380568703</filedate>
       </file>
       <file>
         <url>https://ftp.drupal.org/files/projects/date-8.x-1.x-dev.zip</url>
         <archive_type>zip</archive_type>
         <md5>781eb8cb238ed8649c93f0e8e2b9e778</md5>
         <size>232819</size>
         <filedate>1380568703</filedate>
       </file>
     </files>
     <security>Dev releases are not covered by Drupal security advisories.</security>
   </release>
 </releases>

Not all the information provided is required, but for each release there must be a URL for the archive containing the module code, which is used from Drupal to download and copy the module on the site server.

As side note, updating a module files with Composer would be the first step to update the module. Drupal still needs to invoke the update hooks the module provide, and update the module information it stores in its database tables (and cache).


Rate module: rate icon disappears and no vote is recorded

I was finally able to resolve this issue by enabling Clean URLs (configuration -> clean URLs).  Note, if you are prompted with a Clean URLs test that inevitably fails, you will likely need to uncomment the "RewriteBase" line in your .htaccess file.


Print view field direct in views-view-fields.html.twig

Yes, that is possible, this is the most basic fields twig:

{% for field in fields -%}
    {{ field.content }}
{%- endfor %}

Then you loose most field configuration from views and can put in your own html structure.

You don't need to skip the field twigs for single fields, simply delete you own twigs and let the core twigs take over again.


You can see the jQuery Tabs Field module for this.

  jQuery Tabs Field module allows you to create jQuery Tabs field. Using this you can add upto 7 tabs with tab title and tab body in a node. After saving node, the module will display all these 7 tabs as jQuery tabs.


Automatically fill the default vocabulary term associated with a content type when editing a node

I think the answer will be to make your button/menu item dynamic using arguments from the URL. It sounds like when a user clicks the "Add Classified" they are already viewing the classifieds tagged with a particular location taxonomy term. In which case, I'd imagine that term name (or id) appears in the current url, something like http://yoursite.com/classifieds/LosAngeles. If so, I believe you can pull that term out of the url and use it in your link, something like http://yoursite.com/node/add/classified/LosAngeles. Then, you'd need to alter your 'Add Content' form to pull in the term from the url (the LosAngeles part). This should work in theory, however I'm not sure exactly how to do that in practice. I'll see if I can figure it out before you end up answering your own question, but that should at least help point you in the right direction for now.


Is there a way to tell composer about manually updated modules?

Yes, in the sense if you want to hack composer.lock you can make Composer think it got updates it never downloaded.

That requires you to know what composer.lock properties have changed (like content-hash & packages[*]) and apply them manually to the file.

That said, doing this is breaking the entire purpose of Composer (composer.json represents a manifest of what you need & composer.lock represents a manifest of what Composer retrieved); you
 run the risk of breaking of what composer.lock should do (i.e. composer install on any machine will retrieve the exact same files as when you made your last updates); so you
 should really think about the impacts on other environments/hosts that use your composer.* files.

If you're committing to a Composer-driven process, it's better to troubleshoot why your dependencies aren't updating as other commentators have suggested (e.g. too broad versioning in composer.json, auto-dropped changes from a non-interactive run)


How to run cron more often than every hour?

You can get really fine-grained control over your cron runs with these modules:

Elyisa cron

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

Ultimate Cron

  The Ultimate Cron handling for Drupal.
  Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

(In no particular order) I've only used Elysia cron before, and only recently at that, but it works well.

Either module will let you use a standard cron rule to define it's frequency, which I think means you can get the granularity down as far as seconds if you need it.

I think the only gotcha is that the more often you run cron (if it has expensive tasks to perform), the more load there will be on your server. Testing and benchmarking are the only real way to solve that one :)


What is the right way to implement google_analytics with the eu_cookie_compliance and categories?

As far as I know, it is not yet possible to activate individual 3rd party services with the EU Cookie compliance module. An update is planned, the concept will be completely revised.
I would recommend using the module "COOKiES Consent Management" https://www.drupal.org/project/cookies, which supports various 3rd party integration modules out-of-the-box, such as https://www.drupal.org/project/google_analytics is supported.


Doing this directly in the database can be messy given the way Drupal abstracts its managed files. It is usually better to try and find a solution that works with the Drupal file API directly so you're not forgetting some entry somewhere and leaving extra cruft in your database. You could roll your own solution using the file API and file_delete() but I would suggest that you're better off doing this using an interface like IMCE and combining that with a solution like this module:
http://drupal.org/project/upload_replace
which would resolve this problem for you going forwards:

The problem with drupal is if you have a file called "mydoc.doc" upload it to a node, then make changes to "mydoc.doc" and upload the newer version, the newer version will be renamed to "mydoc_0.doc" because at the time of upload the old file was blocking the desired path name.
This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.


You'll have to create your own webform component to ensure that validation and saving work as you intend. Look at an exisiting webform component to see how its done.


Extend Drupal 6 "form_token" & "form_build_id"

TL;DR: Those values will not expire if

you use the same user to log in to the site
the PHP session is not expired
Drupal finds in its cache the form array associated with "form_build_id."

The token used for "form_token" is the one created using with the following function call: drupal_get_token($form['#token']); the only value that changes in that function call, for the same form, is session_id() which is invoked from drupal_get_token().

function drupal_get_token($value = '') {
  $private_key = drupal_get_private_key();
  return md5(session_id() . $value . $private_key);
}

The value returned from drupal_get_private_key() is unique for each Drupal site; the only way to make it change is to delete the Drupal variable "drupal_private_key" that is never deleted (if there isn't a third-party module that delete it), but it is initialized when Drupal is installed. The value returned by session_id() is the same each time drupal_get_token() is called, if the logged in user is the same, and the PHP session has not yet expired.

As for the value of "form_build_id," its value is totally random, initialized from drupal_prepare_form() using the following code:

  if (isset($form['#build_id'])) {
    $form['form_build_id'] = array(
      '#type' => 'hidden',
      '#value' => $form['#build_id'],
      '#id' => $form['#build_id'],
      '#name' => 'form_build_id',
    );
  }

$form['#build_id'] is initialized from the following code in drupal_get_form():

  $form_build_id = 'form-' . md5(uniqid(mt_rand(), TRUE));
  $form['#build_id'] = $form_build_id;

As you are passing the value of "form_build_id," and "form_id" in the POST data, then the following code is executed (see drupal_get_form()):

if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) {
  $form = form_get_cache($_POST['form_build_id'], $form_state);
}

If the cache contains the form, then "form_build_id" is not generated again.


bulk importing data in articles node catagory based

Using Feeds and Feeds XPath Parser will do the trick. I would also take a look at Feeds Tamper. I have used it myself in the past and it works very wel!

Here is also a basic tutorial to get you started.

Good luck!


Drupal Views: Taxonomy Stripes for Calendar

Use the latest development snapshot. See http://drupal.org/node/1392306#comment-5581466 for the patch.


I recreated the website and added multilingual modules at the end. Now it works fine... still though I have no idea what was wrong...


Query nodes with a specific word in them

I'm not sure I'd agree there's not a lot of documentation out there (there are tons, just search Google for EntityFieldQuery).

That said, something like:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'some_type')
  ->fieldCondition('body', 'value', '%' . db_like($input_string) . '%', 'LIKE');

$results = $query->execute();

is probably what you're looking for


Add additional fields to select list on Webforms

Had to create a fieldset per each select option with only one select option available and then just play around with CSS and it looks like one select list with separate quantity fields.


What you usually write as getValue() without arguments is a method of an entity FieldItemList.
$view->field returns field handler plugins configured in the FIELDS section of a View.
Views fields handler plugins are an abstraction layer for all kind of data not necessarily based on entity fields.
If based on entity fields then getValue($row) runs this code:
/core/modules/views/src/Plugin/views/field/EntityField.php:
 public function getValue(ResultRow $values, $field = NULL) {
    $entity = $this->getEntity($values);

    // Ensure the object is not NULL before attempting to translate it.
    if ($entity === NULL) {
      return NULL;
    }

    // Retrieve the translated object.
    $translated_entity = $this->getEntityFieldRenderer()->getEntityTranslation($entity, $values);

    // Some bundles might not have a specific field, in which case the entity
    // (potentially a fake one) doesn't have it either.
    /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
    $field_item_list = isset($translated_entity->{$this->definition['field_name']}) ? $translated_entity->{$this->definition['field_name']} : NULL;

    if (!isset($field_item_list)) {
      // There isn't anything we can do without a valid field.
      return NULL;
    }

    $field_item_definition = $field_item_list->getFieldDefinition();

    $values = [];
    foreach ($field_item_list as $field_item) {
      /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
      if ($field) {
        $values[] = $field_item->$field;
      }
      // Find the value using the main property of the field. If no main
      // property is provided fall back to 'value'.
      elseif ($main_property_name = $field_item->mainPropertyName()) {
        $values[] = $field_item->{$main_property_name};
      }
      else {
        $values[] = $field_item->value;
      }
    }
    if ($field_item_definition->getFieldStorageDefinition()->getCardinality() == 1) {
      return reset($values);
    }
    else {
      return $values;
    }
  }

You can see how Views API connects with Entity API, but when programming Views API code you should stay at this abstraction layer if possible.


One way to hide the blocks completely without doing any coding is to set up your own custom dashboard using the Panels module.  With Panels, you can override pages (such as the admin dashboard) and then add the blocks using Panels.  The advantage of this approach is that you can use the Visibility conditions feature of Panels to only show the block for certain roles, which will completely hide the block rather than showing an empty version.

The disadvantage of this approach is that this might be overkill if this is all you need to do.


corresponding textbox for each user reference item

I'd use field collections.
In your members content type, create a field (say members collection) with multiple values. Then proceed to the field collections admin and add:

the user reference field
the textbox field

These two fields while creating the content type will now be 'one' with an 'add more' button under each.


How are node and field tables related in MySQL?

Fields belong to entities; entities are generic, and the same field can be shared amongst any number of different entity types. So you'll find potentially data from a number of different entity types in any given field table.

All field tables take the same basic form, with the entity_type, entity_id, language and deleted columns used as the differential (with delta added to make up the primary key, and allow multiple cardinality).

So a manual join for a node to the body table might look like this:

SELECT title
FROM node n
INNER JOIN field_data_body b ON b.entity_type = 'node' AND b.entity_id = n.nid AND b.language = 'und' AND b.deleted = 0

Regarding a "better way", the Views module is usually the best solution for such things. I've never used it but I also understand Forena Reports might be useful too.


Host doesn't support nested folder structures for deployment. How do I adjust Composer?

As you are using an Apache server, you may try to set the Drupal root folder using an .htaccess file in your site_root:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]

(Replace example.com with your actual domain name.)

This way, you can keep the "nested" folder structure created using Composer and serve all requests for your domain with the web sub folder.


Difference between 2 methods of adding a CSS files in theme.info?

Method 2 is provided by core (probably why it seems more standard, it'll be used more often).

Method 1 is something specifically provided by the Omega theme.

I think the only reason to use Method 1 is if you want to be able to control the use of the stylesheet through the optional stylesheets setting in the UI.


Can trusted host settings use an IP address?

Yes using an IP is fine, you just need to make sure you're using a valid host name (I.e. one without the path appended):

^10\.156\.222\.145$


How do I prevent the HTML markup in an item list from being escaped?

$items[] = [
  '#markup' => Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.',
];

$form['mei_marc_list'] = [
  '#theme' => 'item_list',
  '#items' => $items,
];

return $form;


How to search through database of businesses/how to build the content template?

The two major approaches to adding locations in Drupal 7 are location/gmap and addressfield/geocoder.  Comparing these two sets of modules in detail is the subject of a book, Mapping with Drupal, and is outside the scope of this post.  Unfortunately, both approaches are still under heavy development and in all honesty you will likely encounter a fair number of bugs either way.  At the moment, I would choose the Location approach because it has working proximity search (show me all businesses within 100 km of me).

If I were approaching this project, rather than using the built-in Drupal search, I would use the Views modules and filters (exposed filters) to allow users to search.  Once you are proficient with the Views module (Node One has an excellent series of screencasts on learning Views), you will probably find it easier to work with and customize than the basic Drupal search.

A few tips on location-
If you do install the location module it provides a "location directory" view by default, though it is disabled.  You can enable this view and play with it; it creates an index of all your nodes that have locations attached to them.  This should give you some idea about how to build location-based search in Views.

If you do use location, choose Location CCK (which will eventually be named to fields for D7), not the Node Location submodule.  They are mutually exclusive and Location CCK is the direction that the next major release of the Location module will take.


Boolean checkbox in sytems_settings_form

Have you tried removing the "#required" => TRUE line? If you uncheck the checkbox and the form item is required the form won't validate and your submit callback will not be called.

Also, you should check that your variable isn't overridden in settings.php https://www.drupal.org/node/1525472


Use below Drush command to reset admin password.

> drush uli
    (or)
> drush uli user_name

// Display a one time login link for the given user account (defaults to uid 1).

Just copy the one time login link and paste it your browser. Here you will get reset password option.

After successfully login, disbale the workflow module and go ahead.

More about Drush.


What are the various roles supported by the Group module?

Here is a summary of the various roles used by the Group module:

Configured Global Roles: These roles can be configured via the admin interface of the Group module, they are available (to grant permissions) for all individual groups (regardless of the "Group Type"). These roles cannot have permissions that vary per group type (they are all the same). Typical examples of such roles could be "Group Moderator" or "Group Administrator".
Special Global Roles: These are the special (hardcoded) roles named "Outsider" (= a signed in user that did not join a group) and "Member"  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. Unlike Configured Global Roles, these roles can have different permissions sets for each group type. Special case: the role "Anonymous" is related to a user that is not signed).
Group Specific Roles: These roles can be configured per group type and will only be available on groups of that group type. As an example, for a group type like "Class", you could configure roles such as "Teacher" and "Student".


Your backup is incomplete. Talk with your hosting company. In the meantime you can try to download fresh copy of ckeditor module, but even if it'll help, you will never know for sure what else is missing.


How to displayed fixed menus, extracted from the main menu?

If you go to admin/structure/menu/add and add four menus (Footer 1, Footer 2 ...), four blocks of the same name will also be created. Then go to your Main Menu and move the links into the new menus you have created.

Place these blocks where you want them at admin/structure/block and modify your stylesheets to make sure they display the way you want.


For those of you who may be looking to answer the same question, here's how I got it to work in my case (I'm working on a Drupal 8.3 site):

$users = [
  'test_local_contributor' => [
    'password' => '1testme1',
    'langcode' => $language,
    'preferred_langcode' => $language,
    'email' => 'test_local_contributor@example.com',
    'roles' => [
      'employee',
      'local_contributor',
      'testuser',
    ],
    'location' => [
      'Kentucky',
      'Paradise',
    ],
    'sbu' => 'energy',
    'bu' => 'natural_gas',
  ],
  ...(there were other test users, omitted for brevity)
];

foreach ($users as $key => $user) {
  $newUser = User::create();
  $newUser->setUsername($key);
  $newUser->setPassword($user['password']);
  $newUser->enforceIsNew();
  $newUser->setEmail($user['email']);
  $newUser->set('langcode', $user['langcode']);
  $newUser->set('preferred_langcode', $user['langcode']);
  foreach ($user['roles'] as $role) {
    $newUser->addRole($role);
  }
  $newUser->set('status', 1);

  if (isset($user['bu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['bu'], 'vid' => 'tx_business_unit']);
    $keys = array_keys($term);
    $newUser->set('user_bu', $keys);
  }

  if (isset($user['sbu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['sbu'], 'vid' => 'tx_sbu']);
    $keys = array_keys($term);
    $newUser->set('user_sbu', $keys);
  }

  $loc_keys = array();
  foreach ($user['location'] as $location) {
    $newkeys = array();
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $location, 'vid' => 'tx_user_location']);
    $keys = array_keys($term);
    $newkeys = array_merge($loc_keys, $keys);
    $loc_keys = $newkeys;
  }
  $newUser->set('user_location', $loc_keys);

  $result = $newUser->save();
}


Firstly, dirty way. In the template links--node.html.twig change this line {%- for key, item in links -%} to {%- for key, item in links  if key != 'comment-add' and key != 'comment-forbidden' -%}. This is for removing 'comment-add' and 'comment-forbidden' link. If you also want to remove links count apend the line with and key != 'comment-comments'. A simplier way to achieve this is to replace all ifs with if 'comment' not in key. Twig's in.

The second is more right way. The point is in using the hook hook_node_links_alter(doc). This hook alter node links behaviour. There is a core comment module. It realy worth looking if you want to know how node comment works. It requires drupal 8 module knowledge. The service responsible for node comments links is comment.link_builder and defined in core/modules/comment/comment.services.yml. And while observing core/modules/comment/src/CommentLinkBuilder.php you can find that it add different links to render array and all logic. So comment is just a module. So back to hook. It alters node links and add comment links. So you need to remove it again. To do it you can define your own module to create a hook. In module directory you need to create MODULE.module file and place the following code there:

use Drupal\node\NodeInterface;

function kapusta_node_links_alter(array &$links, NodeInterface $node, array &$context) {
  unset($links['comment__comment']);
}

Here nothing special, just implementing hook_node_links_alter. It removes comment link.

The third way is more elegant but need more work. It is based on similar things as the second way. The point is to rewrite the service core/modules/comment/src/CommentLinkBuilder.php. For this you need to define your own module. Then you will create a service with the similar name to CommentLinkBuilder.php. The symfony (framework drupal is using) will rewrite the service from comment module. And you will get your profit. So firsly you duplicate the service. To do this you create MODULE.services.yml in your module folder. The file content is the following:

services:
  comment.link_builder:
    class: Drupal\kapusta\CommentLinkBuilder
    arguments: ['@current_user', '@comment.manager', '@module_handler', '@string_translation', '@entity.manager']

Where do I get this? From core/modules/comment/comment.services.yml. Just replaced class with my own. Then you create that class. You will get the file modules/custom/kapusta/src/CommentLinkBuilder.php with the following content:

<?php

namespace Drupal\kapusta;

use Drupal\comment\CommentLinkBuilder as Base;
use Drupal\Core\Entity\FieldableEntityInterface;

class CommentLinkBuilder extends Base{
  public function buildCommentedEntityLinks(FieldableEntityInterface $entity, array &$context) {
    return [];
  }
}

'kapusta` is my module name. So that's it.

P.S
How I found it. I debugged variables in the twig {%- for key, item in links -%}. I discovered tha value of key in each iteration. It were comment-* keys I wrote about in the beginning. Then I search the project files by comment-add and found CommentLinkBuilder. With xdebug I came to the hook. Then I realize that it is just simple module. Hope this helps.


How to load a view with ajax with all js files needed?

What you did is a HardCode solution ,I suggest you instead of loading JS on block, put your JS in .JS files and add ( or attached) to page you want, with simple if your JavaScript just works for you, and remain only one problem, how pass NID to JS?

Pass it with something like

drupal_add_js(array('YOURMODULE' => array('nid' => $nid)), array('type' => 'setting'));

and get it on your js with

nid = Drupal.settings.YOURMODULE.nid;

1
down vote

There is a lot of documentation about how to include a JS file into a custom module or into your theme in general. Here is the official article: https://www.drupal.org/node/304255

There are plenty of examples and you can inspire yourself with it.


The linked module should try to add suggestions in hook_theme_suggestions_HOOK as long as it doesn't depend itself on existing suggestions, so that other modules still have the option to override these suggestions in an alter hook.

Hooks don't have priorities, which having two hooks, one main and one alter hook, is trying to compensate. This is like a priority system with only two levels. If you add something on the second level there is no third level for other modules, unless they resort to unusual solutions like module weights.


How to put a custom form inside node form with own submit button?

you should use an ajax in inner form on submit like :

  $form['activity']['submit'] = array(
  '#type' => 'button',
  '#value' => t('Execute'),
  '#name' => 'test_button',
  '#ajax' => array(
    'callback' => '_handle_form_submit',
    'effect' => 'fade',
),
);

 function _handle_form_submit($form, $form_state) {
 // your stuff here
 }

you can see ajax example modules Ajax Examples


How to set up Apache Solr with facets so that it uses a front page search form?

Question #1:
Go to admin/config/search/apachesolr/settings and select 'Bias'.  There you can set up the weights next to the terms you want to search through.  Perhaps they're on 'Omit' or something like that...

Question #2: Go to the search settings page and make Apache solr search be your default search.  That way, when users type in keywords in your regular search form, they will automatically use your apachesolr search.
admin/config/search/settings

Let us know if that worked for you!


Drupal 7 taxonomy add term missing url path settings

You probably have to enable path module (core) and pathauto module


How to write hook_field_placeholder_info() for the link module?

There is a feature request to add support for the link module. Unfortunate that patch has not been committed yet, but you can use/apply the patch in #5 and use

/**
 * Implements hook_field_placeholder_info().
 */
function mymodule_field_placeholder_info() {
  return array(
    'link_field' => 'url',
  );
}


Check this Post to learn about re-writing results in views

Add a new field called global:text in views and Choose Exclude from display in all the other fields you use
Now edit global:text and check rewrite result to add your mark-up there


For EFQ, you need to filter on the entity condition column entity_id which is the node id.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('entity_id', $id)
    ->entityCondition('bundle', 'event')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->range($page, 1);
$result = $query->execute();


Set the width of the select box in Drupal form

The size attribute you are trying to set there is related to how many items are shown at one time. So in those terms the height would increase and it would show a scrolling list of items to choose from if you added size to the select box. See Form API Docs for more information.

You need to target the select box with CSS to change the width (most themes/browsers set the width of a select box to width: auto; so it would be as long as the longest item to be selected).

So for instance if you want to set all of your select elements to take up the entire width of their containing divs you would set:

select {
  width: 100%;
}

Or if you want to target all select elements with a class of .form-select you could use:

select.form-select {
  width: 50em;
}

You can use id's also like select#id-of-element but using a class is the more generally accepted best practice for styling (not just in Drupal but general FED practices also).


It sounds like you have your AJAX callback working fine. But you said that the #ajax wrapper is wrapping the entire form. The elements returned from the ajax callback replace everything in the div provided as a wrapper. Since you are wrapping your whole form with the wrapper, everything inside that div (the whole form) is replaced with the elements from the ajax callback.

You'll need to be more selective with your wrapper element. Set it to only wrap the elements that should be replaced.


files[] is only used to register files containing classes or interfaces, not functions. The docs explain it well:

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file, like so:

name = Really Neat Widget
...
files[] = example.test

  When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

emphasis mine. Unless you have classes in any of those files (including the .module and .install file) that you want to be auto-loaded, you don't need an entry for them in the .info file; it just won't do anything.

If you need to pull other files in you can use module_load_include(), e.g.

module_load_include('inc', 'module_name', 'module_name.controller');


Getting field labels from the $node variable

The best way is to use field_info_instance($entity_type, $field_name, $bundle_name) to get information about specific instace of a field. The label of the field is contained in the array returned from that function.

 $info = field_info_instance('node','field_name','content_type_name');
 print $info['label'];


You can do this easily with the help of three modules
1) Entity
2) Fivestar
3) Field collection

Step 1. Install above modules.
Step 2. Create content type gallery.
Step 3. Add field collection as a field in the content type.
step 4. Add fields(Image field and fivestar field) to the field collection http://www.example.com/admin/structure/field-collections


In review, we had the wrong setting for the link. By setting Both internal and external links, the link was displaying properly with the query parameters.

In Summary

Both internal and external links should be set on the field setting
Ensure to use https:// in the beginning of the url


Take a look what is said here about running drush with crontab and pay especially attention to "Setting the PATH". Also you should specify the path to your drupal installation with the --root option.


How to hide view's results before applying exposed filter?

you could link to the view and pass a filter argument in the URL that doesn't have any results.

Or you could hide the exposed filters in a block. Also, create a "block" display for your view results.

Add the filter block to a page. Add the "results" block to the page but only show it for pages with "pagename?*".
That will hide your results block until filter values are passed through the URL.


Why do I get an error about the modules/custom directory not existing?

There is no such thing as modules/contrib or modules/custom with the vanilla download of Drupal.

It is a convention you can use for organization. Create the folders yourself. Drupal will still find the modules in either one. The same principle applies to the themes folder. Some modules that say "download the JS plugin to /libraries" - you would have to create this folder too.

Drush, Drupal Console, and Composer all understand this, as well. If you are using Composer, you just need to inform it in your root composer.json, example:

    "installer-paths": {
        "docroot/core": [
            "type:drupal-core"
        ],
        "docroot/modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "docroot/modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "docroot/profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "docroot/profiles/custom/{$name}": [
            "type:drupal-custom-profile"
        ],
        "docroot/themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "docroot/themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ],
        "docroot/libraries": [
            "type:drupal-library"
        ],
        "drush/contrib/{$name}": [
            "type:drupal-drush"
        ]
    }

When requiring modules, profiles, or themes, Composer will then place them in the appropriate directory.


How to remove Field Group module label length limit?

Try this module remove field length limit

  Removes field label length limit (which is 128 characters).
  The module supports entity field labels and views field labels.

Or you could also write a custom module

function yourmodule_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}


Ctools modal_form not working with webforms

The issue is your modal link path isn't correct. When using Webforms the link needs to use the Node ID (nid), not the form clean-url (/modal_forms/nojs/webform/[nid]) Here's how the link would look considering your example above:

Free Trial


How can I enable my community to flag (report) bad content on my site?

I made my own solution. Using Flags, Rules and Views.

I have also uploaded a video Tutorial on youtube explaining how to flag content and create a "Reset" action on content edition.

http://www.youtube.com/watch?v=b5xieuVf01E&list=PL1A89955CCEB73A09&feature=plpp


Classes aren't naturally aware of the container, you have to implement them in such a way that they are. The most common approach for controllers is to extend Drupal\Core\Controller\ControllerBase, and override the create method, e.g.

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LSWController extends ControllerBase {
  /**
   * @var AccountProxy
   */
   protected $currentUser;

   public static function create(ContainerInterface $container) {
     return new static($container->get('current_user'));
   }

   public function __construct(AccountProxyInterface $currentUser) {
     $this->currentUser = $currentUser;
   }

   public function say() {
     return new Response("Hello");
     //return new Response($this->currentUser->id());
   }
}

For you, though, this approach will be bittersweet...on the one hand you've learned how to inject services into a controller, which is great.

On the other hand, ControllerBase already has a $currentUser property, which resolves to the same object you'd be getting from the injected service. So in applying the common solution, you've removed your original need for DI, and made the create and constructor methods completely redundant ;)

As 4k4 very correctly points out in a comment, you don't have to extend ControllerBase; implementing ContainerInjectionInterface in your own controller class is enough. But the deliciousness of solving the problem with less code than when you started is surely too much to resist.


If statement for page template in node template file

you can do this like

if(arg(0) == 'node' && arg(1) == '1234'){
**Stuff here**
}


Drupal 7 Execute a mysql sql query in Views using Views PHP

You must avoid using php in UI.

As a solution
  - Either you can override the views template.
  - Or you can try implmenting hook_views_pre_render.(Reference https://knackforge.com/blog/sivaji/how-alter-views-field-output-programmatically)

Now, about fetching the results from query result object.

Other than iterating through the result set, there are other ways to fetch results.


I can rsync with drush but not `drush @remote status`

The first thing to do is to ensure that the 'remote-user' in your site alias is the same user that you use when you log in to the site.

The next thing to check is whether or not drush is on your $PATH on the remote site.  You have probably set this up explicitly in a .bashrc file, since it is working when you log in locally.  However, often, .bashrc files exit early when called in non-interactive mode, as Drush does.

Perhaps the easiest way to get around this is to figure out what the correct full path to the drush script is, and set '%drush-script' in the 'path-aliases' of your site alias to point at the correct executable.  See example.aliases.drushrc.php.

UPDATE: Use '%drush-script', not '%drush'.

'remote-user' is the user that Drush will use to log in via ssh. It should be a user that has permission to use Drush. Some people use the webserver user for this, but if you have a separate web admin user, that would be a preferable choice.


Not all Drupal paths end with a content (or node) page. For example, the D7 core Contact module has the path /contact, but in order to "edit" it you need to change administration pages within the admin section (/admin...) or a theme template if you're wanting to change how the HTML is rendered.

The closest thing to what you're looking for is the menu_router (D7) or router (D8) database table. These DB tables contain static/dynamic paths (the path column) with additional metadata about what/how these paths rendered. They should help you discover what controls paths that aren't node or node alias paths.


Share count statistics

Allows your Drupal site to gather statistics on how many times your
content (and other entity types) have been "shared" with
social/sharing services like Twitter, Google+, Facebook, etc. Also
provides an API for other modules to hook into and provide their own
share counts.

Social Stats

This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:

Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one count, share count & total count
Total Share Count : total across all available social networks


Issue trying to implement the Swagger UI module in Drupal: ReferenceError: SwaggerUIBundle is not defined

I seem to have found a resolution to this issue.
In the installation notes for the SwaggerUI module, the instructions state to add this block of code to the composer.json
"extra": {
  "installer-paths": {
    ...
    "web/libraries/{$name}": ["swagger-api/swagger-ui", "type:drupal-library"],
    ...
  }
}

When running composer install, composer will place the external swagger-api in the /web/libraries/<whatever> directory.
In the openapi_ui_swagger.libraries.yml file located within the SwaggerUI module, it is pulling in the external swagger-api here:
swagger_ui:
  js:
    /libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /libraries/swagger-ui/dist/swagger-ui.css: { minified: true }

swagger_ui_integration:
  js:
    js/swagger.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - openapi_ui_swagger/swagger_ui

The library paths need to be updated to match the directories created in the installation notes:
js:
    /web/libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /web/libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /web/libraries/swagger-ui/dist/swagger-ui.css: { minified: true }


how to get the translated taxonomy term programmatically?

Try

$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

Also, a good place to look for more information: /sites/all/modules/i18n/i18n_taxonomy/i18n_taxonomy.module


Can I use a theme done for the previous version in the latest core version?

No. You could convert one if you have the time - which involves turning all tpl files to twig, updating the syntax, and making necessary changes to the template.php file (which gets renamed to template.theme). That also includes replacing any functions that don't exist anymore, and using the new D8 equivalent. Again, not too hard, but it can be if you are brand new to D8.

For smaller themes, this can take few hours to a day or two; for more involved themes, it can take longer.


Getting xdebug to work with BrowserTestBase functional tests?

BrowserTestBase and KernelTestBase use phpunit's 'run in separate process' feature which generates a new temporary php file from a template and then executes that. The output is provided as serialized php object which is then read back into the main thread an unserialized to yield the results.

So at present that makes using Xdebug fairly difficult.

We probably should open an issue to look at shipping our own template that support Xdebug.

In the meantime my suggestion would be to use outputting, you can use the standard approaches like var_export, print_r, echo etc or you can use $this->htmlOutput($something_you_need_to_debug); which then shows up amongst the other HTML output.

Then run your tests with -printer="\Drupal\Tests\Listeners\HtmlOutputPrinter"

This requires the BROWSERTEST_OUTPUT_DIRECTORY environment variable to be set, see core's phpunit.xml.dist for info on how to configure that.


You can't uninstall modules by deleting them. You need to run the uninstall routine. Via UI (which doesn't work in your case as you can't log in) or via CLI (Drush or Drupal Console).

Put the module back.
Uninstall it via Drush.
Log in.

drush pm:download cognito
drush pm:uninstall cognito
Log in.


Best practice for third-party PHP class-based library

Branch 2.x of the Libraries API module allows developers to define, through hook_libraries_info(), or a .info file for the library, the following information (see libraries.api):

The dependencies of the library
The version with which the library is compatible, for each of the dependencies
The list of the files that needs to be loaded (CSS, JavaScript, or PHP files)

The list of files that needs to be loaded is used to load those files, when the library is required. This means that your module doesn't need to load CSS, and JavaScript files with drupal_add_css(), or drupal_add_js(), as that is already done from the Libraries API module. Loading the dependencies is a task done from the Libraries API module, without the calling module doing anything.

All the module does is using the following code, for loading a library. (See Using Libraries API 2.x (as module-developer).)

// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

If you just need to detect if a library is present, the module should use code similar to the following one.

if (($library = libraries_detect($name)) && !empty($library['installed'])) {
  // The library is installed.
}
else {
  $error = $library['error'];
  $error_message = $library['error message'];
}

Between the properties hook_libraries_info() can return, there is also 'download url', which is not actually used, not even in the branch 3.x. Probably it will be used in future, or a third-party modules could hook into the Libraries API module, and download the libraries that are requested, but missing.


How to place a custom javascript link/button in each row of a Views table

You can use a Global Text field to create the link, and, since Views wraps everything in all sorts of divs, use jQuery to grab any of the other fields there for your js


EntityFieldQuery return nodes with all terms

You can try:

foreach ($sections as $section) {
  $query->fieldCondition('field_section', 'value', $section);
}


Authenticated users can't view the front page

Building on Patrick Kenny's comment, I'd recommend looking for the 'URL redirects' page within your admin pages. (You will have this page if you've installed a module which supports URL redirects - 'Redirect' in D7, 'Path redirect' in D6.) Then see if any rule is defined there which'd redirect visitors from site.com/node/4 to site.com/user/4 .

If this module isn't doing this, odds are another one is, so as Patrick says start disabling contrib modules one by one.


How to group taxonomy terms by their parent when using term reference field?

I think Taxonomy Super Select does what you want for Drupal 6, but there's no Drupal 7 version available.

However, the module page recommends the Taxonomy Term Reference Tree Widget module to do the same thing

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


Comment.tpl.php how to add a link back to the node

You can use the entity_uri() and l() functions, similar to how it's done in template_preprocess_node():

$uri = entity_uri('node', $node);
$link = l($node->title, $uri['path'], $uri['options']);


Display Suite Custom Wrappers and Custom Classes Tabs Not Appearing in Manage Display

Two possibilities come to mind.

1) Have you saved since you selected "One Column" as the layout? The configuration options change once you select something other than -None-

or

2) Have you checked that you have the correct Display Suite permissions? Namely, 'Administer classes' and 'Administer fields'


Why do I get a blank page when I create a new node?

The White Screen of Death (or WSOD) can be caused by a lot of different things.  There is an article about them http://drupal.org/node/158043

Without more information, especially error messages or logs, all answers will be guesses.

Follow the steps in the article above, in order and one by one, to track down your problem.  The first step is making sure you can see errors by adding:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

to you index.php or settings.php.  Once you do this, you should see what is happening and be able to address it.

That said, the two biggest culprits of WSOD are errors in custom code and hitting the PHP memory limit.


"Signature" user field not appearing in list of user fields

While it doesn't appear that you can put it in the field list directly and drag and drop it around as the user module only exposes the account and timezone in its hook_fields_extra_fields(), you certainly can move it around "manually" in a hook_form_alter() in a custom module, eg something along these lines:

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

  switch ($form_id) {

    case 'user_profile_form':

      drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>'); // to see what you have to work with

      $form['signature_settings']['#weight']='8';
      $form['field_my_second_custom_field']['#weight']='9';

      break;

    // other forms go here

  }

}

...which, if you had the following in your user:

...would create this in the edit form:

...eg, we moved the #weight around, which is what the drag and drop anchors do in the UI.

In this example, user.module initially creates the signature settings with a weight of 1, and then the custom fields with 7 and above, so, by changing the weight to 8 for the signature settings and the next field to 9, it puts it between those two fields.  Check out the Drupal Form API and #weight for more information on what this is all about.

If you click show row weights at admin/config/people/accounts/fields you can see this more directly:

ADDITION:  Using Field Groups

If you had it set up like this:

...and wanted to put the signature settings inside the "My Group" field group, you could do something like this:

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

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      $form['#fieldgroups']['group_my_group']->children[]='signature_settings';
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

...which would produce this:

YET MORE ADDITIONS:  Tab Groups

If you want to put it in a tab group, eg:

...this will do it:

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

  switch ($form_id) {

    case 'user_profile_form':

      $form['signature_settings']['#weight']='6';
      $form['field_my_second_custom_field']['#weight']='7';

      // $form['#fieldgroups']['group_my_group']->children[]='signature_settings'; // apparently this isn't needed afterall
      $form['#group_children']['signature_settings'] = 'group_my_group';

      break;

    // other forms go here

  }

}

...which produces this:


Exposed filter with "inverted" checkbox: Checked = view all, Unchecked = filtered

I have not tested this but you might be able to do it by using 2 filters. Add a non exposed filter that filters by stock > 0. Make sure it is below your current filter. Views filters in order from top to bottom. So if the page loads and that check mark is un-checked you will only see products with a stock greater than 0. If they then check the box it will re-load and filter by your stock >= 0. That might work. As I said I have not tested this.


I write this module to render custom logo for each Organic Group:

function og_logo_block($op = 'list', $delta = 0, $edit = array()) {
    if ($op == "list") {
        $block = array();
        $block[0]["info"] = t('OG Logo Block');
        return $block;
    } else if ($op == 'view') {
        global $theme;
        global $node;
        $block['subject'] = '';
        $settings = theme_get_settings($theme);
        if (($node = og_get_group_context()) && node_access('view', $node)) {
            $block['content'] = l('title . '" title="' . $node->title . '" src="' . base_path() . $node->field_logo[0]['filepath'] . '" />', "node/$node->nid", array('html'=>true));
        } else if ($settings['default_logo']) {
            $block['content'] = '';
        } else {
            $block['content'] = '';
        }
    }
    return $block;
}


Unable to jump to a specific spot (seek) when mp4 or mp3 is in private field

Problem

Chrome makes multiple HTTP request with Range header for media file and expects HTTP Content-Range and Content-Length response header with 206 Partial Content status (read this). If server send '200 OK' status Chrome will not play the media file, but Firefox will.
If server send '200 OK' status with response header 'Accept-Ranges: none' then Chrome will play media file, but jumping will not work.
I assume you have implemented hook_file_download() already. That hook should return array of appropriate HTTP headers. It's enough to return Accept-Ranges header (only if your module should handle the media file and current user has permission):

return array(
  'Accept-Ranges' => 'bytes',
);

Solution - Drupal 7

Accept-Ranges response header with value 'bytes' is a signal to client that server supports Range request. If you don't want to support Range request you should use 'none' instead of 'bytes'. There is no server support for Range request for private files. Therefore you should install Resumable Download module which will setup other HTTP response headers like: Content-Range, Content-Length and ETag, and set HTTP status 206 Partial Content. Drupal core module File will setup other HTTP response header like Content-Type.


Why does hook_menu() not show my items in menu?

There are a few things that look out of place there:

Your module name is instance_export so you should not use instance_export_form as a function name because Drupal will think that you are defining hook_form() and you will run into problems. Best to use function names that are less likely to clash with other modules.
The menu item admin/config/content/instance_export/settings is using drupal_get_form() as the callback but isn't passing in any form ID as 'page arguments'
The menu item admin/config/content/instances_export uses the page callback drupal_post_form(), which is not a Drupal function. I assume you want drupal_get_form() here also.

Something like this should work better:

function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instances_export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

Note that I made up a form function for the first menu item (instance_export_settings_form) and changes the one for the second menu item (instance_export_export_form). This would be whatever you want your functions to be.

Also, if you want these pages to be tabs in your module's admin area do it like this instead:

function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'type'             => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/config/content/instances_export/export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
    'type'             => MENU_LOCAL_TASK,
  );

  return $items;
}

I'm assuming that your hook_block_info() is not relevant to this question.


You somehow have aggregator uninstalled with its tables existing, which should not be. By examining aggregator_schema() in aggregator.install you can see that upon installation aggregator will create several tables named aggregator_(something). Table names correspond to the keys of the array returned by aggregator_schema(). If any of those tables exist you must delete them from the database before attempting to enable the aggregator module. As always, back up and understand how to restore your database first before attempting something like this and rehearse on a test system.


Disable caching of attached css/js libraries for custom module?

You are on the wrong track. Caching of static assets (and CSS files are static assets when you disable CSS/JS aggregation) has nothing to do with Drupal's cache. Disable the caching of *.js and *.css files on your web server instead (e.g in .htaccess if you are using Apache).


How to create a global language selector page at domain root with i18n when the global language has a prefix?

Consider creating a special "homepage" node, for which you set the "language" to "Language Neutral" (any path will do, even no path if that's what you'd prefer). And use its node ID (preceeded by 'Node/') as the value for "*Default front page *" within admin/config/system/site-information.

From then on, you can create any content for that node as your language selection page, which of course should include a link to each language specific "starting page".


How to import/add translated strings having inline styles?

Yes your guess is correct,locale_string_is_safe  "Check that a string is safe to be added or imported as a translation." if you want to ignore your job you should patch it for a while ,
change it to

function locale_string_is_safe($string) {
  return TRUE:
}

after your job  revert it.


Drupal Commerce - product attribute price based on quantity

You may decrease price by setting up the rule on "After product added to cart" event, checking up the quantity added and calculate discount in a way you want to, for example.


Is It Possible To Show One More Views In Homepage

In Drupal 7, you should create a "block" display for the views you want to show, by selecting "Add" in the view config page.

When you save the view block, the corresponding blocks will show up in the /admin/structure/block administration page and you can add it to any page you want.


How to trigger a rule if a node has a certain Taxonomy term?

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tags" } },
      { "list_contains" : { "list" : [ "node:field-tags" ], "item" : "21" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_tags] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_tags", which is the machine name of the term reference field I want to check for.
List contains item "node:field-tags" and with Taxonomy term identifier value "21" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_tags] just got created or updated." (with [node:field_tags] the actual term with term id = 21).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions.

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Replace the Rules Event (if needed).
Within the Rules Conditions, perform these changes:

replace the "node" entity with your entity.
replace the machine name of term reference "field_tags", and adapt the "term id" to fit your case (for the term "Video").

Replace the Rules Action by whatever fits your case.


How should I include an image field from a taxonomy term in a node view?

If you're using Drupal 7 then you will have to add a "Content: Taxonomy terms on node" relationship before attempting to add the term image field. When you add the relationship then in the Fields section you will be able to choose term fields (like the image field of your terms) to display them in your content view.


How can i put two forms build in one module to two URLs

Have to make small change on function custom_menu.

Try this code.

function custom_menu() {
  $items['custom/first'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_first',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );
  $items['custom/second'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_second',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );

  return $items;
}


My form does not show any action on clicking the submit button

Something like this should work:

/**
 * Implements hook_block_info
 */
function loan_calculator_block_info() {
  // This example comes from node.module.
  $blocks['loan_calculator'] = array(
    'info' => t('Loan Calculator'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

/**
 * Implements hook_block_view
 */
function loan_calculator_block_view($delta = '') {
    switch ($delta) {
      case 'loan_calculator':
        $block['subject'] = t('Loan Calculator');
        $block['content'] = drupal_get_form('loan_calculator_calculator_form');
    return $block;
    break;
  }
}

/**
 * Form builder
 */
function loan_calculator_calculator_form(){
  $month = range(1 , 12);
  $form['amount'] = array(
    '#title' => t('Amount'),
    '#required' => TRUE,
    '#type' => 'textfield',
    '#element_validate' => array('element_validate_number'),
  );
  $form['duration'] = array(
    '#title' => t('Duration (Months)'),
    '#required' => TRUE,
    '#type' => 'select',
    '#options' => $month
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * Form submit handler
 */
function loan_calculator_calculator_form_submit($form, &$form_state) {
  drupal_set_message('<pre>'.print_r($form_state['values'],1).'</pre>');
}

Note, the renamed functions are per Drupal convention, (avoiding hook_form namespace collision), including using default submit handler. Also, no need for validate handler if amount element is required and set to numeric element validator. Tidied up a bit, should be fine but needs testing.


Unfortunately no, I must use a module for that, only because of module_invoke use to call the hook.

Also, I was thinking that you could just add your functions on template.php, but this file is only included in the theme function, that doesn't allow you add some stuff, expect throw theme override.


For a quick fix you can make 'Distinct' in the view setting setting.


Is there a way to mock a procedural function from common.inc in a test without an external library?

I have found a solution on this page: https://www.drupal.org/docs/8/phpunit/unit-testing-more-complicated-drupal-classes

  You can mock a global function by adding fixtures in your test module.
  Let's say that you need to mock base_path().

  Simple go add a fixture in your testing src
  Add a mock for function, for example, you can
  define like above:
  Simply use require_once on your setup and you get your mocked function available and replaceable only in the test you are requiring. Make sure to use function_exists() to check if the function you need to test isn't already available.

 /**
  * Overrides global function if not exists.
  *
  * @return string
  *   Base path mocked.
  */
  function base_path() {
    if (!function_exists('base_path')) {
      return '/';
    }
  }

In my case, I have used fixtures, as refactoring the code was out of question.

As the documentation says, I've created a mocked function in tests/fixtures/function_name.php and included the file into the setUp() method of the test with require_once. This way, I've had my own global function in the test's scope.


HybridAuth has stopped working with FaceBook

Please check the issue already submitted in drupal.org https://drupal.org/node/1860618 . Especially check this comment. You have to use latest 7.x-2.x-dev release.


You will need to preprocess the block instead of the page. Preprocessing pages will not pass a variable to the block. See hook_preprocess_block. If you are needing to determine values based on how many times a block is rendered you can look into using drupal_static to store variables that can be reused during the rendering process.

Drupal static example:

$first_row = &drupal_static('first_row');

if ($first_row == 2) {
  // I equal 2
}

// Since I am passed by reference I can alter and will keep my value.
$first_row++;


How to get next valid `product_id` value within Rules for drupal commerce product?

You cannot set the product ID manually, because it depends on the AUTO_INCREMENT value in your commerce_product database table. What you can do is use "Save an entity" on the product and check the "Force saving immediately" checkbox. The entity will have an ID after that, though I've had scenarios in Rules where for some reason the ID wasn't immediately added to the entity in memory. If this happens to you, you'll just have to use "Fetch an entity by property" after saving and load the product using the SKU or something and use the fetched_entity from then on.


Figured it out. Here's the rules settings. This will take 10% off your order if the total quantity of your cart is 14+

{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_compare_total_product_quantity" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "operator" : "\u003E=",
          "value" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


I suppose this is happening because you set the default language as English (see: /admin/config/regional/language) and set Russian as default to have Russian language on "/" .


Unable to retrieve node object in a block without access permission to said node

What you can do is impersonate another user for a while. More details here https://www.drupal.org/node/218104

At the start of the function:

$session_prev_status = drupal_save_session();
drupal_save_session(FALSE);
global $user;
$actual_user = $user;
$impersonated_user = user_load(1); // This will impersonate user 1, an administrator.
$user = $impersonated_user;

Then, at the end of the function:

$user = $actual_user;
drupal_save_session($session_prev_status);


How to allow integer and decimal fields with default values to be saved as empty.

This is a bug in D7. Checkout https://www.drupal.org/node/1253820. I checked it works while editing content but not while creating. This has been fixed in D8. For D7, you can write custom code to handle this.


You should be able to duplicate this functionality using the Field Collection module.

In short, you attach a Field Collection field to an entity, and then define the Field Collection in a separate UI (/admin/structure/field-collections) by attaching additional fields to it. It will behave like (and is in fact internally represented as) a first-class entity, and the module allows you to manage these items from the same parent form you attached the Field Collection field to, complete with drag-and-drop for reordering and the like. It also has a number of other nice features, such as letting users with appropriate permissions add/edit/delete Field Collection items while viewing the parent node without having to go into the edit form itself.


One of my friend suggested me to create three displays in views each showing result from each table i.e. first display to show the fee details, second fee instalments and third to show the fee students. Then in page display all three views by using the functions views_get_view. Thanks Inian :)

While doing the way Inian suggested, I found attachment as a display type and that solved my problem and I don't have to write any custom code now.


How do I connect vocabularies and filter them to be depend on each others?

The alternative solution is to add a single vocabulary "TV" and make it two level. In first level all the "channels" will come and "shows" will be added as a child term (second level). Now for reference use "Hierarchical Select" module.


set field value from function after user account edit/registering action

Have you tried hook_user_presave() ?

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7

You have access to all fields of your new user and can pick up your value, call your custom code and get your new id. Then add it wherever you need to.

Use dpm($account) to inspect your user object.(devel module)


Here's how I did it in Drupal 7, without the use of any other add-on modules:

Add a select box to the form.
In the select box options field, add your info in this format:

  email-1@address.com|Select Option 1

  email-2@address.com|Select Option 2

  email-3@address.com|Select Option 3

Save your form, then click on the "Emails" sub-tab of the "Webform" primary tab.
Choose "Component Value > The name of the field you created in step 1". Click "Add".
Adjust your settings as needed on the following page, and you're done! The webform will now send an email to the address associated with the choice selected in the select box.


How do I migrate a Kickstart site from one server to another?

drush ard
(https://drushcommands.com/drush-7x/core/archive-dump/)
copy backup file to the new server
drush arr (https://drushcommands.com/drush-7x/core/archive-restore/)
done


Using sticky-enabled Table Headers causes IE10 to crash on printing

In the last paragraph you talk about hook_js_alter.

Basically the first part should be a name of your template or custom module, so if your module will be named ie_workaround.module function should look like this:

function ie_workaround_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

It's important to do your best to have this hook executed when this element is already set by the module or theme that sets it. You can do this using hook_module_implements_alter and placing your hook at the end of hooks array.


How do I access the parameters fields of hook_mail_alter(&$message)?

The message entity is stored in $message['params']['contact_message'] and it contains all the values from the contact form. Given that it's an entity of type contact_message, you can operate with get() method to get the values of any field that your contact message might have. Example:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {
  if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];
    // Get sender's name.
    $sender_name = $contact_message->getSenderName();
    // Get sender's mail.
    $sender_mail = $contact_message->getSenderMail();
    // Get subject.
    $subject = $contact_message->getSubject();
    // Get message.
    $message_body = $contact_message->getMessage();
    // Get the value of "field_request" field.
    $request_value = $contact_message->get('field_request')->getValue();
  }
}


Drupal bootstrap running from command line

You could also try Drush. Once you've installed it, you can cd into your drupal root then run drush scr test.php. In that file, all Drupal functions will be available.


Entity Reference - am I using it correctly?

One way to do it is with Views and a module called Eva (Entity Views Attachment).  Eva allows a view to be attached to a host entity, and understands how to filter the view based using the host entity's id to display only related information.

Since you already have the entity reference field on the credit cart type, the steps would look like this:

Install Eva and Views as needed
Create a View for the credit card content type
In the view, add an "EVA" display
Configure the view to be attached to the customer (under Entity content settings)
Add a Contextual filter using the field that links back to Customer. This will filter credit cards using the customer profile entity


Export views result as json, xml, csv etc?

There are some options to export Views data in CSV format in Drupal 8

Views Data Export Module

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV Microsoft
  XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT

VBO Export Module it adds CSV export feature for Views Bulk Operations  Moule

  The module adds 2 new Views Bulk Operations actions: Export to csv and export to Excel.

3.CSV Serialization Module

This module provides a CSV encoder for the Drupal 8 Serialization API. This enables the CSV format to be used for data input and output in various circumstances. For example:

  Drupal 8's REST module can accept or return data in CSV format Views
  can output CSV data via a 'REST Export' view Module developers may
  leverage CSV as a format when using the Serialization API


Selling user accounts with Ubercart module


How do I adjust the 'Create New Account' settings?

There were a few options for Drupal 6 so it's hard to give generic instructions. Check the module page for modules that include the word password and check for a "Configure" link.

Take Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


If multiple routes match a path pattern, how can I tell which one would be used?

Your question is not clear enough.
Again, Your quote had full answer, the result is sorted by the fitness from highest to lowest fit. In case, they were equal, it would be sorted by alphabet of route name.
Return to your question, people usually use this function when they have a full or nearly full route name to check. or they have to add another condition that out of scope of this function.
You can not ask how Drupal determine which one wins when they are equal.


I have actually resolved my problem by adding a piece of php code within filter criteria. see attached.


You should build your own theme and edit the tpl file to apply the layout you need

the easiest way is to build child theme and edit what you need in tpl files

create child theme


Reloading option in a select list with ajax

Have you tried with $form_state['rebuild']=TRUE. It will help you to update your changes while adding new client.


Help me to implement this plan - limit users to edit content

I would look into the Node Access User Reference module as well as a lot of the other content/node access modules out there, eg, this list off drupal.org.  After getting a good grasp there, it would be up to you to code up the integration of permissions unique to your site, but basically you would need to alter the node forms for this content type, check in there if a user reference is NOT yet set, and if so, set it to user editing the content and then be on your way.


Convert Media tags to markup failing again

For those of us just constantly plagued by this failure in programming, here's a link with the solution that worked for me. Upvote if you find it helpful:
Media with WYSIWYG not converting media tags to markup

Essentially, don't trust print render() - I had to use this in my custom template file:

<?php print render(field_view_field('node', $node, 'body', array('label'=>'hidden'))) ;?>


You can use module_load_include() to include a PHP file.

module_load_include('php', $type, 'includes/google-api-php-client/src/Google/autoload');

Where type can be either theme name or module name. I guess in this you are building some drupal module so it must be module type. In which case it will look for autoload.php file inside your name module directory. However internally it will do the require_once instead of include_once :)
You can use Libraries API module to include a php file. For this you will have to keep this google-api-php-client inside libraries folder. And you will perform these steps to implement it.

function hook_libraries_info() {
  $path = libraries_get_path('google-api-php-client');
  set_include_path($path."/src/" . PATH_SEPARATOR .  get_include_path());
  $libraries['google-api-php-client'] = array(
  'name' => 'Google OAuth2 Library',
  'vendor url' => 'http://code.google.com/p/google-api-php-client',
  'download url' => 'http://github.com/google/google-api-php-client/archive/master.zip',
  'version arguments' => array(
    'file' => 'src/Google/Client.php',
    'pattern' => '/LIBVER = "([0-9\.a-z]+)/',
    'lines' => 40,
  ),
  'versions' => array(
    '1.0.5-beta' => array(
      'files' => array(
        'php' => array(
          'src/Google/Client.php',
        )
      ),
    ),
    '1.1.5' => array(
      'files' => array(
        'php' => array(
          'src/Google/autoload.php',
        )
      )
    )
  ),
  'files' => array(
    'php' => array(
      'src/Google/Client.php',
    ),
   ),
  );
  return $libraries;
}

Note: The version is 1.0.5-beta, so you may need to change the version as per your API version.

Then to include this library in another module.

function hook_init() {
  $path = libraries_get_path('google-api-php-client');
  if ($path) {
    set_include_path($path."/src/" . PATH_SEPARATOR . get_include_path());
  }
}

Since it comes it composer.json/autoload.php you can use these modules to load it automatically from libraries folder.
X Autoload, Composer Autoload, Composer Vender Autoload, although you will still need to define the location inside your module.

Using the XAutoload module

   function mymodule_libraries_info() {
     return array(
       'google-api-php-client' => array(
         'name' => 'Google Client Library',
         'xautoload' => function($adapter) {
           /** @var \Drupal\xautoload\Adapter\LocalDirectoryAdapter $adapter */
           // Scan sites/all/libraries/google-api-php-client/composer.json to look for
           // autoload information.
           $adapter->composerJson('composer.json');
         }
       )
     );
   }


One time change field + personal comments

If I understand the problem. You can write hook_form_alter() in custom module and disable needed fields when user edit node. And configure permissions on this page admin/people/permissions


How to display a block only for an article with a specific node id?

I would steer clear of using PHP for block visibility.  If you type something wrong you can break any number of things.

Just go to your block settings, and take a look at the vertical tabs at the bottom of the page.  The first option is Pages.  Just change the radio button to "Only the listed pages" and enter node/3 in the box.

EDIT

If you use the Views Reference module mentioned in your question, then you can quite easily embed a Views block as one of your fields just as any other field.  The field itself can't be exclusive to a node ID, only an entity type.  However, you could just leave it blank for the other entities of the same type and use Field Permissions if you are worried about other people using the field incorrectly/at all.

One unrelated helpful hint with Views Reference - I generally tag my "reference-able" views with the same tag (i.e. Embeddable, Referenceable e.t.c.).  then you can easily select which Views to make available to the Views Reference field.

You MIGHT be able to embed blocks with Entity Reference combined with BEAN or Boxes, but I'm not 100% sure.  Failing this you are probably looking at breaking up the entire $content variable in the template and embedding it yourself (which would mean much more maintenance if fields get added or removed), using Views and turning the whole content types into blocks that can be positioned (MUCH effort).


A paragraph is a content entity with fields, that is viewed within its parent entity. It uses exactly the same mechanism to be displays as nodes, comments, and so on. Through field formatters.

You can implement your own field formatter plugin that transforms your (link?) field in any way you want. You receive field items and have to return a render array. That's the only restriction.

Like all plugins, it's a class with an annotation, in a specific namespace/folder. The default formatter for link fields is LinkFormatter. The most important method is viewElements().


Migrating a Drupal Node.js website from localhost to web server

The typical NodeJS setup usually involves a Linux server and a nginx web server/proxy that delegates the requests to the application running on a specific/semi-random unprivileged port. In other words, nginx will have a site declaration (vhost) for your Drupal and a another site declaration for your NodeJS application. Your NodeJS application runs in the backgrounds and listens for requests from nginx.

NodeJS itself is usually installed through the Linux distribution's packaging system, similarly to PHP.

On the filesystem, I would treat the two applications as separate projects, in two separate directories on the server. It's pretty rare to find developers who have a good understanding both Drupal/PHP and NodeJS, so keeping it separate will make it easier for other people eventually working on that project to familiarize themselves with the environment.


I recommend to resaving for smaller count of nodes, and run next script few times. Of course using batch will better UI, add itself:

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

$from_nid = variable_get('tmp_from_nid', 0);

$sql = "SELECT n.nid
        FROM {node} n
        WHERE n.nid > :nid
        ORDER BY n.nid";
$result = db_query_range($sql, $from, 1000, $from_nid);

foreach($result as $row) {
  set_time_limit(30);

  $node = node_load($row->nid);
  node_save($node);
  $from_nid = $row->nid;
}

variable_set('tmp_from_nid', $from_nid);
drupal_set_message(t('Last processed nid - !nid', array('!nid' => $from_nid)));
?>

Also VBO for mass resaving nodes.


What I do is create a content type for storing this data and use Views to display/output the attached fields as a block.

Views itself natively supports importing and exporting (if I'm not mistaken through Chaos tool suite (Ctools)), and to copy the content type you could use Bundle copy.

This allows me to easily reuse parts of website structures in other projects.


how to display array in div structure in drupal 7?

After a research of 20 minutes, I came to this answer.theme('item_list', array('items' => $output)); This function follows a simple array key value structure.It doesn't support multiple idexes. so remove $i from array, and it will work.


Why do PAreview/codesniffer gripe about missing "scope modifier"?

As this example blog shows, a testcase is a php class. The definition of setUp in the base class is a public function. Your implementation function of setUp must/should match the defined definition. So Parview bitches.

class MymoduleTestSuite extends DrupalUnitTestCase
{ ... }


Can not find the price of products in ubercart tables

I dont know what modules are installed on the site. But prices were in different tables for different currencies, found them finally

content_field_price_usd
content_field_price_eur