No menu link is working after the website is deployed on hosting server

When I move a site to the production environment and can only access it using an URL as you describe, I have to disable Drupal's 'Clean URLs' functionality (admin/config/search/clean-urls) in order for menu links to work properly (and probably clear the caches afterwards).

Edit:

In the documentation on configuring clean URLs, I found that changing the RewriteBase setting in the .htaccess file is the solution for me to have clean URLs once again.

So, in your case it probably should be: RewriteBase /~HostingServerUserName/foldername


Send mail once content approval of custom content types

It's kind of hard to understand what you want but I think you should use the "Rules" module, which allows you to "to define conditionally executed actions based on occurring events":
https://drupal.org/project/rules


If that string is run through the t() function (which is probably is) and you don't want to use  String Overrides, then you can update your settings file.

For Drupal 6, putting this in your "settings.php" file should work.

$conf["locale_custom_strings_en"] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

In Drupal 7, you would change it to

$conf["locale_custom_strings_en"][""] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

However, I am not seeing the string "Please Select the Valid File Format" in any of my D6 installs, and that is not the message I get when try to upload to a CCK filefield with the wrong file type or the MIME type doesn't match the file extension.


Webform, let data expire after a period of time

Try the Webform auto-delete  sandbox project.

  Automatically delete webform submissions after a set period of time.


Disable ajax history except for some views

My bad, Views_ajax_history is such a minimalist module in fact !

To avoid hacking it, hook_js_alter did the trick :

/**
 * Implements hook_js_alter().
 */
function example_js_alter(&$javascript) {

  if(arg(0)!='taxonomy' ) {//my products views are taxonomy lists

    $history_js = libraries_get_path('history.js') . '/scripts/bundled/html4+html5/jquery.history.js';
    $views_ajax_history = drupal_get_path('module', 'views_ajax_history') . '/views_ajax_history.js';
    $views_ajax_history_2 = array('viewsAjaxHistory' => array('onloadPageItem' => isset($_GET['page']) ? $_GET['page'] : 0));

    unset($javascript[$history_js]);
    unset($javascript[$views_ajax_history]);
    unset($javascript[$views_ajax_history_2]);

  }
}


How to use taxonomy vocabulary with terms and children using views module

You are probably looking for the Simple Hierarchical Select module.

From the module's page:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

  Unlike Hierarchical select this module provides a simple widget for
  taxonomy terms only. As an addition Simple hierachical select works
  as Views exposed filter.

The Hierarchical Select module is still in development for D7 and the Views integration has not been ported, so SHS is the best choice at the moment.


How to use an image styled by ImageCache Actions as background for a node?

I would create some dynamic CSS on the fly and add it to the head of the document.

$styled_image_path = image_style_url('style_name', $image_path);

$css = '
.node {
  background-image: url(' . $styled_image_path . ');
}
';

drupal_add_css($css, array('type' => 'inline'));

You can add this to a hook_preprocess_node() to check for a specific node before adding to the page.


The referenced nodes are inside the list and you can get the first list item with .0, the referenced node with .entity and then the first field value:

For example if you are in a page or node template:

{{ node.field_reference.0.entity.field_in_referenced_node.0.value }}

You can ommit .0 in both cases, when you only want to get the first value.

Other examples could look like this, but your question is unclear exactly where you are:

{{ item.content['#item'].entity.field_in_referenced_node.value }}
{{ elements['#items'].0.entity.field_in_referenced_node.value }}

Edit: Counting the items in multivalue fields

{{ node.field_reference.getvalue|length }}

You can't use count() in twig, because this is not on the whitelist for allowed methods. This uses getvalue() to get the array of the field and then counts the array keys.


Don't use JavaScript validation because some people can disable JavaScript in the browser and you're validation will fall!

If you want custom validation will be better if you will use additional validation for your form (custom code)


How to check if a menu exists programatically in Drupal 8

A menu is a config entity, which means you can use standard entity API to load it.

\Drupal\system\Entity\Menu::load() or \Drupal:entityTypeManager()->getStorage('menu')->load()


After viewing the HTML source to get key/value pairs I've managed to do something similar to the above with the following code:

<?php
/**
 * Implements hook_enable().
 *
 * Create a field. Fields can be created without any needs to attach them to
 * entities.
 */
function youtube_carousel_enable() {
  $field = array(
    'field_name' => 'ytcarousel_field',
    'type' => 'link_field',
    'cardinality' => -1
  );
  field_create_field($field);

  /**
  * Bind field to a entity bundle.
  */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_create_instance($instance);
}

/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */
function youtube_carousel_disable() {
  $instance = array(
    'field_name' => 'ytcarousel_field',
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}
?>

The cardinality controls have many instances the value can have, "-1" is unlimited.

'cardinality' => -1

The title attribute is controlled via the instance not the field itself, I believe, and it uses text based values rather than numeric.

'settings' => array('title' => 'required')


Custom error page: The path is either invalid or you do not have access to it

When you go to admin/config/system/site-information to enter the path in the field Default 404 (not found) page, you don't have to add .html just write errors/404 and it will work.


Field Collection is a good option if the images will not be re-used across multiple Video content types. If you need to re-use the Images (and their field values) across multiple Video nodes, another option is to create a separate "Image" content type and use the Entity Reference module to link the Image nodes to the relevant Video nodes.


How to render a static html from a drupal module

The easiest way is to create a template file and use hook_theme

Put your html in a html-page.tpl.php in your module directory.
Use following code to render the html template in your page.

After adding the code make sure you clear your Drupal cache.

function my_static_page() {
  $html = theme('html_page');
  return $html;
}

/**
 * Implements hook_theme().
 */
function your_module_theme($existing, $type, $theme, $path) {
  return array(
    'html_page' => array(
      'template' => 'html-page',
    ),
  );
}


kiamlaluno gave the perfect hint. Without actually using any additional modules, you can just use tabbing for multiple views, each with different grouping.
Thats how you do it:

Create a new view as a page
Page settings -> Menu -> Path -> e.g. /publications
No Menu link

Add a new page to the view with the same credentials like the one above (in my case grouping by field_year) - IMPORTANT
Page settings -> Menu -> Path -> e.g. /publications/by-year (keep the root path)
Page settings -> Menu -> Default menu tab
Parent menu item -> Default menu item

Add a new page to the view with different credentials (in my case grouping by field_type)
Page settings -> Menu -> Path -> e.g. /publications/by-type (keep the root path)
Page settings -> Menu -> Menu tab

Finally there are three pages:

In the frontend it will look like this:

I hope this steps help you a bit. In this way, you can create as many views as you like.

Thanks to the community again.


Seems you're looking for the PDF module

Uses HTML5 to display PDF files if users don't have pdf plugin for their browsers.
With this module you can use pdf.js to display PDF file all the time or only use pdf.js when visitors don't have pdf reader plugin.


How to search and replace content type (system)name in database for product types

It appears that commerce kickstart uses features in order to create the demo store, and that the content types cannot be deleted. Apparently they are recreated by features when the machine name of the content type is not present any more.

See https://www.drupal.org/node/1796468


How to find out what modules are adding links to a menu?

You're after module_implements(). It will allow you to specify the hook (in this case 'menu') and then get an array of module names back.
Of course, you'll still need to manually open the files to check, but you should be able to narrow it down from the menu path and title.

It might be worth flushing the caches too.


empty ajax block not loaded on cached page

My solution was to create a view where I displayed random node element (i.e. title) in a block and in the same view I attached the attachment display to the block, which contains the fields that should sit in ajax block. Finally I hid the block with css rule. This way the block get's rendered in theme.


How to prevent users from uploading the same file (image) multiple times?

In pseudo/quick code, this is how I would approach it.  In a custom module...

Create a table in the db, with two columns, fid and md5.
Each time you create a file, check if the md5() of whatever you consider unique is in that db, eg:

a.  select fid from TABLE where md5 = ab3783ea6c83bcd9383eef778

b.  if fid then oops, there already appears to be file blah blah blah

c.  otherwise
Store that file's fid and md5() in that table.

You could put all this logic in the validation hook when you are creating the image content.  You could even set up roles that are able to override it, etc.

Now, to the md5()ing of things.

Filename is easily changed and I don't think it is really sent to drupal anyway--but instead crafted there after the fact--so do you really want to use it?
Content of the file might be a better approach.

So, md5 could be populated with a quick md5_file(PATHTOFILE).

Now, let's say you wanted to have an option of doing this system wide or per user, eg, you don't want one user uploading multiple copies of one image or you want to have only one exact image uploaded systemwide.

Just add another column uid to the table above and check it as well, eg:

select fid from TABLE where md5 = ... and uid = $user->uid

Anyway, these are just my quick thoughts after the morning's first espresso here in D6land.  Maybe D7 has some of this already built into it and I am once again reinventing that wheel :)


What is causing Views to consistently but intermittently not find a view provided by the Advanced Forum module?

It sounds like you found the right answer from the IRC.  "Consistently intermittent" in my experience is when there are two sources filling the cache.  Most common is when you have a development site and a staging/production site on different code bases but same database.  The drupal-provided caches that I have read code for connect to the database, so routing/function information that is cached will cross contaminate.  Hitting the admin/modules page will refresh the module cache and locations, hitting the admin/views listing page clears your error because it refreshes the site's understanding of views from the perspective of your site instead of the perspective of whatever is conflicting with you.

If you have server admin ability, change the password to your site's database and the password in your settings.php, and see what breaks.  Your listings should stop being corrupted and what is tampering with them should break ... unless it is directly connected to your site and using your settings.php file.

Also, check to make sure there are not multiple installations of the views module in your docroot.


How do I have menu linked content not on main page?

When you create the Content, be sure to uncheck "Promoted to front page" in the option menu shown at the bottom, under Published options. See image.

If you want this option by default for a specific content type (for example, for Articles) you will need to go to Structure > Content types and edit that content type's Publishing options to uncheck Promoted to front page. This will become the default option when you create a new Article.


Using ajax to process textfield in Drupal 7

change it to and then try again.

$form['license'] = array(
  -
  -
  '#ajax' => array(
    'callback' => 'license_fillin_js',
    'event' => 'change',
    .
    .
    .

  ),

As an example you can check this link


Not possible at the moment with Webform, but hey, do you really need a webform module to achieve what you need?

You could create a custom content type with any fields set you can imagine (single and multiple) and give users permission to create nodes of this type. So this way you'd be able to gather form submissions as separate nodes.


Best hook to use to save a new node when a node is saved

There is no hook which is called AFTER the node is saved. No POST-SAVE hook.

But calling node_save within hook_insert actually works. The warnings were false:

So I ended up with something like:

function MYMODULE_node_insert($node) {
  if ( $node->type == 'blog_post') {
    MYMODULE_insert_statuspost($node);
  }
}

function MYMODULE_insert_statuspost($n) {
  global $user;
  $node = new stdClass();
  $node->title = "New blog post $n->title";
  $node->type = "statuspost";
  node_object_prepare($node); /* Sets some defaults.
     Invokes hook_prepare() and hook_node_prepare(). */
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->body[$node->language][0]['value'] =
    "New blog post: " . l($n->title, "node/$n->nid") . " has been posted");
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 2; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Status post with nid " . $node->nid . " saved!\n");
}

Here is a full commented code to programatically create a node.


How to add data attributes to view list  tags?

Override style output template file using theme information in views.....

Override file with below code..

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */
?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li data-attr="" class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>


How does one change the machine name of a Feature?

Use this procedure to rename a Feature module:

drush pm-disable old_feature_name
drush pm-uninstall old_feature_name
rename the Feature module folder
rename the .info file
rename the .module file
rename any hook prefixes
drush pm-enable new_feature_name


How to display a view on user's profile page?

Looks like you may be looking for Viewfield module:

  Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Install it, and add viewfield to user profile just like you would add any other field.

Alternatively you can create a block display and choose to display only in /user/* paths, using contextual filters. This is the way I like less, as it is more prone to fail if someone will redesign URL system on page, or choose to display users in a way other than default.

Exact steps

As described by OP in comment below:

  I created a view and added a contextual filter (Profile: User UID => Display all results for the specified field => Specify validation criteria/Basic validation);
  created a view field in the Main Profile page; and
  selected the token [profile2:user:uid] from the placeholder tokens' list and checked the box "Always use default value".


Try the Popup module. There is a version for Drupal 6.

  The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.


Using chinese character in drupal_mail_send() generates unreadable character

Try this:

drupal_mail_send(utf8_encode($message));

As Oswald implied, this is a character encoding issue.

If any data is coming from, or going to be stored in, the database, also make sure your database character encoding is utf8_general_ci.


URL alias to access user profile as admin

You can create aliases using the Pathauto module.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

There are various tutorials of this module you can watch.


Create a Form in a Block using API that sends captured data to email

Use simple news module which will give you lots of e-newsletter features out of the box.

For new features you can extend above module to suit your specific requirements.


Can drush make fetch dependencies for a newly added module, without using it to build the whole site?

Yes, it is possible. Just run the makefile on the current codebase, and specify --no-core option from the drupal root:

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example

Here's the log of a test I did:

$ drush dl drupal
$ cd drupal-7.28/
$ drush dl mailchimp
  Project mailchimp (7.x-3.1) downloaded to /tmp/drupal-7.28/sites/all/modules/mailchimp.

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example
  Make new site in the current directory? (y/n): y
  Beginning to build sites/all/modules/mailchimp/mailchimp.make.example.
  libraries-7.x-2.2 downloaded.
  mailchimp downloaded from https://bitbucket.org/mailchimp/mailchimp-api-php/get/2.0.4.zip.

$ ls sites/all/libraries/
  mailchimp
$ ls sites/all/modules/
  libraries  mailchimp  README.txt

If any of the projects/libraries declared in the makefile already exists, it will be overwritten.


Symfony's getQueryString method doesn't return modified query parameters

Symfony's Request object has a query property that is of type
ParameterBag, this maintains an iterable list of parameters.  The ParameterBag however is not directly translatable to a query string.  This causes issues when trying to use the getQueryString() method after modifying the ParameterBag parameters.

Solution 1 - Create a new query string:

   $request = \Drupal::request();
   $parameter_bag = $request->query;
   $parameter_bag->remove('destination');

   // This has to be http_build_query() because
   // \Drupal::request()->getQueryString() returns the original query string
   // but here we need the modified query string (without destination).
   $query = http_build_query($parameter_bag->all());

Solution 2 - Update all global variables:

    \Drupal::request()->query->remove('destination');
    \Drupal::request()->overrideGlobals();
    $query = \Drupal::request()->getQueryString();

Reference to overrideGlobals()

The main issue is that getQueryString() returns the global server variable query string which doesn't reflect changes to the parameter bag.  So editing the parameters is not as straight forward as it used to be.  We either have to build a new query string or override ALL global variables.  In my particular use case I thought that overwritting all globals was too wide reaching and it would overwrite any changes that other modules implemented that our specific code has no control over so I went with solution 1 above as it is generally a safer piece of code to implement.

My two options for solving this the right way is that:

1) ParameterBag either needs a method to build a query string

2) The request object needs to be able to return modified query parameters.  Probably by deprecating / defaulting the existing function to returning the output of a new function called getQueryStringOriginal() and creating another new function called getQueryStringModified().


How to attach browser-specific stylesheets in D8?

I think this'll do it in Drupal 7, it should be the same for Drupal 8:

$build['#attached']['css'][] = array(
  'type' => 'file',
  'data' => $path_to_css,
  'options' => array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE,
    ),
  ),
 );


I recommend separate this from Drupal. I mean if you just want a list of products so write an external application to prepare a xml format of this list and feed it to Drupal.

You need install PHP PDO_OCI to make connection from PHP application into Oracle.

Drupal has an Oracle Driver but I recommend external application instead


Drupal Commerce: Theming the Add Products form (Bulk Production Creation)

I have figured this out.

Step 1):
Find the ID of your form.
To do this, view the source of the form and search for "form" keep on searching until you see a field like this:

<form enctype="multipart/form-data" action="SOME_URL_HERE" method="post" id="commerce-bpc-create-bulk-form" accept-charset="UTF-8"><div>

The id you want is in the id="" string

You need to tell Drupal where to find your tpl.php file.
In template.php add the following:

function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'INSERT_ID_HERE' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--TEMPLATE_NAME',
            'render element' => 'form',
            ),
    );
}

So if you were themeing a  Drupal Commerce Bulk Product Creation form, your code would look like this:

function YOURTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'commerce_bpc_create_bulk_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/add/node--add--bpc',
            'render element' => 'form',
            ),
    );
}

3) Create a tpl.php template file and save it in the appropriate directory.
In our example, the file is called node--add--bpc.tpl.php and is saved in templates/add

4) In your tpl.php file, insert variables for the fields on the form. Here is a list of the most common fields:

<?php print drupal_render($form['product']['sku_fragment']); ?>
<?php print drupal_render($form['product']['title_fragment']); ?>
<?php print drupal_render($form['product']['commerce_price']); ?>
<?php print drupal_render($form['submit']); ?>
<?php print drupal_render($form['static_values']['field_YOUR_CUSTOM_FIELD']); ?>

5) At the end of the tpl.php file, put the following code:

 <?php print  drupal_render_children($form) ?>

It's very important you put this code, or you will get errors when trying to upload images.

6) The code in step 5, might print out fields you do not want. So you to have unset these fields. Here is a list of the most common fields to unset.

<?php unset ($form['product']); ?>
<?php unset ($form['combinations']); ?>
<?php unset ($form['title']); ?>
<?php unset ($form['static_values']); ?>
<?php unset ($form['description']); ?>

You put all this code on a line before:

 <?php print  drupal_render_children($form) ?>

7) If you find that any of the steps don't work, be sure to flush your cache. You can do this at: yousite.com/admin/config/development/performance


Create a commerce product and add it to cart using Services

Here's a link to the Commerce service's README.txt which includes a bit more detail on what kind of abilities it brings out of the box.

  The following grid indicates what callbacks have been defined so far
  out of the current target set of resources:

Resource         | Index | Retrieve | Create | Update | Delete
-----------------|-------|----------|--------|--------|--------
product-displays |   Y   |    Y     |   -    |   -    |   -
products         |   N   |    N     |   -    |   -    |   -
carts            |   N   |    -     |   -    |   -    |   -
orders           |   N   |    N     |   N    |   N    |   N

  The additional relationships and targeted actions are slated for
  development:

  product-displays: products products: add to cart carts: empty, convert
  orders: payments

So then the question is: Can you do what you want with commerce_services?

Can you create a product? Not according to the README

Can you add a product to a cart? Not according to the README


How to alert users when new content is added via email and/or text message?

Have a look at my answer to "How to send an SMS message when a Webform is submitted?", which is a variation of your question here. It describes how you can use the Rules module to get this to work. In your case just use a Rules Event like "after saving new content", and optionally add some appropriate Rules Conditions to better fit your exact needs.


Render form element of type text_format, keeping WYSYWIG format

The solution is render it using the #type => processed_text. That's it, then you will see the element renderd keeping the format used in WYSYWIG.

$elements = [
  '#type' => 'processed_text',
  '#text' => $data,
  '#format' => 'full_html',
  '#langcode' => 'en',
];


programmatically getting custom node belonging to a term

This might be helpful

How to use EntityFieldQuery

It works great for me. As far as the other question is concern, there are many ways of doing this. the simplest would be below, provided that you are accessing link in your question:

<?php
    $arg0 = arg(0);
    $arg1 = arg(1);
    $arg2 = arg(2);

    echo $arg0; //this will echo 'taxonomy'
    echo $arg1; //this will echo 'term'
    echo $arg2; //this will echo 2 (term ID)
?>

Info about arg() can be found here: arg()


You can create a Rule with the event "User account page is viewed". Then, you can add the required condition as follows:

So you select the current user as the user that should be Flagged and select the visited user as the person that should have done the Flagging.


There is two problems:

You form method is GET so form submit action will be the actual path with the params like node/10?search_location=kathmandu&op=Search&form_build_id=form-s4JrAE91au_BWakeBLD7RUsktRTBXFCpJQrnHGiOjg8&form_token=ES2W0RDpLOnWZUsXOnP4f9gBmSXcYLvqhO9uy1ee4Vk&form_id=d7_exp_form
The second one you set your action to '/buy/{_val_}' so automatically after the submit you will redirect to /buy/{_val_} without invoke the submit handler.

Suggestion:

If you want to invoke the submit handler remove the $form['#method'] and $form['#action'], so your form will be with post method and your submit handler will invoked.
Remove only $form['#method'] and create menu entry /buy/% and you can do your submit handler logic in the /buy/% callback function.


How can I recreate the default frontpage view?

Find the file /core/modules/node/config/optional/views.view.frontpage.yml

Next import its content by pasting this at /admin/config/development/configuration/single/import


Proper way to add external JavaScript file

It's actually pretty well documented: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#external

MYTHEME.libraries.yml (or MYMODULE.libraries.yml)

amazon-onetag:
  js:
    //z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789: { type: external, attributes: { async: true } }

MYTHEME.theme (or MYMODULE.module)

function MYTHEME/MYMODULE_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'MYTHEME/amazon-onetag';
}

Now we could start to discuss what is "the proper way"?

As Amazon wants it directly before the closing body tag (which is irrelevant in my experience) and as they also put a nice container with an ID around the script (which very likely is irrelevant as well) you could also simply copy the whole snippet into your (custom or sub-)theme's html.html.twig directly before the closing <body> tag.

But that would at the same time take this script a little bit out of Drupal's influence to handle, preprocess and order all scripts according a desired logic. And it can become a little bit more difficult to maintain in the end.


Which module supports select or other option for Term reference type?

There is a sandbox module available that adds this functionality:
https://drupal.org/sandbox/cameronbprince/1895832

Also there is an issue in the issue queue to incorporate this into the module itself: https://drupal.org/node/1716764

Alternatively, the hierarchical_select module also provides the option to let users add new terms to vocabularies on the node edit form.


Did you customize this page: http://yoursite.com/admin/config/media/file-types/manage/image/file-display/colorbox ?

You should select a display mode for thumbnail (small image) and Colorbox (full size image).
Once you have updated this, clear caches or edit your content and save it again. Otherwise, your changes won't have any effect.


Disable autocomplete entity reference field

There are a couple of options on how to do this.

1) switch the field settings reference method from "default" to "view", and create an entity reference view where the label is the nid

2) create a field widget plugin based on  EntityReferenceAutocompleteWidget.php in your custom module, and replace the form element

'#type' => 'entity_autocomplete',

with a text field.

 '#type' => 'textfield',

Below is a custom widget that does this.

Most of the changes are within the formElement method, but I added some validation to check if the entity is a valid entity of the correct type within the allowed bundles.

namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
 * Plugin implementation of the 'entity_reference_textfield' widget.
 *
 * @FieldWidget(
 *   id = "entity_reference_textfield",
 *   label = @Translation("Textfield"),
 *   description = @Translation("A text field for entity reference"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class EntityReferenceTextField extends WidgetBase  {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => '60',
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['size'] = array(
      '#type' => 'number',
      '#title' => t('Size of textfield'),
      '#default_value' => $this->getSetting('size'),
      '#min' => 1,
      '#required' => TRUE,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $operators = $this->getMatchOperatorOptions();
    $summary[] = t('Textfield size: @size', array('@size' => $this->getSetting('size')));
    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }
    else {
      $summary[] = t('No placeholder');
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $values = $items->getValue();

    $element += array(
      '#type' => 'textfield',
      '#default_value' => isset($values[$delta]) ? $values[$delta]['target_id'] : NULL,
      '#size' => $this->getSetting('size'),
      '#placeholder' => $this->getSetting('placeholder'),
    );

    return array('target_id' => $element);
  }

  /**
   * {@inheritdoc}
   */
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {

    if (empty($element['target_id'])) {
      return FALSE;
    }

    // Do some validation, to make sure this a real entity within
    // the list of allowed bundles.

    $settings = $this->getFieldSettings();

    $storage = \Drupal::entityTypeManager()->getStorage($settings['target_type']);

    $entity = $storage->load($element['target_id']['#value']);

    if (!empty($entity) && in_array($entity->bundle(), $settings['handler_settings']['target_bundles'])) {
      return $element['target_id'];
    }
    else {
      $form_state->setError($element['target_id'], t('This is not a valid entity reference id.'));
    }

    return FALSE;
  }

}


How do you keep the login block on the same page when validation fails?

You are looking for Ajax Login/Register module, it will not redirect on error, instead the login and register forms can validate using ajax and stay on same page.

  This module provides a smooth way for the user to login, register and
  request new password via AJAX at any Drupal site.

Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


How can I access raw field values in a view template?

Since you are using it in views-view-fields--styles.html.twig, it would be {{ fields.field_color.0 }} or {{ fields.field_color.content|striptags }}.


The markup element strips some HTML tags from the output. It is much better to just use the following code.

$attr = [
 'attributes' => [
   'class' => ['use-ajax'],
   'data-dialog-type' => 'modal',
   'data-dialog-options' => Json::encode([
     'width' => 700,
   ]),
 ]
];
$link = Link::createFromRoute($average, 'resume.grade_detail', ['uid' => $id, 'courseid' => $courseid], $attr);

return $link->toRenderable();


Rules: Steps to trigger a rule when a field is updated

I figured what my issue was. I had an earlier version of the CCK module (6.x-2.1) and once upgraded to the latest version (6.x-2.9) the rule behaves as expected.

Thanks to jordojuice for pointing me in the right direction.


Cron has been running for more than an hour and is most likely stuck, problem is persisting

There are too many factors that can stop the cron from being executed.

To see where exactly it breaks, open includes/module.inc and at the line 496 (function module_invoke_all()) add this:

foreach (module_implements($hook) as $module) {
  $function = $module .'_'. $hook;

  // This is the line you should add:
  if ($hook == 'cron') watchdog('cron debug', "Cron is processing module: $module");

Then run the cron from admin. The last module to be called is the one which breaks. Look further into the implementation of hook_cron() of that module and debug further.

This is inspired by this comment.

See this discussion.


I've been using the Advanced Poll module, and it seems to handle what I need.  It lets you display the poll as a block, but doesn't have an option to get rid of the author info.  It looks like the best one so far.


How to get a list of fields that are used in entities?

I would recommend EntityFieldManager::getFieldMap. The EntityManager is only a service to provide functions from other classes.
From documentation:

Return value
array An array keyed by entity type. Each value is an array which keys are field names and value is an array with two entries:

type: The field type.
bundles: An associative array of the bundles in which the field appears, where the keys and values are both the bundle's machine name.


I haven't used mapping yet because of the performance contraints of showing more than a few hundred points on an openlayer map.

Leaflet Marketcluster promises to solve this problem:

  All Leaflet maps will now be using clustering out of the box.


You need to add a 'Term reference' field on the relevant content type:

Go to http://mysite.com/admin/structure/types/manage/page/fields (where 'page' is the name of your content type).
Add a new field, using 'Term reference' as the field type.
On the next page, choose the vocabulary you want the content type to reference.
On the page after that, choose specific settings for the field.

Next time you go to add/edit a node of that content type, you'll be able to choose terms from your selected vocabulary.


How to set configuration value for drush site install?

It is not possible to override this since the install_check_translations() has this hard-coded.


Drupal pages translated, but both translated and untranslated pages showing up on view

ANSWER

Heya, found the answer.
The view needs to have the correct filter added to it.

Go to Adminstration->views
Click the plus button next to the Filters section.

You will then see a list of filters pop up.
Find "Node Translation: Language. Add it.
You will then see a section that asks what you want to do with the filter.

Choose "Is One Of: Current User's Language"
That is it. Your views should now NOT contain multiple translations of the same document.


<?php
$block = module_invoke('module_name', 'block', 'view', 0);
print $block['content'];
?>

Try including the view block.


Is it possible to set the user picture as the value of an image field from a node?

A quick grep through privatemsg shows that it is using theme('user_picture'...) so you should be able to copy user-picture.tpl.php from "drupalroot"/modules/user to your theme and edit it to your specifics...just flush caches :)


Best way to store custom commerce pane form data as part of an order?

I have had the same issue for some time with field collections and simply switching the panes on and off in the order entity was not doing the trick.  I ended up being able to work up a solution using order types.  http://drupal.org/project/commerce_order_types

In addition I want to mention that we used the following patch: http://drupal.org/node/1887812 so that commerce could recognize panes from different order types.  At this point your already there, its a simple process of switching order types and subsequent panes based on the order type.


Drush dl not working with PHP 7 and ubuntu 16.04

Sounds like you managed to install/configure PHP without the simplexml extension.

Install the php7.0-xml package with apt-get as follows.

sudo apt-get install php-xml

Also check the UI installer, if you're missing this, then you're likely also missing a bunch of other extensions link mbstring, gd and so on to install/use Drupal.


Is there a way to send emails when someone logs in?

A possible solution is to use the Rules module and create a custom rule like so:

Rules Event = After a user logs in.
Rules Action = Send an eMail.

That's really it (a kind of Rules 101 also if you want ...).

Here is a rule (in Rules import format) that should answer your question:

{ "rules_notify_about_login" : {
    "LABEL" : "Notify admin about login",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "New login",
          "message" : "Some user just completed a login to [site:name], located at [site:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The rule will be triggered (Rules Event) right after login was completed. For any user who does not have the role that matches "role id = 3" (= Rules Condition), aka for any user who is not an administrator, it will send an appropriate eMail to the admin user of the site.

If you have the Rules UI enabled, you can just import the above rule. As an alternative just use the Rules UI to create a similar rule from scratch.

Some further refinements you may want to apply to the above sample rule:

Adapt the value (=3) of the role id to fit your needs or just omit the Rules Condition if you want to perform the Rules Action for any role.
Include relevant info about the user who performed a login (using available tokens about that user).
Adapt the eMail subject and content to fit your needs.

PS: This answer applies to D7, though for D8 it should be similar.


How to implement a Subscribe block functionality?

Assuming this question is about D7 (at least), I wouldn't recommend using either of both modules anymore. This because these days there is a way better alternative available, which is the Message Stack. It consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of the modules' object orientated architecture).
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
Attention: the Message Stack is really amazing (I think), but also not obvious to get started with it. Especially if you try to do so only using site building techniques. But after you climbed this Drupal Message ladder, you might not ever want to consider building a site without it ... trust me.


How can I override the field in my view?

You need to have the field field_node_type called somewhere in your view to use it as a token in rewrite results for a field. Value that you're trying to use in rewrite results should be available within replacement patterns for the field you're trying to configure.


You'll need to provide a menu item and page that lists information about your entity type (typically settings). If you provide multiple bundles you'll need to provide a page for each bundle.

After you've done that you can add a simple snippet to your hook_entity_info similar to the foreach loop at the bottom of node_entity_info(). Specifying the 'admin' info under your bundles will provide the "Manage Fields" and "Manage Display" tabs for the path specified. Note that if you do not have multiple bundles, the only two required keys under the 'admin' section are 'path' and 'access arguments'

Keep in mind that the path referenced in the ['bundles'][BUNDLE_NAME]['admin']['path'] section has to exist and be defined elsewhere in your hook_menu. Field module will only take care of the two tabs and the pages they link to.


A good start would be here: http://drupal.org/project/domain_roles - This allows you to segment roles by domain. So you could create different roles, then assign those roles to users and by way of other access modules (Content Access could be useful but I'm not certain how it handles user entities) you could then limit the users to only their domains.

FWIW, this used to be done in Drupal 6 by way of the unstable module: http://drupal.org/project/domain_user_edit - Could be worth contacting the maintainer and seeing what you can do to take it over for Drupal 7 and on.


Arranging related nodes in doubly linked list

I've used the PrevNext module to accomplish a similar requirement.

Out-of-the-box functionality of this module would normally cover basic requirements in choosing the Previous and Next nodes such as:

Selection based on node created or changed date.
Selection based on node's nid field and title.
Additionally one has the ability to limit the previous and next to nodes of the same content type.

The nice part is that for any given node the previous and next nodes will be determined earlier and saved in the module's table by its own cron task (hook_cron implementation). Hence instead of determining the previous and next nodes (which could be costly in terms of time and space) while viewing a node and adding those to the page load a simple select query gets the predefined value.

Making call to prev_next_nid with your node id and operation as 'prev' or 'next' would provide one with the previous and next nodes' values which can themed to be displayed.

Additionally a hook hook_prev_next_nid is provided for developers to customize the function.

The caveats are that

if your logic for prev/next are not covered within the default functionality you might have to consider alternate means as there's not much option to cover such features as stated in the module's home page and
that the module showing up as dev version if you feel insecure by that status. However  it seemed to work pretty well for me and appeared to be stable.

Note that the prev/next index will be cleared and rebuilt from scratch when user changes settings per a node type in the admin interface.


How to fix menu links going below the fold?

You can create a new dropdown under the entity type ("Paragraphs types") that groups the links by first letter. Also, you can can change the weight of your item, and even move it out of being nested under configuration.

In the following example, we look for all the children of 'entity.paragraphs_type.collection' and we nest them under a copy of 'entity.paragraphs_type.collection' labeled with the first letter of the paragraphs underneath it.

function mymodule_menu_links_discovered_alter(&$links) {

  $links['entity.paragraphs_type.collection']['weight'] = 8;
  $links['entity.paragraphs_type.collection']['parent'] = 'system.admin';

  foreach($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.paragraphs_type.collection') {
      $first_letter = substr($link['title']->render(),0, 1);
      $links['entity.paragraphs_type.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.paragraphs_type.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.paragraphs_type.collection'
      ];
      $links[$key]['parent'] = 'entity.paragraphs_type.collection.' . $first_letter;
    }
  }
}

Here's the same alphabetical grouping technique on vocabularies:

    foreach($links as $key => $link) {
      if (!empty($link['parent']) && $link['parent'] == 'entity.taxonomy_vocabulary.collection') {
        $first_letter = substr($link['title']->render(),0, 1);
        $links['entity.taxonomy_vocabulary.collection.' . $first_letter] = [
          'title' => $first_letter,
          'route_name' => 'entity.taxonomy_vocabulary.collection',
          'menu_name' => 'admin',
          'parent' => 'entity.taxonomy_vocabulary.collection'
        ];
        $links[$key]['parent'] = 'entity.taxonomy_vocabulary.collection.' . $first_letter;
      }
    }

If you move the paragraph types to it's own drop-down, as in the example above, you'll want to style an icon for it.

.toolbar-icon-entity-paragraphs-type-collection:before,
.toolbar-icon-entity-paragraphs-type-collection:active:before,
.toolbar-icon-entity-paragraphs-type-collection.is-active:before {
  background-image: url(../../../../core/themes/stable/images/core/icons/787878/wrench.svg);
}

Here's my current version, which adds an "Add Paragraph Type" link:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function mymodule_menu_links_discovered_alter(&$links) {

  // Move paragraphs to its own drop down.
  $links['entity.paragraphs_type.collection']['weight'] = -7;
  $links['entity.paragraphs_type.collection']['parent'] = 'system.admin';
  $links['entity.paragraphs_type.collection']['title'] = 'Paragraphs';

  // Move taxonomy to its own drop down.
  $links['entity.taxonomy_vocabulary.collection']['weight'] = -7;
  $links['entity.taxonomy_vocabulary.collection']['parent'] = 'system.admin';
  $links['entity.taxonomy_vocabulary.collection']['title'] = 'Taxonomy';

  $links['entity.paragraphs_type.collection.add'] = [
    'title' => new TranslatableMarkup('Add Paragraph Type'),
    'route_name' => 'paragraphs.type_add',
    'menu_name' => 'admin',
    'parent' => 'entity.paragraphs_type.collection',
    'weight' => -100,
  ];

  // Break paragraphs into groups by starting letter.
  foreach ($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.paragraphs_type.collection') {
      $first_letter = substr($link['title']->render(), 0, 1);

      $links['entity.paragraphs_type.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.paragraphs_type.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.paragraphs_type.collection',
      ];
      $links[$key]['parent'] = 'entity.paragraphs_type.collection.' . $first_letter;
    }
  }

  foreach ($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.taxonomy_vocabulary.collection') {
      $first_letter = substr($link['title']->render(), 0, 1);
      $links['entity.taxonomy_vocabulary.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.taxonomy_vocabulary.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.taxonomy_vocabulary.collection',
      ];
      $links[$key]['parent'] = 'entity.taxonomy_vocabulary.collection.' . $first_letter;
    }
  }

}


How do I get a field rendered with translated labels?

You have the change the current config translation language. user_mail() has an example for that:

  $language_manager = \Drupal::languageManager();

  $language = $language_manager->getLanguage('en');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Do your thing here.

  $language_manager->setConfigOverrideLanguage($original_language);


How to perform views date calculations using global math?

You can try Views PHP which allows you to add a php code field to a View.

Otherwise, for a less "dangerous" solution, you can add a field to your content type for which you are creating the View, hide the field from the node creation form with css, hook_form_alter() or Display Suite, and create a Rule that calculates the new date when a user save new content. This field could be a Date field, or an Interval field if you want to store the interval between two dates.


Where is documentation for $entity->data property? I.e. $commerce_order->data

The data attribute is part of the Commerce Entity definitions, and I think this might be part of the larger de facto Entity API setup for contrib entities (don't quote me on that ;).)
If you want to find the documentation on properties and how they are handled you need to review the EntityController class, which each Commerce module has in its includes folder.
commerce_order.controller.inc#n135
/**
 * Unserializes the data property of loaded orders.
 */
public function attachLoad(&$queried_orders, $revision_id = FALSE) {
  foreach ($queried_orders as $order_id => &$order) {
    $order->data = unserialize($order->data);
}

The database layer automatically serializes, if I recall correctly. However controllers need to unserialize.
Hopefully this this question and other entity related items (also make sure to review hook_entity_info() implementation.)


What are the potential security issues when importing an entity type?

Who would you expose this feature to?

If it's users with one of the permissions listed on http://drupal.org/security-advisory-policy then you shouldn't really worry about the security implications because those users can already do a lot of malicious things to the site.

I believe that all field names and field values should be filtered appropriately already and Drupal handles filtering on output, so I don't see a need for something like xss filter during import.

The fact that you want to use JSON instead of a PHP array as the method to represent the code seems great: copy/pasting PHP arrays around is an easy way to create an arbitrary code execution problem.

There is more discussion about safe ways to offer this feature in an issue in the Views queue.

If this doesn't answer your question please leave a comment and I'll do my best to expand.


Restrict delete operation on a node referenced by another node

I believe you are invoking the hook incorrectly - according to the API page for hook_delete():

  This is a node-type-specific hook, which is invoked only for the node
  type being affected

Further disccussed on the Node API Hooks Page:

  Node-type-specific hooks: When defining a node type, hook_node_info()
  returns a 'base' component. Node-type-specific hooks are named
  base_hookname() instead of mymodule_hookname() (in a module called
  'mymodule' for example). Only the node type's corresponding
  implementation is invoked. For example, poll_node_info() in
  poll.module defines the base for the 'poll' node type as 'poll'. So
  when a poll node is created, hook_insert() is invoked on poll_insert()
  only. Hooks that are node-type-specific are noted below.


Context Module Rehashing Blocks Slows Website on Development

It turns out that my settings.php file had some custom code to completely disable caching for localhost machines, so that developers wouldn't be forced to refresh the cache all the time. Commenting out that code produced the performance that I expected


@redhatlab is correct about Drupal 7 not invoking hook_node_save(). If you need to be sure the status is effectively set to 0, without other modules to alter it, I would use code similar to the following one.

function mymodule_node_insert($node) {
  mymodule_update_status($node);
}

function mymodule_node_update($node) {
  mymodule_update_status($node);
}

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_insert' || $hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_update_status($node){
  if ($node->type == 'mytype' && in_array('simple', $GLOBALS['user']->roles)) {
    $node->status = 0;
  }
}

The code checks the roles assigned to the currently logged-in user. If you want to check the roles assigned to the node author, you should use $node->uid to load the user object of the node author. It is then generally preferable to check the user has a specific permission, rather then checking which roles are assigned to the user.

node_save() first invokes hook_node_presave(), and then hook_node_insert(), or hook_node_update(). The code I wrote would allow your module to be the last one changing the node status.

References

node_save()
hook_module_implements_alter()


How to set an openlayers preset to full screen?

On the OpenLayers project page, it says:

"Behaviors
Map interactions like popups, zoom controls, editing, and fullscreen can be added via the UI and extended by other modules."

I don't have a site up and running with OL or I'd check it.


Format 'Table Of Files' Field Display For Commerce Product Display?

I am not sure which tpl.php file you will need to override, but you can try to "inspect" for it using Devel Themer and then override it with your own tpl.php.

This doc page has some common overrides and you can kind of get the override pattern. I am guessing you will need to something like field--field-name--content-type.tpl.php.


Does it make sense to set a constant like THEME_IMAGE_DIR?

Dark side of the moon. Definitely ;)

Seriously though...any file that's included in every page load should be fair game to put this in. Personally I'd put it in a .module file so it's included before the theme level is even considered, but if you're only using it at the theme level then your theme's template.php file would be fine too.

As for whether or not it makes sense...if you find yourself repeating code of any kind then it makes sense to implement a constant/global/function to wrap around it. As the value in your particular case will not change in a single page load, a constant makes perfect sense to me.


How do the variables in .twig files work?

The site_logo block is available in the page.header region because that logo block itself is placed into that region using Drupal's block layout: mydrupalsite.com/admin/structure/block
Drupal's template/twig system is a set in parent and children type templates. So the page.header region/template may print {{ site_logo }} - but the contents of {{ site_logo }} are outputted in block--system-branding-block.html.twig
Blocks are placed in regions so you can't really access a block directly in page.html.twig unless you add it programmatically.
Probably what you are looking to do is place the site_logo block into the region which approximates the position you want it to be displayed. Then if you want to "fine tune" it you can override that regions template using the following naming convention:
my_drupal_theme/templates/region--[region].html.twig

E.g.
my_drupal_theme/templates/region--header.html.twig

Then maybe your region--header.html.twig file looks like:
<div class="my-custom-wrapper-class">
  {{ site_logo }}
</div>

What can be really helpful here is knowing the basics of twig template naming conventions - and also turning on "twig template debugging" which gives you template names you can use to override.
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates#s-enable-debugging
Just for completeness: if you did want to load the logo directly in your page.html.twig you could add it via a hook_preprocess_HOOK
@file my_drupal_theme/my_drupal_theme.theme

/**
 * Implements hook_preprocess_page().
 */
function my_drupal_theme_preprocess_page(&$variables) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $plugin_block = $block_manager->createInstance('system_branding_block', []);
  $variables['site_logo'] = $plugin_block->build();
}


I have made some progress on this. I downloaded the TinyAutoSave module from https://code.google.com/p/tinyautosave/ which I believe is more recent than the 'autosave' plugin included with TinyMCE 3.4.4. There may be updates in the latest version of tinymce, but I haven't checked. It seems the codebases have forked, however.

Anyways, I ended up removing autosave from the tinymce.inc file located in sites/all/libraries/wysiwyg/editors. I put tinyautosave/ into sites/all/libraries/tinymce/jscripts/tiny_mce/plugins.

The solution involved was to not use the 'restoredraft' setting, and use the 'tinyautosave' one instead. I have some strange way that builds the wysiwyg settings table but it basically does:

$settings['tinyautosave'] = array('tinyautosave' => 1);


You're never making it to your callback because you don't have your #ajax array defined correctly, callback should not be defined as a hashed key. Take a look at the Adding an AJAX event example on d.o.
This should work:
$form['content']['validate_client'] = [
  '#type' => 'button',
  '#value' => $this->t('Validate Client'),
  '#ajax' => [
    // Change the callback key and update your callback value.
    'callback' => [$this, 'clientValidateForm'],
    'event' => 'click',
    'wrapper' => 'validate-phone-number',
  ],
];

Also note that Jaypan is right, you can't define new elements in your validation callback so you'll have to change that too. You may want to set a $form_state value in your validation handler and use that to add your element inside your build method. You may also need to update the wrapper value in your #ajax definition to align with the other changes.


This can be solved by building a 'select' element with an option for each row id in the tableselect that gets an ajax link. Then we can add links to the tableselect row with '#markup' and use Drupal.behaviors to attach a function that sets the value of the select element and triggers its 'change' event. In the form building function, if $form_state['triggering_element']['#name'] is the new select element, $form_state['triggering_element']['#value'] is the one we want to process.

The select element could then be hidden and the in-row ajax links are still fairly clean. Of course this won't work if javascript is off.


Sounds like something you can do with Views Dynamic Fields. Unfortunately there's only a D6 release atm, but perhaps you can port the module to D7 when it seems to fit your needs.


Is it possible that a view list entities that are not related to other (like a not in (select ...) )?

Views is a simple query builder, it's UI doesn't really support this out of the box.

I recommend looking at Views Custom Conditions:

  This Views Custom Conditions module facilitates the site administrator
  to inject custom conditions into a views query. ‘Views’ is a powerful
  and highly flexible module that provides website builders with
  critical list making abilities. It generates a dynamic SQL query
  according to views construction for displaying data. So, adding a one
  more step to filter your data as per your requirement, this module
  will really be helpful.

  This module adds the condition specified by the site admin to any
  views where clause with the existing conditions implemented by views
  itself in conjunction with AND operator.

Also if you want to do custom calculations on Fields see Views Raw SQL or Views Calc.


how to extend FormBuilder::processForm from multiple API endpoints in one class

A. EntityFormBulder::getForm is just a shortcut for instantiating the form object, injecting the entity and building the render array. You can split this up:

  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = []) {
    $form_object = $this->entityTypeManager->getFormObject($entity->getEntityTypeId(), $operation);
    $form_object->setEntity($entity);

    $form_state = (new FormState())->setFormState($form_state_additions);
    return $this->formBuilder->buildForm($form_object, $form_state);
  }

B. You have to inject the entity before you can build an entity form, see the steps above.

C. _entity_form is for integrating an entity form in a route, then the route parameter is upcasted and injected into the form automatically, see How to Inject entity object in EntityForm

The best approach is C. (standard pattern) and refactor the OOP code.

BTW if you don't find a OOP solution or if it is too complicated then you could simply add a custom process callback to $form['#process'] in a form alter hook to all or specific entity forms.


unable to extract dumped files in .tar extention on my site

No. Tar is what's supported.

Downloading the files I generally feel is a pain though, I would encourage you to look at managing the features with Drush instead. It's often a lot faster as it mostly enables you to skip the whole download step.


You can use keywords from contexts when you override a title of a pane in Panels. Go to Contexts in the Page Manager UI. The summary of contexts displays the available keywords.

In your situation you may want to add a new context, the node that you want your pane title to be pre-populated from. You can select the node ID, and the same node will always be loaded.

If it's not always the same node that you want to use, but e.g. a reference field in your already loaded node defines it, you can use a relationship to create the appropriate node context.


Checkboxes in a simple form are not displayed

You code works for me. I used the exact following code and got checkboxes in my form using Drupal 8.3.4:

$form['container'] = [
  'categories' => [
    '#title' => t('Select a Category'),
    '#type' => 'checkboxes',
    '#options' => [
      1 => t('Option 1'),
      2 => t('Option 2'),
      3 => t('Option 3'),
    ],
  ],
];

return $form;


Restrict publishing to certain Taxonomy Terms

I have found a solution with the Rules module.

Here's how I managed to get it to work:

1) install the module
2) activate it
3) GO to /admin/config/workflow/rules and add a new rule
4) set post type to my post type
5) Added an OR condition
6) Under that OR condition added Data Comparision to [node:field-section:tid] to my term's ids
7) in Action added unpublish content

Seems to be working so far.


Assuming everything is using proper Drupal methods for attaching stylesheets (.info, drupal_add_css, $foo["#attached"]["css"], etc), I think it is impossible for core to create a bad link to a file.  Still, it would be worth it to search the code for "drupal_add_css" and "#attached" to see if there are any problems.

I think there are two possibilities here.

One could be a JS library dynamically attaching a stylesheet to the page.  Unless you are doing this yourself, I don't think this is a likely culprit.  Most of the libraries that do this (eg, jQUery UI) are rather well tested and I doubt would do this.  Stranger things have happened, though.

The other possibility is a bad url() reference in your CSS for a font or background image.  Search though all of your CSS for "url" and see if you have any problems.  Validating the CSS couldn't hurt, either.


Pass no. of pages arguement to Drupal views pager

I still don't quite get what you are asking about, but you should be able to examine $view->pager in a hook_views_pre_build and do what you want.  For example, this is a snippet of code I have used in Drupal 6 and Views 2 to set the number of items per page:

function mymodule_views_pre_build (&$view)
{
    if ($_GET["perpage"]) {
        $perpage = check_plain($_GET["perpage"]);

        if (is_numeric($perpage) && (int) $perpage > 1) {
            $view->pager["items_per_page"] = (int) $perpage;
        } else if ($perpage == "all") {
            $view->pager["use_pager"] = false;
            $view->pager["items_per_page"] = 0;
        }
    }
}


What could cause a View template to ouput wrong row index?

To solve it using views-view-field.html.twig
First in view settings, add field "View Result Counter" and hide from display.
Now in your twig you can do

...


How do i remove main menu title once it's in sidebar,

Welcome to the wild world of theme functions, friend. You're going to need to do some overriding of the main menu in a file called "template.php" which should be included in whatever base theme you're using. Create a function in that file that looks something like this:

function MYTHEMENAME_menu_link($variables){ // Code here }

Use this link as reference to understand how to change what's there: https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

And for a real brain buster on everything you want to know about how to theme menus, check out this answer by Sheena, who's basically a genius: Advanced menu theming in Drupal 7


I've had something similar happen to me before. Turned out that Automatic Entity Label module was overwriting the title field with an empty token.


a lot of template (.tpl.php) files, is it good or not?

Say you override the default page.tpl.php with your own in your theme folder, and compare this to the case of using the default. In both cases, one page.tpl.php is being evaluated during the page render process - either the default template or yours. Even if you do not override the template, Drupal must search the theme folder to check if an override exists. Of course, if you have a lot of complex logic in your override the page will render more slowly, but that is not due to the overriding itself.

Creating custom templates with hook_theme might slow things down, though.

In general, caching will do more to speed up your site since it bypasses page rendering altogether.


The "use ajax" checkbox in Views refers to the pager only. Any other magic you may want to work with ajax would require some custom code or additional modules, depending on what you're doing.


The first step is to set "search" as the path of your homepage in the "Site Information" configuration section of the site. This step requires that you have already enabled the search module.
If still have blocks of content on your home page the edit each one of the and make sure to set home page " < front > " as the place where they are not visible.
Add the login block to the footer and you are done.
If the any menu is still showing the create a page-front.tpl.php (D6) or page--front.tpl.php (D7) by duplicating page.tpl.php and the remove the code that shows the menus.
To make the search field larger you can use CSS.


Call python from module and receive output

Thanks for the responses.  The basic take-home for me here is to try a simple python script shell_exec first.  Once I did this I was able to quickly see that shell_exec was working as expected.  This in turn led me to my issue which ended up being not really related where I had some minor path issue that were throwing me off.  Perhaps drupalist advice to "try a simple command to make sure shell_exec works, then check the python" will help others with the same issue.

Derek


How to add a modal which then opens a ctools modal?

Any pointers as to where I can find a workable solution to this?

If you know jQuery and CSS you can create your own custom modal. Modal one has div id of modal-1 and for two modal-2.

use the z-index css property, and make sure modal 2 is higher than 1, so it displays on top:

#modal-2 { z-index: 10; }
#modal-1 { z-index: 5; }

Use CSS to center the div, so it appears in the middle of the page, like this. Probably better to use fixed position rather than absolute, up to you.

Then with jQuery use the .click() function

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings)

      $( "#some-show-button" ).click(function() {
        $('#modal-1').fadeIn();
      });

      $( "#some-x-button", "#some-submit-button").click(function() {
        $('#modal-1').fadeOut();
      });

      $("#some-other-show-button").click(function() {
        $('#modal-2').fadeIn();
      });

      $( "#some-other-x-button", "#some-other-submit-button").click(function() {
        $('#modal-2').fadeOut();
      });

    }
  };
}(jQuery));


If you read up on the documentation the function returns FALSE if there is no data. isset() would actually fail because you are assigning FALSE to the variable so it's actually been set to something. The correct syntax would be:

$field = field_get_items('node', $node, 'field_post_image');
if ($field) {
   //Do something with the field
}
else{
   //There are no results
}


how to display Variables in User account page

Try get_defined_vars

If you install the Devel Module there is a page for viewing and editing variables.

Also you can try

<?php
 dsm (array_keys(get_defined_vars()));
?>

See also:

get_defined_vars()

get_defined_constants()

get_defined_functions()


Grandchild nodes (of a nested taxonomy term) on node page

You can start with Content Views that show all nodes tagged with term from Vocabulary A, then add relationships to Taxonomy information, including the reference between terms from vocabularies A and B, and the one introducing content tagged with those terms.

Create a new Views of type Content showing Fields, add a Block Display to the View, change its name to something meaningful you can recognize later on Blocks page
Add a Filter to limit to your desired Content types
Add a new Relationship Taxonomy term referenced from field_a and Require this relationship

This one merely introduces more information about the Vocabulary A term that the current node is referencing.
Add a new Relationship Taxonomy term referenced from field_b, make it use the first Relationship and Require this relationship

This one introduces information about the term from Vocabulary B that is referenced by the term that node is tagged with.
Add a new Relationship Taxonomy term using field_b, make it use the second Relationship and Require this relationship

This one goes reverse, back from Vocabulary B to terms from Vocabulary A that reference specific term from B
Add a new Relationship Content using field_a, make it use the third Relationship and Require this relationship

This one introduces nodes that are tagged with terms from A that also reference term from B that is referenced by term from A that the current node is tagged with.
Add a new Contextual filter ID from Content Category and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
[your relevant CTs]

This one just gives Views information about the current node.
Edit the Content: Title Field you already have and make it use the fourth relationship (it will actually be the only one available). Now the Title won't be showing the Title of the current node, but the Title of the node that is related to the current node through A > B > A "relation path".

You should now see a list of nodes related to the current node through the "grandparent" term.


How to create a list of paragraphs not linked to a node

No, this is not possible. By concept paragraphs are always tied to a parent entity, just like normal fields. If it can exist on it's own, better use a node instead.


Encode Forward Slash with &#x2F in Text area drupal 7 form

You can use something like the following to convert all characters you want to convert into their corresponding HTML entity version. I have added a check on converting only non alpha-numeric characters into HTML entities. You can add a different logic to convert only those characters you want to convert (in the if condition with ctype_alum)

The following is adapted from the answer here

function encode($str) {
  $str = mb_convert_encoding($str , 'UTF-32', 'UTF-8'); //big endian
  $split = str_split($str, 4);

  $res = "";
  $pos = 0;
  foreach ($split as $c) {
    // Check if the character is alpha numeric and
    // if not, convert to HTML entity.
    if (!ctype_alnum ($str[$pos])) {
      $cur = 0;
      for ($i = 0; $i < 4; $i++) {
        $cur |= ord($c[$i]) << (8*(3 - $i));
      }
      $res .= "&#" . $cur . ";";
    }
    else {
      $res .= $str[$pos];
    }
    $pos++;
  }
  return $res;
}


File_load for image path errors when empty

Found the answer here: http://www.drupalden.co.uk/rendering-drupal-7-fields-custom-node.tpl.php-templates

<?php
// field_my_image is the name of the image field

  // using field_get_items() you can get the field values (respecting multilingual setup)
  $field_my_image = field_get_items('node', $node, 'field_my_image');

  // after you have the values, you can get the image URL (you can use foreach here)
  $my_image_url = file_create_url($field_my_image[0]['uri']);

  print $my_image_url;
?>


ckeditor underline not allowed on filtered HTML

You have to allow <u> HTML tags in 'Filtered HTML' filter (/admin/config/content/formats/filtered_html).


Copy sites/all/modules/views/theme/views-exposed-form.tpl.php into your theme's template folder.  Rename it to views-exposed-form--YOURVIEWMACHINENAME.tpl.php and clear caches.  You should be able to put your button after the exposed filter content.


What could happen if cache_form is stored in Memcache?

Memcache will drop cache content to make room for new cache objects.

That may be a problem if using a single memcache server instance for several cache bins.

cache_form needs to be more persistent to avoid losing form build validation data.

You could have a dedicated memcache server instance/port for cache_form and that would work ok, provided the service isn't restarted. However, in practice, servers need occasional reboot which could cause loss of user form data.

Usually cache_form is stored in the database as it provides the semi-persistent storage required there.

If cache_form isn't working properly, your users will experience "This form has been outdated" and other form validation errors.


Which Views template file to override to display fields in formatted table?

There are quite a few ways to find this information, most of them are pretty easy to accomplish. I'm going to list a few different ways that I usually include in my process. (See update below for the choice to use template suggestion or template.php override function)

Theme Debug

Read here:
https://www.drupal.org/node/223440#theme-debug

When turning on theme debug you can inspect the HTML of the page and you will see the templates that are actually used and template suggestions for the markup of the page. The Drupal gods blessed us with this one as of D7.33, so it won't work on anything before that.

Views Theme Information

There are quite a lot of little tricks built into views to help developers. One of them is the ability to see what template file is being used for a particular view.

This is where the magic is for the template files being used.

This is what that modal shows.

Read here for more in depth documentation of each particular template file and what it does exactly.

Notes:

From your question and your layout of what your view is doing or trying to do (only speculation, so take this with a grain of salt, the more information given the easier it is to answer these types of issues) you are using views grouping of some sort to achieve that layout or hierarchical display of information. Views grouping is a little bit different than the regular template files as it uses a registered theme function for that, which is better for performance but you can still override with a template file as well. You can find that template file here if you think that may help in your current situation. I know that there are a lot of ways to skin a cat and a Drupal page so I could be off on that assumption. If I can add anything more to help just let me know.

I haven't watched the video mentioned in the comments yet but if I see exactly what that is referring to I will add some more information about that. You can also search for custom view handlers and other cool custom view options to achieve basically anything a BA can imagine.

Update:

I watched the video from the comments. I'm guessing that is fairly important to you since you mentioned it specifically in the comments on your question. Just to be clear for future readers incase the video is ever lost or deleted, OP is asking if he should use the template override (as in getting the template suggestion and copying the file to your theme/sub-theme and changing it from there) or overriding the template file in a function in your themes template.php. I have seen either way used before but there is a rule of thumb to use for this, if you are doing a major logic change of some sort use the override function in template.php. If you are only making basic markup changes and small data display changes you are safe to just use the actual template file. I will go ahead and say that on larger projects the amount of template files can get pretty large and unruly so unloading some of that in your template.php (even better broken out into inc files, see Bootstrap/Zurb themes for examples of breaking pieces out) helps out in some cases, but besides the rule of thumb mentioned that is up to you as the developer. (I haven't ever been told any different or read anything in Drupal standards as to say which way to go on this one besides the basic rule of thumb I mentioned and I consider myself pretty high up there with wanting/needing to follow Drupal standards, if anyone has any more information on that please chime in)


Turns out it was an error in hook schema() unfortunately the function failed more or less silently. For example :

'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'not null' => TRUE,
                'description' => 'Description of vaule type.',
        ),

Failed.

'description' => array(
                'type' => 'varchar',
                'size' => 'normal',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'Description of vaule type.',
        ),

Worked.

The problem was exacerbated by my mistakenly assumed notion that disabling and re-enabling a module would trigger the install, rather then the removal of the module from the system table.

Thanks again to everyone who provided feedback.


My solution was to add this line to my .bash_profile

alias drush='/usr/bin/php5 -c /home/000000/etc/drush.ini ~/bin/drush/drush.php'

It turns out the CLI on MediaTemples Grid Service uses a different PHP.ini file. So that line basically tells it to find your drush.ini file to override some settings. Make sure to replace the 000000 in with your server number. Thanks to kiamlaluno and MediaTemples support folks for the help.


Switch between two views by clicking on a menu tab without any page refresh

You can try the Quick Tabs module.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content. Clicking on the tabs makes the corresponding
  content display instantly, using jQuery. With the 6.x-2.x branch, this
  can be done in either ajax or non-ajax mode:


Trying to use Panelizer for a node content type with a panels layout

Panelizer 7.3.1 Panelized content shows in preview, but when I view the live page, it looked like a regular, un-panelized node.

Turned on and off everything I could think of...

Finally, I looked at the Display tab of my content type, and clicked open the Custom Display Settings. I turned OFF "use custom display settings for view modes: Full Content and Teaser". Suddenly my nodes were panelized. Click back on "Full Content", and panels disappear.


Best way to create a property of an association in Drupal 7?

Look into Field Collection:

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

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

You can then create:

a content type Movie. You could have fields like a Poster image field, Title, Cast, synopsis, and then a Showtimes field collection.
Then have a content type Theater. Which is a theater. It can have fields like geolocation, a picture of the building, a description, hours of operation, etc.
Then your Showtimes field collection is itself a multi-value field which contains 2 fields: an entityreference to a Theater, and then a multi-value collection of times (maybe look at event module).

Using Views you should be able to list movies, Theaters and their movies, Movies at a certain time -- etc.

How to integrate this all into the Commerce module or something ... I leave this as an exercise for you.

I don't guarentee this is the best way to build the relationships between data you want. Another alternative to field collection and even the entities could be the Relation module.

EDIT:

If you want to easily create like a Theater that doesn't exist yet for a Movie (when making a movie entry) look at the Inline Entity Form module.


How to combine Image and Video fields in a views slideshow in a single carousel?

You should be able to simply add both fields.  To help matters along you should can add a bit of logic to only show one field if both are populated.  To do this follow these steps:

First decide which field to show if both have values, for the purposes of this example I'll say that it's video but reverse everything if you want it to be the image field.
Make sure you view has "Fields" selected next to "Show:"
Add the image field and tick "Exclude from display"
Add the video field
In the settings for the video field under "Rewrite results", click on "Rewrite the output of this field" and then on "Replacement patterns"
Copy the token that relates to your image field (including the surrounding [ and ])
untick "Rewrite the output of this field" and click "No results behavior"
Paste the token you copied (including the [ and ]) into the "No results text" box.
Save.

Then the view row will show the video unless there is no video in which case it will show the image.


form_set_error() field not highlited red

If your form element is defined like that:
$form['panes']['webform_nid31'][0]['contact_person'] = array( ... );

your form_set_error call should look like that:
form_set_error('panes][webform_nid31][0][contact_person',
                t('You must select a name for this group of settings.'));

You need to set full path to element, without outside [ and ]. You could have many "contact_person" fields in one form, just in different branches of a form tree. Using only last index would made setting errors ambiguous, thus it's not supported. At least officially. Might work, but only as an undocumented feature.
Formatting this string is described in API:

Parameters
$name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

Last but not least, actual output is defined in theme, it might well be something other than red border if theme author decided so.


I will present a solution for empty front page here with help of views module.

You can create or use a content type which you are not intended to use. Either you can create one or use article etc.

Create a views with selecting that content type & set other things such as no pager & 0 posts, so that this views doesn't produce any result.

Give it a name such as home & make a page with same name.

Go to your site configuration & set this home as front page path. You are done.


Error: Call to a member function addWhere() on array in hook_views_query_alter()

Try to add your condition to conditions array in the where  $query->where like the following:

/**
 * Implements hook_views_query_alter().
 */
function myModule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'search_filter' && $view->current_display === 'block_1') {
    $field = 'node__field_country.field_country_target_id';
    $value = 'someValue';
    $operator = '=';
    if (isset($query->where[1]['conditions'])) {
      $query->where[1]['conditions'][] = [
        "field"    => $field,
        "value"    => $value,
        "operator" => $operator,
      ];
    }
  }
}

Read this Article it's very useful.


How to import beans using the migrate module?

This forum post shows an example DestinationHandler and Migration

https://drupal.org/node/2141211


Popup dialog window based on selection in radio select list?

Since the popup appears as an immediate reaction to the user selection, this looks like a job for JavaScript or jQuery. Take a look at the jQuery Dialog user interface. And here is a tutorial on working with JavaScript within Drupal.


How to I add a node reference field using the Webform module?

I done this but for a user reference by creating a new module and a new webform component.

This new component effectively recreates the user reference functionality and allows you to choose it on the webform. You could try the same approach to do it for a node reference.

Also there are some good examples in the webform examples to help you with the basics in creating a new component with hooks like _webform_defaults_component().

The main thing which will help you is the '#autocomplete_path' => 'autocomplete/node', in _webform_render_component() which you will need in the component.

...In the module add something like the below (obviously change for node lookup):

//create a url path for the autocomplete
function hook_menu() {
  $items['autocomplete/users'] = array(
    'path' => 'autocomplete/users',
    'title' => 'Auto Complete Users',
    //page callback to a custom function
    'page callback' => 'hook_autocomplete_users',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

//custom function created to mimic auto complete functionailty
function hook_autocomplete_users($string = '') {
  $matches = array();
  $query = "SELECT u.name, u.uid FROM {users} u WHERE name LIKE LOWER('%s%%')";
  $result = db_query_range($query, $string, 0, 10);
  while ($user = db_fetch_object($result)) {
    $matches[$user->name.' uid:'.$user->uid] = $user->name;
  }
  //print drupal_to_js($matches);
  drupal_json($matches);
  //exit();
}

You will need to choose what you want in the node reference too as by default it would just be the nid which in an email would be pretty useless..


How to do views random sort for all the items in a pager?

In your view under filter criteria, use Aggregation settings -> group results together.
This should remove your duplicate results


Thanks for the help.

I did try to login with an email and username, same results for both.

But very strangely everything works now...
And i have no idea what i did to fix it.

Last thing i did was update every module and the Drupal Core.
And today the login form works again as it should...

I would love to give more information for future people experiencing this problem but frankly i have no clue what solved it.

Thanks again for all the help!

Greetings


Module broken by drupal core update (mysql_num_rows)

You should use db_affected_rows() function of the Drupal instead of mysql_num_rows() function of mysql to check number of rows result from query.

Your code should be:

$result  = db_query("SELECT nid FROM {httprequest}");
    if (db_affected_rows()) {
    //your code
    }

Instead of

$result  = db_query("SELECT nid FROM {httprequest}");
if (mysql_num_rows($result)) {
//your code
}


Unlike forms, specific invocations of theme functions don't have identifiers associated with them, so there's no mechanism like hook_form_FORM_ID_alter() that you can use unfortunately.

I can only find one call to theme('table') in the nodequeue module so I think you're talking about the theme_nodequeue_arrange_subqueue_form_table() function.

Luckily enough, this function assigns a unique id to each table (which believe me isn't always the case), so at least you can target it in a preprocess function:

function MYMODULE_preprocess_table(&$variables) {
  if (isset($variables['attributes']['id']) && $variables['attributes']['id'] == 'the_id') {
    // Alter the table
  }
}

As the theme_nodequeue_arrange_subqueue_form_table() function actually renders the table to a string (it has to, being that it's a theme function itself), I don't think there's any other way to do this.

The other (more long-winded way) would be to implement your own version of the entire theme_nodequeue_arrange_subqueue_form_table() function, copying the code from the original and just changing what you need to.


How can I add custom markup with a theme function?

To do this the drupal way, you should use a theme function:

function MY_MODULE_form($form, &$form_state) {
  $form['MY_MODULE']['message'] = array(
    '#theme'    => 'mymodule_markup',
    '#var1'     => $var1,
    '#var2'     => $var2,
  );
  return $form;
}

Then implement hook_theme:

function MY_MODULE_theme() {
return array(
  'mymodule_markup' => array(
    'variables' => array('var1' => NULL, 'var2'=>NULL),
  ),
);

}

Then implement your theme function

function theme_mymodule_markup($var1, $var2) {
    return 'some string';
}

You also could use a template to render your markup. That way themers can overwrite your markup without having to dig into your module files.


How to add Flag Link field to view based on Search Index?

This doesn't work out of the box, but there's a patch for this
https://www.drupal.org/node/1362298


Prev/Next on field group horizontal tabs

OK, well before this is closed, I will post what I did in the hope it might help someone.

I added a #tab_back/#tab_next buttons to the form, and used a bit of jquery to handle the UI.

  var current_tab = 0;
  jQuery("#tab_back").hide();
  jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();

  function click_tab(inc)  {

    newtab = current_tab + inc;
    if (newtab >= 0 && newtab <= 4 )  {
      jQuery('.horizontal-tab-button-'+newtab).find("a").click();
      current_tab = newtab;
      jQuery("html, body").animate({ scrollTop: 0 }, "slow");
    }
    return false;
  }

  jQuery("#tab_back").click(function () {
    click_tab(-1);
    return false;
  });

  jQuery("#tab_next").click(function () {
    click_tab(1);
    return false;
  });

  jQuery('.horizontal-tab-button-0').find("a").click(function () {
    current_tab = 0;
    jQuery("#tab_back").hide();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-1').find("a").click(function () {
    current_tab = 1;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-2').find("a").click(function () {
    current_tab = 2;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-3').find("a").click(function () {
    current_tab = 3;
    jQuery("#tab_back").show();
    jQuery("#tab_next").show();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').hide();
  });

  jQuery('.horizontal-tab-button-4').find("a").click(function () {
    current_tab = 4;
    jQuery("#tab_back").show();
    jQuery("#tab_next").hide();
    jQuery(".entitytype-tab_tool-form").find('input[type=submit]').show();
  });

For what it's worth, I didn't really need tutoring, just help knowing which avenue to explore as it could have been done many different ways.  Anyway, hope this helps someone.  feel free to pick at my javascript... It's not my forte.


jQuery in D7 is in noConflict mode. You need to use jQuery instead of $, or a closure.
See http://drupal.org/node/171213


For using Bootstrap tabs with views you need to use the Views Bootstrap module: Views Boostrap module enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.

Views Bootstrap module supports following:

List item
Grid
Tables
Thumbnail
Media object
Accordion
Carousel
Tabs
List group


This can be done using the power of Rules Module and exactly Rules Scheduler which is a part of rules.

Create a Rule component with the condition "User has role: Role A" and the action "Send email".

Events: After saving a new user account
Conditions: None
Actions: Schedule component evaluation

In that Action, I chose these options:
Component: the component from step 1
Scheduled evaluation date: account:created
Add offset: 7 days
User > Data Selector: account

For an in-depth tutorial on how to set this up please see this blog post on how to use Rules Scheduler to send emails
You also need to likely have your drupal cron job properly configured as well.


Fatal Error after creating Custom Display Suite layout

Have a look in the code for Display Suite, specifically the block mentioned in the error message:

function _ds_layouts_scan_theme($theme, &$layouts) {
  $theme_layouts = file_scan_directory(drupal_get_path('theme', $theme) . '/ds_layouts', '/inc$/');
  foreach ($theme_layouts as $file => $values) {
    include_once(DRUPAL_ROOT . '/' . $file);
    $function = 'ds_' . $values->name;
    $layouts[$values->name] = $function();
    $layouts[$values->name]['path'] = str_replace('/' . $values->filename, '', $file);
  }
}

Note that when it goes looking for layouts is it prepending your layout name with 'ds_'.

I imagine this is to prevent functions being included that were not intended for this purpose, a bit like using your module name in place of hook_ when you implement hooks.

That's why changing your function name worked.