Getting data out of Profile2 with field_get_items()

As @Clive mentioned profile2_load_by_user() takes user account object not uid, but you also need type name as second argument to retrieve field_lastname using field_get_items function.

I recommend you to use this function profile2_by_uid_load instead of profile2_load_by_user

So your code should look like the following:

$profiledata = profile2_by_uid_load($variables['comment']->uid, 'profile_type_name');

$lastname = '';

if($profiledata) {

  $lastname  = field_get_items('profile2', $profiledata, 'field_lastname');
}


Replacing core forum pages with views throws a warning

I ended up just using a different URL and fixing links to point to that one. Not a real fix to my problem, but whatever.


How to get delta of a file from within hook_tokens

It's the relationship between a file entity and another entity via a reference field that has a delta, not the file entity itself. A single file could, theoretically, be referenced by many entities, via multiple separate fields, or even twice in the same entity - meaning it doesn't conceptually have a single delta related to it.

What you'll need is to run an EntityQuery with sufficient contextual conditions to narrow down to one result, load up that parent entity, and loop through the field values until you find your file, giving you the delta.

If your use case enforces that a file can only be referenced by a single entity, it'll be a lot easier to implement. But it would probably be safer to include at least some kind of limiting.


Reference a block plugin, or Form, from a Paragraph?

I haven't tried it, but the Dynamic Entity Reference module looks good. The 8.x-2.x branch, although currently in alpha, sounds like it has the functionality you're looking for:

  This version allows all content entities as referenceable entities. This version also allows all config entities as referenceable entities but it is only configurable programmatically. The content and config entities can be referenced in the same field as well.

It'll mean a bit of coding to get the config entity working, but a lot less code than writing the whole thing from scratch.


Form element replaced via Ajax callback doesn't seem to be submitting or the values are not appearing in buildForm

The ajax callback returns the part of $form which is inside of the ajax wrapper:

  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form['color_wrapper'];
  }

The wrapper has to be a div container.

Complete code example  https://cgit.drupalcode.org/examples/tree/form_api_example/src/Form/AjaxColorForm.php


Web Widgets now has a Drupal 7 release, so it might be worth trying it out.


This is an example for D8:

$node = Node::load('1');
$display_settings = array(
  'label' => 'inline',
);
$build = $node->body->view($display_settings);


How to add .current class into menu link when page is being viewed

If you create a new menu and make it a block then it will set a class called "active" when you are on the current page. You will also get a class called "active-trail" for each parent item. If you want to create something more custom then you can check and see if the url matches the link you are building.

You can see here how the menu is being built to get some ideas:

https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_output/7

If you want to do something custom then you will need to compare $_GET['q'] to the link that you are building in order to set an active class.

I am pretty sure you can also use theme_item list and the active class will be set:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_item_list/7


How to make a node appear across *all* Taxonomy terms?

Assuming I understand you correctly... why don't you create a custom checkbox field "Worldwide?" for the node type? Then in any views you could insert an OR checking if the node has it set. Still, you would be able to group the results by another field, such as geographical region name.

This is where you get the dialog in Views3


Why do sub-menu items not appear on front page, but work on other pages?

I suspect your problem could be resolved by ticking the "Show as expanded" checkbox on that menu item.

This worked for me. Thanks, Adam!


How do I structure node data that records time and quantity?

These are just my opinion...

A custom entity would probably be overkill, unless you plan to extend the functionality at some point. If your end game is just to store those key/values pairs, the extra code and DB complexity doesn't feel worth it.
To extend on that, Field Collection already implements that entity for you, plus all of the entity/field/views niceness. Add the Field Collection Table module as a table formatter, and you'll be probably be ready to go in about 10 minutes.
A custom field (and formatter for the table) would be reasonably straight forward to implement, but is tricky to extend if you decide, for example, you need another data column. It does have less DB overhead than the Field Collection method (as there isn't another entity involved), though, in case performance is a major issue.

If you're looking for simple, I'd say Field Collection is the way to go.


Drupal 7 commons AJAX bulk operations active queue error

For me, this error was due to the PHP version being used (5.3). Using PHP 5.4+ resolved it. You may also want to look at https://www.drupal.org/node/1871702 if the PHP version isn't your issue.


Accessing custom block fields from a template file

This was the final solution.

{% block content %}

{% endblock %}


problem merging views row-data into Drupal.settings

If the string literal is giving you what you want, I'd try this:

drupal_add_js(array('o4mmgal' => array($view->name => array('merged_rowdata' => $rowdata))), 'setting');


Why does my selection gets only the last row?

Don't use fetchAllAssoc(). Just $result = $query->execute() and then loop over that


Is there a way to pass a PHP value to JavaScript?

You're looking for drupal_add_js(). You can use it to pass data from PHP to JavaScript. Something like the following should suffice:

/**
 * Implementation of hook_init().
 */
function modulename_init() {
  if (!user_is_logged_in()) {
    drupal_add_js(array(
      'modulename' => array(
        'path' => $logged_out_path
      )
    ), 'setting');
  }
}

Note that I am calling this from within an implementation of hook_init(), but really you can do this anywhere, be it from a module or a theme. Also note that I have provided a sufficient namespace for the value to live (i.e. within 'modulename' => 'path'). This will make it clear from JavaScript's point of view exactly who owns the variable (i.e. which module it came from), but more importantly will help to prevent collisions with settings in other modules.

From JavaScript you can access the value of $logged_out_path like this:

var path = Drupal.settings.modulename.path;


How do I change and translate the "completion message" in Commerce checkouts?

Template approach (recommended)

As revealed in the comment by @bojanz, you can just make a copy of the template file in your theme:

commerce/modules/checkout/templates/commerce-checkout-completion-message.html.twig

Custom checkout pane approach

There is documentation for this.

You can create your own custom checkout pane, which can be done with drupal console or by hand.

/MYMODULE/src/Plugin/Commerce/CheckoutPane

<?php

namespace Drupal\my_checkout_pane\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @CommerceCheckoutPane(
 *  id = "custom_completion_message",
 *  label = @Translation("Custom completion message"),
 *  admin_label = @Translation("Custom completion message"),
 * )
 */
class CustomCompletionMessage extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['message'] = [
      '#markup' => $this->t('This is a custom completion message.'),
    ];
    return $pane_form;
  }

}


Problem with adding Views - they cannot be saved

Have you tried running update.php? Or try clearing the Drupal cache which you can do quickly with drush using drush cc all.

I find this is always a good place to start.


Now this has been moved to Migrate Manifest module. You can enable this module and use drush migrate-manifest command.


Pathologic input filter will do that for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.

Download and install the module, and then enable it for the text format you're using. It also supports the feature to bulk update your existing paths.


I cannot say what exactly is the problem (it is a bug for sure), but here's how you solve it: Go to the "Manage Display" tab for the content types for which the teaser display setting is not imported.
On your DEV instance go to the teaser display and save it without changing anything (or changing something if you want to).
Now export the config and push it via Git.
Re-import on Stage and it should import cleanly now.


Front page

But this doesn't respect the base folder. E.g. if your Drupal installation path looks like http://example.com/drupal_site/, this won't help you, because link will lead to http://example.com/.


You can use the  i18n (Internationalization) module (requires the Variable module).

You can follow this tutorial.


This is essentially impossible to answer.  You have one part of your question, wrong

Your first method uses a single node_load_multiple() with multiple node_save
Your second answer uses multiple node_load() with multiple Entity API calls

My gut tells me the first will be quicker, as a single node_load_multiple() is typically more performant than multiple node_load() calls, given the same set of nodes.  You also aren't creating the the metadata wrapper objects.

However, you need to do the benchmarking on your system.  There may be a difference, but it may be small enough to not make a real imapact.  Some things that make cross-system benchmarks unreliable

entitycache can have a tremendous impact on a system, especially if you use a non-SQL backend for it
the number of fields on your node can effect how long the wrapper creation process takes, and also how long the node_save() takes
APC and/or OpCache usage and configuration
PHP version
MySQL configuration (or whatever database backend you are using), including some of the Drupal-specific tricks that can improve performance
The number of hook_node_update() instances that fire for each save


I have found the issue, "Make the starting level follow the active menu item." needs to be unticked.


Filter view based on several user profile fields (D7)

You should try chain relationship, this discussed here, similar problem to yours.
Here the answer on similar question on drupal.stackexchange.


Running ajax callbacks on custom composite field

You can not modify the $form in the ajax callback. The option for the element out_serial should be set inside form build not in ajax callback. Try with following approach:

// Inside your form build or alter function.
$form['elements']['test']['#element'] = array(
  'out_part' => array(
    '#type' => 'select',
    '#id' => 'out_part',
    '#options' => array(
      '80002192'=>'80002192',
      '80002191'=>'80002191'
    ),
    '#ajax' => array(
      'event' => 'change',
      'wrapper' => 'serialNumber_wrapper',
      'callback'=> 'populateOutSerialNumbers',
      'method'=> 'replace'
      )
    ),
  'out_serial' => array(
    '#type' => 'select',
    '#id' => 'out_serial',
    '#validated' => TRUE,
    '#attributes' => [
        'id' => ['serialNumber_wrapper'],
      ],
    )
);

// Set value here as when you return the element in ajax callback.
// the form will come here again for rebuild with $form_state having filled values.
if (!empty($form_state->getValue('test'))) {
  $partNumber = $form_state->getValue('test')[1]['out_part'];
  $partNumber = isset($partNumber) ? $partNumber : 'Onboard';

  // Update the $result with dynamic database query results with respect to selected out_part
  Drupal\Core\Database\Database::setActiveConnection('***');
  $db = Drupal\Core\Database\Database::getConnection();
  $query = $db->query("select distinct T1.serialnumber from assets T1 where T1.dbid <> 0 and (T1.manufacturerpartno = :partNumber)", [':partNumber' => $partNumber]);
  $result = $query->fetchAllKeyed(0,0);

  $form['elements']['test']['#element']['out_serial']['#options'] = $result;

  db_set_active();
}
// End of your build or form alter function.

/**
 * Ajax callback of out_part element.
 */
function populateOutSerialNumbers($form, $form_state){
  return $form['elements']['test']['#element']['out_serial'];
}


Where should I search uncompressed .css?

when I go to sites/default/files/css/ I find only set of gzipped .css files

You need to change your configuration.

Go to Configuration > Performance

and unchecked the aggregate and compress CSS files box, Save Configuration.

You then need to go to /sites/all/themes/YOURTHEMENAME/css folder and hopefully you should see .css files now. (Assuming you are using Drupal 7 and NOT using Drupal 8)

(might need to re-start FileZilla to seem them, assuming you are using FileZilla that is.)


How to access List type from an option set in conditions of the Rules module?

These are the Rules Conditions you should use:

Entity has field "field_weight_options", which is the machine name of the field you want to check.
List contains item (for your field_weight_options, which is a list since it is a multi value field) and with the value (such as "2lb") you want to check for.

What is crucial in the context of this question, are these 2 Rules Conditions. Especially because of your "field_weight_options is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).

PS: This answer applies to D7.


How to edit and theme Comments & Comments form?

You can copy the file called comment.tpl.php from the folder where base AT theme is located (something like adaptivetheme\at_core\templates) and paste it into sites\all\themes\YOUR_AT_SUBTHEME\templates.

Assuming recipes is the machine name of your content type, you can also name it comment--recipes.tpl.php if you want to theme specifically comments for recipes.

Then with the help of comment.tpl.php API (you can also find a lot of information in the php file itself), you can edit the way your comments will be displayed.

I.e instead of

print render($content);

You can display specific fields :

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

or hide specific fields

hide($content['author']);
print render($content);

To alter the form itself, you need to use hook_form_alter() in a custom module.

/**
 * Implements hook_form_alter().
 */
function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //get the form id
  drupal_set_message("Form ID is : " . $form_id);
  $print = '
' . print_r($form, TRUE) . '
';
  drupal_set_message($print);

  switch($form_id){
    case 'YOUR_COMMENT_FORM_ID':
      //alter your form (with the complete correct fields names)
      $form['YOUR_FIELD_YOUR_NAME']['#type'] = 'hidden';
      $form['YOUR_FIELD_SUBMIT']['#value'] = t('Post comment');
    break;
  }
}

You can also use dpm($form) if you have Devel installed, or make a

$print = '
' . print_r($form, TRUE) . '
';
drupal_set_message($print);

in order to retrieve the exact form fields


How do I hide the authoring information?

Edit the node type, in the "Display settings", there is a checkbox "Display author and date information", turn that off.


How to modify field_suffix after form submit?

I found a solution to achieve this functionality.

function hook_node_view($node, $view_mode, $langcode) {
$node->content['field_test'][0]['#markup'] = $node->content['field_test']['#items'][0]['value'].'Suffix-2';
}


Image Styles Not Generating Thumbnails/Previews

The solution for the image style issue was to alter the HTACCESS in that folder so it would allow apache to use image files.

I can also confirm that it WILL NOT work if you do not have your apache rewrite module turned on.

Final note - this will work without the octal being "777" as I mentioned in original post.


How to do a RedirectResponse with a destination query parameter?

Better use a route, so that the path processing in Drupal can do its job.
If custom.cart_add is the route to /cart/add/{page}, this returns a redirect response with a destination query parameter from a controller:

  return $this->redirect(
    'custom.cart_add',
    ['page' => 'p2'],
    [
      'query' => ['destination' => 'somewhere'],
      'absolute' => TRUE,
    ]
  );


How do I add venue location automatically when user selects a venue?

EDIT: Just realized that this post is a few months old. Hopefully you already found a solution to your problem. If not, maybe this can be of use.

If I'm understanding correctly, you would like to have the address appear in the published comment, and comment is a content type. I emphasize published because this method only allows the information to appear in the published node and not within the content creation form (which is unfortunate, because I've been searching for this functionality for my own site). Assuming the above is the case, then I think the best way to do this would be with Rules. These instructions should get you close, I think, but I haven't used the functionality in quite this way before. Once installed:

Add a field in your comment content type that matches the address/location field in your venue content type
Go to admin/config/workflow/rules
Add a new rule, and under "react on event" select "After saving new content"
Add condition "content is of type", and select your comment content type
Add action "fetch entity by id", and in the data selector input/select "node:your-reference-field:nid"
Add action "set a data value", in the data selector drill down to "node:address-field-of-comment-content-type", click continue, click on "switch to data selection" in the new value area if it's not already selected, and then on that data selector field drill down to "entity-fetched:address-field-of-venue-content-type"
Save changes

This should grab the address from the referenced node before the comment is saved, and populate the comment's address field with the referenced venue's address, after the user clicks the save content button but before it is saved.  You're probably going to want to hide the address field in the comment content creation form so that users can't mess with it. It will more than likely just confuse them since they are not directly editing it. Hopefully this helps you out. Like I said before, I haven't used it in quite this way, but I have used it in a similar fashion.

You also might want to check out Entityreference Prepopulate. It allows you to fill an entity reference field automatically within the url. So, if you have a link on the venue page to create a "comment" for the venue, the you can use this module to automatically populate the entity reference field with the venue, making it so that users don't have to make the selection themselves.


I want to create a new command for the nodes like the standard edit and delete

You need to use hook_menu() to define the path, coupled with the MENU_LOCAL_TASK type, e.g.

function MYMODULE_menu() {
  $items['node/%node/approve'] = array(
    'title' => 'Approve',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('my custom args'),
    'page callback' => 'MYMODULE_approve_node_page',
    'page arguments' => array(1),
    'weight' => -1 // Controls the display order for the tab
  );

  return $items;
}

Then you just implement a callback function, which has the node passed as a parameter, and build up your page output:

function MYMODULE_approve_node_page($node) {
  // Do something with $node...
  $build = array(
    '#markup' => node_view($node, 'teaser')
  );

  return $build;
}

Once you clear Drupal's caches you should see the new tab appear alongside the View/Edit tabs on a node page, but only for those users who have the permission you define in your access arguments.


As it stands, there are a few options from a module perspective.

Calendar
FullCalendar
Google Calendar

Calendar and FullCalendar are the popular calendaring options in Drupal - neither seem to have a stable Drupal 8 release yet but their dev branches may be workable. You'd have to try, and read through their issue queue to understand where they are at functionality wise.

Lastly, you could iframe embed a Google Calendar onto a page. But as you may have guessed, this means events need to be managed in Google Calendar itself, unless you set up a sync from Drupal to Google Calendar.

Other than that, there are no 'ready made' modules for this yet that are stable and production ready for Drupal 8. It looks like the others only have a Drupal 7 release or have been abandoned.


It depends on your need.

From Form API Reference,

  #ajax['callback'] and #ajax['path'] are mutually exclusive. 'callback' is easier to use and requires less code setup, but may not provide the
  capabilities required for some functions. When you can, use
  'callback'.

In simple words the function specified in #ajax['callback'] generates the content and #ajax['path'] controls the execution of that callback.

#ajax['path'] is defaults to system/ajax which fetches the respective form from the cache and process it then calls the specified callback for fetching the new content.

However if you want alter this flow, instead of system/ajax give your custom callback(But you will end-up with writing another AJAX system).

For example Views module uses its own path(
views/ajax) instead of system/ajax. The reason is that Views doesn't want the cached form so its re-builds it again(However there is a issue going on with regards to this approach).

So just set the #ajax['callback'] alone to have AJAX Form.


You can easily do your requirement with Conditional Fields module. You can show different fields depend on the select list of topics.

Conditional Fields allows you to manage sets of dependencies between
fields. When a field is “dependent”, it will only be available for
editing and displayed if the state of the “dependee” field matches the
right condition.
When editing a node (or any other entity type that
supports fields, like users and categories), the dependent fields are
dynamically modified with the States API.


How to create a view of all the nodes sorted by date width header per each year

I'VE FOUND THE SOLUTION:

I created a view with fields, i added the field date, under "format -> setting" i used the option Grouping by and I selected the date field and here we go!


How can I check which nodes have the highest value in a certain field?

If within your Computed Field you've selected Store value in the database, you can easily use Views to sort results based upon this field.

So, for example, in broad strokes, you could create a View that filtered on whatever you needed, most probably published and node type; then for sort, you would select this field and select descending; in paging, you'd select a specific number, eg, 3; and in fields, you'd select whatever you wanted to display.

If you wanted to have a block of the top three nodes, in the fields I could see you selecting the title and so forth, but if you are wanting to see if a specific node was in the top three, I'd just put the node nid in there.

So, if that's the case, when this View is run, it will return three nids.

If you look into views_get_view_result() you can quite easily access that output, eg:

$result=views_get_view_result('top_three'); // or whatever the name of the view is

will populate $result with something along these lines:

Array
(
    [0] => stdClass Object
        (
            [nid] => 2340
            [node_created] => 1390349535
        )

    [1] => stdClass Object
        (
            [nid] => 1176
            [node_created] => 1390086303
        )

    [2] => stdClass Object
        (
            [nid] => 1133
            [node_created] => 1390086313
        )

)

So, now you just have to look in there to see if your current nid is in there and if so, act accordingly.

Now, of course, the other question is where to put all of this?  I'd suggest looking into hook_node_update() but be aware of the performance considerations of doing all of this each time a node is updated.  Caching is certainly your friend here.


Display Vocabulary (VID) From Selected Field

Answering my own question for future purposes:

<?php

$vocabularies = taxonomy_get_vocabularies();
if ($vocabularies) {
  foreach($vocabularies as $vocabulary) {
    if ($vocabulary->vid == 1) {
      $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
      if ($terms) {
        foreach ($terms as $term) {
          print $term->name;
        }
      }
    }
  }
}
?>

Did the trick.


How to not include page titles in the webform included email values?

This should be as easy as changing the wizard page's display settings, but you found a bug.

Issue #3106037: Allow a multi-step wizard page's display to be customized

Once you apply the patch, in the page element's 'Advanced' you can change how the page is displayed via HTML and text. You can use Twig to just render the child element.


NOTE:Make sure to take backup of database before doing below changes to avoid any issues.

Search for "field_housing_coop_ref" field in entire database including cache tables, mostly cache_* and key_value tables. Once you've all matching records with you, delete one by one very carefully by reading there names properly to make sure nothing else get deleted.

Once you've deleted matching records for "field_housing_coop_ref" field, rebuild cache by navigating to "Admin => Configuration => Development => Performance" or using Drush command "drush cr".

Updates:

If there are any other references for this field inside other fields in key_value table, make sure to delete those field from Field UI and then cross verify again.


You can take that id from get array, try

print $_GET['category'];


It solved by :

1- give the right permissions for the images folder (where the uploaded images).

2- disable the web server authentication.

hint (if you use ckeditor add the tag img to the text format)


Render page with theme wrapper from custom controller?

solution is

    return $pageArray;

Adding Response bypasses Drupals rendering.


How can I stop Views from eating my query strings when rewriting a link?

Issue is not with views. What views does is it calls drupal_get_query_array to build the query array. And as of now drupal_get_query_array does not support same name array in the query params. All it does is just explodes the query and saves it as follows;

$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';

So if you see the see it is going to be overridden and it is just going to store

array ('age' => 44, 'friends' => 1)

I have created a ticket and reported this issue and attached a patch as well at https://drupal.org/node/2023815

The same patch should work for 7.x as well.

Alternatives

So Views php / Custom module looks like a good alternative without hacking the core.


Automatically adding paid membership products based on field values with Ubercart and Content Profile

I would look into Rules (may require some patches and the Ubercart Rules module, as I don't know if it can add products to the cart by default).

That said, a Google search (which I'm sure you've also done) doesn't hint at much. If you have time, I would suggest doing it the way you're planning (validate and submit hooks and uc_add_item). It will work well. Then contribute back what you've done either to an existing, similar module or as a new uc_ module.

Before doing so, you could ask in #drupal or, more specifically, #drupal-ubercart on IRC.


using {{ twig variables }} inside external jquery

It's not possible to access Twig variables in jQuery directly. Instead access the content of PHP variables inside of an external jQuery code by attaching them to drupalSettings. See the documentation:

  Attaching configurable JavaScript

  In some cases, you may want to add JavaScript to a page that depends
  on some computed PHP information.

  In this case, create a JavaScript file, define and attach a library
  just like before, but also attach JavaScript settings and have that
  JavaScript file read those settings, via drupalSettings (the successor
  to Drupal 7's Drupal.settings). However, to make drupalSettings
  available to our JavaScript file, we have to do the same work as we
  had to do to make jQuery available: we have to declare a dependency on
  it.

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

  and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

  Where 'bar' is some calculated value.

  Then cuddly-slider.js will be able to access

  drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

https://www.drupal.org/developing/api/8/assets


Prevent users of role from being flagged?

Here is a sample code you could use for your custom template.

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

// Check if the user has the 'standard' role.
if (in_array('standard', $user->roles)) {
  // enter the code to print your flag
}


Add a taxonomy term to many vocabularies

I don't think it's possible. It's always one to one relationship between vocabulary and term...

If you see taxonomy_term_data table which stores term id and vocabulary id reference below..

tid is primary key which means always unique. So, you can't have another row which points to different vid.

Below schema definition in taxonomy.install confirms same..

  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The term name.',
        'translatable' => TRUE,
      ),
      'description' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'description' => 'A description of the term.',
        'translatable' => TRUE,
      ),
      'format' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'description' => 'The {filter_format}.format of the description.',
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The weight of this term in relation to other terms.',
      ),
    ),
    'primary key' => array('tid'),
    'foreign keys' => array(
      'vocabulary' => array(
        'table' => 'taxonomy_vocabulary',
        'columns' => array('vid' => 'vid'),
      ),
    ),
    'indexes' => array(
      'taxonomy_tree' => array('vid', 'weight', 'name'),
      'vid_name' => array('vid', 'name'),
      'name' => array('name'),
    ),
  );


How to display the description of the article with 150 characters?

Check out Smart Trim module.

  Smart Trim implements a new field formatter for textfields (text,
  text_long, and text_with_summary, if you want to get technical) that
  improves upon the "Summary or Trimmed" formatter built into Drupal 7.


Two sort criteria. How to display first those with a specific List (float) selection

You can do it using views_query_alter. Find out what are the key values being stored from your list and then use them accordingly in the code below.

function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'shop' && $view->current_display == 'page') {
     $query->orderby[0] = array(
           'field' => 'CASE table.type WHEN '1' THEN 1 WHEN '0' THEN 2 WHEN
            ELSE 3 END');
  }
}


How do I display a username on their profile pages?

Do I add a computed field?

No

  What's a line of code would I use?

In your theme's .theme file add:

/**
 * Implements hook_preprocess_HOOK().
 */
function THEMENAME_preprocess_page_title(&$variables) { // your theme might already have this function/hook.
  $user = \Drupal::request()->attributes->get('user');
  if ($user instanceof \Drupal\user\UserInterface) {
    $variables['title'] = t('Username') . ': ' . $user->getAccountName();
  }
}

Note: Clear/flush the cache for changes to kick in.


As said before, it is in

$form['fieldname']['#type']

You don't need the state for this because it is not a state, it's static.


Get order title value from $order variable

You can get the order title from this method.

   uc_order_page_title($order)

check out all the methods you need for ubecart. ubecart drupal 7 API


How to update a Drupal 6 website to latest release with drush?

As near as I can tell, drupal.org just removed all of the release xml for all contrib modules, and every version of Drupal 6.x core except for the latest release.

See the Drupal 6.x release xml for reference; all versions except 6.38 have been removed. Ah, look, the Views 6.x release xml contains content again!  Just a short while ago, it was gone.

Without the full release XML for Drupal 6 core, Drush cannot your existing versions; if it has no information about the current release, it gives up.  It is possible that this situation was accidental, and is being updated (c.f. the views release XML, which was recently restored).  Maybe this will start working again later.


Change Search API Facet title for boolean values

I downloaded Facet API Bonus module, and used the exclusion option to hide fields that were "false" or "0".

I then went into the content type and changed the "1" value to what I wanted it to say.

Along with a little CSS around the field to neaten it up, I now have exactly what I was after.


Create a wrapper div within field groups on node displays

Try hook_field_group_build_pre_render_alter() since node content solution seems not longer working.

/**
 * Implements hook_field_group_build_pre_render_alter().
 * Adds additional wrappers
 */
function [your_theme_or_module_name]_field_group_build_pre_render_alter(&$element) {
  if (!empty($element['group_tabs'])) {
    $element['group_tabs']['#prefix'] = '
';
    $element['group_tabs']['#prefix'] .= '
';
    $element['group_tabs']['#suffix'] .= '

';
  }
}

Check Field group for developers for more info.


Basing on the documentation, 70xx updates are only necessary if there are updates from Drupal 6.x to Drupal 7.x that are necessary for any branch the Drupal 7 module has (e.g. 7.x-1.x, 7.x-2.x, 7.x-3.x). If that is not the case, then you don't need to use 70xx as update numbers.

As said in the documentation, updates numbered 72xx allows updating from the 6.x-2-x version of the module to the 7.x-2.x version, but not from the 6.x-3.x version. This is generally not a problem, since project maintainers normally create a version 7.x-3.x together a version 6.x-3.x.

As the documentation reports, updates numbered 71xx are for updated from version 6.x-1.x to 7.x-1.x; updates numbered 70xx are for updates from Drupal 6 to any branch of the module for Drupal 7.x. You don't copy the 70xx updates in 71xx updates, since those are already executed for the 7.x-1.x branch.

As for the updates to keep, the documentation says:

  A good rule of thumb is to remove updates older than two major releases of Drupal.

So, updates for a 7.x-1.x version should still be kept for a 7.x-2.x version.

Keep in mind that, as far as I recall, what described in the documentation about which updates are run when updating from Drupal 6 to Drupal 7 doesn't describe what the code actually does. For what I recall, Drupal code simply run any updates higher than the last executed update. For example, if a module last time ran its 6123 update, Drupal will run any update higher than that number, such as 7000, 7100, and 7200, if they are defined.


How to write a view of a user signed up nodes?

There is a default view called signup_current_signups that provides this functionality out of the box.


Using Field Collection module must serve your purpose.

After installing the module, create a field collection with two text fields - label and value.

Now attach this field collection to a content type and set its value to unlimited.

in essence what you will have is:
 1. When the form loads, you have two fields, a label and a value
 2. An add more button, which when clicked will generate another set of label value pair.

Hope this helps.


How can I add points for selected answers to questions implemented using Polls?

By using the Rules module, and some extra work, you can get this to work, as detailed below ...

Step 1: Use Rules to grant User Points

Use Rules to create a custom rule with a Rules Action that grants points (using the User Points module). Have a look at the rules exammple included in my answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?", especially the very first Rules Action in it. Here is how that Rule looks like:

{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

The 2nd and 3rd Rules Action is rather to facilitate testing (you may want to ignore those Actions after QA-testing).

Step 2: Make (core) Poll trigger the Rule

To continue with the Rule from Step 1, you don't want to use that Rules Condition there, so just delete that. However the crucial part for your case is to have an appropriate Rules Event to replace the event used in the Rule from Step 1. In your case you want to use a Rules Event like "When user casts a vote".

Guess what, there seems to be a (sandbox) module that provides exactly that Rules Event: the Poll Rules Integration. If you don't want to use a sandbox project, then just look at this project to see what's needed for that event to build your own custom module to create such event.

Step 3: Further complete your Poll-puzzle

After you complete Step 1 and 2 above, the only thing left to complete your "puzzle", is to implement an appropriate Rules Condition to check "if they answer the test correctly" (as in your question, for which you did not specify any further details).


Take a look at the Field Group module. That will enable you to group fields under a heading as you require. You can add groups on the form or on the display independently.

After you enable the module the display editor at Administration -> Configuration -> People -> Account Settings -> Manage Display will show a new entry to "Add new group". Add a new group of type fieldset, give it a title as required and set it to be "open" (not collapsible). You can then drag and drop individual fields into the group.

By default the group will display in a box. If you don't want that, the CSS to override it is pretty simple, eg:

body.page-user fieldset {border: none;padding:0;margin:0}


Ctools content type- How do I access a context that is provided by a panel page?

There might be a more elegant way, but here's what I came up with:

$user = reset($context);
$user = $user->data;


Adding text before and after cart contents block in Drupal 7 commerce

The easiest way to do this, for me, is by code, as checkout pages are normal Drupal forms and as such, we can use hook_form_alter() to do whatever we need. In this case, you can use

(yourmoduleorthemename)_form_commerce_checkout_form_checkout_alter (&$form, &$form_state)

And inside it, you can use Form API(https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#markup-attribute) to change the way you want.

You can also create a block and put on the "checkout/%/*", but it generates a lot of extra markup for almost nothing.

I believe you can solve your problem with one of these, but let me know if you need more details.


Custom module permission option not available

Here is to implement the hook permission

/**
 * Implements hook_permission().
 */
function form_example_permission() {
  return array(
    'administer your module' => array(
      'title' => t('Administer permission for your module'),
      'description' => t('Some description that would appear on the permission page..'),
    ),
  );
}


Display POA in Ubercart 3 / D7 for products of zero dollars

I have not tried this out but I would think you could override theme_uc_price() in your template.php something like this:

function THEMENAME_uc_price($variables) {
  if ($variables['price']) {
    $output = '' . uc_currency_format($variables['price']) . '';
    if (!empty($variables['suffixes'])) {
      $output .= '' . implode(' ', $variables['suffixes']) . '';
    }
  }
  else {
    $output = t('P.O.A');
  }
  return $output;
}


What your after is the following...

context_active_contexts()

http://api.drupalize.me/api/drupal/function/context_active_contexts/7

Example:

if (module_exists('context')) {
    $active_contexts = array_keys(context_active_contexts());
    if (in_array('SOMETHING', $active_contexts)) {
       //...
    }
}


Access denied for admin user after new drupal 6 install

It may be that your cookie domain is not set correctly, this is a known cause of Access Denied errors when logging in, and it might be worth removing cookie domain info from settings.php and see if that works, and go from there.


There exists a module for that called Active Sessions

Active Session is a module that allows a user to see if there is more than one session opened for their user and allows them (with permissions) to end other sessions belonging to their user. There is also an interface where a user with permissions can view all active sessions and close them.
Active Session creates a block that, by default, is placed in the footer of the page for users with 'view own sessions' or 'view all sessions' permissions to see and get more details about the sessions.

Images from module page


How to have calendar popup in a form field of 'date' type?

This issue is coming because of jQuery confliction.
Either you can update jQuery version or find out the confliction of jquery object.


Commerce Extra Pane wont drag in checkout UI

It looks a bit odd, but the only thing I can come up without more information is that you might have the node disabled in the commerce extra panes tab:

If that's not the case, try also to disable the js in the checkout configuration form, click on "show row weights" so you can select the page for each pane without dragging and dropping.


How to print taxonomy id of the current taxonomy term

You can use below code to get Taxonomy id by Taxonomy Name

 $taxonomy_term = taxonomy_get_term_by_name('Taxonomy Term Name');
 $tid = $taxonomy_term>tid;


Missing bottom level item when a node is linked to two menu objects

I resolved this by manipulating the tree object manually further down my module. I checked if the url of the parent object matched any of the child objects via a loop.

$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Setup current link
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Get the parent of current menu so we can use its
// children as the links
$parameters->setRoot(reset($tree)->link->getParent());
$tree = $menu_parent_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_parent_tree->transform($tree, $manipulators);

foreach($tree as $key => $menu_item) {
  // Check if the link is the current page?
  $current_internal_path = $menu_item->link->getUrlObject()->toString();
  foreach($menu_item->subtree as $sub_key => $sub_link) {
    $sub_internal_path = $sub_link->link->getUrlObject()->toString();

    if($current_internal_path == $sub_internal_path) {
      unset($tree[$key]->subtree[$sub_key]);
    }

    // Check if we have another sub tree (we are not the parent). This can happen when a parent
    // link is attached to the same node as a child one.
    if($sub_link->subtree && count($sub_link->subtree)) {
      $lower_level_links = $sub_link->subtree;

      foreach($lower_level_links as $lower_link_key => $lower_level_link) {
        $lower_level_url = $lower_level_link->link->getUrlObject()->toString();
        if($sub_internal_path == $lower_level_url) {
          // Set the active menu level as this.
          $tree = array($sub_link);
        }
      }
    }
  }
}

// Build up our menu
$menu = $menu_tree->build($tree);

This is perhaps not the cleanest solution with a lot of extra processing required but seems to work in this instance.


How to call template when Custom form is submitted?

Please update your _menu function with this code.

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

    $items['events-filter'] = array(
        'title' => 'Events Listing',
        'description' => '',
        'page callback' => drupal_get_form,
          'page arguments' => array('filterevents_form'),
        'access callback' => TRUE,
    );
    return $items;
  }

And then clear drupal cache. Hope it will work.

Thanks.


Module to Create Historic Timeline Snapshots of Drupal Sites?

You should take a look at Aegir. Although it is more than a module, it has the functionality you describe. Basically what Aegir can do for you is create a complete copy (database, codebase and files) of your Drupal website. The catch here is that your Drupal site should be managed by Aegir as well.

On the more technical side, if you take a look at what Aegir does, you will notice that creating a copy of your website is performed by a number of drush scripts. These scripts could of course be used/modified to make your snapshots.


How to inform future developers about hack in the core?

Good question. I know that many Drupal shops have their own rules about documenting patches and hacks, but other than that, I have not seen a convention or standard.

That said, the methods I have seen in various organizations do have some common characteristics. Below are some guidelines that come to mind. Note that these are only meant for non-security patches. If you're fixing a security problem, never store the patch in a publicly accessible place (ie. under your web root) and do not submit the patch in the issue queue but report a security issue instead.

Have a single directory with an understandable name where all patches and their documentation are stored. For instance /patches or /sites/all/patches.
Add the patch file, stored in the patches directory, to your version control system. If you didn't download a patch, but edited some code yourself, create a proper patch file and add it to your version control system.
If you wrote the patch yourself, submit it in the appropriate issue queue on drupal.org so it can be reviewed and committed by the project maintainer.
Create in a text file, eg. /patches/patches.txt, and write down:

What has been patched
Why the patch was needed
A link to the issue on drupal.org where you found the patch (or submitted your own).

When committing all of this to your version control system, write a clear commit message (you always do that, right?) that indicates that you are committing a patch.

IMHO when a developer starts working on a site he didn't build himself, he should always be aware that some code may have been patched. If you use the points above as guidelines your own documentation method, other developers should have no problems in finding out what you patched and why you did that.


Categorized view for an entity reference content

Drupal 8 taxonomies are entities so you can add custom fields, images (magazine covers), icons, as well as using for classification.
It doesn't sound like the Magazine "content type" is that complex, more of a catch-all for a listing of all your various articles and content related to each magazine, so that (Magazine as a taxonomy) would be my inclination in this situation.
The classification features of taxonomy work better out of the box than if you were do something custom with your content type.
I'd have 2 taxonomies for organising topics by:
(1) Magazine
(2) Topic
If you are doing - or envisage possibly doing - something more complex with your Magazine type at a later stage then content type rather taxonomy may be the way to go.
As always with Drupal, there's more than one way to do it and you have to weigh up the pros and cons taking into account: ease-of-use, navigation, theming, scaleability, overhead, etc.


managed_file #progress_indicator never finishes

Since you seem to be having trouble with javascript, you might check your install to see if you have the jquery_update module and check to see if it needs to be updated?


Webform - Replace Form title with Node title

In CCK there is a module called Field Reference. Enable that an you can create a field reference field, which you can link to a specific field in another node.


How to check the remaining capacity for an event when using the Registration module?

The Rules module is a very flexible framework and it has a comprehensive api. While you may be able to accomplish your task using just the UI you may find it easier implement one or couple of hooks to alter your existing condition, or perhaps, add a new condition to be used. For example,

/**
 * Implementation of hook_rules_condition_info().
 * @ingroup rules
 */
function yourmodule_rules_condition_info() {
  return array(
    'yourmodule_condition_example' => array(
      'label' => t('Compare two users'),
      'arguments' => array(
        'user1' => array('type' => 'user', 'label' => t('First user to compare')),
        'user2' => array('type' => 'user', 'label' => t('Second user to compare'))
      ),
      'module' => 'user',
    ),
  );
}

If you decide to go this way, you may want to check https://drupal.org/node/298533


Hook to catch a variable in a POST request to a specific url?

You should use the services module to create an endpoint and use the url where is sent as the path to endpoint.

You don't state which type format the data is being posted to your site but the services module can handle many different types.

Also it's not stated exactly what you want to do with the received data but the services module can be set up to process it in a variety of ways.

You can capture it to a databse table etc
or Here's an example of creating a node using services:
http://www.drupalwoo.com/content/blog/drupal-services-creating-node-from-external-form


when you create a sub-theme you do not need to create any "new" template, but you can change something from the "main-theme". So try to create a new sub-theme and put that files into sub-theme.

M.


Drush site-install and extra settings for the settings file?

Checkout the post about Collecting and writing configuration settings to setting.php from an install profile.

It describes how a custom task was injected into the installation profile and then details how drupal_rewrite_settings() was used to inject the custom settings into settings.php.


Webform on 'hostile development' environment

Coming from a huge production environment with Drupal multi-site running, the Webform can be a constant headache if there is no SPAM protection turned on, or if modules/core aren't kept up-to-date.  Maybe they had problems in the past with Drupal admins not running protection on their forms and not keeping their modules up-to-date with the latest security fixes?  Also, Drupal, the Webform module and open-source CMSs in general have a bad rap with the IT/Security crowd.  I have experience it more than once in my career.

The best thing you can do is find out why they feel the way they feel about that particular module, and then explain to them how, if maintained correctly and used correctly, it should be of little to no concern.


This does not answer the question exactly but: it is possible to create the field simply by using proper schema BUT the issue is writing and reading data. It is possible with \Drupal::database()->query() but not with \Drupal::database()->select() or any other method since we have no control over value escaping so spatial functions are not interpreted.


How to grant userpoints to users who perform a login 5 days consecutively?

Statistics module in the core would work in this case.


What cache should be cleared for front end theming work?

Here's the comprehensive list of cache-clear options and the underlying API functions & what they do:

drush cc drush - drush_cache_clear_drush(): Drush's internal cache for data from the Drupal install (e.g. available module commands).
drush cc all - drupal_flush_all_caches(): All Drupal caches.
drush cc theme-registry - drupal_theme_rebuild(): All theme metadata.
drush cc menu - menu_rebuild(): All menu metadata.
drush cc css-js - drupal_clear_css_cache() drupal_clear_js_cache(): Aggreggated/Minified CSS/JS files.
drush cc block - cache_clear_all(NULL, 'cache_block'): All block metadata.
drush cc module-list - system_rebuild_module_data(): All available modules (reloaded from file system).
drush cc theme-list - system_rebuild_theme_data(): All available themes (reloaded from file system).

That should let you fine target the cache to clear when it's needed.

Depending on your workflow, you might also want to force the cache off (e.g. $conf['preprocess_css'] = 0; & $conf['preprocess_js'] = 0;) in local.settings.php for your local dev environment so it doesn't interfere with feedback.


How to reference existing taxonomy terms in a migration

I was able to solve the issue by moving the queries for the term ID to the process plugin.

/**
 *
 * @MigrateProcessPlugin(
 *   id = "existing_term"
 * )
 */
class MigrateProcessExistingTerm extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    db_set_active('my_migration');

    $sub_task_id = db_select('TableA', 'ta')
      ->fields('ta', ['OriginalId'])
      ->condition('Id', $value)
      ->execute()
      ->fetchField();

    $term_id = db_select('TableB', 'tb')
      ->fields('tb', ['DrupalTermId'])
      ->condition('OriginalId', $original_id)
      ->execute()
      ->fetchField();

      db_set_active('default');

    $term = Term::load($term_id);

    return [
      'target_id' => $term->id(),
    ];
  }

}

It seems like having the queries in the main class were confusing the migration into thinking the term data was in the migration source database.


Fire custom submit handler in form embedded in node edit form

I came across https://www.drupal.org/forum/support/module-development-and-code-questions/2015-09-03/put-a-custom-form-inside-node-form which, while old, claims that what I wanted to do is not possible. To get this to function the way I wanted I:

Attached a JS event handler to the embedded form submit buttons that performed .preventDefault()
This handler then .ajax'd a custom route that I created.
In the Controller for that route, I had to perform all the primary operations for submitting the form and return markup back to the .ajax call.


How do I perform a 301 redirect for all old .asp pages?

Why not use Drupal 7's core URL redirect interface? It has an option for 301 redirects: Configuration > Search and metadata > URL redirects.

I like it because it captures stats on how many redirects are happening.


if you get the filter slider effect how you want save the view and disable the BEF module then go back to the view it can work. I remember I tried something like this before. It might break if you go back and mess with the filter and not just grouping.


Where does drupal store content-type display settings?

By Default it stores in field_config_instance table.. For relevant code check below function in field.crud.inc file

function _field_write_instance($instance, $update = FALSE) {
  $field = field_read_field($instance['field_name']);
  $field_type = field_info_field_types($field['type']);

  // Set defaults.
  $instance += array(
    'settings' => array(),
    'display' => array(),
    'widget' => array(),
    'required' => FALSE,
    'label' => $instance['field_name'],
    'description' => '',
    'deleted' => 0,
  );

  // Set default instance settings.
  $instance['settings'] += field_info_instance_settings($field['type']);

  // Set default widget and settings.
  $instance['widget'] += array(
    // TODO: what if no 'default_widget' specified ?
    'type' => $field_type['default_widget'],
    'settings' => array(),
  );
  // If no weight specified, make sure the field sinks at the bottom.
  if (!isset($instance['widget']['weight'])) {
    $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], 'form');
    $instance['widget']['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
  }
  // Check widget module.
  $widget_type = field_info_widget_types($instance['widget']['type']);
  $instance['widget']['module'] = $widget_type['module'];
  $instance['widget']['settings'] += field_info_widget_settings($instance['widget']['type']);

  // Make sure there are at least display settings for the 'default' view mode,
  // and fill in defaults for each view mode specified in the definition.
  $instance['display'] += array(
    'default' => array(),
  );
  foreach ($instance['display'] as $view_mode => $display) {
    $display += array(
      'label' => 'above',
      'type' => isset($field_type['default_formatter']) ? $field_type['default_formatter'] : 'hidden',
      'settings' => array(),
    );
    if ($display['type'] != 'hidden') {
      $formatter_type = field_info_formatter_types($display['type']);
      $display['module'] = $formatter_type['module'];
      $display['settings'] += field_info_formatter_settings($display['type']);
    }
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($display['weight'])) {
      $max_weight = field_info_max_weight($instance['entity_type'], $instance['bundle'], $view_mode);
      $display['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
    }
    $instance['display'][$view_mode] = $display;
  }

  // The serialized 'data' column contains everything from $instance that does
  // not have its own column and is not automatically populated when the
  // instance is read.
  $data = $instance;
  unset($data['id'], $data['field_id'], $data['field_name'], $data['entity_type'], $data['bundle'], $data['deleted']);

  $record = array(
    'field_id' => $instance['field_id'],
    'field_name' => $instance['field_name'],
    'entity_type' => $instance['entity_type'],
    'bundle' => $instance['bundle'],
    'data' => $data,
    'deleted' => $instance['deleted'],
  );
  // We need to tell drupal_update_record() the primary keys to trigger an
  // update.
  if ($update) {
    $record['id'] = $instance['id'];
    $primary_key = array('id');
  }
  else {
    $primary_key = array();
  }
  drupal_write_record('field_config_instance', $record, $primary_key);
}

It stores in above table data column as blob format... Sample example goes below inside blob..

a:6:{s:5:"label";s:7:"Comment";s:8:"settings";a:2:{s:15:"text_processing";i:1;s:18:"user_register_form";b:0;}s:8:"required";b:1;s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:6:"hidden";s:4:"type";s:12:"text_default";s:6:"weight";i:0;s:8:"settings";a:0:{}s:6:"module";s:4:"text";}}s:6:"widget";a:4:{s:4:"type";s:13:"text_textarea";s:8:"settings";a:1:{s:4:"rows";i:5;}s:6:"weight";i:0;s:6:"module";s:4:"text";}s:11:"description";s:0:"";}


Drush on distributed server architecture

If it is possible for your Drupal site to access the database, then it is possible for Drush to access the database. In fact, Drush uses Drupal code to bootstrap, so it should really work the same.

What appears to be the issue here is that you do not have all of the same extensions (esp. the PDO extension) available in php-cli as you do in php-cgi or php-fpm or whatever you are using for your web server. Another issue that can sometimes come up is permissions, if you are running Drush under  a different user than the web server.

Finally, it is also worth noting that not all Drush commands go through the Drupal bootstrap to access the database. The sql-* commands use the database commandline tools (mysql, psql, etc.), so these Drush commands may not work (e.g. if the database commandline tools are not installed).


What URL do I use to view an OG membership entity?

I don't think that there is a page you can view the membership. I've just skimmed the code of OG module and didn't found any relating part which displays a membership in a separate page.

However, since memberships are entities, it should be possible that you can setup a view which takes a membership id as contextual filter and display it in a selected view mode.

Here is how you do that with views:

Create a new view visiting admin/structure/views/add

Give your view a name like View Membership
Set it to Show OG Membership
Set a Path with a placeholder like view-membership/%
Display format Unformatted list of Rendered entity
Items to display 1, uncheck Use a pager
Continue & Edit

Under Advanced section, add a contextual filter OG membership: Og membership ID

WHEN THE FILTER VALUE IS NOT IN THE URL: Show "Page not found"

Save
Visit the page view-membership/<membership_id> and you'll see the membership entity.


You create a link to the taxonomy display page. This page will show all the nodes (product display types) that are tagged with the taxonomy term (category). How you display the taxonomy page is up to you. There are many modules which can give you more flexibility to the taxonomy display pages.


Can you make a field unique in a content type?

You can add a validation constraint to your field.
There is two ways to do that:

Setting a validation constraint to a field you haven't defined by implementing hook_entity_bundle_field_info_alter:

function YOURMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'ENTITY_TYPE' && $bundle === 'BUNDLE_NAME') {
    if (isset($fields['FIELD_NAME'])) {
      $fields['FIELD_NAME']->addConstraint('UniqueField');
    }
  }
}

Setting a validation constraint to a field you have defined in baseFieldDefinitions

public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
 $fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
   ->setLabel(t('MY UNIQUE FIELD'))
   ->addConstraint('UniqueField');

 return $fields;
}

If you want to create your own validation constraint you can check here.


How do I create a link that redirects to a destination after completing an action?

Have a look at the Login Destination module.  From the project page:

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Lack of permissions on sites/default/files

You can install the devel module and visit /devel/php on your site. This will give you a place to run ad-hoc PHP from where you could run chown() or something similar on the files in question.

I'm sure it doesn't need to be said but be careful, the last thing you want to do is make a mistake with permissions!


How do I render search block form in theme template?

Here are the 3 methods I found.
1 - Use plugin.manger.block to render search_form_block
-- in mytheme.theme
function MYTHEME_preprocess_page(&$variables) {
  $customblock = \Drupal::service('plugin.manager.block')->createInstance('search_form_block', []);
  $variables['content']['custom_block_output'] = $customblock->build();
}

-- in page.html.twig
{{ content.custom_block_output }}

2 - Same as 1 but render a customized search block from block--search-form-block.html.twig.
-- in mytheme.theme - Same as method 1
-- in page.html.twig
{% include '@MYTHEME/block--search-form-block.html.twig' %}

3 - Use Twig Tweak - credit to No Sssweat's Post

install the Twig Tweak module
insert {{ drupal_block(search_form_block') }} on page.html.twig


How do I get the block title from the plugin implementing it?

If your block plugin derives from the BlockBase class, BlockBase::label() returns the default title for the block, but the block title is set in BlockBase::buildConfigurationForm().

  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Title'),
    '#maxlength' => 255,
    '#default_value' => $this->label(),
    '#required' => TRUE,
  );
  $form['label_display'] = array(
    '#type' => 'checkbox',
    '#title' => $this->t('Display title'),
    '#default_value' => ($this->configuration['label_display'] === BlockInterface::BLOCK_LABEL_VISIBLE),
    '#return_value' => BlockInterface::BLOCK_LABEL_VISIBLE,
  );

So, your block class should check if $this->configuration['label_display'] is set to BlockInterface::BLOCK_LABEL_VISIBLE; if it is, then use $this->configuration['label'] for the title.

That said, I feel like the code you want to implement is actually not necessary, since the BlockBase class already takes care of showing the block title.


'Unlinking' a link for users without permission

Here's what I've come up with myself. It works fine:

if(user_access('edit record')) {
    $link = l(t('Edit this record'), 'edit-record/' . $nid);
} else {
    $link = t('Edit this record');
}

If you know of a 'cleaner' more 'correct' way. Please let me know. Thanks


How to delete data from a field programmatically

I think it's already answered here. You just need to build an interface to display images in grid format using views and a delete button is just a link where you pass the node id and delta value of field value to delete.

Once you call the link which will be a custom menu path with callback which executes the code shown in above link to delete the delta field value.


Best method of pushing content changes that contains paragraph fields from dev to production?

One recommendation is to use "Features" to generate:

a Feature export of any config changes to the content types, paragraph bundles, and fields
a separate Feature export of the content/nodes themselves

To accomplish this, you'll need:

"Features" module:  https://www.drupal.org/project/features
"Features Extra" module:  https://www.drupal.org/project/features_extra
"UUID  Features" module:  https://www.drupal.org/project/uuid_features
"Strongarm" module:  https://www.drupal.org/project/strongarm
"Diff" module: https://www.drupal.org/project/diff

NOTE:  this approach generally works well, as long as the effected content/node IDs between production and your staging/dev environment are the same.


How to insert conditions into Global Custom Text?

Add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder)

function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){

        if (strpos($vars['fields']['title']->content, 'multi') !== false) {
          $vars['fields']['title']->content = "
" . $vars['fields']['title']->content . "
";
        } else {
          $vars['fields']['title']->content = "
" . $vars['fields']['title']->raw . "|" . $vars['fields']['field_annual_number']->raw . "
";
       }

      }

    }

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name

Once you update your template.php file, don't forget to clear/flush your cache in Drupal to see changes.


Displaying the node title in different region

Not sure which version of Drupal you're using, but the method is basically the same. In D6 just place  where ever you need it in the page.tpl.php template and remove it from the node.tpl.php template (or use conditionals to output it there when needed).


How to Display a Block on a Page with a Variable URL

I'm not sure what you mean by the PHP box.  You could do this with the block's visibility settings.  For example, if you wanted to show the "Powered by Drupal"
 block on only the URLs you mentioned, you would go to...

/admin/structure/block/manage/system/powered-by/configure

...and in the Pages tab of the Visibility Settings, enter...

user/*/recurring-fees

Also make sure you have ticked the radio button for "Only the listed pages".

If you are coding the block yourself, you could do something toward the top of your block function like...

if ('user' !== arg(0) || !is_numeric(arg(1)) || 'recurring-fees' !== arg(2)) {
 return array();
}

See http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/arg/7

But the usual approach is to use the visibility settings.


The better way I think is to use Views and Views Bulk Operations and you can do a simple admin interface to delete all of them.

Otherwise, you still can delete directly throw a SQL query.


How to add a flat amount to an order. Using Drupal commerce module

You should be able to accomplish that using Rules.

Create a product that has the flat amount of 230€ and use the Rules action "Add product to the cart" to add that product to the cart.

To create the rule:

Create a Rule for event "After adding a product to the cart"
Add the "Order contains a particular product" condition to check if the
order already has the flat amount product
Then add the "Add a product to a cart" to add the flat amount product to the order

You could add the same rule for the "After removing a product from the cart" event, so if they remove the flat rate product, it would just re-add it to the cart.


How to make XML sitemap to work after transfer from localhost?

Did you define base_url in settings.php file? Try to set your current website address for base_url, then clear cache and run cron to generate sitemap. If this doesn't work, backup your database and run SQL query as:

UPDATE variable SET value='s:99:"http://example.com";' WHERE name='xmlsitemap_base_url';

Where the 99 is the length of your domain (including the http and all) and example.com is your domain.


The ajax from a form is handled by the form function itself wich is edited in the mdule layer, not in the template layer. The custom module approach would be.

Find the id of the entity form, see this Tutorial

Once you have the id you can use the MY_MODULE_form_FORM_ID_alter to edit the form elements to use ajax.
See this Tutorial for more info on ajax forms.

If you want the ajax callback to alter an external element/several wrappers you can use the ajax_command_* functions to change pretty much anything selectable by JS.
Have the ajax callback return something like this. (you won't need to set the #ajax wrapper in this case).

More about the drupal's ajax_command_* functions

function AJAX_CALLBACK_CALLED_FROM_FIELD($form, &$form_state){
  $commands[] = ajax_command_html('JQUERY_SELECTOR', 'VALID_HTML'); // Or any other valid ajax command.
  return array(
    '#type' => 'ajax',
    '#commands' => $commands
  );
}


This is what the related change record has to say:

  Instead of the submit hook, an #entity_builder callback should be used to map form values to an entity (or better; use a field with a widget). If the submit hook is not about mapping values to the entity, register a custom #submit callback on the submit button and put your logic there.

And here are the related code samples:

// Implements HOOK_form_BASE_FORM_ID_alter
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // For entity builders.
  $form['#entity_builders'][] = 'mymodule_node_builder';
  // For submit callbacks.
  $form['actions']['submit']['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_builder($entity_type, NodeInterface $node, &$form, FormStateInterface $form_state) {
  $parent = $form_state->getValue('menu', 'parent');
  if ($parent) {
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $parent);
  }
}

function mymodule_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  mymodule_do_something($node);
}


How to use Views to make slideshow of the content created using block type

I assume you're trying to create a View from Blocks? It's not possible as far as I know, and it's not really a good idea I think. You could instead create a new Content Type (Structure -> Content Types), and add each of your block's contents into a separate node of the type you made.

Then use Views to create a node view, filtered by the Content Type you created. You can then display this view as a Block, with a "Slideshow" display style using the Views Slideshow module


Admin menu is an yet another menu, which builds programmatically. So you can modify items using hooks registered for any menus.

If you would like to disallow atricle creation by specified role, just remove appropriate permission.

If this does not helps, look at admin_menu_menu_alter() and theme_admin_menu_links().


How can we create configurable product in ubercart?

If I had this problem,

I would have created taxonomy terms corresponding to the attributes
The taxonomy terms can be used as search filters, rather than hacking the uc_attributes.

or

If views is used to display the products, then add filters in the views as product attributes.
The taxonomy terms can also be used in views to filter the products.


Try the following code

function commerce_bulk_invoice_block_view($block_name = '') {
  $block = array();
  if ($block_name == 'showinvoiceoptions') {
    $content = '
';
    if(!isset($_SESSION['selected_entities'])) {
        $content .= 'select a product first';
    } else {
        $content .= '
SESSION Variables:
';
        foreach($entity_array as $book) {
            $content .= '
';
            $content .= print_r( $book, true );
            $content .= '
';
        }
    }

    $content .= '
';

    $build['content']=array('#markup' => $content);
    $build['form']=drupal_get_form('commerce_bulk_invoice_form');

    $block['content'] = $build;
 }
 return $block;
}


To un-check a check box with Services in Drupal 7 (aka setting false on a boolean field), try this:

"field_character_type": {"und": null}

I've just verified this works on my localhost (for both users and nodes), here's the payload for the PUT:

{
  uid: 1,
  name: "admin",
  field_character_type: { und: null }
}

And here's the path:

api/user/1.json

Make sure you include the [my-endpoint-path]/user/[uid].json for the call.

You only need to cast the data payload into a string if you're using vanilla .js and an xhr object, otherwise jQuery's ajax does it automatically for you.


After creating a node in activity module I am getting an error "undefined index"

Have a look at the issue queue for Activity.

In particular: Causes undefined index _node_query_node_access_alter

  Not sure why activity would be a culprit of this, but non admin users
  see this error when viewing default activity view or any other
  acitivity views created. This error will also occur on a page when the
  view is a block.

  Notice: Undefined index: table in _node_query_node_access_alter()
  (line 3197 of /var/sites/my/modules/node/node.module).


Are there terms to distinguish between the different levels of Drupal Core?

I'm not aware of any official definition of the various levels.

I will however, referring to your suggestions, explain a bit about what levels there are.

The Drupal Kernel is actually a component in Drupal 8, which is a Symfony Kernel
"Deep Core Modules" could be the include files that are not even modules. Some files, for example database.inc, bootstrap.inc and module.inc are so fundamental that core cannot function without them. (There are some more .inc files however that reasonably could become modules, I don't know why they are not)
Core modules then, core parts that are written in the same style as contrib modules, but are still so fundamental that core wouldn't work without them. There's a system module that manages a lot of low level administrative functionality. The node module is (in D7) still required. Field sql storage cannot be turned of either.
Outer Core Modules, are all the other things that are shipped with core because they are commonly used, but not necessary for Drupal to function. The forum, taxonomy terms, the user interface for the field system etc.

Again, I'm not familiar with any official terminology, other than all of it being "Core". When people work on core, I only hear references to the individual "components" of core, as specific in the Drupal issue queue.

When I hear "actual core", I think of levels 1 - 3.


Private nodes in Private group are visible to non-members by their URL

I had a similar issue too.  In the end, my mistake was having "group visibility" set as a field for the Post content type when it should have been "group content visibility."


Display language in entity reference field

You can do this with views. Views allows you to add a "Reference" display. There you can choose how your title or your reference entry should look like. The view can then be chosen from the settings of the node reference field.


Views display of every user's flagged nodes grouped by flag type

For grouping, I have used Views Grouped Table to good effect. You might also look at Views Complex Grouping, a more recent module.


Themes can only implement alter, theme and pre/process hooks.

Re-implement those hooks in a custom module and they should work fine.


validation question for webform validate

Here are the steps you'll need to follow:

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use ^\d*$ and check the negate rule box below

OR

Go to your webform
Select the "form validation" button.
under the "Add a validation rule" select "Regular expression, case-sensitive"
For the regex, you can use [^\d]+


content type showing as link but not in "node_type" table

Found the resolution on drupal.org

One comment explains how to "reset" the content type from the navigation menu.

  This fixed the problem! What I did:

Go to the navigation page, admin/structure/menu/manage/navigation
find the link to the content type that is no longer there. It should be in the list under "add content".
To the right there's buttons to edit and reset the link. You want to reset. This forces Drupal to reevaluate the link.
It refreshes and poof! Gone from navigation, from add content page as well.


What is the correct way for a Drupal 8 custom theme to override the JS collection renderer?

Themes have no mechanism to provider or alter services. A custom module is needed.


How to compare before and after state in whatever_submit($form, &$form_state)

First of all: You should migrate to Drupal 7 or 8. Drupal 6 is no longer supported as of Feb 24th, 2016.
If migration is not possible, perform security updates. The latest version of Drupal 6 is 6.38 released on 24 February 2016. Have you also heard about the Drupal 6 LTS initiative? I highly recommend reading the details https://www.drupal.org/project/d6lts, https://github.com/d6lts/drupal.

Answering your question, the simplest thing would be to pass the object with the data in the form:

$form['my_object'] = array(
  '#value' => $my_object,
  '#type' => 'value',
);

$form['some_field'] = array(
  '#default_value' => $my_object->some_field,
  '#type' => 'textfield',
);

Then in the submit handler you can compare values:

if ($form_state['values']['my_object']->some_field != $form_state['values']['some_field']) {
  // Value of some_field has changed!
}


How to keep a specific module on -dev version (with patches) on a Drupal8 site managed by composer?

Firstly, the 8.x- is not part of the composer version; the correct version is 1.x-dev or dev-1.x.

However, composer require drupal/search_api_solr:1.x-dev always updates to the latest revision on the dev branch. If you want to stay on a specific commit and prevent updates entirely, use something like composer require drupal/search_api_solr:1.x-dev#46e16862.


How to convert an order price to a different currency in Commerce 2?

This is what I've done for now.

Add the currencies you will use in the UI. /admin/commerce/config/currencies
Add a "currency" product attribute in the UI. /admin/commerce/product-attributes
On the product edit page for the product you want, add variations with the currencies and set the prices.

This lets the user choose the currency he/she likes. So you can just put a message "If you're using JCB, you must pay with JCB."  It's not perfect but it's a decent solution.


Drupal 7: How do I translate the content of a checkbox I created?

You've got content translation enabled but have you installed and enabled the entity translation module as well? In Drupal 7, you need this to be able to translate each field / entity. I've used this guide (also referred from the entity translation project page) as a good step-by-step process on how to set this up.


Need help changing out theme based picture on front page, can only be done through host site, not admin panel

I would guess that the current image is hardcoded into the template. Best would be create a content type, add an image field, (upload new image), and set that new node page as the home page in the system site settings.


Create drupal node programatically and set custom select list field

With a select list, you need to store the key value of the custom field.

I just noticed that you're storing taxonomy term reference value, which means you should be storing the term ID and not the actual text value of pending.

Theres a handy function which allows you to grab the TID based on a term name:

$term = taxonomy_get_term_by_name('pending');
$node->field_referee_status[LANGUAGE_NONE][0]['tid'] = $term->tid;

See the docs here.

EDIT

To save into a normal textfield select list:

$node->field_referee_status[LANGUAGE_NONE][0]['value'] = 'pending';


How to automatically upload a file on form submission

If a file has been selected in a file upload field, it will be uploaded on form submit regardless of whether the "Upload" button has been pressed.


Display a message to user for empty user fields

This solution may be less performance happy than preprocessing (or not, it's difficult to say depending on caching etc), but I thought I'd be good to throw it out there since it's a "no-code" solution.

Create a Views with Block display listing users
Filter according to Location field Is empty to show only users who don't have it filled in
Add a Contextual filter for the user ID and set it to the current user, Hide Views if it doesn't validate
Add Custom text field and enter your message to be shown
Add the No results behaviour, this may need some thinking around how to handle the cases when the uses do have the Location field filled in
Place the block in as many regions of your theme as you need, and configure each Block visibility so it makes sense for your cases
Don't forget to also configure the Block contextual filter settings


Trying to use hierarchical select in exposed view filter - dont get the option

Use Simple Hierachical Select module instead which works

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy.


Batch API to process millions of records

Add a column for 'processed'. Each time you run the batch process select rows with a limit of 100 unprocessed rows for you batch process and then mark each row as processed.

You could run this on cron or something or run a nested batch.


How to display specific forms in drupal 7?

I would recommend using blocks with conditional views instead of hard coding this into your template file, but if that's really what you want to do, you basically just need to use drupal_render and drupal_get_form in the appropriate places in your template file i.e.:

Login:
<?php print drupal_render(drupal_get_form('user_login')); ?>
 - OR -
Register:
<?php print drupal_render(drupal_get_form('user_register_form')); ?>


If you absolutely need to piggyback on theme_field() rather than implement your own theme function (which would be preferable IMHO), then you'll have to jump through a few more hoops.

The key place to look is template_preprocess_field(), which will show you all of the elements that are expected to be in the array. Specifically for the label, the #title property is used. So this

return array(
  'test' => array(
    '#theme'                => 'field',
    '#label_hidden'         =>  false,
    '#title_attributes'     => 'class="test123"',
    '#label'                => 'test',
    '#title' => 'test',  // Required
    '#label_display' => 'visible',  // Required
    '#content_attributes'   => 'class="test456"',
    '#items'    => array()
  )
);

will return what you're looking for (with a bunch of notices about undefined indicies).

Eventually you'll also need to provide #field_name, #field_type, #bundle and #entity_type for each of your 'field' items.


After enabling Calendar the Next/Prev buttons are off to the side

CSS is your friend.  Find the id and/or class of these offending buttons and override their positioning in your theme.


How Can I change the machine name of product type

You can alter the machine name through the database to change the product type. See table commerce_product_type and alter the 'type' column.

Make proper adjustments in commerce_product for products using the old type. You could execute something like the following SQL query

UPDATE commerce_product SET type = REPLACE(type, "tv", "lcdtv");

Be sure to test this on a local or development version of the site.

UPDATE: As mentioned by Clive, you also have to update field data/revision tables.

You'd want to run UPDATE field_table_name SET bundle = REPLACE(bundle, "tv", "lcdtv"); on any field_data_* or field_revision_* table that relates to your product type.


How can I view nodes on my site from Drupalgap?

In mymodule_sample_page() just return an empty div container, for example:

Then attach a pageshow handler to your page via hook_menu(), then in the pageshow handler call node_load(), and in its success inject the content into your empty div container.

The page_callback can not have any async calls in it, as all async calls have to be handled after the page is actually shown.

FYI, DrupalGap has built in support to view nodes, just navigate to node/11 in the app. Here's a brief example demonstrating pageshow: http://www.drupalgap.org/node/154


How to modify form fields before validation

From the documentation:

  Note: Changes made to the $node object within your hook implementation will have no effect. The preferred method to change a node's content is to use hook_node_presave() instead. If it is really necessary to change the node at the validate stage, you can use form_set_value().


Importing nodes with different field names from Drupal 6 to 7

I have solved by checking which fields i needed, i made a table with those fields then made a custom boostrappable script to import them as new nodes


Config import constantly showing configs to import

Check that the UUID of the remote and local drupal sites match.

drush config-get "system.site" uuid

You can also get the id from the remote site, by looking into  system.site.yml of your config folder you are trying to import.

To set your local UUID use drush

drush config-set "system.site" uuid "UUID-GOES-HERE"


Can we use math expression in Field collection

First off, would this be for D7 or D8? I'm assuming you're using the node entity. I would think a good approach is to have the result field as a field on your node, make the calculation, and set the value in a hook_node_presave() (for D7, hook_entity_presave() for D8). At this point, the values are about to be stored to your DB, so you'd have access to your total_amount and installment_value values, and you can set your third "result" field to this computed value. You'd probably want to set the "result" field to not be visible to the end user, by setting it's #access to false in a hook_form_alter(), since anything they input would be overridden by your calculation anyway. I could provide you a more detailed answer if you can clarify which version you're on, or hopefully this can get you going in the right direction!


add link programmatically to views field Drupal 7

Instead of coding why you don't use views fields.

Add the title and node id fields to the view.
Exclude them from display.
Add a global: custom text field.
Use tokens to print the HTML you want.

It should look like this:

[title]


How to hide a published Taxonomy page unless you're an authorized user?

To get tac_lite to work covering your question on a vanilla Drupal 7, one has to do the following:

Enable at least one tac_lite permissions scheme for the target vocabulary, in your case, "Manitoba" (scrsht.1)
Configure the scheme to allow 'viewing' for authenticated users (scrsht.2)
Create a node, e.g. an article and assign a term to it. Authenticated users should be able to see it (scrsht.3), anonymous not (scrsht.4).

Hope that helps!


Overwrite an empty field value on node / rendered entity

You might consider overriding an appropriate Twig template, something along the lines of {% if content.field_caption %} {{ content.field_caption }} {% else %}} default text {% endif %}


How to query external database for Count

You need to use ->addExpression() instead of ->fields()


You can use References module (https://drupal.org/project/references) and create Node Reference field, which will allow multiple values.

Steps:

Create the node reference field
Add Node:nid to the views contextual filters to know which node you are on
Add related content field to the views Relationships to filter out the correct related nodes


Collapsable, grouped field in View (Bootstrap, D8)

I solved it using Bootstrap. I hid the field, then added it one more time. Then I rewrote the second field like this:

Show members

{{ field_research_group_ext_members }}
{{ field_connected_user_names }}


Path (alias) does not work after migration, nor Content view

Actually, I have just found out it was due to the i18n setting of the node and site.  The language of the node was set to be ja (Japanese), correctly.  Probably because of that,

http://localhost/info/legacy.html

does not work (HTTP 404), but

http://localhost/ja/info/legacy.html

does display the node imported.

Similarly, the Content manager does not display the node in the default-language mode (English) /admin/content, however it does display the newly imported node in Japanese /ja/admin/content.  I should note I allow all the URL (Path prefix), Session, User, Browser in the language configuration (/admin/config/regional/language/configure) in my environment.

My browser's HTTP request, when I test, is

"Accept-language": ja

So, I expected when I opened

http://localhost/info/legacy.html

it would open the node in Japanese, following the browser's request, as opposed to 404, but it does not, apparently.

Hmm, I guess it is likely my understanding of the i18n handling in Drupal is not sufficient.  Anyway, I think this can be solved with the redirection module in Drupal, after investigating and finding out how to set it up during migration.  I didn't want the default URI to be something like node/21, but if it is ja/info/legacy.html, I am fine with it, as long as the redirection works.

[Edit: 2014-10-06]
I have figured out why.  In my i18n setting of Drupal, URI-path-prefix is checked and is given the highest priority, where English is default with its language-code for path-prefix being undefined.  Hence,

http://localhost/info/legacy.html

is the English version of the content, which does not exist.  When I define the language-code of English (en) for path-prefix, then the access to the URI brings up the Japanese version, if my browser's preferred language is Japanese (and the i18n of the site is configured to accept the browser's preferred language at the lowest priority), because the URI is not any more specific for the English version.

Another note is the redirection module works only when redirecting to a node URI [or path without the language-code prefix (added on 2014-10-11)].  The redirection to, for example,
/ja/info/legacy.html
does not work well, as it can bring up the path of

http://localhost/ja/ja/info/legacy.html

in some cases.

[Edit: 2014-10-11]
The whole point (and much more) is covered and summarised in the document published at drupal.org:  https://www.drupal.org/node/2354755


How to add a new row to the registration form?

Without using LoginToboggan also you can achieve you requirement.

Goto Configuration > Account settings > Manage Field and then add field.
In field configuration Display on user registration form checkbox.


This question was asked on the Drupal forums here.

If your frontpage is a node you can control access using the Content Access module.

If your frontpage is being generated by a custom module then you can do it by modifying the hook_menu implementation in your module. You can change the access_callback to the value TRUE so that everyone can access that page. See this related question

  "access callback": A function returning TRUE if the user has access
  rights to this menu item, and FALSE if not. It can also be a boolean
  constant instead of a function, and you can also use numeric values
  (will be cast to boolean). Defaults to user_access() unless a value is
  inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
  items can inherit access callbacks. To use the user_access() default
  callback, you must specify the permission to check as 'access
  arguments' (see below).

See the full documentation here.


Have module .install create a table in a non-default DB

To my mind, the entire purpose of hook_schema is to build the Drupal schema. If you need/want to create tables outside of Drupal, it seems like just using PDO in a hook_install() and hook_uninstall() implementation might be the way to go. Can you explain your use case a little bit more?

All that said, I don't see an obvious reason for your code to fail.


Drupal behaviors not attached after Ajax load

Behaviours are fired after a Drupal AJAX call - a call to jQuery.ajax isn’t the same thing.

Fortunately it’s easy to attach them yourself, just add this in the success callback when you’ve finished manipulating the DOM:

Drupal.attachBehaviors();


Drupal shows ?? instead of special characters with oracle

Check you are using UTF8 character set in Oracle database, and in apache config.
For data in Oracle db that is not UTF8 be careful if you need to convert, you need to identify what the original characterset is and the best way to convert to UTF8.

  The general rule of thumb is that if you are using UTF8 all the way
  you should not see those question marks in the browser.

Take a look here for Oracle UTF8 conversion info: https://stackoverflow.com/questions/8239250/how-to-configure-utf8-character-set-in-oracle


Drush error when running dmu-analyze to update drupal modules

One of the modules in your installation is incorrectly using references to services without quoting them.

e.g.

[@container.namespaces]

instead of the valid:

['@container.namespaces']

The error message doesn't provide enough details to be able to identify which module is causing the problem. It's going to be a contrib/custom one, though, so check the .services.yml file for the extra modules you have installed and you should find the culprit. It's likely to be under a service whose name begins with plugin.manager..


Where is the best place to insert additional logout functionality?

Instead of modifying core, you can implement hook_user() in a custom module. Then you can check the $op parameter to see if it equals "logout". This code will run whenever a user logs out, regardless of what menu item or link they click to log out.

Note that this is different between Drupal 6 and 7. This question was tagged Drupal 6, but if you're using Drupal 7, or plan to later, be aware that this hook was replaced with hook_user_logout().


The problem was caused by Domain Access Module. Since i didnt needed it anymore, i deactivated it.