How to print a field value in page front tpl file?

I am not sure if this is what you are asking for, I think you want to show a download link for an image on your home, you have image on your node with node id 3.

In this case you can use download_file module, it allows to create direct download link for fils/images.All you need to do is create a view(through views module) of display type block, in your view add image field and keep the formatter as direct download file, place this block on front page.

If you want to render the download link programmatically, you can use the same function as defined in download_file module to render the links.

If you want to print image programmatically consider this:

print theme('image_style', array('path' => $node->field_theme_image[$node->language][0]['uri'], 'style_name' => 'home_theme'));


Authentication cookie in a load balanced environment

Yes, if you've configured your servers correctly.

Authentication state is stored in the DB. As long as each Drupal node (app server) in your load balancer pool is configured to talk to the same database, it shouldn't matter what server the browser is talking to. Login data will persist in the database and each Drupal node should be able to find it via the user's cookie data.

The challenge is making sure all the infrastructure correctly. Those details are off topic here, but you might find Using a load balancer or reverse proxy on drupal.org helpful for other Drupal-specific stuff to know when dealing with Drupal behind a proxy (load balancer).


Try this

<?php
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;
?>

Or

$uid = \Drupal::currentUser()->id();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getUsername();

You will get more details about User::getUsername.


Do it in the actual database, not via Drupal but via CLI, PHPMyAdmin, or whatever you have.

Find out the user's ID.
Go in to the raw database, i.e. not via Drupal but via CLI, PHPMyAdmin.
Go the user table.
Find their ID.
Set the status field for that user to 0 (which means blocked).

The raw SQL would be something like (I haven't tested this):

UPDATE users SET status = 0  WHERE id = [user's id]


Update entity ref field in parent form with new node created in ctools modal

There are few existing modules which gives the same functionality.
 - https://www.drupal.org/project/entityconnect
 - https://www.drupal.org/project/references

If you want to handle it in custom way, fetch the field and set the default (target_id) value in the form array element and use drupal_render/drupal_render_children to convert the form element array into html and try to replace it in the front end.


Can't tell you why, but can tell you how I fixed it last time when it happened to me:

Disable Admin Menu
Uninstall it if possible
Delete it's files and directory
Download and unpack fresh copy
Clear all caches (Drupal and browser)
Enable Admin menu

Worked for me, when menu disappeared during 6.x -> 6.x upgrade, when everything else failed to bring it back.

If the problem is only with core toolbar module, and not Admin Menu module, you have 2 options, really:

Try steps above, just for Toolbar. You can download core archive and then just extract toolbar's directory. Admin menu and toolbar are build in similar fashion, and purging all module's data is a pretty solid method anyway, so it still can work.
Give up on toolbar, and use 3rd party module instead.


Write a module to replace jquery with another js library

Theoretically you could use hook_js_alter() to remove all traces of jQuery (and any JS files that rely on jQuery) from the page build, and drupal_add_js() to add your replacement library/code.

Bear in mind that you would have to re-implement a lot of system/contributed javascript in your library of choice to maintain the same UI experience for your admins/users.

Also remember you'll lose access to jQuery UI so none of those widgets will be available until you provide an alternative in your new library.

All in all, it would be a lot of work to do this.


In order to do the mapping correctly, you have to instruct the feed importer how to do it. This is done through the configuration steps, shown in the following screenshots:

For sake of simplicity and time saving, I have created a content type called i.e. SimpleCar and added all the fields from the CSV file with the same name. Here is the screenshot of the content type:

Once you created a content type that closely correspond the screenshot shown above, then install/enable the following modules namely feed, feeds_ui,job_scheduler. And create a feed with the following configuration screens (closely watch how the feed is configured to read the CSV - Comma seperted file).

For simplicity, I have used the Standalone Form to directly upload the CSV. If you want this process to be triggered by CRON then you need to attach it to a content type - from the list).

You can also set the periodic import and tick the process in background option, you must have the CRON already configured.

Click on Fetcher and select either File Upload or HTTP, in this test case I have chosen File Upload, Save.

Once saved then you will see the File UPload Settings, Click it and see what is there. You can leave this settings intact. You can also tick the tick-mark to indicate where the feed importer should automatically pick up the CSV file and process it (should you have a way to automatically store the csv file in a directory then importer can pick it from there - that is advanced, you need to read about it).

Click on Parser and select CSV parser then SAVE. Once SAved then you will see the CSV Parser settings. By default it looks for Comma seperated, leave this intact and Save it. If you notice in this settings, there is a tick mark for Header, if you tick that then feed importer will start from top-most row, if you don't select it then first row will be skipped.

Click on Processor settings and choose Node Processor, Save. Once saved the Node Processor settings will appear and it has two sub-settings, Settings and Mapping.

The settings for this example, look as follow:

I have chosen Bundle as SimpleCar (which is the Drupal content type). This says that for every row of the CSV create one of the SimpleCar node. Save this screen.

The mapping settings of Node Processor should look as follow, to avoid mistakes, I recommend that you copy/paste fields directly from CSV and map them to their corresponding SimpleCar content type fields. Don't forget to map a unique value as VIN to GUID and Title and then Save.

Now go back to the basic settings and there is a link under the Standard Form drop down, you can use that link to upload your CSV and it should process and create your drupal nodes.

See my results:

and here is how the node looks like

In case you are lazy to follow the instructions, then at least create the content type and import the following code to Feeds using Import feed functionality and give it ago. You can then customize this to do it for you automatically either via HTTP download from server or pick up the CSV file from a location. You of course need to do some reading, google, there are a thousand tutorials on feeds module.

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'csv_importer';
$feeds_importer->config = array(
  'name' => 'CSV Importer',
  'description' => 'Testing CSV Importer',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'DEALERSHIP_ID',
          'target' => 'field_dealership_id',
          'unique' => FALSE,
        ),
        1 => array(
          'source' => 'STOCKNUMBER',
          'target' => 'field_stocknumber',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'new',
          'target' => 'field_new',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'VIN',
          'target' => 'field_vin',
          'unique' => FALSE,
        ),
        4 => array(
          'source' => 'Year',
          'target' => 'field_year',
          'unique' => FALSE,
        ),
        5 => array(
          'source' => 'Make',
          'target' => 'field_make',
          'unique' => FALSE,
        ),
        6 => array(
          'source' => 'Model',
          'target' => 'field_model',
          'unique' => FALSE,
        ),
        7 => array(
          'source' => 'series',
          'target' => 'field_series',
          'unique' => FALSE,
        ),
        8 => array(
          'source' => 'Body',
          'target' => 'field_body',
          'unique' => FALSE,
        ),
        9 => array(
          'source' => 'Ext Color',
          'target' => 'field_ext_color',
          'unique' => FALSE,
        ),
        10 => array(
          'source' => 'Int Color',
          'target' => 'field_int_color',
          'unique' => FALSE,
        ),
        11 => array(
          'source' => 'Asking Price',
          'target' => 'field_asking_price',
          'unique' => FALSE,
        ),
        12 => array(
          'source' => 'MILEAGE',
          'target' => 'field_mileage',
          'unique' => FALSE,
        ),
        13 => array(
          'source' => 'Transmission',
          'target' => 'field_transmission',
          'unique' => FALSE,
        ),
        14 => array(
          'source' => 'Engine',
          'target' => 'field_engine',
          'unique' => FALSE,
        ),
        15 => array(
          'source' => 'restraint type',
          'target' => 'field_restraint_type',
          'unique' => FALSE,
        ),
        16 => array(
          'source' => 'image url',
          'target' => 'field_image_url:url',
          'unique' => FALSE,
        ),
        17 => array(
          'source' => 'Comments',
          'target' => 'field_comments',
          'unique' => FALSE,
        ),
        18 => array(
          'source' => 'options',
          'target' => 'field_options',
          'unique' => FALSE,
        ),
        19 => array(
          'source' => 'certified',
          'target' => 'field_certified',
          'unique' => FALSE,
        ),
        20 => array(
          'source' => 'VIN',
          'target' => 'guid',
          'unique' => 1,
        ),
        21 => array(
          'source' => 'VIN',
          'target' => 'title',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '2',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'samplecar',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => 1800,
  'expire_period' => 3600,
  'import_on_create' => TRUE,
  'process_in_background' => FALSE,
);


Media theme missing from the file system?

This warning generally occurs if Drupal can't find the folder of the related module or theme. There is a manual page on how to get rid of this error: How to fix "The following module is missing from the file system..." warning messages

But looking at the date of the question, there is a big chance this is happening because of version conflict in media_entity module and source provider modules. If your media_entity module is installed and its version is 1.x, then your core media module is not installed. And if you are using 2.x versions of media source provider modules like media_entity_video or video_embed_field, they are probably looking for the core media module. If you're building a new website you should start over with the core media module. If you're upgrading your existing site, you should follow the upgrade path. Instructions for both are at the media_entity module page.


Entity Background 'parallax image' positioning 'top' value issue when DOM is manipulated by other modules

For anyone coming across this issue, the real problem was not having a value in the 'speed' field.


Files uploaded to managed files will be set as temporary. You need to set the file status as permanent, and add a usage, to prevent the file from being deleted.

Setting files as permanent can be done using File::setPermanent(). File usages can be added as follows:

$fid = 1; // The file ID
$file = \Drupal\file\Entity\File::load($fid);
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', $entity_type, $entity_id);

This will add a 'usage' for the file. When deleted, you need to remove the file usage. Files that have been set to permanent, and have a file usage applied, will not be deleted.


Why does the default image for an image CCK field not show in a view?

OK. So my solution was to use Customfield to write some PHP to check if the image field is empty. If it is, then I output some HTML to render a default image. I had to hard-code the image URL which is not ideal.


mvf field is not working with view dependant filter

finally i have to change the field type .


File Field description field default using tokens?

Good news - it's not that hard!  Here's what you need to do:

Install Drupal Console (if you haven't already): https://drupalconsole.com/
Install the devel module: https://www.drupal.org/project/devel
Enable the webprofiler module (part of devel) drush en webprofiler
Webprofiler adds a toolbar to the bottom of your browser window.  Use this to get the form ID of the form you want to modify.
Use Drupal Console to generate a hook_form_FORM_ID_alter() function.  You'll need either a custom theme or a custom module for this.

Warning: If you're modifying the node edit form, it probably uses the admin theme.  You probably don't have a custom admin theme, so you may want to put this in a custom module.

Customize your function to prepopulate the field the way you want.  Here's what I did:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() on behalf of coit_customizations.module.
 *
 * Provides a default for file description on meeting edit form
 */
function coit_customizations_form_node_meeting_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Check to see if there's already a file description
  $existing_description = $form['field_supporting_documents']['widget'][0]['#default_value']['description'];

  // If there isn't, add the default
  $new_description = $existing_description ? $existing_description : 'Download Supporting Documents';
  $form['field_supporting_documents']['widget'][0]['#default_value']['description'] = $new_description;
}

Don't forget to enable your module!

For further reading:

http://enzolutions.com/articles/2016/02/01/form-altering-will-not-be-the-same-in-drupal-8-after-using-webprofiler/
How to change a field's description using hook_form_alter in Drupal 8?
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.4.x
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_FORM_ID_alter/8.4.x

One last tip: xdebug is very useful for inspecting your form array so you know what to customize.  If you're trying to do this kind of thing and aren't using xdebug, I recommend you check it out.

As an easier alternative, just add this to your function: drupal_set_message($form);


Field-images wont be migrated in a migrate-upgrade --- Not sure if it's a bug

You've included a critical piece of information here which was not included in https://www.drupal.org/node/2759309:

You specified your file path as /var/www/html/benia.biz/sites/default/files.

Actually it should be /var/www/html/benia.biz/.

The sites/default/files portion is automatically included in the file paths by the migration process.

In the correct path note you have an extra slash (one after the benia.biz so it's benia.biz/); Missing this slash as well could make the migration process miss the images.


Get the select list current value not key

Try this code:

$key = $node->field_opinion['und'][0]['value'];
$label = list_allowed_values(field_info_field('field_opinion'))[$key];


In the pdf view under "PDF SETTINGS" you can add a css file for styling. Note that it only supports basic css.


Here's a trick: create a new date format by navigating to Admin > Configuration > Regional and Language > Date and Time and clicking on the Formats tab (admin/config/regional/date-time/formats).

Set it to W (that's uppercase W), and it will give you week number, which you can use with any date.

That way you can include the date field directly in views, set the W filter and use the aggregation, filter, etc without any additional coding.


Problem with token when unchecked "Enable signatures" and "Enable user pictures"

That error is showing up because you are using wrong names of the tokens.

[sito: login-url] should be [site:login-url].
[site: url-breve] should be [site:url].


Getting form Array from a webform created with Webform module?

First off you'll need to know the form_id. You can get this a million ways but the 2 I use frequently are using the devel module that has the dpm() function to display any variable you want to the screen. So in a hook_form_alter you can put dpm($form_id) and get it that way. Another way is to just view the source and find the opening form tag. The id is in there as well.

Once you have the form id you can use drupal_get_form($form_id) to get the form array.


Images are uploaded but those are not avaliable in a form

Case is resolved, issue appears in drupal 7.43 and 7.44, I last version - 7.50 works ok


Colorbox - Only display some of the images in a gallery

Create a custom template page.
Display the first 3 images - wrap the remaining images in a div that you hide, with css eg:  display: none; or add a hide class to them - attach the gallery_class class to them all so you can call them using

$(".gallery_class").colorbox({rel:'gallery_class'});


Showing local tasks in toolbar with hook_toolbar: caching problem

"The toolbar is a container for administrative and site-global interactive components."

https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/function/hook_toolbar/8.2.x

That would indicate that the toolbar is not the solution you are looking for as the more contextual tabs are not site global but page specific.


Add field value in the value of another field

You might find Field reference useful. If you're trying to leverage more functionality, you might like to use Entity reference. But you sound like you want embed the value of one field within the value of another, more like concatenating strings?


Solved it by overriding node template for my content type.

1) Copied node.tpl.php of my theme and renamed it to
node--content_type.tpl.php.

2) Put the following code at desired place:

<div class="fullmode_summary">
    <?php if ($view_mode == 'full'): ?>
      <?php print render($node->body[$node->language][0]['safe_summary']);  ?>
    <?php endif; ?>
</div>

May help someone having same issue.


Deleting a field from a content type deletes the view where that field has been included

Yes, that's what currently happens. Drupal informs you on the delete confirmation page that will be deleted.

https://www.drupal.org/node/2468045 is an issue that tries to improve it so that the view updates itself instead.


Why does my admin menu link for my custom module not get created?

The path for the configuration menu is at admin/config, so try this:

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

  $items['admin/config/question-mark'] = array(
    'title' => 'Question mark',
    'description' => 'Manage your question mark',
    'page callback' => 'question_mark_page',
    'access arguments' => array('administer question mark'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

Also, make sure your user has the 'administer question mark' permission that you have specified.


You can use the token [node:group-audience] to add the group name in your email notification.

Here is the export of the rule I am using:

{ "rules_og_group_content_notification" : {
    "LABEL" : "OG group content notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "og", "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [ { "og_entity_is_group_content" : { "entity" : [ "node" ] } } ],
    "DO" : [
      { "og_get_members" : {
          "USING" : { "group_content" : [ "node" ] },
          "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : [ "list-item:mail" ],
                "subject" : "New [node:content-type] in [node:group-audience]",
                "message" : "Hello [list-item:name],\r\n\r\nThere is a new [node:content-type] called [node:title] that belongs to [node:group-audience]: [node:url]\r\n\r\n\r\n--\r\n",
                "from" : [ "" ],
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


try to use MediaElement and library MediaElement.js
simply install and enable it and put the library in sites/all/library/mediaelement .

Creat content type and add song/video field then go to manage display anad select which type of media you want (Song or Video)
That's it , you're done
let me know what's happen ;)


Display an image from an external database

Views fields have an option to overwrite the output of the field. You can use this to add any html you want, using twig. You'll have all fields rendered before your field available as twig variables.
In your case, since you know that you're getting an image url from your external database, you can rewrite the output of your field using twig. For example:
<img src='{{ my_image_url }}' alt='{{ "Alt text for my image"|t }}'>

To access the Rewrite Results option, click Edit on your field in the Views UI. Near the bottom of the dialog, you'll see several collapsed fieldsets. Open the Rewrite Results fieldset and check the box for Override the output of this field with custom text. You'll get a text area and another fieldset, Replacement Patterns, below it that lists all variables available for your rewrite. Find your field name for your image url and write your output similar to the snippet above.


Is there a module for google maps in drupal 7?

There is the GMap Module module, but there is just a development snapshot, for Drupal 7.


Setting site name in installation profile

The solution was to use hook_install_tasks.

The source of the issue was that Drush was filling in the install configuration form during the installation process. Because the form comes after the profile's hook_install, it will override whatever configuration we write in hook_install.

Using hook_install_tasks will work by defining a new install task for setting our preferred configuration, which Drupal will run after submitting the configuration form. See function install_tasks() in core/includes/install.core.inc, line 716.


Views, group by first letter as rest export (Alphabet/Glossary listing?)

I am not sure if this is the best solution, but I came up with this:

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "serializer_glossary",
 *   title = @Translation("Serializer Glossary"),
 *   help = @Translation("Serializes results and groups them by first letter, for small result lists only."),
 *   display_types = {"data"}
 * )
 */
class SerializerGlossary extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];

    foreach ($this->view->result as $row) {
      $entity = $this->view->rowPlugin->render($row);
      $title = $entity->label();
      $first_letter = Unicode::strtoupper($title[0]);
      $rows[$first_letter][] = $this->view->rowPlugin->render($row);
    }

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    return $this->serializer->serialize(['results' => ['items' => $rows, 'totalCount' => count($this->view->result)]], $content_type);
  }
}

I am open to other answers if there is a better way.

The frontend is processing this via ReactJS to do the screenshot in the original question. The reason it is wrapped with 'results' and then 'items' is from a request from the frontend developer to have it structured that way.


You should create a view and add relationship using node reference(entity reference) and after adding relationship you should add fields corresponding to node for which relationship has been added.
Check the link on how to add relationship in views


I managed to get it going using the standard tokens so in Completed URL I had https://URL/API?query=[webform_submission:values:fieldname] - so just swap out fieldname for the key in the webform you want to pass


You're essentially correct I think. You can write a hard-coded Entity or make something more flexible supporting bundles (hard coded bundles, or say user-defined bundles like the Profile2 module) .... it can get as complicated as you want! :D

Have you seen this sandbox released a few days ago showing the mimimum for 1 hardcoded entity using Drupal core API and then an Entity supporting bundles via the EntityAPI.

https://drupal.org/sandbox/AlexanderAllen/2062531

  This module aims to provide a developer friendly, ready to use,
  barebones implementation of a custom Entity.

  The master branch provides a single, hardcoded entity (bundles are not
  supported), lacks entity revisioning support, and the only CRUD
  operation supported is save(). At a total of 16 functions, 4 files,
  one class and one method - the mater branch is recommended for
  understanding what is the bare minimum needed to create a custom
  Entity by code - using the Drupal core Entity API only.

  The bundles branch adds bundle and automatic CRUD support with the
  help of the Entity API contributed module.

  This module was inspired by the Profile2 and Model modules. This
  module is simpler than Model in that it uses the default UI and Entity
  controllers. If you're already comfortable with Entities, you should
  refer to the Model module instead for help with creating custom UI and
  Entity controllers.


Create a template for a custom page in Drupal 7?

Drupal automatically provides path based overrides; so if the path to your custom page is, say, 'custom/page/path' you can create a template file called 'page--custom--page--path.tpl.php`, which will only be used for that page.

Remember to clear Drupal's caches each time you add a new template file or the theme registry won't pick it up.


How do I grab the current product SKU in code, as early as possible?

Have you tried using menu_get_object?  It provides access to objects loaded by the current router item.

Once you've got the node, the product reference field is just going to list the products and Drupal Commerce may exclude products from the add to cart form based on rules and other modules.  But you can get the SKU of the first referenced product on the product display like this:

$node = menu_get_object(); // May want to check that it's a node.
$node = entity_metadata_wrapper('node', $node);
$products = $node->field_product->get(0)->sku->value(); // field_product is my product reference, may want to check that it exists.


This issue has been resolved.

After a lot of research, i came to know that the Facebook Application for FbConnect did not have a Canvas URL and Secure Canvas URL

So i did below:

Added Canvas URL to the Application as domain.com
Added Secure Canvas URL as Fb's changed policy required so added https://www.domain.com
Now, i could click the Application and it opened In Fb IFRAME,
I wanted it to redirect on the website, (NOT ALLOWED AS PER FB TERMS & COS)
Solution an Image Pointing to External link (www.domain.com)

Thanks for the viewers of this question. I got a Tumbleweed badge for this question.


Change

$content=db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchField();
$content.='';

to

$records = db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchCol();
$content = implode('<br />', $records);

At the moment you're just getting the first record from the result set, not all of them.

As a side note, going directly into field tables isn't the best idea. Have a look at EntityFieldQuery for an alternative.


How to set 'INSERT IGNORE' in db_insert without db_merge

You've got two options:

Subclass InsertQuery and add that functionality in yourself (it's currently not implemented)
Use db_query() to run a raw SQL string instead.

The only mention of INSERT IGNORE in the Drupal 7 codebase is in DatabaseConnection_mysql:nextId; it's not actually used, but in its place is a raw query string containing ON DUPLICATE KEY UPDATE, that gets passed directly to db_query().

I may be wrong, but I'd assume that's as good an indication as any that a raw SQL string along with db_query() is the way to go.


How to create a view of Users and use uid field with Display Suite view mode

Just as it does not provide a nid field for nodes, so it does not provide a uid field for users.

For format in your view you can also show 'Display Suite' which will open up more ds-goodness.

To show the uid you need to add a ds code field. it is best used with the token module installed as well.

Add the token [user:uid] as the field value.

The field will now become available for display suite to use. You could also use html in the code field, and for instance use the [user:uid] token to create a link, as in:

[user:name]

Also note that you do not need to display the primary identifier of an entity (uid for users) in order to use it in views relationships. As users is the base table it will already be available.


How to show reset button in a view only when filter is applied?

hook_form_alter() can also do this

function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your_form_id") {
    if (!$form_state['view']->exposed_input) {
      unset($form['reset']);
    }
  }
}

You will have some other value for ['view']->exposed_input. Use dpm(0 to get the exposed_input value. ['view']->exposed_input returns nothing if filter is not applied. Hope it works.


Display node's details instead of ID with relation module

When you go to the reference fields there will be an option to display view as a reference option. You need to create a view and attach it there.


In drupal 7 you can easily connect to 2 or more different databases.
From your question I guess you have a module to handle the users rather than the normal Drupal Way. So you can follow the following,

$databases = array (
  'default' =>  // main drupal db starts from here
  array (
    'default' =>
    array (
      'database' => 'drupaldb', // main drupal db name
      'username' => 'root', // main drupal db username
      'password' => 'password', // main drupal db password
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),'yourcustomdb' =>  // additional database starts here
  array (
    'default' =>
    array (
      'database' => 'database', // additional database name
      'username' => 'root', // additional database username
      'password' => 'password', // additional database password
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    )
  ),
);

Then in time of calling it,

db_set_active('yourcustomdb');
$query = db_query('....');
db_set_active('default'); // We need to call the main (drupal) db back

I hope this one helps you.


How do I take payments via Ubercart and distribute them to vendors?

This is outside Ubercart, but it's definitely possible with Drupal!

For this demonstration, I will use a point system. Let's say 100 points = $1.00.

Drupal 7 method:

Create a content type, called Products.
Install a Drupal module, called Entity Reference and add an Entity Reference field to the Products content type, select users. This will allow you to reference the product to vendors.
Create another content type, called Points. Also add an Entity Reference field to it, and select type as users, to reference users. In addition, add a decimal field (amount).
Install another Drupal module, called Rules
Create a rule that would, after a certain time (30 days, etc...) from the sale date, create a Point node with that User referenced and add the commission earned.
Create a rule, that would unpublish the Point node anytime the payment is withdrawn.

Another option is to use the Relation module. It's more work and still in early stages.

By creating a Point node for each commission, you're leaving all records of transactions. I would never overwrite the old commission value with new commission, i.e. $user->payment = $user->payment + 10. It will mess things up.

You can still use Ubercart with this, as it uses Drupal's entity/field structure. Simply skip #1 and use Ubercart's product content type.


How to show all terms with are used in Content?

Is this in Drupal 6 or Drupal 7? In Drupal 7, you should create a content view, use fields, and then in the fields section and select the relevant content field. This should then display all the various options that are selected.


Post the same menu as two different blocks?

The Menu Block module will do this.

  So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”

  Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!


Unable to import due to "Field 'sourceid2' doesn't have a default value"

Ok, I resolved this issue. I am new to Migrate module and I think the message was not clear enough.

First I have mapped to complex foreign key with two columns:

<?php
    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'id' => array(
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
          'id2' => array( // no longer exists in my code
            'type' => 'int',
            'description' => t('Article Source ID'),
            'alias' => 'N',
          ),
        ),
        MigrateDestinationNode::getKeySchema()
      );
?>

But then I used only the first foreign key. The database table storing the mapping between source and destination had two columns sourceId, because of first attempt to run migration, but hasn't updated with the new migration in the code.

I dropped the migration_map table and everything was freshly rebuild and works like a charm.


I solved the problem using Entity Reference  Module.

I made a custom content type - "Movie List" , and add a field of "Entity Reference" type , then made a reference to "Movie" content.


How do I add secondary tabs to the user (profile) edit tab?

Tabs can be added to the user edit page as follows:

1) Define the route(s) for your tab(s) in [MODULE].routing.yml as normal:

[MODULE].something.user_defaults:
  path: '/user/{user}/edit/something'
  defaults:
    _controller: '\Drupal\[MODULE]\Controller\SomeController::someSettingsTab'
    _title: 'Some Settings'
  requirements:
    _permission: 'some permission'
    user: \d+
  options:
    parameters:
      user:
        type: entity:user

2) In [MODULE].links.task.yml, add your tab(s) as you would primary tabs, except rather than using base_route, use parent_id, and set it to (somewhat unintuitively) the user edit form tab key, which is defined in user.links.task.yml as entity.user.edit_form (same as the route name):

[MOUDLE].something.user_defaults:
  route_name: [MODULE].something.user_defaults
  parent_id: entity.user.edit_form
  title: Some Title
  weight: 10

3) You also need to define a tab for the user to switch back to, as tabs are only rendered if there are more than two tabs. In this case, we want to add a tab for the user edit form, using the user edit form route, again using the user edit form tab key:

[MODULE].entity.user.edit_form:
  route_name: entity.user.edit_form
  parent_id: entity.user.edit_form
  title: Profile


Display Taxonomy Terms Based on user login in a select list in a view

There is no way you can get the author uid of taxonomy term. But here is a solution you can try:

Add a user reference field to the vocabulary, the field will contain author uid.
Add term exposed filter to the view.
Using hook_form_alter() alter the exposed filter so that it shows only those taxonomy terms which are created by the currently logged in user.


You might check out the 'Examples for Developers' project page for some relevant examples:
https://www.drupal.org/project/examples

I think you want to use hook_init instead of hook_menu. Try this:

function mymod_init() {
  if (drupal_is_front_page()){
    $items = array();

    $items['/'] = array('page callback' => 'mymod_do_it');

    return $items;
  }
}


In this case I'd have a look at the field_collection module. It may be more suited for your purposes.


Yes, this is possible with only views. Here is a good thread to get you started. http://drupal.org/node/301485#comment-1065230


How to remove default div of views block?

Click on field and edit settings
Override style settings for field

Customize field HTML
Customize field and label HTML


Disable email registration requirement in Drupal 7

For removing unique e-mail address requirement see Shared Email module:

  The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Disabling email requirement for registration is quite complicated task because many things in Drupal use mail notifications. I can recommend to set special email users.without.mail@yoursite.com for users without emails.


Is there any SIMPLE way to hide errors ONLY for anonymous users?

I think the Disable Messages module is what you need.

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from
any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the
end users.

-- HOW DOES IT WORKS? --
1. install and enable the Disable Messages module
2. Go to "/admin/config/development/disable-messages", and check the "Enable filtering"
3. Go to "/admin/people/permissions", and give the permission who should "View status messages", "View warning messages", View error messages", and "Exclude from message filtering" if desired.

-- Updated July 31st 2015, 2:23pm --
CSS trick
to not display for anonymous user(not login)

body.not-logged-in div.messages.error { display: none; }

to not display for logged in user(you should not do this for admin user, but here is the trick)

body.logged-in div.messages.error { display: none; }


what PHP errors do you get when errors are set to be shown on the website from your php.ini or htaccess file. webform2pdf has a dependency on TCPDF library and they often become out-of-sync with one another. So as a developer you need to be sure you're using the recommended versions of the required dependencies.


Given $form, how to programmatically generate its corresponding $form_state?

Here is what I did to fill $form_state['values'] with the default values from $form:

function mymodule_get_form_state($form){
  $values = array();
  _mymodule_form_get_values($form, &$values);
  $form_state = array();
  $form_state['values'] = $values;
  return ($form_state);
}

function _mymodule_form_get_values($element, &$values) {
  foreach (element_children($element) as $key) {
    if (isset($element[$key]) && $element[$key]) {
      if (isset($element[$key]['#default_value']) && $element[$key]['#default_value']) {
        $values[$key] = $element[$key]['#default_value'];
      } else {
        // Recurse through all children elements.
        _mymodule_form_get_values($element[$key], &$values);
      }
    }
  }
}


Exporting a view from one site to another

By Default views have option to import and export. By using that we can do it.

In drupal7 views3.x has option of import link in this url admin/structure/views

With this image you will get clear view of how to import and export a view.


Trying to get my form_alter function to be more specific

The hook for specific form ID's is hook_form_FORM_ID_alter() (at the moment you're using something more like hook_FORM_ID_form_alter()). You should just need to change the name of the function to:

function MYTHEME_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

and clear the caches.


Configuring Node Reference URL to auto populate with outbound (internal) link (node title)

Adding the node reference field step 1:

Adding the node reference field step 2:

a) Choose your Content type from 'Content types that can be referenced ' select list
b) Fallback behavior *-> choose Use select list widget , leave all other options if you not need

All the settings are over.

Now access your create content type with the node_id, in url

sitename.com/node/add/{the content type}/23, where 23 is the node id passed from the link

You can find that the options with particular node is is selected in the list box

Creating links - it is well explained in modules readme.txt please go through well


How to hide a field from anonymous users?

Use the Field Permissions module.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


Expose (other) user's role to anonymous using views

Ok, I figured it out with help from @Dropa. What I had to do was to build my view in a different way than I initially had it set up.

Initially I had my view built as showing fields from profile, and then I pulled in the user information through a relationship.

What I had to do was to switch it around and create the view showing fields from user. This allowed me to display the user information, including the role info that I am after.
All other desired information (e.g. other information from the profile module) is then pulled in through a relationship.


How are access permissions prioritized when multiple modules implement them?

Have a look at this feature request Allow other modules to alter gnode_node_access's forbidden result, especially this part of it:

  If the group node's gnode_node_access module doesn't find a reason to return neutral, or to grant access, it returns a AccessResult::forbidden(). This prevents any other module from granting access. ...

So to "determine the priority of multiple modules arranging permissions for the same node" (as in your question): if the Group module denies access, then there is no way for any other module to overrule that access.

Maybe not what you like to hear/read, but this is how access is handled via Group module.


"\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container."

You need to mock the services you will be using in your test, so that they return values. You can do that as follows:

public function testDefaultBehavior() {
  $some_resolver = $this->getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    ->disableOriginalConstructor()
    ->getMock();
  $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory')
    ->disableOriginalConstructor()
    ->getMock();
    $service = new CustomService($some_resolver, $config_factory);

}

Note that you should use the actual interface (or class if you have no interface) instead of Drupal\namespace\for\custom_utils\someresolver

You'll need to set up expectations to return the values from the services you mocked. You can read more on that here:

https://www.drupal.org/docs/8/phpunit/understanding-phpunit-expectations


It seems like you have tried everything except to supply the URL.

You must supply a --url argument to execute simpletest. This is what I use, where "IAS" is the test group I have selected to execute:

php scripts/run-tests.sh --url http://localhost/drupal7 --concurrency 4 IAS

It follows that you must have a Drupal install to do this.


When should I "send mail by queue" with the SMTP module?

TL;DR: send the email by queue if you are sending larger number of emails at once, or if your SMTP server takes longer time to process a request (for whatever reason).
Below is a brief overview of the main pros/cons.
Pros

Better handling of large volume of emails. Email sending task will be split into batches, and Drupal will process them in smaller chunks during cron runs. This is better because your server might time out or become unresponsive for visitors if you are trying to send 500 emails at once.
If the same task is split into multiple batches, it will be easier to process them, and regular visitors will not experience as big decrease in performance.

Cons

Requires more frequent cron (or a custom script that will process the batches), which translates into more used resources at all times. You might see certain decrease in performance if the site is processing email batches and there are a lot of users online simultaneously. This of course depends on many factors (number of emails you are sending, frequency of your cron, speed at which remote SMTP server processes the requests, number of visitors on your site, complexity, and so on).
See Elysia Cron module for fine tuning the cron implementations of all modules on your site. It will help you use less resources during each cron run, because you will be able to choose how often will cron of certain modules be run.

In some cases this can result in slower email delivery. If you have a large number of emails to deliver (e.g. 100k newsletter subscription list), last user in the queue will receive the message significantly later than the first one. Also, all emails requested to be sent during that time, will be delayed as well.


How to redirect anonymous users to login page using Rules module?

The way I solved it as follow:

Events: Drupal is initializing
Conditions:

User has role(s) - Parameter: User: [site:current-user], Roles: anonymous user
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login

Actions: Page redirect - Parameter: URL: user/login

Export rule as follow:

{ "rules_login" : {
    "LABEL" : "login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "login" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "NOT text_matches" : { "text" : [ "site:current-page:url" ], "match" : "user\/login" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/login" } } ]
  }
}


theming nodes as forms - any advantage using drupal_render?

Using the Form API instead of doing things in the theme layer (rendering the node as a form) will give you all the advantages that the Form API has to offer (e.g. custom validation, submit handlers, form alters, etc.)

I would do things differently by creating a menu item with drupal_get_form as the page callback and the node as the parameter.

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items = array();

  $items['custom/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('example_custom_form', 1),
  );

  return $items;
}

/**
 * Form constructor that takes a node as a parameter and creates a form based
 * on its values.
 */
function example_custom_form($form, &$form_state, $node) {
  $form['#node'] = $node;

  // Start generating the form...

  return $form;
}

Although subjective, this feels a little less hacky and might be easier to maintain in the future.


Additional classes for price based on price components

Yes, you could theme the price components to add your own classes via a theme override.

The base implementation is in commerce_price.module

Here's a tweak that includes the price component $name in the class:

e.g, in template.php

/**
 * Themes a price components table.
 *
 * @param $variables
 *   Includes the 'components' array and original 'price' array.
 */
function MYTHEME_commerce_price_formatted_components($variables) {
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');

  // Build table rows out of the components.
  $rows = array();

  foreach ($variables['components'] as $name => $component) {
    $rows[] = array(
      'data' => array(
        array(
          'data' => $component['title'],
          'class' => array('component-title', $name),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total', $name),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}


If a vocabulary and a view have the same machine name, will they conflict when exporting to a same feature?

If it's in a different table it's in a different scope. If it allowed you to set a similar machine name you are obviously in a different scope. If you go to a node page and try to create similar machine names you will get an error while adding the field.

taxonomyTable.same_machine_name is different from viewTable.same_machine_name

No they wont conflict when exported from features. on the features page it shows different sections like taxonomy terms, nodes, strongarm, image styles ect.. anything that could be related then it auto detects anything related and you can select what you want to go with it. That's why it's important to have unique machine names so you know right away what you are working with. When using features try to avoid using the same machine names; but you can get away with it


The $form_id argument is the internal form ID, not the CSS ID. For views exposed forms it'll always be views_exposed_form.

I think this is the easiest way to target a specific exposed form:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $view = $form_state['view'];
  if ($view->name == 'foo' && $view->current_display == 'bar') {
    // Alter the form...
  }
}


Can be just a typo, look at requirement, you missed a 's'.

  requirements:
    _permission: 'administer site configuration'

Look at here for a complete skeleton. (or a collection of modules examples here)


Your code is missing one part that I can see, the #attached key:

  $build['ajax_edit_link'] = array(
    '#theme' => 'links',
    '#weight' => -2,
    '#links' => array(
      'ajax_edit_link' => array(
        'title' => t('Edit'),
        'url' => $entity->urlInfo('edit-form'),
        'attributes' => array(
          'class' => array('use-ajax'),
          'data-dialog-type' => 'dialog'
          'data-dialog-options' => Json::encode(array(
            'width' => 1200,
            'height' => 500,
          ))
        ),
      ),
    ),
    '#attached' => array('library' => array('core/drupal.ajax')),
  );


You should ideally be using the render functions to output the stuff in content and node arrays in Drupal 7, the reason you are not seeing the suffix is that you are simply pulling out a value and not rendering.

So the following should work for you:

<?php echo field_view_field('node', $node, 'field_price'); ?>

Take a look at Drupal's reference on field_view_field and this article too


Programmatically created list_boolean checkbox field value won't get saved

Thanks @Clive, all that was missing were 'allowed_values' in $field['field]:
$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
    // It's mandatory to add at least two empty values here,
    // Drupal will do the rest then:
    'settings'    => array(
      'allowed_values' => array(
        '',
        '',
      ),
    ),
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

You simply have to declare empty On/Off values. Which may not seem too obvious, but logical at least since when you create options_onoff checkbox from the backend there's written:

On value [_____] If left empty, "1" will be used.
Off value [_____] If left empty, "0" will be used.


Yes, you use relationships under advanced to first expose the Content:Author. Then you use relationships again which will now show the User:Profile relation. Now you will have access to all the user details :)

It should look like this when you are done:


I get this error with my custom module, Any advice on tracking down the problem?

You need to create a custom field called for_date which will be represented in the database as field_data_field_for_date or remove field_data_field_for_date from the SQL query.


Is there a standard environmental indicator for Drupal 8 projects?

A standard way to use different settings files per environment is through the use of sites folders.  Check out /sites/example.sites.php in your Drupal 8 codebase. It gives instructions.

Basically, you'll copy this file from example.sites.php to sites.php.  You don't need to edit it, (but you can if you want to do something unusual).

Then for each site (or environment), you'll have a separate settings.php file in a folder named after the site.

So you might have

/sites/example.com/settings.php
/sites/qa.example.com/settings.php
/sites/dev.example.com/settings.php
/sites/example.local/settings.php

If you are using git, you might want to uncomment this
/sites/example.local/settings.php

if (file_exists(__DIR__ . '/settings.local.php')) {
  include_once __DIR__ . '/settings.local.php';
}

and git exclude

/sites/example.local/settings.local.php

so that each developer can customize his settings.

If you run drush, you can run from the site specific folder on that environment or specify the --uri parameter.

Of course, you could just add conditional code in your /sites/default/settings.php

if ($_SERVER['SERVER_NAME'] == 'example.com') {
  $config['system.logging']['error_level'] = 'hide';
}

If you jut want to change one variable, and you know that on your production environment $_SERVER['SERVER_NAME'] is available and correct, then this is an option.


Add ubercart catalog paths to xml sitemap

Make sure that you have XML sitemap node enabled.

Go to /admin/structure/types and make sure that your product type in set for inclusion in the XML Sitemap by default. If you have to change it, then if the pages you already have are set to 'default' they will react properly. If they are set to 'exclude' you will have to edit each page and change it.

Then go to /admin/config/search/path/patterns and set your catalog path to catalog/[term:name]
and your catalog product page paths to catalog/[term:name]/[node:title].

If you have to regenerate your aliases, make sure that you retain the old alias, or use the Redirect to issue a 301 redirect for old aliases.

Then regenerate the site map. These steps should cover off any reason why the paths are not in your current sitemap.


Problem with theming form for my module setting page

It's because you haven't defined a theme registry entry called form_style, but you're setting the form's theme handler to a function with that name.

You just need to change your implementation of hook_theme() to match the function name and form theme setting you've actually defined:

function actionadscatalog_theme() {
  $path = drupal_get_path('module', 'actionadscatalog') . '/templates/admin';
  return array(
    'form_style' => array(
      'render element' => 'form',
      'template' => 'actionadscatalog-admin_run_import',
      'path' => $path,
    ),
  );
}


search_api_solr with accurate radioactivity sorting in views

As you say there's no API, so you're probably going to have to resort to patching the module.

There are at least two places you'll need to make additions as far as I can tell:

_radioactivity_update_energy()
radioactivity_cron()

I would suggest adding your own hook which gets fired whenever an entity is updated in either of those functions, and perform the search indexing there.

You should have a good think about the values you use for half lives/Solr processing delays if you choose to implement it like this. If your values for those settings aren't sensible you could end making the changes without actually seeing any effect. Also, depending on the amount of traffic the site receives, you could slow your server down quite a bit doing this.


Can 'terms' be shared across 'vocabularies'?

It sounds like you are using vocabularies where you could be using nodes.

So a node called the 'grand hotel' would have a rating, it may be suitable for some types of people and may also have a location.

So you can create node type 'accommodation' which can use the vocabulary 'accommodation types', 'suitable for' and 'location'.

You could have a node type 'eating out' which can use the vocabulary 'cuisine type' but share 'suitable for' and 'location'

So each cafe or hotel could be a node of the respective type, but could appear in the search results for 'London' for example.


Unable to change the author of content using views/action

I just created a module for this, which allows you to change the Author as a batch operation on /admin/content, with a custom selection step to pick the new author.

Module: change_author_action


This how solved my problem.

Found out that jquery_update uses hook_theme_registry_alter() to unset jquery in Drupal core and replace a new version of Jquery. So this preprocess function is being load after everything all. What I did is I created a hook_theme_registry_alter() and update the weight of the module higher than jquery_update module so I can override the jquery_update_theme_registry_alter().

This jquery_update_theme_registry_alter() prevents any alteration in javascript which a big headache if you're working on some adjustments like in my case.

Code:

function my_module_theme_registry_alter(&$theme_registry) {
    global $theme;

    // Only apply this code in mobile theme
    if($theme == 'myTheme') {
    //Attach the my_module_preprocess_page in the theme registry preprocess functions
      $theme_registry['page']['preprocess functions'][] = 'my_module_preprocess_page';
    }
}

function my_module_preprocess_page(&$variables) {

    // Perform the logic if either jQuery Update's jquery.js is newer than core's.
    if (variable_get('jquery_update_replace', TRUE)) {
        // Get an array of all the JavaScript files loaded by Drupal on this page.
        $scripts = drupal_add_js();

        // Replace jquery.js first.
        $new_jquery = array(jquery_update_jquery_path() => $scripts['core']['misc/jquery.js']);
        $scripts['core'] = array_merge($new_jquery, $scripts['core']);
        unset($scripts['core']['misc/jquery.js']);

        // Loop through each of the required replacements.
        foreach (jquery_update_get_replacements() as $type => $replacements) {
            foreach ($replacements as $find => $replace) {
                // If the file to replace is loaded on this page...
                if (isset($scripts[$type][$find])) {
                    // Create a new entry for the replacement file, and unset the original one.
                    $replace = JQUERY_UPDATE_REPLACE_PATH .'/'. $replace;
                    $scripts[$type][$replace] = $scripts[$type][$find];
                    unset($scripts[$type][$find]);
                }
            }
        }
        // Unset javascripts that is/are not needed in mobile theme
        unset($scripts['module']['sites/all/modules/boxes/boxes.js']);

            .....

        // Recreate the scripts variable
        $variables['scripts'] = drupal_get_js('header', $scripts);
    }
}

Hope this will help others. Please let me know if this approach is a violation. Thanks


Can a domain redirect work for both http and https?

Nginx/settings.php

Try this: $base_url = 'https://'.$_SERVER['SERVER_NAME'];

Apache/.htaccess:

You can simply add the following to your .htaccess. It will redirect all traffic from http://example.com and http://www.example.com to https://example.com. Put that below RewriteEngine on.

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www.example\.com*
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]


How do I import latitude/longitude into geofield?

You can use the Feeds module to import your csv file and map it to your content type.


Problem changing colors in the mayo theme

Have you installed the theme in the right location (sites/all/themes)? If so, verify that each template has a CSS file for it. If so, then the next place to check is within the template's .info file to ensure that the CSS file is indeed being used.

Perhaps this thread would help assist you:  http://drupal.org/node/1118068


Placeholder working, but giving Notice: Undefined variable: value and Notice: Undefined index: #type

There can be some form elements, for examples, markup, without an explicitly set #type.

foreach ($form["submitted"] as $key => $value) {
    if (!isset($value["#type"])) { //If #type is not set, skip this iteration.
      continue;
    }
    if ("textarea" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "webform_email") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
    if($value['#type'] == "file") {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}


Override module javascript file in theme or custom module

hook_js_alter() allows you to modify any JS before it is written to the page.
The documentation includes a snippet to replace a core file with an alternate from a module:

function hook_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}


Why can html.twig files be placed outside the templates folder?

Ok, I have found a solution, I just need to add in my settings.php the "styleguide" folder in the ignore directories
$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
  'styleguide'
];


Programmatically create a user and assign a role

This code worked for me:

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);


How to create flexslider slideshow as a background in drupal 8?

Flexslider is a javascript library that makes a bunch of changes to the markup once it is loaded.  Instead of trying to put the images in as background images I suggest using position: absolute on either the flexslider itself, or the items you want to sit on top of it.

You may also need a z-index on some items to bring the to the front or send them to the back.


I havent done this but I have seen code to make Views in D7 work with remote database tables. If you can get Views to see those tables and fields -- a bit more work should be able to allow you to filter/search through this stuff from Views:

Fields with Multiple Entries in Views w/ External Data Source

It looks like you just have to give drupal a database key for your remote database connection defined in settings.php per field description. The rest looks like a typical implementation of hook_views_data().


I found what I needed. It is the function hook_url_outbound_alter...

function myModule_crawler_url_outbound_alter(&$path, &$options = FALSE, $original_path){
    $mother_nid = $options['entity']->field_mother_series_nid["und"][0]["value"];
        if( $mother_nid > 0 ){
            $path = "CLEAN-URL/".$mother_nid;
            $options['alias'] = "CLEAN-URL/".$mother_nid;
        }
}

Thanks for helping!!!


loading newer jquery with hook_js_alter() breaks file upload on node edit form

Worth noting, Drupal is released with a particular version of jQuery.
You generally can't add a newer version of jQuery without refactoring some core js files.

http://drupal.org/project/jquery_update

provides those core patches and more recent jQuery versions.


How to loop over OG group members from comment

I found a work-around by implementing all of the desired functions in the custom action provided by my custom module:

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_comment_notify_og_members' => array(
            'label' => t( 'Notify OG members of comment' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'comment' => array(
                    'label' => t( 'Comment entity' ),
                    'type'  => 'entity',
                ),
            ),
        ),
    );
}

/**
 * Notify relevant OG group members of a new group comment
 *
 * @param   object (entity metadata wrapper)    $comment
 */
function mymodule_comment_notify_og_members( $comment )
{
    //~ dpm( $comment->getPropertyInfo() );

    // Get the nodes we need from the comment entity metadata wrapper
    $node = $comment->node->value();
    $author = $comment->author->value();

    // Get all active group members
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    foreach( $members as $member )
    {
        if( $member->uid !== $author->uid )
        {
            // We're not notifying the author of his own comment

            $subject = format_username( $author ) . ' commented on ' . check_plain( $node->title );
            $body = '';
            $body .= 'Hi ' . format_username( $member ) . ',';
            $body .= '' . l( format_username( $author ), 'user/' . $author->uid ) . ' just commented on the ' . l( $node->title, 'node/' . $node->nid ) . ' group.';
            $body .= '' . l( 'View the comment', 'node/' . $node->nid, array( 'fragment' => 'comment-' . $comment->cid->value() ) ) ;

            privatemsg_new_thread( array( $member ), $subject, $body, array( 'author' => $author ) );
        }
    }
}


The answer is that the submit button was being generated by the actions array item.

Simply changing my form value to this:

$form['actions']['submit']['#validate'][] = 'MYMODULE_validate_relationship';

Correctly allowed it to be executed.

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#actions


Views module core patching inside a sub-site

Modules that are placed inside sites/all/modules directory are accessible to all sites setup inside sites directory. Thats why it is showing you the error.

So basically you are trying to apply a patch for pqr-child site only. So you can do :

If it is a general patch, you can apply it to sites/all/modules/views directory. So there is no need of adding views directory for pqr-child site.
If it is a hack, then my suggestion is not to hack the module, instead you can write a custom module to fulfil your requirements.
But if it still necessary to hack the module, you need to copy the sites/all/modules/views to all the sites/subsites/modules directory and delete it from sites/all/modules.


When implementing AJAX in a form, it will send a callback to system/ajax, if you didn't set your path in the AJAX properties. So, when you use arg(1) in your code, it will return ajax, which is the value assigned to the hidden form field.


Use taxonomy but automatically assign the taxonomy. So anytime you create a car, it's automatically assigned to term "transportation." You can do this with the Taxonomy Defaults module.

  Taxonomy Defaults allows you to assign default terms from any vocabulary to any node-type. The default terms will be pre-selected on the /node/add form, but can be edited.

  If a vocabulary is marked as "Hidden" for a particular content type, then that vocabulary will not be shown on the /node/add form and the default terms will be assigned automatically and cannot be edited.

The module is a bit tricky to get at first, make sure you select "hidden" so that the user can't change the default taxonomy.


How do I get the timezone form reference on a date field?

Use hook_date_timezone_process_alter in your custom module to do the magic, see below example and adapat if for you needs

function MODULENAME_date_timezone_process_alter(&$element, &$form_state, $context) {
  // add some logic here
  // keep only the needed values
  // dsm($element['timezone']['#options']);
  $element['timezone']['#options'] = array(
    'Africa/Abidjan ' => 'Africa/Abidjan',
    'America/Detroit' => 'America/Detroit',
  );
}


Showing block in specific urls and content types

You could do one more thing over it.

Just remove the block from the assigned region and render that block using module_invoke() in the template file page.tpl.php.

<?php
  $match = TRUE;
  // block is visible on the content types entered here
  $types = array('product_display' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }

  if (strpos($url, "somewhere")) {
    $match = TRUE;
  $block = module_invoke('block', 'block_view', 'block_delta');
  print $block['content'];
  }

Render your block with the applied condition as you want.
If you just want to display block at some specific urls and content types.

It works well for that!


This would be because an empty value and NULL are two different things to a database. Deleting the value in the UI is not the same as setting it to be NULL. That field is stored in the database with the setting that I cannot be NULL and so the VBO operation is failing.


Is db_set_active a global or local setting?

It's a per-request global setting. db_set_active calls:

Database::setActiveConnection($key);

Which sets the static $activeKey property of the Database class.

Database::getConnection(), which is where the connection for all queries comes from, then uses that same static $activeKey.

So once you've used db_set_active, all queries in that request will use the new connection until changed again.

It doesn't persist across multiple requests.


Panels page or Panels node - which to use?

"Essentially, this boils down to what are the main differences between Panels page and Panels node?"

A Panel page takes over the layout of the entire page. It can override one or more full pages.

A Panel node takes over one or more node(s) layout.


Display order of entity reference fields

In case someone stuck on this, i have a solution for Drupal 8 (you can figure it out for 7):
In themename.theme add a preprocess funtion:

function themename_preprocess_field__field_entity_reference(&$variables) {
    usort($variables['items'], function ($a, $b) {
        $a = isset($a['content']['#node']) ? $a['content']['#node']->field_display_order->value : null;
        $b = isset($b['content']['#node']) ? $b['content']['#node']->field_display_order->value : null;

        // Do the comparison
        // This <=> operator only work for PHP >= 7
        return $a <=> $b;
    });
}


How do I change total number of rows in a view programmatically?

You're probably looking for the view::set_items_per_page() method, e.g.

/**
 * Implements hook_views_pre_build
 **/
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'foo') {
    $view->set_items_per_page(10);
  }
}

That method updates both the instance var and the limit on the internal query that Views will eventually run.

Note that you need to make this change before the query is executed (i.e. in a pre build, not pre render, hook), or you'll get inconsistencies with pagers etc.


Yes. Using Views you can add a Feed display, with a path that contains a with a wildcard component (e.g. /rss/%/feed), & Content: Nid for a contextual filter. This will create a path that will have an RSS feed for each nid (e.g. http://www.example.com/rss/1/feed. http://www.example.com/rss/2/feed, etc.).


How do I validate an entity before programmatically saving it?

Looking the api it should be simple:
$violations = $entity->validate();
  if ($violations->count() > 0) {
    // Validation failed.
  }


Aegir Installation - how to get the sender email correct to allow install to pass

Found the answer in section 7.1 at https://docs.aegirproject.org/install/#7-install-aegir
sudo apt install debconf-utils
mkdir -p ~/projects/aegir/core
git clone https://git.drupal.org/project/provision.git ~/projects/aegir/core/provision
echo "aegir3-hostmaster aegir/email string valid@email.com" | sudo debconf-set-selections
sudo apt install aegir3


How can I load webform content inside a custom webform composite element?

Finally I used the good old session.

My solution:

//mymodule.module
function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $session = \Drupal::request()->getSession();
    $session->set('value_from_earlier_step', $form_state->get('value_from_earlier_step'));
}

//\src\Element\ExampleComposite.php
class ExampleComposite extends WebformCompositeBase {
    public static function getCompositeElements(array $element) {
        $session = \Drupal::request()->getSession();
        $expectations = $session->get('value_from_earlier_step');
    }
}


Omega theme on Ipad slides across and disappears

This is caused by my social icons in the footer, the same problem is referred to in this posting, it occurs when a DIV gets too big for the page, the Ipad cant cope with this and creates a load of space on the right of your page. In my case, I have an text indent -999 in the class of my social button, defined as :-

.social-button{

    width: 30px;
    height: 30px;
    text-indent: -999em;
    display: inline-block;
    background-repeat: no-repeat;
    background-position: center center;
    margin-right: 2px;
    text-decoration: none;
    border: 1px solid #FFFFFF;

}

To resolve I put :-

width:auto;
overflow-x:hidden;

on the css for the social icons Block in the footer and it worked perfectly as suggested in the link above. Sorry this is slightly off topic with a CSS resolution, but I though it would save someone (like me) hours of messing around with their theme to find a problem thats not there . Thanks


Please follow the below steps. You will achieve what you have asked.

1. Go to Structures > Views > Add a New View (named Courses)> Select Type as Courses > Create a Block

2. Enter the Block Title as Courses > Continue and Edit

3.  Under the Advanced > Add Relationships search for Entity Reference: Referencing entity (select the same field which was referenced under school content type) and click on apply

4. Under contextual filter > Search and select Content: Nid and in relationship option select the relationship and under WHEN THE FILTER VALUE IS NOT AVAILABLE
 select as  Provide default value > Content id from URL > Click on apply

5.  And under format or Fields, you can select anything depending on how you want to display the data


What is the correct way to update existing module's rules programmatically?

You can export the rules configuration via the Rules UI and then implement hook_default_rules_configuration_alter() like this:

/**
 * Implements hook_default_rules_configuration_alter().
 */
function MODULENAME_default_rules_configuration_alter(&$data) {
  if (isset($data['commerce_cart_add_to_cart_message'])) {
    $data['commerce_cart_add_to_cart_message'] = entity_import('rules_config', '{ "commerce_cart_add_to_cart_message" : {
        "LABEL" : "Display an Add to Cart message",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "TAGS" : [ "Commerce Cart" ],
        "REQUIRES" : [ "rules", "commerce_cart" ],
        "ON" : { "commerce_cart_product_add" : [] },
        "IF" : [
          { "data_is" : { "data" : [ "commerce-order:commerce-nocart" ], "value" : "0" } }
        ],
        "DO" : [
          { "commerce_cart_add_to_cart_message" : { "commerce_product" : [ "commerce-product" ] } }
        ]
      }
    }');
  }
}

Just change the instances of $data['commerce_cart_add_to_cart_message'] to use your rule machine name and replace the export string with your own.

You can also use rules_import() instead of entity_import(). Either is acceptable.

Since the rules module loads default rules from code into the database and from then on loads them from the database, it won't immediately pick up your override.
To make it do so navigate to the Rules UI and revert the rule. It will revert back to the default code, which will be your override.

To programmatically revert a rule you can do this (again replacing the rule machine name):

if ($rules_config = rules_config_load('commerce_cart_add_to_cart_message')) {
  $rules_config->delete();
}

An example usage of that may be to do it during an update function for a custom module.

It may seem wring to be deleting it but delete and revert are equivalent for rules that are provided by code because delete means delete from the database. If this was a rule created via the UI then it would be gone, however a rule from code will just delete from the DB and then read in again from the code.

Unfortunately there are currently only drush commands for enable/disable of rules.
There is a feature request for a delete/revert command at https://www.drupal.org/node/2507187


Duh... It isn't the Devel config that controls it. It's the "Access developer information" permission. Someone had turned it on for anonymous users. Doh!


Error after installing module twice: Configuration object already exist

As the error says, the problem isn't with your module, but simply that the configuration your module is trying to create already exists in your installation.

You have two options to get it installed:

delete the configuration first, in the UI or programatically (How do I remove a configuration object from the active configuration?) and then add an enforced dependendency on your module, to make sure it is removed when your module is uninstalled. Note that you must first remove the config, the enforced dependency that removes your config only works once installed using the new definition.
Provide as optional config in config/optional instead of config/install. Optional config is different from other config in two ways:

First, it is only installed when all the required dependencies exist. That is useful if you have optional integration with another module and if it is installed, provide some configuration for it. This even works if that other module is installed later on. Configuration with missing dependencies in config/install fails with an error as Drupal assumes your module will not work correctly if the config can not be installed.
Second, it will also be silently skipped if the config exists already, which is the relevant thing for your case. It will however also be silently skipped if the existing config just happens to be a view with the same name that is actually something else.


Problem with image file names containing utf-8 characters

Use https://www.drupal.org/project/transliteration to automatically rename the files and avoiding problems like this. No need to train your editors. :-)


How can I indent parts of a Views field?

Put the class clearfix as the row class (format->settings). If your
theme does not have clearfix defined, define it yourself.
Hide the output of the other two fields (click on the field in views
form and you will see this setting 'exclude from display').
Create a global: Custom text field and make sure it is the last
field in the views list of fields.
Rewrite results -> rewrite the output of this global
text field, and from the replacement patterns select field 2 and 3
as tokens. Also add a class for that field in style settings such as
'align-block'. Define it as follows:

align-block {
overflow:hidden;
}

in your css file.

Add a class to your image field such as 'float-left'. Define it as follows:

float-left {
float:left;
}

in your css file.


How Can I Create a Front Page Based on Blocks?

If it was me, I would create a custom page-front.tpl.  I'd omit the $content region and probably create a few custom regions for the homepage.  I can then place my blocks into the regions.

D6 create page-front.tpl.php
D7 create page--front.tpl.php

Cheers.


How do I change status from "Pending" to "Completed"?

Under the drupal 7version of Ubercart 3, order status would be changed using the dropdown found under

http://shop.example.com/admin/store/orders/100001/view


How can I seperately display a view's exposed filter and its content in page.tpl?

As per my understanding, why you want to doing via coding. Create views exposed filter as blocks and place in the sidebar and by default the content will load in the right side of the content area. Now you will get filters and content separately...


Drupal insert query with uploaded CSV file

The data come form a file where string were not convert to utf8 at the opening thus the Drupal 7 parsing function for database query couldn't convert string to avoid SQL error.

Sorry but I didn't think that the problem could be as much upstream...


drush perm-grant gives "The drush command 'perm-grant' could not be found"

according @MDP, Permissions API module is required for this, and according its module page is only for Drupal 6, so this command is not available in drupal 7. @greg_1_anderson user recommends to use Drush 8.x-6.x to get this feature working built-in


How not to display some required fields on registration form?

First make fields not required and then use the Field Validation module. You can validate each field as per your requirement.

  The following validators are currently included:
  •Regular expression
  •Numeric values (optionally specify min and / or max value)
  •length (optionally specify min and / or max length)
  •number of words (optionally specify min and / or max words )
  •Plain text (disallow tags)
  •Must be empty (Anti-Spam: Hide with CSS)
  •Words blacklist
  •number of selections (optionally specify min and / or max selections )
  •Unique
  •Match against a field
  •Match against a property
  •Specific value(s)
  •Require at least one of several fields
  •Equal values on multiple fields
  •Unique values on multiple fields
  •PHP Code (powerfull but dangerous)
  •URL (support internal path and external url validation)
  •Email
  •Pattern (Regular expression lite)
  •Date range2
  •Date range(living in sub module date validation, deprecated in future)


How to call ctools modal window from mycustom.tpl.php?

You have to include below code in your mycustom.tpl.php also.

ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();


By default, giving a role the permission to delete messages will not delete the message for the other user. I just tested this and it works as you require.

As for only allowing messages between certain users, you can prepopulate the "To" field with /messages/new/[nid]. So on the user page or in views or whatever, you can create this link using tokens or replacements.
Then disable the field with a custom module. Savvy users could change the [nid] in the url or even the html in the page so this depends on how secure it needs to be. They'd need to know another user's nid to be able to do this but they can only know that if they can already view the user.

function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_new') {
    $form['recipient']['#disabled'] = '1';
 }
}


If you want to change output of the field in a Views, use Semantic Views

You can also turn on the Theme Developer module, check which .tpl is used to display piece of content you want to change and then create this file in a way you want.

Another modules that provide similar functionalities are:

Quickest solution, just turn this module and forget about drupal's nested divs:

Fences

More complex, this lets you to set up fields markup - for views as well as full node:

Semantic CCK

The most complex, apart from fields markup, this lets you to set up columns, headers, footers etc. inside of full node view, as well some views integration:

Display Suite


Make form to show multiple field widgets with predefined values

You will probably need to build a custom module that calls hook_form_alter() or hook_form_FORM_ID_alter() and insert your required pre-filled values before the form is rendered.

Your function should look something like this:

<?php

/*
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id){
    // Install devel module and uncomment below to see the variables in the form printed on the screen
    // dpm($form_state);

    // Once you know where to put the variables you can add new values to the field array like this
    $form_state['values']['field_something_important'][] = 'First thing';
    $form_state['values']['field_something_important'][] = 'Second thing';
    $form_state['values']['field_something_important'][] = 'Third thing';
}

Note that the actual location to put the values will be different, and might be a few levels deeper into $form_state.

As always when making modules:

Replace the 'hook' part of a function name with the module name (case sensitive)
Make sure you have the right form id in the hook
Clear your cache so Drupal can find the hook


Find out which nodes use a specific filter

Create a view for nodes & add Content: Body (body:format) in Filter Criteria, then set the text format value as bbcode.


Overwrite the url function of a specific node entity

Entity URI callback

You can implement an URI callback. Example in comment.module:

/**
 * Entity URI callback.
 */
function comment_uri(CommentInterface $comment) {
  return new Url(
    'entity.comment.canonical',
    [
      'comment' => $comment->id(),
    ],
    ['fragment' => 'comment-' . $comment->id()]
  );
}

and add the callback to the annotations of the entity type:

*   uri_callback = "comment_uri",

For an existing entity use a hook_entity_type_alter().

Bundle specific URI callback

A URI callback for a specific content type can be defined in the bundle definitions:

**
 * Implements hook_entity_bundle_info_alter().
 */
function mymodule_entity_bundle_info_alter(&$bundles) {
  if (isset($bundles['node']['my_content_type'])) {
    $bundles['node']['my_content_type']['uri_callback'] = 'my_content_type_uri';
  }
}

The callback:

/**
 * Bundle URI callback.
 */
function my_content_type_uri(NodeInterface $node) {
  // build a url object $url
  return $url;
}

A bundle-specific callback takes precedence over the generic one for the entity type and a link template (defined in the links array of the entity type) takes precedence over both, so you need to remove the link template if you want to override an existing one, e.g. canonical, which makes you responsible to provide the route needed for the custom url, if it was built before by a route provider and is not defined in a *.routing.yml file.

Edit:

To modify the url in links to a specific content type you can use a hook_link_alter():

function mymodule_link_alter(&$variables) {
  $url = $variables['url'];
  if ($url->isRouted() && $url->getRouteName() == 'entity.node.canonical') {
    if (isset($variables['options']['entity'])) {
      $node = $variables['options']['entity'];
      if ($node->bundle() == 'article') {
        // modify the links to articles
      }
    }
  }
}


hook into third party API after checkout

You should probably be looking to use the hook_uc_checkout_complete() hook.

From the docs, it takes two parameters, $order and $account - I'm guessing $account will be the one you'll need to create the account on the third party web service as it's the object that contains the customer/user information.

The registration part of your question depends completely on which third-party web service you are talking about, and will probably fall outside the scope of Drupal Answers unless there is either an existing integration module, or you are looking to write one and need help on the Drupal side of things (i.e. this is not the place for general API usage questions).


In the OG API, which hooks are available when a group admin adds or removes a user from a group?

You can find all OG hooks here.

You already mentioned two of them, but for the sake of a complete answer here are the hooks fired on membership add/edit/delete:

hook_og_membership_insert
hook_og_membership_presave
hook_og_membership_delete

Also, as memberships actually are entities you can also use all hooks used for saving and deleting entities, like hook_entity_update and hook_entity_delete. You can find them in this list.


Is this table generated from Views?

If so, you should be able to just add a node link, rewrite it to output ONLY the URL, hide it, then use that field as a rewrite pattern in your facebook button's output, so the like button is applying to the URL of the node itself.


It appears Webforms has conditional rules which works great. Also there is a module called Webform Conditional for in page conditional statements.


Menu alter for a particular content type

There are o node type specific edit routes, only one. You'd have to alter that and then in your access callback, decide if it is your node type or not.

But, why don't you just implement hook_node_access() and check for the update operation? That allows you to control access to that page and also any edit operation elsewhere on th system, on whatever condition that you want.


Proper way to cache custom entities with Entitycache?

entitycache.module and entity.module integrate, so that just just work.

All you need to do is make sure that the cache table for your entity table exists and set the keys in hook_entity_info() as you already do.

Not sure why it doesn't work, but I'd start by removing the custom controller and rely on the default one from entity.module.


How to override breadcrumbs defined by a module using a custom module?

Different solution depending of your context.

Change the module order by changing their weight: http://drupal.org/node/110238
Use an other hook than is called later like hook_node_view_alter
Add a flag in your node and test against it

First module

 <?php
 function property_bc_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property') {
        $breadcrumb = array();
        $breadcrumb[] = l(t('Home'), NULL);
        $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
        $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }
    }

In your other module

    <?php
    function property_bc_plus_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property' && isset($node->custom_bredcrumb_is_set) && $node->custom_bredcrumb_is_set != TRUE) {
        $breadcrumb = array();
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }

}


Drupal 8 - Check if language prefix is present in url or not

There might be something more elegant, but doing it the dirty way is pretty simple:

$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$parts = array_filter(explode('/', \Drupal::request()->getRequestUri()));

$has_prefix = count($parts) && $parts[0] == $languagecode;


get commerce order variables dpm without loading order again

You need to use commerce_order_load to load the order with all the data. If the order already has been loaded somewhere else on the page, the order won't be loaded twice, but the order will be fetched from static cache instead. So it's fine to load the same order multiple times.

If you do need to clear the cache, (maybe you need to compare the order to what is in the datebase to see what has changed), then you can use use commerce_order_load_multiple or call entity_load directly.


Could be a redirect loop. You have to check whether the query string is already present and then stop redirecting again:

  public function redirectWithFilter(GetResponseEvent $event) {
    $request = $event->getRequest();
    if ($request->query->has('city')) {
      return;
    }
    ...
  }


There is now a Drupal 7 version of Views Datasource. Here is a quote about it (from the module's project page):

... is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.
The project consists of 4 Views style plugins (and related row plugins):

views_xml - Output as raw XML, OPML, and Atom;
views_json - Output as Simile/Exhibit JSON, Canonical JSON, JSONP/JSON in script;
views_rdf- Output as FOAF, SIOC, and DOAP;
views_xhtml - Output as hCard, hCalendar, and Geo.


How to change a field value with a Rules Action?

You first need to add a condition to check if the field exist on that node, only then it is available to the actions. There is a specific condition to do this.


add user profiles fields into comment fields

Your solution is ok. But you could also

Add a field on the comment fields of your content type that uses a reference to the user
On hook_comment_presave fill out the user reference field with the uid of the logged in user
On manage display of your comment fields, just render the user field as a rendered entity
You could use a custom view mode on user that only shows the fields "job title" and "bio".


Exposing a single field to users to create new nodes from a page

So you want to create something like simplistic Twitter/Facebook wall? Check following modules:
Microblog

Users can publish microblog updates, follow and be followed by other users, and reply to other users' microblog updates.
Module also provides "public timeline" page as well as followers and following pages, and a block of "recent microblog updates."

Drupal 6 & 7: https://drupal.org/project/microblog
Statuses (Social Microblog)

Provides status updates / microblogs like Facebook's Wall / News Feed, Twitter's Timeline, and Yammer's Feed. Users can update their own status or write messages to other users, nodes, Organic Groups, taxonomy terms, or other entity types. @mentions and #hashtags are supported, as well as comments on status updates, viewing conversations between users, the ability to "like"/"reply" to/RT a message, automatic updates without page refreshing, and integration with over 20 modules.

For Drupal 6: https://drupal.org/project/facebook_status
For Drupal 7: https://drupal.org/project/statuses


Speed difference between db_select and EntityFieldQuery

There might be a slight difference in performance but I guess it depends on your implementation. As you said yourself: it might be possible to replace a couple of db_select queries with EntityFieldQuery, although I can't really think of a situation where you'd be able to do that, if your db_selects are solid.

If I'm not mistaken EntityFieldQuery actually uses db_select or at least a SelectQuery to fetch data. I also think EntityFieldQuery looks up information about the entity that needs to be  queried (ie: base table), this is cached though.

My guess is EntityFieldQuery would be somewhat slower, but the only way to see if you're losing any performance is by benchmarking (timing) it.

All in all I wouldn't worry about the performance of EntityFieldQuery. The biggest advantage of EntityFieldQuery is that it adds another layer of abstraction, making your code more loosely coupled and more cohesive. It's also pluggable so somebody could change the backend without you having to change any of your code.