format_date() seems to ignore the time zone

Yep, i was having similar problems, but in Drupal 6.

I'm surprised your  $field_event_date[0]['value'] was in New York time. My understanding is that that value comes straight out of the database, and it's pretty standard to keep all times in the db as UTC times, and only use local times when displaying them (since local times go crazy a couple of times a year).

$field_event_date[0]['timezone_db'] will tell you for certain what timezone $field_event_date[0]['value'] is in.

And $field_event_date[0]['timezone'] will tell you what timezone it should be displayed in (according to your site's 'default timezone'). If you look at $field_event_date[0]['view'], it should be in the display timezone.

When i'm trying to display dates from the raw 'value', i do something like...

/**
* @param
*     $date A CCK date field, like you'd get in your node templates,
*     e.g. $field_event_date[0]
*/
function get_display_date($date) {
    $date_convert = new DateTime($date['value'], new DateTimeZone($date['timezone_db']));
    $date_convert->setTimezone(new DateTimeZone($date['timezone']));
    return $date_convert->format('Y-m-d H:i:s');
}

I've yet to find any documentation which can confirm all this, so i may be totally wrong! But it works for me so far. Hopefully Drupal 7 isn't too different.


It's no different, you can also save an array in state:

\Drupal::state()->set('cleanupeditform_formkeys', ['foo' => 'bar']);


mytheme_preprocess_field is not called on add/edit node

I believe the theme functions are called on render (as in view) and not the add/edit pages.  If you want to affect the markup of the fields on the add/edit forms you would use a hook_form_alter or hook_form_FORM_ID_alter() and change the render array there.


Sorry, it is my fault, I forgot to use the "&" to pass the reference variable in the loop. Here is the final code :

/**
* Implements hook_form_node_admin_content_alter()
 */
function MYMODULE_veilleur_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
    foreach ($form['admin']['nodes']['#options'] as &$option){
      if($option['type'] == "Document"){
        $option['title'] = $option['title']['data']['#title'];
      }
    }
}


What's wrong with my taxonomy links or my taxonomy view and contextual filter?

You mentioned that changing the alias doesn't update all pre-written aliases. Could you pick one term, edit it, and hit "Automatic alias" under URL aliases so that it updates, then post whether that resolved the issue for that individual term?

If so, all you need is to bulk update aliases for that vocabulary, which can be done with a VBO - I'll detail how if that's the issue.


Rules: after saving new content and after updating existing content both triggered on node create

This is very easy to accomplish, you have a few attributes of the node to compare and check in order to decide which trigger to be true/false.

Method 1:
Put the following PHP code into your both conditions (create & update) by selecting execute PHP code

CREATE

if($node->created == $node->changed) {
   return true;
} else {
   return false;
}

UPDATE

if($node->created != $node->changed) {
    return true;
} else {
   return false;
}

Method 2:

UPDATE:

if($node->is_new) {
     return false;
} else {
     return true;
}

OR

if(!empty($node->nid)) {
    return true;
} else {
    return false;
}

I have not checked the Method 2 but, method 1 is easier and should definitely work out for you.

Don't forget to Accept this answer solve your problem.

Cheers.

Raf.


How to sync two different content types?

Assuming you have an Issue content type, and an Article content type

Install References and enable Node References.  On the Article content type, Add a Node Reference field (could name it "issue") and restrict its options to nodes of type Issue.

Then create a View of Articles and add (under Advanced) a Contextual Filter of Content: Issue (and if you are using url aliases for the Issues, then provide the Contextual filter with a default value of Content ID from URL).  Make it a Block display.

Then display the block on Nodes of type Issue, and it should work great for you.


How to create a content type with associated products and customized attributes?

You can use the Field collection module

  Provides a field-collection field, to which any number of fields can
  be attached.

And create a Field collection field (in your Offer Content Type) with a reference to Product and a field named quantity and other named custom price.

So in your Offer you can have many Products with theirs quantities and custom prices.


PHP evaluation for "Send HTML email body"

If field_software_product_sku is text field you should test on value of the field something like:

if ($node->field_software_product_sku[LANGUAGE_NONE][0]['value'] === "Some Product Name"){
    echo "Trial Version Download Link
";
  }

other ways if it doesn't work, i suggest you to use Devel Module and dump the $node->field_software_product_sku using dpm function to see the value of the field:
dpm($node->field_software_product_sku) and then check on the value of the field.


You can use the entity type manager to load entities of any type:

$entities = \Drupal::entityTypeManager()
  ->getStorage('a_process')
  ->loadMultiple();

foreach ($entities as $entity) {
  // ...
}

If your code is in a container aware context, be sure to inject the entity manager as a service instead of referring to \Drupal explicitly.

Of course if you always know the entity type up-front you can use the method on the entity class itself, eg

$entities = \Drupal\foo\Entity\AProcess::loadMultiple()


How to calculate the user's average rating on all his/her nodes with Fivestar?

I know that something like this can be done with computed field. It will require some PHP code though. See some discussion here

Here's what you need to do:

Install Computed Field and Fivestar
Go to admin/config/people/accounts/fields and create a computed field on the user entity type. In my case I named it "field_computed_rating". On the settings form for the field make sure the checkbox "Store value in the database" is unchecked.
Click on "Manage Display" for the content type you created the field on. Then make sure the format for that field is set to "Unsanitized".
(if you already have a custom module you can skip this step) In your code base within sites/all/modules, create a new folder titled fivestar_user_aggregate. Within that folder you will need to create  fivestar_user_aggregate.info with the following contents.

name = Fivestar User Aggregate
description = Assign users an aggregate rating based on all their nodes
core = 7.x
package = Custom

Add this custom php function to your module file or create fivestar_user_aggregate.module within fivestar_user_aggregate with the following contents. If you named your field differently then you will need to modify the function name accordingly.

<?php

function computed_field_field_computed_rating_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
    $result = db_query("SELECT n.uid, n.nid, vote1.value AS count, vote2.value AS average FROM {node} n
INNER JOIN {votingapi_cache} vote1 ON n.nid = vote1.entity_id
AND vote1.function =  'COUNT'
INNER JOIN {votingapi_cache} vote2 ON n.nid = vote2.entity_id
AND vote2.function =  'average'
WHERE n.uid = :uid", array(':uid' => $entity->uid));

    $rating_count = 0;
    $rating_total = 0;

    $nodes = $result->fetchAll();
    foreach ($nodes as $node) {
        $rating_count += $node->count;
        $rating_total += $node->average * $node->count;
    }

    if ($rating_total == 0) {
        $weighted = 0;
    } else {
        $weighted = $rating_total / $rating_count;
    }

    $variables = array(
        "rating" => $weighted,
        "average_rating" => $weighted,
        "votes"  => $rating_count,
        "stars" => 5
    );
    $variables["widget"]["name"] = "basic";
    $variables["widget"]["css"] = "sites/all/modules/fivestar/widgets/basic/basic.css";
    drupal_add_css(drupal_get_path('module', 'fivestar') .'/css/fivestar.css');
    return theme('fivestar_static', $variables) . theme('fivestar_summary', $variables);
}

Enjoy! You should now see a weighted average of all a user's node's ratings on their page.


How to make custom fieldset collapsed by default in Drupal 8

All collapsible fieldsets have been replaced with HTML5 details
  elements.

Fieldset and legand are very hard to style and its not recommended to use with Drupal 8 any more. Instead its replaced with more cross browser way, which is the HTML5 Details & Summary tags.

'#type' => 'details'

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

Drupal 7

$form['advanced'] = array(
  '#type' => 'fieldset',
  '#title' => t('Advanced settings'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#description' => t('Lorem ipsum.'),
);

Drupal 8

$form['advanced'] = array(
  '#type' => 'details',
  '#title' => t('Advanced settings'),
  '#description' => t('Lorem ipsum.'),
  '#open' => TRUE, // Controls the HTML5 'open' attribute. Defaults to FALSE.
);


Reviewing and displaying node reviews in Drupal 7

If you wanted to do this very simply, you could just add a fivestar field to Drupal's built-in comments.  Comments already provides the author name and a description field (the comment), and enabling comments on nodes is easy (you can do it from structure/content types).


How to load an include file from Drupal's include folder?

require_once DRUPAL_ROOT . '/includes/actions.inc';

is the correct way.

Using 'content' just worked, because there is no module named content and just did work due to a side-effect. It also caused silent performance problems on Drupal versions < 7.50.

There is no Drupal specific function to load a core include file, and this is how it is done in includes/common.inc line 5242.

Fabianx, Drupal 7 core branch maintainer and core committer


Specific localization server for a module

You can specify an alternative source for translations in .info file in different ways:

l10n server = http://example.com

l10n url = http://example.com/path/to/l10n_server.xml

l10n path = http://example.com/path/to/%core/%project/%project-%release.%language.po

If your localization server is based in l10n_server module, l10n server is enough.

If you're not using l10n_server but a custom solution, you may want to provide l10n url key with the url to a custom-build xml file to inform l10n_update about where to get translation updates from.

Lastly, if you're not using l10n_update and you're not planning to generate such an update xml file, you can pass the path to the .po file with l10n path, you can use some placeholders in this path, as shown above.

For more information, see l10n_update's README.txt and docstrings for l10n_update_build_projects().


By default the text format filter "Limit HTML tags" will strip out "style" attributes in your HTML.  You can't configure this via the admin but you can replace the filter with WYSIWYG Filter and configure that to allow specific styles whilst still filtering out dangerous HTML.  The settings are found at /admin/config/content/formats/filtered_html (or replace "filtered_html" with the name of any other text format you need to alter).  See this issue for pointer as to how best to set this up.

Please note though that if you're not sure what you are doing here then you may compromise the security of your site by setting up WYSIWYG Filter in a less than ideal way.


How can I use rules to grab fields from one content type to another then delete the old nodes?

In your rule, i think your can write a custom php code:

  //$node is your original node

  $node_new = new stdClass();
  $node_new->type = 'content_type_2';
  $node_new->status = 1;
  $node_new->uid = $node->uid;
  $node_new->title = $node->title;
  $node_new->promote = 0;
  $node_new->created = $node->created;
  $node_new->timestamp = $node->timestamp;
  $node_new->field_article_url = $node->field_article_url;

  node_save( $node_new );
  node_delete( $node );


Drupal installation creates innoDB tables even though myIAM is set as default in my.ini

Drupal overrides the default to set it to innoDB because innoDB is a better choice for Drupal in many cases. Two main reasons for this:

InnoDB supports transactions; MyISAM doesn't.
When a row in a MyISAM table is being updated, the entire table is locked, so no other process can write to it. InnoDB locks rows in tables, rather than entire tables. For example, on this site, if many people are writing to the comments table at the same time, they would have to wait in a queue if the table were myISAM, but with innoDB, multiple writes can happen simultaneously, provided they're not to the same row in the table. This has obvious performance ramifications.

If you absolutely have to, you can edit the information schema table in mysql to set all the tables to MyISAM, but make sure you know what you're doing...


When to use a preprocess function instead of changing the template

From the docs

  The main role of the preprocessors is to set up variables to be placed within the template (.tpl.php) files.

And building on that:

  There can be numerous preprocessors for each theming hook. Every layer from core, modules, engines and themes can have one, each progressively building upon the variables before being rendered through template files. This keeps the markup clean and easy to work with inside templates by placing most of the logic inside these preprocessors.

So if you're setting up a variable that you want to be rendered in a template, your code will go in a preprocess function.

When it's time to render the variables that have been set up, wrap them in specific markup and so on, you'll be editing template files.


How to mass update recurring date rules?

This sounds like it will need a custom module, However have you tried the bulk update module?, you could extend this and adapt it for dates, I do not have any code examples, as it does sound quite complex.


Drupal Field Hierarchy or Fields By Selection

I think the Conditional Fields module could provide a solution for you.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.


How can I implement a shopping cart limit?

Sure it's possible there are several ways of doing it.

The simplest solution would be to add a custom validation handler to the add_to_cart_form and raise a validation error if there is something in the cart:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'MODULE_cart_validate';
}

function MODULE_cart_validate($form, &$form_state) {
  $order = commerce_cart_order_load($GLOBALS['user']->uid);
  if ($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if ($order_wrapper->commerce_line_items->value()) {
      form_set_error('', t("You can only have one item in your cart");
    }
  }
}

Another option is to remove other items in the cart when you add a new one. This could probably be done with rules, but is more easy to do with code if you know a bit of Drupal and PHP.


How can I temporarily prevent any logins?

The correct way to avoid users can access the login form is changing the access callback of the route used for the login form and removing the login block from any page.
Altering the form with hook_form_alter() or hook_form_FORM_ID_alter() and setting $form['#access'] to FALSE would just hide the form to the users, who would just see a blank page.
Altering the access callback, users would see an access denied error page if they try to access the login page entering directly the login path in the address bar of the browser (http://example.com/user/login, if clear URLs are enabled, or http://example.com/?q=user/login, in the case clear URLs aren't enabled) which would make clear the login page is not accessible to them. Plus, Drupal wouldn't show any link pointing to the login page, if users don't have access to that route. This means that, if you have a module that adds a link to the login page, that link would not be shown to the users who cannot access the login page.
Since the User module is already using an access callback for user/login, it's sufficient to change it, for example with the following code.
function mymodule_menu_alter(&$items) {
  if (isset($items['user/login']) {
    $items['user/login']['access callback'] = FALSE;
  }
}

Setting the access callback to FALSE makes user/login not accessible from any user.
I would not use that code, if I am not totally sure users aren't automatically logged off, for example because the session cookie has expired, or because there is a module that logs them off when their session lasted too long.


Facets rendering on all pages irrespective of value dynamicaaly form contextual filter in views

I believe, this is the default behaviour, where the facets are filtered based on the result set.
What you want may not be achievable OOB.
But this is not a bug, it is a correctly working behaviour.


How do I populate fields in content type not in feed when importing?

You can use the Feeds Tamper plugin "Set value or default value".

Install the modules Tamper and Feeds Tamper.
Go to the mapping page.
Select a target that you want to set a default value for.
On the source selector that appears, select "New CSV source". Type in a source name that does not appear in your CSV file.
Repeat step 2 and 3 for every field you want to set a default value for and save the mappings.
Go to the 'Tamper' page.
For each target you want to set a default value for, click on "Add plugin". From the selector that appears, select "Set value or default value".
A field called "Value" appears. Fill in the default value and click "Submit".


There is a size limit of 300kb per file and a limit of 32 files.

http://joshua.perina.com/africa/gambia/fajara/post/internet-explorer-css-file-size-limit

http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/ad1b6e88-bbfa-4cc4-9e95-3889b82a7c1d


form_set_error not showing error message on webform

I think it could also happen if $messages haven't printed in the page.tpl.php in your theme.

Is the <?php print $messages; ?> included in your page.tpl.php file?

Check this line in your page template. You might have missed it.

Hope it will help you!


Change default option of installation profile

In your profile .info file you can add the distribution name property in the following format:

distribution:
  name: ABCD

Notice: ADD this property but leave original top level "name" property in place.

This will totally omit  the  "Choose profile" step, and your profile will be auto selected for the entire process.


See this page about how to manually construct H5P packages and follow the same process for each repo.

You need to download the repo Zip file. Decompress into a temp directory. Delete the LICENSE, README.md, and .gitignore files

Create a new folder to hold the rest of the files like library.json, CSS, JS For the H5P editor, name it H5PEditor.ScormFile. For the h5p-scorm-master, use H5P.Scorm:

Outside of the new folder, create an h5p.json file.

For the H5PEditor.ScormFile, use this:

{
  "title": "H5PEditor.ScormFile",
  "language": "en",
  "author": "Pavlo Shevchuk",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5PEditor.ScormFile", "majorVersion": 1, "minorVersion": 0,"patchVersion": 8, }
  ],
  "mainLibrary": "H5PEditor.ScormFile",
}

for the H5P.Scorm, use:

{
  "title": "SCORM/xAPI",
  "language": "en",
  "license": "cc-by-sa",
  "preloadedDependencies": [
    { "machineName": "H5P.Scorm", "majorVersion": 1, "minorVersion": 1, "patchVersion": 16, }
  ],
  "mainLibrary": "H5P.Scorm",
  "embedTypes": ["div"]
}

Now Zip up the right h5p.json folder and the H5PEditor.Scormfile or and the other with H5P.Scorm directory. Zip compress each, naming the editor file H5PEditor.ScormFile.h5p and the second library H5P.Scorm.h5p.

Creating H5PEditor.ScormFile.h5p.

So create Zip file renamed to H5PEditor.ScormFile.h5p. Inside of that you have a folder named H5PEditor.ScormFile with contents of the Git repo, https://github.com/pavloshevchuk/h5p-editor-scorm, specified files removed. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5PEditor.ScormFile directory.

H5PEditor.ScormFile.h5p
├── H5PEditor.ScormFile
│   ├── library.json
│   ├── scripts
│   │   ├── scormFile.js
│   │   └── scormFileUploader.js
│   └── styles
│       └── scormFile.css
├── H5PEditor.ScormFile.h5p

Creating H5P.Scorm.h5p.

Create a second Zip file renamed to H5P.Scorm.h5p. Inside of that you have a folder named H5P.Scorm with contents of the Git repo: https://github.com/pavloshevchuk/h5p-scorm, specified files deleted. Place the icon.svg file in a directory called content, inside the Zip file. You also create a h5p.json file with the code provided. Place it in the Zip file but outside the H5P.Scorm directory. The Zip file contains this structure:

H5P.Scorm.h5p
├── content
│   └── icon.svg
├── h5p.json
├── H5P.Scorm
│   ├── css
│   │   └── scorm.css
│   ├── js
│   │   ├── api
│   │   │   ├── api_1_2.js
│   │   │   ├── api_2004.js
│   │   │   ├── datamodel.js
│   │   │   ├── debug.js
│   │   │   └── flash_detect.js
│   │   └── scorm.js
│   ├── library.json
│   └── semantics.json

You should now have two H5P files and you will now be able to update them at the H5P admin libraries page:

admin/content/h5p

Here's a repo containing the files I made following these instructions:
https://github.com/jackrabbithanna/h5p-scorm-libraries


views pass argument for number of records to display to pager contextual filter?

I don't think it's possible through the Views interface. But I think you could probably do it through a small custom module.

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $limit = $arg(1) //where $arg is the argument from your url
    $view->items_per_page = $limit;
  }
}


Make the page display path taxonomy/term/% and the first argument to the view should be the term ID. There is a disabled view for this purpose which should set these up for you, but if you already have a view you can also make that override the core taxonomy path by making the two adjustments I mentioned.


Deprecated Dependency Warning not removing

The Lighting Media modules have hard-wired checks to report this information if it finds Video Embed Media or Entity Embed & Views Infinite Scroll installed. It doesn't check the Composer requirements to see if the warning message is still applicable.
Either ignore the warning until the 5.x release is out or patch away checks in hook_requirements() if it bothers you that much.


What is the expiration time of Email verification link?

The first time login link has no expiration time. Only password reset links have expiration time, which can be get or set using the system variable user_password_reset_timeout which has a default value of 86400 (24 hours).


Inside node.tpl.php instead of printing the whole content you can print fields seperately:

<?php print render($content['field_name']); ?>


That is because hook_boot() is invoked too early in the bootstrap process, which means:

Not all the modules are loaded, including the Locale module that is the one that alter the path, and the reason why arg(0) returns "apple" in your example, when called in hook_init().
The language has not been set; it is initialized during the DRUPAL_BOOTSTRAP_LANGUAGE phase, while hook_boot() is invoked during the DRUPAL_BOOTSTRAP_PAGE_CACHE phase.
The call to drupal_path_initialize(), which alters $_GET['q'] with $_GET['q'] = drupal_get_normal_path($_GET['q']); is done during the DRUPAL_BOOTSTRAP_FULL phase, which is the last bootstrap phase.

Differently, hook_init() is invoked as last step done in the DRUPAL_BOOTSTRAP_FULL phase, which means all modules are loaded, the language has been set, and drupal_path_initialize() has been already called.

As side note, hook_boot() has been removed from Drupal 8; if you are using it, you will need to change your code. Using hook_init() is a possible alternative, since it is still used in Drupal 8.


How to make a link in calendar module to current date?

<a href="event/<?php print format_date(time(), 'custom', 'd f y'); ?>">Event of today

Do something like this in the calendar theme. Change the path and the format API and put it in one of the tpl.php file of the calendar.

Or just put a link on the tpl.php, pointing to the default view without date on the url

Event of today

Where do you want to put it?


hook_node_grants() implemented by a custom module is not invoked

It didn't have anything to do with my code. I'm new to Drupal so I didn't know hook_node_grants() don't get invoked when I'm signed in as an administrator. Newbie mistake from my side :)


Views: How to sort in Table format naturally

Try to install Views_bootstrap module.

Then in views/Format select Bootstrap Table

  Don't forget the Settings


Get future node id (nid) of nodes being programmatically created (future node)

Unfortunately, there's no a clean way to do that!


A good question, and surprising there's not an easier way to rollback a deleted field, given the data is still available.

Assuming you have:

Renamed the field_deleted_* tables back to field_data_field_myfield and field_revision_field_myfield (latter also important)
Updated the 'deleted' flag from 1 to 0 in the relevant data tables.

There is also

field_config

  The main field configuration

field_config_instance

  The field configuration on a particular entity bundle.

You may need to adjust the 'deleted' flag there also:

e.g:

UPDATE field_config SET deleted = 0 where field_name = 'field_my_deleted_field';
UPDATE field_config_instance SET deleted = 0 where field_name = 'field_my_deleted_field';
TRUNCATE TABLE cache_field;


Im trying to pass an array as an argument in a page callback

That happens because the code you are using is similar to the following one.

$url = url('add_selected_prints_to_cart/' . $array);

If each photo has an ID that can be used to univocally identify each photo, in the same way a node ID univocally identify a node, you could use code similar to the following to create the URL. I assume the structure of the $photos array is the following one.

array(
  'photo ID 1' => array( /* data for the photo with ID equal to 1 */),
  'photo ID 2' => array( /* data for the photo with ID equal to 2 */),
  'photo ID 3' => array( /* data for the photo with ID equal to 3 */),
  // ...
);

$url = url('add_selected_prints_to_cart/' . implode(',', array_keys($photos)));

In this case, add_selected_prints_cart() can get the photo IDs using code similar to the following one.

function add_selected_prints_cart($photos) {
  $photo_ids = explode(',', $photos);

  // Load the photos from the database.
}

If you need to pass the array to the menu callback, I would add the array to the session variables. In this way the code would for defining the menu callback would be similar to the following one.

function mymodule_menu() {
  $items['mymodule_add_selected_prints_to_cart'] = array(
    'page callback' => 'add_selected_prints_cart',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function mymodule_add_selected_prints_to_cart() {
  $photos = $_SESSION['mymodule_selected_photos'];
  // ...
}

(If you use 'access callback' => TRUE, the access arguments are not used.)

Otherwise, the code to convert an array to a string is similar to the following one.

$string = strtr(base64_encode(serialize($array)), array('+' => '-', '/' => '_', '=' => ''));

The code to obtain the array back from $string is the following one.

$array = unserialize(base64_decode(strtr($string, array('-' => '+', '_' => '/'))));

Bear in mind there is a limit for the URL length accepted from browsers.


Is it possible and reasonable to convert a complicated, heavily styled html page into an editable Drupal site page?

You can use drupal to develop and complexity of site including that of a complex css design.  I personally work for a digital agency and every single project I have been on has been built in drupal and has been heavily design oriented.  I have also built JS apps in drupal as well.

If you are looking for a theme out of the box then you probably wont find it as they are generally free and not a whole lot of design into them.  If you are comfortable or willing to learn to create your own theme and template files then you most certainly can do this inside drupal.

It all depends on your level of knowledge and effort.

Here are a few heavy sites designed in drupal:

http://www.elmwoodreclaimedtimber.com/virtual-showroom (js app, but the site is also built on drupal)

http://www.servicesource.com

http://www.jedunn.com

http://www.tnvacation.com/made-in-tennessee

With drupal you have CSS, PHP, and MYSQL which means you can do anything those technologies can.

EDIT***

Also to answer your question more specific it really depends on how much of the content will be editable.  Drupal provides a more flexible GUI type layout called panels and panelyzer that provides more of what you may need.  Research into Panopoly distribution as its geared more towards landing pages


My views slideshow doesn't work when the display is called from page.tpl.php

you can try views_embed_view to call a views block programatically.

views_embed_view

<?php
print views_embed_view($view_name, $display_id, $argument); // with single argument
print views_embed_view($view_name, $display_id, array($arg1,$arg2,$arg3)); // with multiple arguments
?>


Why are there "template_" and "theme_" prefixes instead one?

The functions whose name start with theme_ are theme hooks, while the functions whose name start with template_ are preprocess and process functions implemented by the module that implements the relative theme hook.

For example, theme_image() is a theme hook that renders an image.   template_preprocess_node() is the preprocess function implemented by the Node module, which the module implementing the node theme hook. (See the first code lines of node_theme(), the hook_theme() implementation done by the Node module.) There are other modules that can implement a preprocess function for the node theme hook, but for those modules, that preprocess function is named MYMODULE_preprocess_node(), not template_preprocess_node().

A theme can implement both a theme hook (see bartik_menu_tree()) and a preprocess function (see bartik_preprocess_node()). The difference is that bartik_menu_tree() overrides the default implementation (theme_menu_tree()) when the current theme is the Bartik theme, while bartik_preprocess_node() doesn't override template_preprocess_node(), but it is executed after it. (See the documentation for theme().)

As for using two prefixes, the reason is to documenting the purpose of the function. Even if theme_ were used in both the cases, the difference between theme_image() and theme_preprocess_node() would still be clear, but it would require you to read what follows theme_. With the current implementation, you just read the first word of the function name.


Customizing User Profile - adding lots of extra parameters retrieved from my own database tables

Don't put business logic into template files. Override the template files to present the information differently, not to calculate the information in the first place.

Profiles can be extended with the built-in Profile module or with Content Profile module. The latter uses nodes as profile categories, which means you can use CCK fields. You can also write your own profile module. For for this, you have to implement hook_user. You need to react to at least the following values for $op:

categories to provide your own profile categories,
form to show the form for editing items of the categories you provide (in case the $categories parameter is one of values you returned via categories),
delete, insert, update to persist changes to the user,
view to show the profile information for your categories.

For the matching, I suggest custom views handlers. Use the Advanced help module to access the developer documentation that comes with views.


I faced similar situation while trying to inject checkboxes to user_register_form. I think checkboxes type is not valid type for typical rendering. Form elements of type checkboxes get totally reformatted within form_builder after form_alter hooks have executed. Make sure that form builder runs after you place your field.


View of users with the same 'entity reference' field vale

You need two entity references and a contextual filter to accomplish this.

The contextual filter does not use either of the relationships. Just select provide default value, User ID from logged in user.

The first relationship will get you the manager of the currently logged in user: User entity referenced from field_manager

The second relationship will get you the users that have that manager reference: User referencing User from field_manager. Set this relationship to use the other relationship. That's the first dropdown after you create the relationship.

Then you can simply add the User name field to your view and set it to use the second relationship (User referencing User from field_manager).

Any questions let me know. I have this running on a stripped down local install of Drupal 7.


How to disable Google fonts and other things like that?

Ex: if the theme is called "cooltheme"

You need to go to drupal/sites/all/themes/cooltheme

and edit the cooltheme.info file

you should see something like this inside:

scripts[] = js/main.js  <-- so just delete this so it won't load it.

Then go to drupal/sites/all/themes/cooltheme/js and delete the .js file from here too.

For the fetching data from google fonts, they might be inside the .css file of the theme.


Another way is set the access to false to the login form. Whenever you want to re-enable the login, just comment out the hook.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#access'] = FALSE;
  }
}


I finally found out from this post here drupal.stackexchange.com/questions/100102/… that I was overlooking the theme.info file in the themes root directory:

regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[sidebar_bottom] = Bottom sidebar
regions[footer]         = Footer

Works perfectly now. There are three steps to adding a region to the Omega template.


Does a new site installation run through hook_updates of every module?

When you install a module, the largest number found in hook_update_N hook will be stored in the system table's schema_version field. It will not run the function. Just stored in the table.

When you copy a module to a new site, any of the hook_update_N hooks will not be executed for you. However, if you would like to make any change, you can implement hook_install to make the necessary database or any other changes.


How to display Views exposed filters fields as a table?

It's easier than I expected.

How-to steps:

Copy views-exposed-form.tpl.php (http://pastebin.com/V77CPxPG) from the Views module's views/theme directory to your own theme's templates directory (but some themes have their template files in their root directory! (or maybe even other directories like theme or sg. else)).
Copy ANOTHER instance of this file to the same directory, BUT now name it so that it also contains the particular view's machine name after two dashes:

views-exposed-form--page_test_ct.tpl.php

(like it's explained here; you should give a unique machine name to your view!)
So in my example, the machine name of the view is page_test_ct, like you can see it here:

Modify views-exposed-form--page_test_ct.tpl.php like this:
http://pastebin.com/1qfim7VX
Clear cache (theme registry).

SCREENSHOTS

BEFORE

AFTER

AFTER; having some exposed operators and descriptions too


How do I set permissions for user roles in the install profile

To add a role you can use user_role_save():

$role = new stdClass();
$role->name = 'role_name';
$role->weight = 5;
user_role_save($role);

To grant specific permissions to a role you can use user_role_grant_permissions():

$grant = array('access content', 'access comments', 'etc...');
user_role_grant_permissions($role->rid, $grant);


Using #cache key on a render array generates 2 entries per role, how to change that?

Yes, by default cached render arrays are varied by the hashed user permissions. See this container parameter:

/sites/default/services.yml

parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

Though this should be changed only in rare cases, because caching content with the wrong user permissions can cause security issues.

If you don't want the variations of the render cache, another approach might be to cache the query results directly:

use Drupal\Core\Cache\Cache;

  if ($cache = \Drupal::cache()->get($cid)) {
    $data = $cache->data;
  }
  else {
    $data = my_module_query();
    \Drupal::cache()->set($cid, $data, Cache::PERMANENT, $tags);
  }

Then you can manually pick a cid. With the cached query results the rendering of the list shouldn't take too much cpu time and so probably you don't need render caching anymore.


Different fields of same content type to different roles

Go to /admin/build/modules/list and enable "Content Permissions" under the cck group.

Then go to /admin/user/permissions. Here under "content_permissions module" section  enable permissions for the fields you want to be displayed for authenticated users or anonymous users.


How to customize a field price in Drupal Commerce?

You might want to try to customize the price via either of these contributed modules that can be used in combination with Drupal Commerce (quotes are from their project pages):

Drupal Commerce Extra Price Formatters (has a stable D7 version):

  This is an add-on module for Drupal Commerce that provides additional options when displaying the formatted price in your store.

Commerce Price FlexyFormatter (DEV version only).

  ... adds more options to format your products price.

Another option is to try what is described in the (accepted) answer to the question about "Additional classes for price based on price components", which includes a template.php tweak and states:

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


How to retrieve form entry for use as default value?

$form['savings_ages']['savings_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => $whatgoeshere?,
);

I guess $form['savings_ages'] is a fieldset. If so, then you can use the following code to get the default value that was saved in database during previous edit.

Explanation

When you save a form, a variable gets created with the id that you use to create form element. In your case variable_get('savings_age21', '') will fetch the previously saved value.

Documentation variable_get

Edit

$form['savings_ages']['savings_age21'] = array(
    '#type' => 'textfield',
    '#title' => t('21'),
    '#size' => 10,
    '#maxlength' => 10,
    '#default_value' => variable_get('savings_age21', ''),
);

return system_settings_form($form);

Sorry, I forgot about system_settings_form($form), this way when you save the form a variable with id of form element will get created, later you can retrieve it using variable_get().

If you do not wish to use system_settings_form($form), then you can use variable_set() to save a variable with any name. You have to do this variable_set() inside the submit handler of the form. Later while displaying the form, use the same logic variable_get() to retrieve the variable.


After some R&D got the solution as follows:

$sql="select * from project_status where node_id=".$vid." and ".  strtolower($field_progress_flags)."!='' and ".  strtolower($field_progress_flags)." IS NOT NULL";
$result = db_query($sql);
while($record = $result->fetchAssoc()){
        $data[]=$record;
}

and its works for me


Undefined variable - base_url in include() in Drupal 7 html.tpl.php

You will need to bring the variable $base_url and $base_path into the global scope. At the top of your function or template file add:

global $base_path, $base_url;

or call base_path()


If you have a feature where you need to create a menu whenever something happens, using the code should be just fine.

I prefer using the static create method on the entity object \Drupal\menu\Entity\Menu::create, but the manager is fine as well.

If you are creating menu's on your development environment as part of setting up your drupal site, I would advice using config export/import. If you use drush, you can make it part of the deployment to import configuration so production always reflect the configuration you have saved. I prefer to do things like this, but for small sites it might be a bit overkill.


How to select from a specific choice of images on content forms?

You can use

function template_preprocess_node

then loop in the variable you want.
For each value you have selected, you could add an  to your imagetype variables.
Then just display the variable in you node template.


6 - No content displaying though content is there

This can be of due to many reasons. Check one of these,

Go to configuration/system/site information, Make sure, you have correct number of posts and front page. [Number of posts on front page ]
When you add content, then, make sure, you click on publishing option and click on 'published' checkbox. You can check the content is published or not, by making a menu link of it.
If these are okay, then, please check by changing the theme, may be your theme page is broken or something. Go to appearance and select new theme.

Make sure, you flush your system, cache and try.


Hide a block depending on the value of a field?

As Letharion points out you can use Panels to do this, but panels does indeed have a bit of a steep learning curve. It might be quicker to learn something like the Context Module with Context Entity Field.

To do this with context, create a new context with whatever name you like. Then in the Conditions area add the "Entity field" as a condition and select entity type as taxonomy term. Then select the field you created in your vocabulary e.g. "field_show_block" and uncheck the "empty field" checkbox and put in "show" into the field value. Then in Reactions select which blocks you want to show, and assign them to the relevant regions.

If you don't want to do things using a Drupal contributed module though, the following visibility code (with the core PHP filter module on) may work with a bit of tweaking to match your exact field name:

<?php
// assumes the user is visiting taxonomy/term/<tid>
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
  $term = taxonomy_term_load(arg(2));
  if (isset($term->field_show_block[LANGUAGE_NONE][0]['value'])) {
    return $term->field_show_block[LANGUAGE_NONE][0]['value'] == "show";
  }
}
return FALSE;
?>

The reason why using the PHP filter for block visibility is bad practice is because, when the PHP code is written incorrectly, it's a little awkward to fix it (e.g. clearing database columns). It's also a potential security risk, allowing database stored PHP code to be executed unchecked.


How to get the paragraph information in a custom display suite code item

I'm using a view and want to display the first paragraph of text type
  and the first paragraph of data type . But only the first one .
  Currently they all come out in the view

In Views click on your paragraph field, mine is called "test".

Then in Multiple Field Settings, change Display to 1


Image Repo and Uploader for specific role

You could use taxonomy easily enough.

Create a vocabulary called Node Images
Add an image field to the taxonomy term
Add all your terms (just name and the image)
Under manage display (for the term), set it up to only show the
image field
Under manage display -> full content (for the node), add the
taxonomy reference field and set the format to Rendered taxonomy term <- (requires display suite)

On the content type that your staff uses, add a taxonomy reference field with a dropdown or autocomplete.  When they create new content, they would be able to select the correct term/image to attach to the node.  You would just need to initially add all the terms/images to the vocabulary.


How to theme back end forms created by a custom module?

One option is to add a prefix and suffix to your form arrays

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Name'),
  '#required' => TRUE
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['#attached']['css'] = array(
 'path/to/my.css' => array(
   'group' => CSS_AGGREGATE_THEME,
   'weight' => 999
 ),
);

my.css

.something {
  border: solid red;
}


How to change the default term path "taxonomy/term/[tid]"

Please go Configuration->search and metadata -> url aliases -> pattern.

Check over to the Taxonomy Term Path. If you have created the plan as Taxonomy.

Go to the Pattern for the Taxonomy plan and then create the URL path of the plan

If you want to display the Id in URL,give plan/[term:tid] or taxonomy name give it as plan/[term:name].


Remove one of the two "Apply to selected items" submit buttons with Node Bulk Operations

This is intentional functionality for some workflows (for long lists of results).
If you wanted to get rid of the button, you could hook_form_alter it away. Form IDs and array structure are dynamic based on your view so you'll have to adjust accordingly based on the view & action button to remove (this can be found in the Views UI, if not known).
/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // @TODO: Determine view_id / display_id / field_id for a specific VBO form:
  if ($form_id == 'views_form_' . $view_id . '_' . $display_id) {
    // HEADER ACTION BUTTON:
    //unset($form['header'][$field_id]['actions']);
    // FOOTER ACTION BUTTON:
    //unset($form['actions']['submit']);
  }


Get array of all entities from entity reference field

I can't say for sure on that specific field but usually there's the referencedEntities() method you can call

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.4.x

So something like this perhaps:

$entities = $node->field_taxonomy_term->referencedEntities();


Instead of views_php use something like this. Add it as a field - you just need a custom handler to call the revisioning function that returns the latest vid.

/*
* Implements hook_views_data_alter().
*/
function MYMODULE_views_data_alter(&$data) {
  $data['node_revision']['latest_revision'] = array(
    'title' => t('Latest revision'),
    'help' => t('Get the latest vid.'),
    'group' => t('Content revision'),
    'real field' => 'nid',
    'field' => array(
      'handler' => 'MYMODULE_field_handler_latest_revision',
      'click sortable' => TRUE,
    ),
  );
}

And the handler:

/**
 * Provide the latest revision number from the nid field.
 */
class MYMODULE_field_handler_latest_revision extends views_handler_field {

  // Return latest vid as the field value.
  public function render($values) {
    $value = $this->get_value($values);
    return revisioning_get_latest_revision_id($value);
  }
}


$form_state->setRedirect not working after a $form_state->setResponse

short answer RedirectResponse;

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('/where-ever');
$response->send();


This should be a folder permission issue. What you need to do is check the image style folder (sites/all/default/files/styles) if it is writable. You can use ls command to check the directory permission. To change the permission you either need chmod or chown commands to make the folders writable by Drupal.

Once the permission are correct you may need to flush the cache for images. If you have Drush you can do that by running drush image-flush STYLE_NAME or by clearing them all by running drush image-flush all.


Pretty close; here's the correct way:

/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items['languages'] = array(
    'page callback' => 'YOURMODULE_languages_enabled_json',
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Render enabled languages in JSON.
 */
function YOURMODULE_languages_enabled_json() {
  $out = array();
  foreach (language_list('enabled') as $languages) {
    foreach ($languages as $language) {
      $out[$language->language] = $language->name;
    }
  }
  drupal_json_output($out);
}

The important piece is https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_output/7 which should be used for JavaScript callback functions returning data in JSON format, and it sets the header for the JavaScript output.


Exclude a block from specific parts of the website with the Context module

You can achieve this with the following steps in Context:

Conditions
Type: Path
Configuration:

*

~/user
Reactions
Type: Blocks
Configuration:
What you want.

The trick is inside the configuration part of Conditions
With the * you say it should be on all pages and you can exclude path(s) with the ~


DB API: How to add the result of an embedded query and a retrieved value

This was indeed a database question; a fix for the "unknown column" problem can be found at https://stackoverflow.com/questions/14879342/can-i-do-math-on-the-result-of-an-embedded-query-in-the-parent-query (short answer: the computing of count_task_views needs to be done in a lower-level SELECT).  Back to Drupal: I have my query working as pure SQL handled through db_query; I should probably figure out how to do it via the API, but that's going to wait for awhile...


querying content type via drupal database API

Instead of querying directly against a table you can use Entity field query.

I'll assume the machine name of your content type is called fauna and that there is a field called field_fauna_area. Now lets find all nodes where the field field_fauna_area is "Europe".

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'fauna')
  ->fieldCondition('field_fauna_area', 'value', 'Europe', '=')
$result = $query->execute();
if (isset($result['node'])) {
  $fauna_nids = array_keys($result['node']);
  $fauna_items = entity_load('node', $fauna_nids);
}

In $fauna_nids you will find all node ids and in $fauna_items all the nodes will be loaded.


How can I keep the current language prefix for internal link?

Generally you want to use Drupal core functions as much as possible. Both the l() and url() functions fit perfectly your need. The difference between them is that l() returns an anchor tag, and url() returns a URL without HTML.

As a perk, the l() function allows you to specify the language for the link. Example:

<?php
$options = array('language' => 'jp');
$link = l('About Us', 'about-us', $options);


As per Drupal 7 Template (Theme Hook) Suggestions

block--[region|[module|--delta]].tpl.php
base template: block.tpl.php

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

block--module--delta.tpl.php
block--module.tpl.php
block--region.tpl.php


Update pathauto alias without node_load?

Nope, not without circumventing the pathauto module logic (e.g. altering the alias directly in the DB).

The main function that gets executed in pathauto node updates/inserts, pathauto_create_alias, requires a parameter, $data, passed to it. In a node context, $data is the node object. Without this node object data, pathauto would not be able retrieve data needed for tokens pattens (e.g. [node:title]).


yes/no rating with node reference target

The Rate module allows one to attach multiple rate widgets to a content type.  Create one rate widget for thumbs up/down and second for yes/no.

Drupal Commons Distribution with Commons Q&A includes both a Like and Points system in this manner...

When you add a second widget, choose to attach it to the same content type(s).


How to make the search engine use search api db?

So ok I found out what is my problem.
I miss the other entity necessary to build to use the search api db: the search page using the search page module or views, instead of the system search page.

There is a tutorial here to have a more accurate and complete picture of the process: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages


Sortable, paged table retrieved using EntityFieldQuery

To add conditions for the content of the fields, you use EntityFieldQuery::fieldCondition(), while for enabling the pager you call EntityFieldQuery::pager() passing the number of rows shown in each page.
EntityFieldQuery::fieldOrderBy() could be handy, if you need to order the results by the value of a field.


How to change path using the Content: Link to Content

Download Pathauto module. After installing go to http://YOURSITE/admin/config/search/path/patterns and click add patterns like below.

After adding pattern go to http://YOURSITE/admin/config/search/path/update_bulk and select content and check "Regenerate URL aliases for all paths" and click update. After this, ALL your node path alias should be generated with the title of that nodes.

Then in rewrite result's add this line:

{{ title }}

All your links and tags will be on your node titles.


Show all values of a multi File field sorted by upload time

I found the module Extended File Field does exactly what I want.

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


Views output does not match actual output

I found the answer. Honestly, I was being a derp and a noob. Maybe I just needed time to think about it before posting a question. I will answer it here in case anyone else runs into the same issue.

Make sure you do not have any other views using the same url pattern!

This is a view I have been trying to make work for a while because I needed to reference two different vocabularies that were attached to the content type: location and department. It proved to be slightly more complicated than a typical view because of the two vocabularies and because of Drupal 8 which I am still getting used to. I forgot to delete or disable the previous view I was trying to figure it out in. When I deleted the old view that didn't work (but used the same url pattern), everything was fine.


Filtering on node whose user ID is equal to the current user

You need to add the filter as a "context" (Advanced) where you can supply a default argument. If you context is for a user, like the node author, then you can select stuff like id of logged in user.


How do I make a page available via only a single URL?

That's what the <link rel="canonical"> meta tag is for.

I'm not sure where you've got the information that this meta tag is not good for SEO, but I'm afraid your source is incorrect; the exact opposite is true. This is what Google have to say on the matter:

  Carpe diem on any duplicate content worries: we now support a format that allows you to publicly specify your preferred version of a URL. If your site has identical or vastly similar content that's accessible through multiple URLs, this format provides you with more control over the URL returned in search results. It also helps to make sure that properties such as link popularity are consolidated to your preferred version.

As you can see this is what Google recommend you do to avoid the problem of SEO penalties for duplicate content. This information is several years old and hasn't changed.

To my knowledge the following modules will add a canonical link to your documents:

Global Redirect
Redirect
Meta Tag

There may well be more though. The 2 redirect modules above will probably help you out even further, as they will automatically perform a 301 redirect to the canonical URL when any of the others are visited. Google also encourages the use of such headers in this situation.

Be sure to read the whole Official Google Webmaster blog post linked to above to understand why this method is the correct one, it's pretty important in terms of SEO these days.

Oh, and if I were you I'd be suspicious of anything else your original source for this tells you...they obviously don't know much about SEO!

Further Reference:

About rel="canonical" on Google Webmaster Tools
Canonical URL Tag - The Most Important Advancement in SEO Practices Since Sitemaps on SEOMoz
Google, Yahoo & Microsoft Unite On “Canonical Tag” To Reduce Duplicate Content Clutter on Search Engine Land

And there are literally dozens more...search Google for "SEO canonical".


I have embed view that shows “Links”. How can I only show “Links” that
  have the same terms as the actual “Media”?

I'm not sure you used Entity Views Attach module to attach the View or just placing the View as a block.

Whatever it is, you can do it. But if you have EVA, you will be able to set the current node ID argument easily.

Add a new View as Show: Content, Of Type links. Continue and Edit.
Then, in the Views UI, you will see a filter to show only Link nodes are added. Now, add extra fields you want from the Link nodes.
Set configuration as marked in the image below.
Save the View.
Save the View and enjoy!

if you have EVA module, do not set to inherit node ID to the View (it will give wrong results). Send the term ID as argument(s) if possible.


Attaching a field of a node type in another form

"EntityMalformedException: Missing bundle property on entity of type node."
means that Drupal does not recognize your entity as a valid one. In the entity info listing, there is a mapping from "bundle" to "type", for nodes.

Either your $node doesn't have a ->type, or Drupal no longer has the type registered. The type could have been removed, either from the UI, or by disabling a feature, and possibly in more interesting ways as well.


How to find which block is causing PHP errors?

The most probable cause of the error is a missing or a mismatched parenthesis in the PHP code you are using in your custom blocks or functions. To solve the missing parenthesis error in PHP blocks or in other areas, the code has to be checked from the beginning to search for it. But it's really hard to check all PHP code. One way to avoid errors is to use proper indentation in the code. Once all the parentheses in the code have been set correctly, parse error: syntax error, unexpected $end will be fixed.

What causes this error?

In fact, this error means that PHP has finished analyzing your code, but you forgot to close a symbol somewhere in your page or in those that were included. There could be a number of causes:

This issue could happen when someone used <? instead of <?php somewhere, but your server's php.ini disables short open tags. Check this line in your php.ini - "short_open_tag = On".
You forgot to close a quote, so PHP is continuing to analyze your code until it finds the closing quotation mark.
You forgot to close a bracket, so from the last opening, PHP considers all the code that follows as part of a block that never ends.
You forgot to close a parenthesis, so from the last open parenthesis, PHP considers all the code that follows as part of a specific block (condition, arguments of functions etc) that does not end.
You forgot a comma, so for PHP there is an instruction in your code that has no end.

NOTE: This means that the problem may not be on the line mentioned in the error message, as the missing symbol could be anywhere after that point.


You can try user_multiple_role_edit, something like this might help.

  $user_id = $user->uid;
  // user the role human name
  $role_name = 'My Awesome Role';
  if (user_role_load_by_name($role_name)) {
    // No need to check if the role is already granted
    user_multiple_role_edit(array($user_id), 'add_role', $role->rid);
  }


How do I detect the language using node alias

To get the path alias of specific language try with:

$current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
/** @var \Drupal\Core\Path\AliasManager $aliasManager */
$aliasManager =  \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/node/10', $current_lang);

If you want to get the language code from alias try with:

$aliasArray = \Drupal::service('path.alias_storage')->load(['source' => '/node/' . $nid]);
$lang_code = $aliasArray['langcode'];


Adding a clearfix class to hook_node_view

You can do this in a hook_preprocess_node() function in your theme's template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if (isset($vars['content']['links'])) {
    $vars['content']['links']['#attributes']['class'][] = 'clearfix';
  }
}

Remember to clear Drupal's caches once you've added the function so the system picks it up.


How to add Facebook share/like icon in Blog Entry header?

The AddToAny module lets you do this.  You choose to have the button show in the content, and then use a negative weight to float the button to the top of your content (aka the header section).


How to share a D8 configuration without the UUID limitation?

The best way is to use the features module which is pretty stable and useful. You can even bundle specific configs and install them later on any website as a module (thus not needing to install the module there).


I'm assuming the Block you're using is a Views Block.
You can filter out the current node with the ID Contextual filter (under Advanced Views settings) from the "Content" Category with these settings:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type recipe
Set the option for the case when the argument doesn't validate to something that makes sense to you.
More
Exclude
The last section of settings (More) is where you have the Exclude option that makes the selection of the Contextual filter and reverses it, so it finds the ID of the current node, and excludes it from the list.
Test it by entering a node ID into the Preview field in Views, the node with the entered ID should be removed from the Views results.
You also need to select the Contextual option in the Block configuration or it won't work when you place the Block on pages, Views Preview can't test the Contextual works in actual placement.


Field collection - Delete "Remove button" on line

Write following code in your theme template.php file. It will added css classes to body of a specfic page.

    <?php

    function hook_preprocess_html(&$variables) {
      global $user;
      $args = arg();

        if( isset($args[0]) && ($args[0] ==  'your-page-url-first-argument')){ // Check ur page url parameters
        $account = user_load($user->uid);
        if(in_array("test", $account->roles)){
          $variables['classes_array'][] = 'test_user';
        }
      }?>

CSS:

.test_user [remove_button_class/id] {

  display:none

}


You should be able to manually delete the demo forms, blocks, and nodes and then uninstall the demo module.

Please create a ticket in the Webform issue queue.


Solution 1

You could try making the path for each display some kind of hierarchy and using Menu tab as the menu Page settings in order to display both views next to each other in the primary tabs of a page.

Example paths

mypath/view1 // Display 1
mypath/view2 // Display 2

Solution 2

Add a header or footer to the view in Basic settings and include the link to the other view.

More info on Drupal Menu system.


Display count of nodes from the parent terms of a taxonomy where dummy nodes are based on the child terms of the parent terms of taxonomy

Try creating a Taxonomy View with the following settings.

field: taxonomy term/id
filter: taxonomy vocabulary; states vocabulary
contextual filter: taxonomy term parent; display summary, show link w/ count, set a base url for link

I have done something similar with a contextual filter of Taxonomy Term/ID and it works fine.  Should work with Term Parent.  you might have to add a relationship to content as well, not too sure but that should get you started.  Good luck!


How can I set a placeholder variable in page.tpl.php from a page callback?

There are a few possibilities, not sure which one would work best for you. There isn't a really easy way to do that.

I would say the "drupal way" of doing that would be to expose your additional content as a block. You can configure that to only show up on specific pages and place it above the main content.

There is also hook_page_alter(), but that requires the same conditonal checks as a template_preprocess.

You could also return a render array in your page callback and then display it separately in your page.tpl.php, something like render($page['content']['system_main']['part_a']) and so on. You could do that only in a template suggestion for a specific page, like page--yourpath.tpl.php.

To avoid messing with page.tpl.php too much, there is also the possibility of overriding the so called 'delivery_callback' (see menu_execute_active_handler() in your menu router item for that page. The default delivery callback is drupal_deliver_html_page().


How do I print out values from a select field with multiple values

I ended up just making a custom loop like this and it works fine (Also added a custom if statement to change html output based on single or multiple categories in the field.

<?php
    $categoryCount = count($field_category);
    if ($categoryCount != 1):
?>

Categories:
<?php else: ?>

Category:
<?php
    endif;
    $i = 0;
    while ($i < $categoryCount) {
        if ($i != 0) {
            $html .= ', ';
        }
        $html .= $field_category[$i]['value'];
        $i++;
    }
    echo $html;
?>


flexslider is failing on version recognition and perms

Basically this is a duplicate issue, workaround (cannot be called solution) is to downgrade from v.2.3.0 to 2.2.2.
I already posted in the module's issue queue.
The other issues were caused by ownership and perms issues, while I was testing both library versions, disregard that part.


Same Image in Multiple product with feeds

If the images in the same place where the field is waiting for it the images will not multiple.


I think this issue: https://www.drupal.org/node/2295227 addresses your question.

Though haven't tried it myself, but the current dev-version of Zen should contain the 'fix' (i.e., using FireCompass instead of FireSass) to debug SASS-code in an easy way.


How to show a place holder block if a view is empty

Views has a feature that already accommodates this; under the Advanced section there is a NO RESULTS BEHAVIOR option that lets you add different fields on the condition there are no results in the view.


I have 4 facets set to filter results by taxonomy terms but only one of the four filters work

Did you check the corresponding blocks for each facet are set in sidebar region (or where ever you want them to be?).


It means what it says: There is no file included in the current page request that contains the definition for a function called modalframe_close_dialog().

A quick Google search shows that this function is part of the ModalFrame API module, for which there is only a Drupal 6 release (not Drupal 7). I guess you've copied this code from a Drupal 6 site without changing it?

The comments on the ModalFrame API module page say:

  It seems this feature is being included in Drupal core itself. So, probably there will be no stable release of this module for Drupal 7 because it will be already there

My best guess is that the Drupal 7 equivalent of this function is overlay_close_dialog(), but I can't comment as to whether that will work as in a drop-in replacement for you current code.

It might be worth reading the Initial D7UX admin overlay thread, it's basically the discussion about moving ModalFrame API into core.


Best way to deal with node data that should only be displayed in views

A couple strategies here...

One is the obvious one you mention: Don't publish the 'Slide' content type, so it never appears on the 'live' site.

Another is that you don't make special 'slideshow' content types. You just add fields to your normal content types that will be displayed in a slideshow display mode. Then you hide them for other display uses like Default and Teaser.

Drupal's flexibility with this type of scenario is one of its major strengths. But it also means that site editors have to remember which field does what, or which type of nodes not to publish.


Clientside-validation for form-api for field either digits or empty

The way I did this was to add a custom validation handler.  I know I asked for a solution without one, but it turned out to be a fairly simple thing to do.  See the "#element_validate' array element below.

$form['hours'] = array(
  '#type' => 'textfield',
  '#title' => t('Hours worked per week'),
  '#size' => 3,
  '#maxlength' => 3,
  '#element_validate' => array('mymodule_validate_integer'),
  '#default_value' => '',
  '#rules' => array(),
  '#filters' => array('numeric', 'trim')
);

function mymodule_validate_integer($element, &$form_state, $form) {
  if (!empty($element['#value']) && (!is_numeric(parse_size($element['#value'])) || $element['#value'] < 0)) {
    form_error($element, t('"!name" must be a positive number.', array('!name' => t($element['#title']))));
   }
 }

function mymodule_clientside_validation_rule_alter(&$js_rules, $element, $context) {
switch($context['type']) {
case 'element_validate':
  if (in_array('mymodule_validate_integer', $context['functions'])) {
    _clientside_validation_set_minmax(
        $element['#name'],
        $element['#title'],
        0,
        99999,
        $js_rules,
        t('"!name" must be a positive number.', array('!name' => t($element['#title'])))
    );
  }
  break;
  }
}

I hope this helps someone in the future.


If you want a form in the main menu of every page, you don't need a route for it.  You can just create a block, either for just the search form or for the main menu, and load the form in as a variable into that block.

namespace Drupal\module_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header Search Block Form' block.
 *
 * @Block(
 *  id = "header_search_block",
 *  admin_label = @Translation("Header Search Form Block"),
 * )
 */
class HeaderSearchFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
    return [
      $form,
      '#cache' => [
        'contexts' => ['url.path', 'url.query_args']
      ],
    ];
  }
}

What you're returning is a render array, so you might want caching settings on there, otherwise, you can just return the form itself.  If you want to prefill the search term on every page, you'd want a cache context that includes page arguments, like above.  If you want the fields empty, such as if your form only contains a textfield for searching, then you don't need a separate cached version on every page and you can just return the form in your build() function:

  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
  }

Another option, you can preprocess your main menu block to add the form as a variable as well.

function mymodule_preprocess_block__system_menu_block__header_menu(&$variables) {
  $variables['search_form'] = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
}

then in your block template (such as block--system-menu-block--header-menu.html.twig)

add

{{ search_form }}

As far as redirecting to search, my preferred method is with javascript, as you don't need to hit the backend.  You can just redirect to your search page from the javascript.

Just attach the javascript library to your form

$form['#attached']['library'][] = 'mymodule/mymodule.header_search';

(etc.  there are many tutorials on this)

and then in the javascript do something like:

 $('#' + formID).submit(function(e) {
   e.preventDefault();
   var filters = self.gatherFilters();
   var url = searchURL + '?' + $.param(filters);
   window.location.href = url;
 });

If for some reason, you need backend processing, your form can have a submitForm method that then sets the redirect on the $form_state object:

$query = ['keyword' => $search_term];
$form_state->setRedirect($route_name, [], ['query' => $query]);

with $query being an array of query arguments.

For your search results page, I would recommend you create a different search form.  As a small textfield in the header is different than filters on a form.

Without custom coding, you could use a Drupal view page, and set a contextual filter set to keyword, or you could create a controller in your custom module that returns a different search form with filters as well as the results from Elastisearch.


How can I display the results of webform submission in a block and place it on front page?

There are 2 possible approaches to consider, as further explained below ...
Approach 1: using the Charts modules
This is like rolling your own cookies. You create your chart (as you already seem to have done in the image above), using either the "Charts API" (= write some PHP code to populate the charts Array, whereas you put that PHP code in the content of your block) or using the "Views integration of the Charts module" (where you format the Views result as a block).
Disclosure: I'm a (co-)maintainer of the Charts module,
I hope this does not violate the site's policy on self-promotion.
Approach 2: using the typical Webform related charting modules
If you want to create charts from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

Webform Charts (used in about 350 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 575 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).
Note:
In both approaches you need to decide about which "Charting Library" (= engine) you want to use, either Google charts (easiest setup) or Highcharts (which might require a license also). At any time it should be pretty easy to swap between either library also (that is a key feature of the Charts module also ...).


How to fix the variable names in a simplenews subscription confirmation mail?

I am guessing you upgraded from D6. The tokens you are using are D6 tokens.

Go to /admin/config/services/simplenews/settings/subscription and change the tokens. For instance, the default subject for D7 is :

Confirmation for [simplenews-category:name] from [site:name]

Note the new (D7) token format. You can find he new tokens by expanding 'Replacement patterns'.


Yes, for procedural code in hooks you have to use the static service container wrapper \Drupal. Either to get a service or to use one of the predefined static functions. See for example:

shortcut.install

/**
 * Implements hook_install().
 */
function shortcut_install() {
  // Theme settings are not configuration entities and cannot depend on modules
  // so to set a module-specific setting, we need to set it with logic.
  if (\Drupal::service('theme_handler')->themeExists('seven')) {
    \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
  }
}


It seems like you want to retrieve the value of a single field from a field collection. And that the field collection you want to retrieve a field from is a field of a 'cv' profile2.

The returned value of profile2_load_by_user($account, "cv"); is a Profile entity object. When $fieldset is the (machine) name of a field collection field, then you can retrieve its value using $items = field_get_items('profile2', $profile, $fieldset) (see field_get_items()). This will return an array of field collection values (or FALSE if there is no value for the field). The values are arrays containing a value entry which is the entity id of a field collection entity. You can load the field collection entity for an ID using field_collection_field_get_entity(). Finally, using $key as field name, you can retrieve the values of one of this field collection entity's fields using field_get_items() again.

$items = field_get_items('profile2', $profile, $fieldset);
if ($items) {
  $item = reset($items);
  if (!empty($item['value'])) {
    $field_collection = field_collection_field_get_entity($item);
    if ($field_collection) {
      $items = field_get_items('field_collection', $field_collection, $key);
      if ($items) {
        $item = reset($items);
        return !empty($item['value']) ? $item['value'] : 0;
      }
    }
  }
}
return 0;


no acces to /admin urls after site migration to local wamp server

Doing a

   drush pm-update

solved the problem.

Any fine explanation why?


How do I remove the progress bar in Webform module?

long and short of it  just use css to hide it.


Sort grouping field associated with taxonomy term by weight on drupal 8 views

I had to manually move the terms to a new order for the weights to change from a default 0 (you can click "show row weights" on the taxonomy page to see that they have changed after dragging out of order and then back into order; you only need to do this with one term to apply to all terms within a given level).


How do I replace the SQL query of a view?

Well, nothing is stoping you from building your own SelectQuery object and replacing the existing one. Overriding the query plugin is also an option. In this case it would be best to know WHY you're trying to replace the whole query. It makes very little sense to me.

Also, you're using alpha1? Why? That code is four and a half months old. Before attempting anything else, please update to -dev.


Create Relation between two vocabulary terms in views expose filter

I am posting answer to this question, as it might help somebody.
I havent got any suitable module which can create relation between two taxonomy vocabularies as i want, But i have modified my taxonomy a little bit to do this from a module.

I have merged my 2 vocabularies into single . I have placed country as parent term and all the cities as sub-term. So my structure is like this :

India

Delhi
Rajashtan
Chandigarh
Gujrat

USA

Alabama
Alaska
Georgia
Illinois

Then I have used a simple module called "Simple Hierarchical Select" https://drupal.org/project/shs or you can also use Hierarchical Select" https://drupal.org/project/hierarchical_select
But hierarchical select has more functions but if you have taxonomy related task only then you can use only SHS as in my case.

Now go to the content type -> manage fields -> select term reference-> simple hierarchical select .

Now go to your views => select the "your-field-name" (hierarchical select ) from filters
and force it to some depth.

Then it will show first country name and then child term which are city names.


Creating a rule for changing user role when related profile is filed

This is doable with Rules:

Create rule that reacts on two events: 'After updating an existing profile' and 'After saving a new profile' - both are necessary because at some point, users might not have the profile created yet.
Add conditions to see if all fields are filled in (use "Data comparison", "Data value is empty" or "Text comparison" conditions and their negations based on what type of fields you have)
If all the conditions are met, give the role to the user with action "Add user role".

Btw. you do not have to worry if the user already has this role, it will not cause any unwanted behaviour if it is assigned several times.


hide if on front page and on taxonomy pages

Try something like this:

<?php
   function hook_preprocess_page(&$variables) {
       if (drupal_is_front_page() || drupal_is_taxonomy()) {
           $variables['title'] = NULL;
       }
   }

Change hook to the name of your theme.  Based on your example, it looks like you're hacking core which isn't good. Create a subtheme and implement your custom themeing there.


You could use the FileField Sources module.  To browse the server it looks like you need to use this with IMCE.  From the FileField Sources project page:

  The FileField Sources module expands on this ability by allowing you
  to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Select existing files through the IMCE file browser


How to iterate through an object returned by fetchAll?

<?php
// Retrieve all records into an indexed array of stdClass objects.
$info = $result->fetchAll();

// Retrieve all records into an associative array
// keyed by the field in the result specified.
$info = $result->fetchAllAssoc($field)

To iterate just use:

foreach($info as $key => $object) {
  print $object->property . "<br>";
}

References:

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


editing how a field is output (changing commas to )

Just for security purposes I would wrap $commaString in check_plain() to get rid of any naughty characters or code that could come through.

And as for doing extremely simple things with PHP, you shouldn't have to worry about doing it the "Drupal way" too often. There are such things as PHP wrapper functions which are useful for keeping your code safe from PHP version quirks.

Also just to add, if the question were: "I want to format this CSV as a bulleted list." Then I would've suggested using a theme() function like the following:

print theme('item_list', array('items' => explode(",", check_plain($commaString))));

Because Drupal's theme layer is your friend and will help you to almost never write markup in your code. And I'm not aware of a theme function that converts a CSV string into a newline separated one. Item list is a good example of a theme function, so is a table theme.


Do you know that Webform now supports conditional form items from the now merged webform conditionals module?

You can then manage this form like any drupal webform and show/hide child pieces of the form based on selection rules. If your form is huge good luck the conditional page/logic settings can get huuuge and cumbersome.

If you want to this in php code yourself I recommend this tutorial using the Ctools based Multistep Form. I've made multi-step forms using native drupal node forms -- just the stepping logic is very ugly. This is clear and precise using a multi-step ctools form.

You could even show/hide stuff I believe on 1 page of the form usig FAPI #states API. A tutorial explaining #states provided by Shane Graham is on this blog post. Also review this for more complicated XOR type logic in forms here on d.stackexchange:
Multiple Values to Trigger #states


just make sure when you move your roles that you spell them the same!
then you can use the traditional

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}

or the more flamboyant

function user_has_role($roles) {
    //checks if user has role/roles
    return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};

if (user_has_role(array('moderator', 'administrator'))) {
  // $user is admin or moderator
}

see here for more answers to the simple question Check if a user has a role


I'd suggest you simply integrate with mollom to expose your form.

You just need to implement two simple hooks and you can also configure if it should be CAPTCHA only or analyse some fields.

Hook documentation:

hook_form_mollom_list()
hook_form_mollom_info()

As an example implementation, you can have a look at my patch against Privatemsg: http://drupal.org/node/720038#comment-3501758 or have a look at these: http://drupalcontrib.org/api/search/7/_mollom_form_.


Please check:

your cookie_domain value in your settings file

Normally it should work when it's empty, however if you're using across multiple domains or protocols (e.g. form is HTTP, but you're submitting to HTTPS), you should set it to its full domain name, so Drupal automatically generates a unique session cookie name for each site. E.g.

$cookie_domain = '.www.example.com';

or assign it dynamically like (not recommended):

$cookie_domain = @$_SERVER["SERVER_NAME"];

watchdog logs, e.g. drush ws --tail,
if you're using LoginToboggan or similar, check whether you should use username or e-mail to login,
whether cookies are created fine in DevTools console,
if you're using Varnish, check whether cookies are deleted,
try login to the site using one time login link, e.g. via drush uli command and verify that your account works (it's not blocked or something),
try in another browser or in incognito mode,
disable any 3rd party authentication modules (ldap, openam, etc) which may override the default logic,
debug your code using XDebug.


Be sure too understand how the menu system works. The menu structure is only build once every time the cache is cleared. It is at that moment that hook_menu_alter() will be called. The results are then stored in the database. So simply implementing this hook is not sufficient to create dynamic menu titles. You can use it though to add a title callback that will be called every time a link to the menu item will be rendered. For details have a look at http://drupal.org/node/140311 (D6, but basic logic still applies to D7).

From the top of my head:

function mymodule_menu_alter(&$items) {
    $items['toggle-review-process']['title callback'] = 'mymodule_title_callback';
    $items['toggle-review-process']['title arguments'] = array(1, 'some string');
}

function mymodule_title_callback($arg1, $arg2) {
    $title = 'create the title';
    return $title;
}


Why is my Pantheon git clone not loading correctly?

The issue you're exhibiting is most likely a result of the database reflecting a temp directory (on the Pantheon server) that does not exist or is not writable on your local LAMP environment.

To reset the temp directory for your local development instance, you can:

use drush to set the temp directory (typically /tmp)
navigate to admin/config/media/file-system

If after setting the temp directory and clearing caches, you still exhibit similar behavior, you may want to double check the file owner/group permissions for the public files directory.

See https://www.drupal.org/node/244924 for a how to identify and set permissions, and refer to http://www.drupalden.co.uk/file-folder-permission-settings-drupal-7 which provides a good summary (note- permissions recommended for D7 also apply to D8)


How to rearrange the user registration form fields

Fields can be rearrange by changing '#weight' attribute of field in hook_form_alter(). You will have to create a custom module and have to alter the form and its element. The associative array would be something like this

$form['account']['name']['#weight'] = 7;


Is it possible to divide two columns using the the query builder?

For complex expressions you can use the addExpression() method, e.g.

$query->addExpression('A.valsA / B.valsB', 'alias');


Drupal commerce re-indexing causes exception

It sounds like a field got messed up somewhere. Try running Commerce Repair and seeing if that fixes the problem.


Creating the files is not enough: The module needs also to be installed. /admin/modules gives a list of modules and allows to install them.

After a module is installed, all its hooks are invoked from Drupal.

As side note, YAML files are required to use the correct indentation. The content of the  hello_world.routing.yml file should be the following one.

hello_world.hello:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
    _title: 'Our first route'
  requirements:
    _permission: 'access content'

See the example give in Routing API, Registering simple routes.


You can at least start debugging the issue using the devel module: it can tell you if the field collection entity is loaded (so, a render problem) or not.
Also it can gives you the id of the entity for further debugging.


How can I add more than one pointer to a map?

You can use Get Location module for this functionality. It will create multiple location markers on a single map, with a popup bubble info and it comes up with inbuilt views. You just need to enable a block after installing it. Some more details about this module (from its project page):

... will provide Google maps API version 3 enabled maps on which to display markers of locations found in location-enabled content-types.
These can be displayed per node, eg "/getlocations/node/xxx" will display all the locations associated with that node. They can also be displayed per content-type, so if your content-type has a machine name 'venue' you can show them all with "/getlocations/type/venue" and it also supports paths like "/getlocations/user/xxx" and "/getlocations/users" for location-enabled users. These links have their own access permissions so control can be exercised on a per role basis.

If looking for custom thing, specify your complete requirement.


Views exposed filter between label AND replace with -

You have to use a hook_form_alter() to edit the form programmatically. This will go in a custom module.

Here's some boilerplate code:

function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id !== 'views_exposed_form') {
    return;
  }

  if ($form_state['view']->name !== '<your_view_name>') {
    return;
  }

  $form['field_<your_field_name>']['max']['#title'] = '-';
}

Replace the view and field names with your particular ones. Hope it works for you.


Feeds Xpath Parser module can help you map custom fields to your xml values.  I've used this myself.  There is also Querypath Parser which may do the same thing (I've never tried this one).


Native Android app with Drupal backend and Login

You didn't mention your version of Drupal, and I cannot speak for D8. But D7 has the Services module, and this provides all the functionality you will need. We use the Oauth2 module (that ties in with Services) to provide the authentication mechanism for the apps we build. With this, the user will first log in with their credentials, from which they will receive an authentication token. This token is then used for all further communication between the app and the server.

The Services module is highly customizable, and can be used to code your own resoures that can be called through the API from the app. You can choose the output format, of which JSON is one option.

Shawn answered your questions regarding protection of the user's credentials. This is the same as with a browser - use HTTPS (SSL certificate) and the credentials will be protected. If you don't use HTTPS, the credentials will be there for anyone who looks.


The array returned from the implementations of hook_block_info() doesn't contain a property equivalent to the access callback for the menus. If you have a module that implements a block, then you can implement hook_block_view() using code that checks if the user has a specific permission. The following code is used from a Drupal module; as you see the block is "rendered" only when the user has the "access content" permission.

case 'recent':
  if (user_access('access content')) {
    $block['subject'] = t('Recent content');
    if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
      $block['content'] = array(
        '#theme' => 'node_recent_block',
        '#nodes' => $nodes,
      );
    }
    else {
      $block['content'] = t('No content available.');
    }
  }
  break;

You can use similar code, but checking a different permission, even a custom one your module uses for checking if the user can see the block.


Programmatically upload a file to a custom file field

The following code works for me.

$image_url = 'http://test.com/misc/druplicon.png';
$file_info = system_retrieve_file($image_url, 'public://documents/', TRUE);

if ($file_info->fid) {
  $node->field_custom_file['und'][0]['fid'] = $file_info->fid;
}

$node_ready = node_submit($node);
node_save($node_ready);


function mytheme_links__system_main_menu($variables) {
$site_frontpage = variable_get('site_frontpage', 'node');
  $html = "\n";
  foreach ($variables['links'] as $link) {
      if($link['href'] == '<front>') {
        $html .= "" .$link['title'] ."";
      }
      else {
        $html .= "" .$link['title'] ."";
      }
  }
  $html .= "\n";

  return $html;
}

The code can be used in template.php to override the output of the . However, the only variable it seems to accept is $tree, which prints out all the contents of a  and so is not very helpful.


How to create a user object of a custom form and add a user in drupal 7?

You can save the details of the user in an array and can use "user_save" function to create new user.
You can get the values from the $form_state elements

    $details = array(
      'name' => '',
      'pass' => user_password(),
      'mail' => '',
      'init' => '',
      'status' => 1,
      'access' => REQUEST_TIME,
      'field_fname' => '',
      'field_lname' => '',
    );
    user_save(drupal_anonymous_user(), $details );

drupal_anonymous_user() will generate the default anonymous $user object.


Filter to display articles from the last edition date only

What if you filter by Edition Date, order it by descending, and display only first value?

It should give you the last available edition, if I'm not mistaken.


It sounds like one of two things might be happening:

You're overwriting the default database (which needs to be the Drupal database) with your custom database.
You're calling API functions that interact with the Drupal database before switching back from your external db.

In either case these are abridged versions of the code from the docs page you linked to with a few comments that will hopefully help it to make more sense:

Drupal 6:

// Define the default database, this MUST be the database containing the Drupal installation.
$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';

// Define your external database separately.
$db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';

module file:

// Switch to the external DB
db_set_active('mydb');

// Perform a query. Note that you should not call any Drupal API functions that will
// interact with the database until you've switched back. If you need your data to
// interact with the API, save it in a variable, switch back to the Drupal DB, and
// THEN make the API call
db_query('SELECT * FROM table_in_anotherdb');

// Switch back
db_set_active('default');

Drupal 7:

settings.php:

$databases = array (
  'default' => array (
    'default' => array ( // Again this must be your Drupal database.
      'database' => 'drupal',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'mydb' => array (
    'default' => array (
      'database' => 'db1',
      'username' => 'username2',
      'password' => 'password2',
      'host' => 'db.example.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

module file:

// Switch to the external DB
db_set_active('mydb');

// Get some data. The same rules about accessing the API functions apply here.
$results = db_query($sql);

// Switch back to the default db.
db_set_active('default');


Redirect anonymous user to login in custom module

Have you tried drupal_goto('user/login', array("query" => array("destination" => $dest['destination'])))?


How to pass argument in ctools_modal_form_wrapper?

You must use $form_state to do it.

$form_state['build_info']['args'] = array($node);

function generate_tpls_callback($cid, $ajax) {
    if ($ajax) {
        ctools_include('ajax');
        ctools_include('modal');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Display box to change title'),
            'cid' => $cid,
        );
        $form_state['build_info']['args'] = array($myvar);  //Check form below
        $output = ctools_modal_form_wrapper('myform', $form_state);
        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }
        print ajax_render($output);
        drupal_exit();
    } else {
    }

}

function myform($form, &$form_state, $myvar) {
...
}


How render view with programmatically passed parameters of contextual filter

Use hook_views_pre_view

function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for view_name.
  $paragraph_id = 22;
  if ($view->id() == 'view_name') {
    $args = [$paragraph_id]; // args must be an array.
  }
}


Credit to @Felix Eve.... Adding more details so that it will be helpful for others..

Edit Size & Price fields and check Exclude Checkbox
Create Global: Custom Text field below above fields so that you can use replacement patterns
Label it as Description
Use Replacement patterns in "Global : Custom Text" something like below .. Use correct tokens from replacement patterns

Size : [field:size]
Price: [field:price]