Is it possible to alias paths for contextually generated page views?

This is the use scenario behind the Sub-pathauto module. In your scenario, you're creating a "more link" page View with a /node/%/news path and a contextual filter for the NID to retrieve that specific node's contextual news view. With the sub-pathauto module installed, that page view should be viewable via [category]/[english_title]/news alias.


Entity Reference Autofill does exactly what you want.

    The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


We primarily build our sites using Bootstrap with this same technique, so here are 3 modules that will make your life a lot easier.

Block Class - add classes to blocks.

Block Group and/or Region Class - group blocks together in faux regions, add classes to regions.

Blocker - places blocks on specific pages in different regions, alternative to using the core block placement system. Really useful for site building and putting blocks on basic pages.


As you can see in the code of theme_get_settings(), if data is not in cache, it's obtained from variables:

// Get the saved global settings from the database.
$cache[$theme] = array_merge($cache[$theme], variable_get('theme_settings', array()));

if ($theme) {
  // Get the saved theme-specific settings from the database.
  $cache[$theme] = array_merge($cache[$theme], variable_get('theme_' . $theme . '_settings', array()));

So usually when you need to change them from code, you will need to use good old variable_set(). And don't forget to clear the cache.


FBOauth: how to pass arguments to the callback function?

I modified the fboauth_action_menu() to make it accept arguments:

function fboauth_menu() {
  $items['fboauth/%fboauth_action/%/%'] = array(
    'title' => 'Facebook connect',
    'page callback' => 'fboauth_action_page',
    'page arguments' => array(1, 'foo', 'foo'),
    'access callback' => TRUE,
    'file' => 'includes/fboauth.fboauth.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

But then I had another problem with the function fboauth_action_page()it executed because it called the another function to get the access token because the two redirect_uri parameters were not the same between the code request to FB and the access token. All this, because the function to get the access token was not taking into account the parameters.

function fboauth_access_token($code, $action_name, $app_id = NULL, $app_secret = NULL) {
  $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
  $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

  // get the parameters from the redirect_uri by the drupal function arg() and includes them in the redirect_uri to get the access token.
  $query = array(
    'client_id' => $app_id,
    'client_secret' => $app_secret,
    'redirect_uri' => fboauth_action_url('fboauth/' . $action_name . "/" . arg(2) . "/" . arg(3) . "/", array('absolute' => TRUE, 'query' => !empty($_GET['destination']) ? array('destination' => $_GET['destination']) : array())),
    'code' => $code,
  );

// rest of the function

}

Now, both redirect_uri are the same and my callback function defined earlier must also catch parameters from the url:

function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $event_name = arg(2);
    $event_start_date = arg(3);

    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $event_name, "start_time" => $event_start_date), 'POST');

}

Hope this helps someone!


I don't understand module_load_include()

We see that require_once $file is used to load $file into the scope of module_load_include()

Not quite. This is from the include docs (identical to require in this respect)

  When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Emphasis mine.

So functions/classes defined in an a file sourced with include/require will be available to all subsequent code. Or more specifically, all functions/class defined in the file you include via module_load_include will be available in mymodule1_myfunction1() after the call.


Display text in an empty field group tab using custom code

Adding something like the below in hook_form_alter() works

<?php
    $group_name = 'group_some_name';
    $form['test'] = array(
      '#type' => 'container',
      'content' => array(
        '#markup' => 'test',
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      ),
    );
    $form['#group_children']['test'] = $group_name;
    $form['#fieldgroups'][$group_name]->children[] = 'test';
?>

Seems like I had to add wrap the content in '#type' => 'container' for it to work


Your question is very broad. As I understand it, you want to know how the Drupal theming system works ;)

If you want to style the output of a node then have a look at the default node template in order to find out, what variables are available.

Before creating a theme from scratch I find it highly advisable though, to look through the default core themes and some more popular contrib themes in order to understand different approaches. If it's only about some styling changes, you could also use a minimalistic theme and change it according to your needs.

  A lot of styling that I made with HTML/CSS was missed up when I start creating contents and didn't appear as I expected.

Is it possible that you use a wysiwyg editor for content editing and that this interferes with the CSS in your theme?

Edit:
The title in node--article.tpl.php will only be printed if the node is not shown as a full node (but in teaser view), e.g. no visiting /node/NID. That's controlled by the $page variable. Once again, please look at the default node template: node.tpl.php to see what variables are available and what they mean. If you visit /node/NID then the default behavior in Drupal is that the page title (the one used in page.tpl.php is set to the node title and displayed in the page template, not in the node template. You can change that off course, but you have to adapt the display logic inside the templates to match your needs. You could try something like the following.

In page.tpl.php:

<?php if (!isset($node) || $node->type != 'article'): ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

This will print the page title only if you are not on a node page or if the node is not of type article.

In node--article.tpl.php:

<?php print render($title_prefix); ?>

<a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php print render($title_suffix); ?>

This will always print the nodes title whenever node--article.tpl.php is used, regardless if the node is displayed as a full page or as a teaser view.


How to grant edit access only to set of users defined in a cck field of a node?

As per me the best way to restrict the edit access would be by implementing hook_node_access, something like the following:

function MODULE_node_access($node, $op, $account) {
  if ($op == 'update' && $node->type == 'YOUR_TYPE' && $node->field_custom[LANGUAGE_NONE][0]['value'] == 'some value') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }

}


Create a panel with related group content based on a view

Is it possible to relate the group to the view based on an argument in the path?

Yes, it is. In the view, in the contextual filters select the radio button "Provide default value", there you can decide which kind of field you want to give. If you want to get the path you should select "Row value from url" and then choose the "path component" (The numbering starts from 1, e.g. on the page admin/structure/types, the 3rd path component is "types".)

I hope this helps you.


Programmatically create field instance of field and content type created in module code

Field helper attempts to handle the creation/deletion of fields and instances for you and allows you to define them in hooks. It will not update the field definitions since that is not something Drupal core supports. Otherwise Features handles creation of field instances on content types if you were to make your module a feature.


Fatal error when restoring PostGreSQL DB from dump: undefined function system_run_automated_cron

After looking into this a bunch, I just decided to move the DB to MySQL. I hated to have to do it, but support for sql-dump in drush is limited to MySQL, and Backup and Migrate is as well. Kills me to have to run two DB servers (all my other applications use PostGres), but desperate times call for desperate measures.

I would hope some day that these modules would support PostGres. As Drupal supports both, so should the modules.

Some notes to others when using Backup and Migrate and Backup and Migrate Files

File ownership travels with the files, so I've had to "chown apache" files that get moved
It looks like the Temporary Directory setting is stored as a machine-specific folder, so be sure to update this on the destination machine
Clear the cache on the destination machine. I had a case where a tpl.php file wasn't being used until I did this.


It seems that all you'd need to do, is to use the Group module.

Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


list links to nodes in another node with Views

Assuming the offer node holds a reference to the event node, this can easily be done without any custom modules.

Create a view with content type = offer.
Create a relationship to the event using 'A bridge to the Content entity that is referenced via', not 'A bridge to the Content entity that is referencing Content via'.
Add the date field into the field and use the relationship.

So for example, if it's a table view and you have one offer and two events, you should have two rows. offer 1 and event 1 date, and offer 1 and event 2 date. If you want them combined into offer 1 and event 1 date + event 2 date, then you can combine them using views distinct filter.


The relationship between group content and a group is via a membership relation.  Since it is possible for group content to be a member of multiple groups then the following code will retrieve the list of groups:

$groups = og_get_entity_groups('node', $node);

This is a multidimensional array with the group entity_types as the key and memberships as the value. Each membership is an array with the membership id as they key and then group's entity id as the value.  So to go from a group content node, to all it's group parents you would use ...

foreach (og_get_entity_groups('node', $node) as $entity_type => $og_memberships) {
  foreach ($og_memberships as $membership_id => $entity_id) {
    if ($entity_type == 'node') {
      // Assuming we only want to deal with node groups, we can
      // access the group node with...
      $group_node = node_load($entity_id);
    }
  }
}


Show last, last two or last three nodes depending on role

Create a fresh (block) view that displays all nodes.  Then you can add a relationship to Content: Author.

After adding the relationship, you will be able to add a new filter for User: Roles that uses the Author relationship.  Set this filter to your Gold member role.  Set the view to display 3 items.

Add a new Attachment display:

Under attachment settings, attach it to your first views display (the gold member display).  Attachment position should be "After".  Set the User: Roles filter to show Silver members and set the "Items to display" to 2 items.

Add another Attachment view and repeat the last steps, setting the User: Role to Bronze and changing the Items to display to 1.

Now when you view the block, it will show 3 gold, 2 silver and 1 bronze node.


entity_query: sort: Column not found: Unknown column 'membership__field_year.field_year_value'

Found the culprit. Apparently I was calling $query->execute() twice.


How can I retrieve the value of variable I have defined in a config form from a Twig template?

The values saved as configuration items can be accessed using code similar to the following one.
$slogan = \Drupal::config('system.site')->get('slogan');

Since you are asking for a template file, that code should be split in two parts. My example is for the node.html.twig template file, but you can use the same kind of code for other template files too.

In the preprocess function of your template file (e.g. mytheme_preprocess_node(&$variables)) you get the value of the configuration item
$variables['slogan'] = \Drupal::config('system.site')->get('slogan');

In the template file (e.g. node.html.twig), you access that variable
{{ slogan }}

Be sure not to use a variable ($variables['slogan'], in my example) that is not already used from the template file, or its preprocess functions.


Drupal web cluster with memcached. memcached failover?

If you might want to setup a memcache cluster, consisting of multiple servers. The idea is that you have more than one server in the cluster and if one of the servers is offline for some reason the others will be used.

This is fairly easy to setup and is documented in the memcache module as well, the config could look something like this:

$conf['memcache_servers'] = array(
  '10.0.0.1:11212' => 'default',
  '10.0.0.2:11212' => 'default',
  '10.0.0.3:11212' => 'default'
);
$conf['memcache_bins'] = array('cache' => 'default');

PHP will handle the clustering, so you wouldn't need to do anything. This means that if a server dies, that cache wont be available, but will automatically be generated on one of the other servers.

One of the ideas with memcache is that you can pool the memory of multiple servers to create a single shared pool.

In your example, you could also use your webservers as a memcache cluster, but that would require that the webservers can talk to each other. Usually when you require multiple servers, you also want to have separate memcache servers, so you can optimize the servers for their specific task.


hook_field_extra_fields on node types stored in variable

hook_field_extra_fields is invoked by FieldInfo::getBundleExtraFields. This method caches the extra fields info in the database.

cache_set("field_info:bundle_extra:$entity_type:$bundle", $info, 'cache_field');

So you want to empty cache when the affected bundles changes. That is, add a custom submit callback for mymodule_admin_settings() and check what bundles changes over the previous settings.

Tip to Empty the cache:

$cid = "field_info:bundle_extra:$entity_type:$bundle";
cache_clear_all($cid, 'cache_field', true);

You may prefer to empty the cache for all bundles. In this case, $cid is the common prefix for all bundles:

$cid = "field_info:bundle_extra:$entity_type";


hook_menu() with a query string parameter?

hook_menu() doesn't handle query parameters, so the behaviour will have to be within a single page callback.

function MYMODULE_generic_page_callback() {
  $query = drupal_get_query_parameters();
  if (empty($query['code'])) {
    return MYMODULE_without_code_page_callback();
  }
  return MYMODULE_with_code_page_callback();
}

If you need dynamic behaviour for some of the other hook_menu() options, many provide a callback option.  For example "title callback" would also let you use a function to change the page title based on the presence of the query parameter in the same manner as the page callback.

For access control, it's probably better to return MENU_ACCESS_DENIED or MENU_NOT_FOUND from your page callback.  "access callback" will be called when rendering links to the path to determine if the user has access and the link should be shown, so the query parameter will not be available on the page that contains the link.


Link in main menu does not point to specified path

Try setting the $base_url variable in your settings file. Open settings.php, usually sites/default/settings.php, and search for '$base_url', there are instructions within the comments about how to set it correctly.


I ran into the very same 2 errors but in the context of of sub-theme preprocess function when using the format_date() function as follows.

$vars['timestamp'] = format_date($dc_file_items[0]['timestamp'], 'custom', 'd M, Y');

After searching in many directions (including installing the Date module - not required), I came to realize that $dc_file_items[0]['timestamp'] was returning a string and not an integer. Adding intval() around it made the errors disappear. In the end, the code above should look like this.

$vars['timestamp'] = format_date(intval($dc_file_items[0]['timestamp']), 'custom', 'd M, Y');

Hope this helps.


How to populate a dropdown list from array in FORM API

In a while looping over your result, populate array.

$user_list = array();
while ($row = $stmt->fetch()) { // See this line in your original code
   $user_list[$row->user_id] = $row->name;
   // Apply transformations and conditions here, if needed
}

Or, as Clive suggested:

$user_list = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

Then simply use this array

'#options' => $user_list,

By the way, if you really want to make assignment in condition, proper way to write it is:

while ( ($row = $stmt->fetch()) )

As you can see, assignment is wrapped in double parentheses. It is the way to say future developers and code review tools "yes, it is not a typo, I really wanted it this way, I did not forgot about second =".


<?php
/**
 * Implements hook_css_alter().
 */
function seven_css_alter(&$css) {
  // Use Seven's vertical tabs style instead of the default one.
  if (isset($css['misc/vertical-tabs.css'])) {
    unset($css['misc/vertical-tabs.css']['data'] = drupal_get_path('theme', 'seven') . '/vertical- tabs.css');
  }
  // Use Seven's jQuery UI theme style instead of the default one.
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    unset($css['misc/ui/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'seven') . '/jquery.ui.theme.css');
  }
}


There is an option in views for this. Go and edit the exposed filter, In the edit form there will be option called

Remember
Remember the last setting the user gave this filter.

However I dunno, how to restrict this functionality only to authenticated user.


How to install drush extension / addon globally?

Put it in /usr/share/drush/commands for global accessibility.  On Windows, Drush will look in the folder named Drush/share/drush/commands inside the location specified by the ALLUSERSPROFILE environment variable.

After adding new commands, you will need to run drush cc drush to clear the Drush command cache, so that Drush will once again scan its command searchpath.


How do I get the email of the one submitting contact form in the "reply to"?

If the person submitting the form is an anonymous visitor the form will be empty and the visitor will have to fill in every field.

If the visitor is logged in (authenticated user) the name and email address are already pre-filled from their user profile.

Are you sure you're not testing this while being logged in as an admin account that has the same email address as the site? Then it's expected to see that email there.

Try to login as a different user, and also test as anonymous to see that the email is now from that different user/empty respectively for those two cases.

If you're constantly seeing the site email as From in all three cases then it's a bug and you should try to see where it's coming from. I haven't seen any problems with the Contact module, it's showing the correct "From" value every time.


Is there a module that lets one person do a bulk publish/update?

This should be possible using the Views Bulk Operations module (=VBO) ... Quote from its project page:

  ... augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

So create a view that lists all "content waiting to be published", whereas you might want to limit the access to such view to only that "one person" (the content approver?).

Then have the content approver use VBO to select "all" content to then apply "bulk operation" = "publish".

Should you want to do so, you could further enhance/refine this content approval process with modules Flag and Rules modules also. Refer to these questions to get an idea of the possibilities:

How can I allow anonymous visitors to submit content?.
How to implement a nomination process for nodes?


How do I get the user name of the user profile page that is being visited?

You can load a user object like this :

$current_user = menu_get_object('user', 1);
$username = $current_user->name;

Reference of menu_get_object function.


Store entity with entity reference field?

You should try this for entity reference fields:
Single value:

$entity_data = [
'field_student_account' => ['target_id' => 10],
];

Multiple values:

$entity_data = [
'field_student_account' => [
    ['target_id' => 10],
    ['target_id' => 11],
  ],
];

Hope that works :)


Why is the Edit View link not appearing in Panels?

I discovered the answer by accident yesterday. When adding a Views block to a Panels pane, Panels will ask you if you want the "Master" or "Block" display. I'm not sure there's a difference in the output at all, but if you select the "Block" display, the contextual cogwheel "Edit View" link will not show up.  If you select "Master", it will.  Unfortunately, you can't change the display once it has been added, so you need to remove the "Block" display and re-add it, selecting the "Master" display.  This could cause you to have to redo some work, if you had spent any time configuring things already.


Here is what I did to solve this problem:

Learn how to run scripts with Drush http://www.oliverdavies.uk/blog/dont-bootstrap-drupal-use-drush/
Write this script:

<?php

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')->addMetaData('account', user_load(1));
$result = $query->execute();
$nids = array_keys($result['node']);
$n = count($nids);

foreach($nids as $i => $nid) { // go through ALL nodes
  $node = node_load($nid); // load the node
  $type = $node->type; // get the content type
  $field_langs = field_language('node', $node); // get the language of each field
  foreach($field_langs as $field => $lang) { // go through ALL field of this node
    if ($lang != LANGUAGE_NONE) { // if the field is in the wrong language
      $items = field_get_items('node',$node,$field,$lang); // get all field values
      if (!empty($items)) {
        $node->{$field}[LANGUAGE_NONE] = $items; // put it under language neutral
        unset($node->{$field}[$lang]); // remove the old language
      }
    }
  }
  $node->language = LANGUAGE_NONE; // set the node language to neutral
  node_save($node); // commit changes
  echo ("$i/$n\tnid=$nid\t$type\n"); // progress report
}

Run it to translate every node on the site back to language neutral

I cannot guarantee that this works for nodes with fields that have values in more than one language at a time. Feel free to use and improve this code. I have tested this on my development site, and all seems fine after disabling & uninstalling locale. Let me know in the comments if this works for you, too!


How to customize the "Read more" link in D7?

node_build_content is where it's originally set. You should be able to override this by implementing hook_node_view or hook_entity_view. The links should be in $node->content['links']


How do I create a Twig override for server 500 error?

This cannot be done in Drupal as a 500 error is a server error. Drupal will never be reached.

However, if you can configure the server, you can accomplish this yourself. This may also work from the .htaccess level in Drupal. I suggest trying it at the server level first if you can.

If you are running Apache, you can use custom ErrorDocument directives.

If you are running Nginx, see How To Configure Nginx to Use Custom Error Pages on Ubuntu 14.04.


How do I prevent the automatic removal of a database table when a module is uninstalled?

Uninstall is there just to delete changes made to database. If you do not want that deletion to happen, do not uninstall. If you need only one table, back it up before uninstallation and restore it after. If you want to remove module from uninstall list, simply delete it's files.

If you need selected module to be always on, you can use hook_modules_disabled() in a helper module, to display message like "Disabling of this module is not permitted" and instantly re-enable it. If module is never disabled, there will be no option to uninstall it. Of course if someone with admin privileges will want to destroy your data, he will, so don't give those privileges to those who can't be trusted with them, but at least it should prevent accidental module removal by developer who is not bright enough to stop and think.

Last but not least, if module's data is of significant importance, you have daily or maybe even hourly backups anyway, so accidental deletion is not a problem at all. Backup and Migrate and Elysia Cron are great help with setting up backups like this, but you should also ask your sysadmin to provide automatic copy to another physical machine, if possible.


Domain Access but isolated user and content perfectly

Use the References modules and enable user reference submodule.

Add a user reference field to your content. Then, in the "Views - Users that can be referenced" section of your field options select a View that filters users by current domain. You must create this view before add the field to see the view.


I wasn't able to make this work, so I ended up setting up a "fake anonymous" user in its own module - a bit of a superhack that I'm not happy with.  That said, it works.  This "fake anonymous" user id is set via an admin settings page, and gets added to every group created.  When new posts are created I added a form hook to change the author to this "fake anonymous" user id if the submitter is anonymous.  Maybe this is easier in D7?


Download entire drupal contrib repository

http://drupal.org/sandbox/greggles/1481160

  This project provides one way to help solve the issue Provide a way to download the entire git codebase for all projects.


Is there a module or way to edit all my product's categories from one admin menu?

Here are a couple of possibilities:

Perhaps try Views Bulk Operations - this might have an operation for changing taxonomy term in content in a batch.
If you are changing the same taxonomy term (old) to another term (new) on many products, I wonder if deleting the new term and then renaming the old term to what that new term was would do the job? The end result is that you now have products all using the new term. This idea would only be suitable if there isn't other content using that new term which is not part of the change.


If your only need is to add new required fields to the user registration form, you do not need modify the form through a module; by marking any user entity field as a Required field in the field UI, it will be presented in the registration form as a required field for registration.

If you require custom validation that goes beyond "it must be non-empty" you might need to employ a custom validation handler in a custom module, another helper module (e.g. Field validation), or a custom field module that matches your use case (e.g. Address field module).


Altering widget produces error, "Class name must be a valid object or a string"

I discovered that the target field was of a type that required different settings. I solved it by entering this:

$widget['active'] = '1';
$widget['#access'] = '1';
$widget['module'] = 'taxonomy';
$widget['type'] = 'taxonomy_autocomplete';
$widget['settings']['autocomplete_path'] = 'taxonomy/autocomplete';
$widget['settings']['size'] = '60';

I also realized you can go to the content type, select a field type and the underlying html for that dropdown will reveal the field type module value, and the settings under the widget dropdown will reveal the 'type' value you need to use. Hope that helps someone.


pathauto patterns showing an empty page drupal 7

Have you tried to flush the site's cache ? Sometimes it just reapear by magic (It happened to me on building a big corporation site).

Another lead in drupal.org, they seems to think that is a "php value memory_limit" problem : https://www.drupal.org/node/1267966


How to change "Description" in File field to drop down instead of text field?

You can use hook_field_widget_form_alter() to add your own #process callback to the element.

In the callback you can just change the description field from a textfield to a select.


Apparently yes, because reasons

https://stackoverflow.com/questions/9607393/drupal-7-ajax-command-creates-unwanted-div

The solution to anyone else having this issue is to use either your own callback, or instead use ajax_command_invoke("#my-div", 'append', array($content)); and that will do the same as ajax_command_append, both solutions are more fleshed out in the link


Drupal 7 and Ubercart - admin approve sale before payment

I think you can do this by using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

You need to create a rule with below condition :

  Condition : Data comparison for the order state "Approved by admin" with
  a Negate option (checkbox in bottom).

So if you change the order state to "Approved by admin" this rule will not trigger anymore because this condition will return FALSE.


Why does adding a relationship change the display of my view?

It does not alter the markup, it just potentially reduces the result set, depending on whether the flag is set as required or not.

It depends on how you add the flag. If you add it and tick Include only flagged content, then you make the relationship required and the relevant SQL has this form:

INNER JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

whereas if you add it and don't tick Include only flagged content, then the relationship is not required and the relevant SQL has this form:

LEFT JOIN {flagging} flagging_node ON node.nid = flagging_node.entity_id AND flagging_node.fid = '1'

So views alters the type of join depending on whether the relationship is required or not - INNER JOIN vs LEFT JOIN.

Look at A Visual Explanation of SQL Joins and Visual Representation of SQL Joins


List outline of books related to another book by a node reference field

Have you tried views to create the outline.

A simple custom module will also do the trick and then you can use the generated result to show in the block as outline. In my opinion this is the best and fastest possible way to do your job.


This is an nginx configuration issue and discussed intensely on this page Yet curiously no solid solution could be offered. Some guy on an other page proposed a solution. I applied that proposed solution and can confirm that in works!

To apply proposed solution go to your nginx configuration file under

/etc/nginx/sites-available/ directory on Ubuntu and add

rewrite ^/core/authorize.php/core/authorize.php(.*)$ /core/authorize.php$1;

just above the

location ~ \..*/.*\.php$ {
    return 403;
}

block. Location does matter!.. Restart your server:

  sudo service nginx restart

and that's it. The problem solved!


Change the path used by a route dynamically

I don't believe that there is any need for custom route manipulation in your case, and besides, while I am not entirely sure, I don't think that something like what you describe, would actually work, since then you might have issues with the view's contextual filtering.
I believe the TVI Module is the answer to your problem. It can be used to specify the view/views that will be used in the vocabularies of your choice.


Tick "Authenticated User" and the rest will automatically become ticked


How to access data from a page on a form hook?

By default variables defined in one function aren't available in any other functions (see PHP: Variable scope), which is why your variable is undefined in the form function.

You can declare $variable as a global (see the link above) to make it available in both your functions:

function mymodule_page() {
    global $variable;
    $variable = $_GET['variable'];
    return theme('mymodule_page', array(
       'form' => drupal_get_form('mymodule_page_form'),
       'variable' => $variable
    ));
}
function mymodule_page_form(){
    global $variable;
    var_dump($variable);
}

But to be honest there's no good reason why $_GET would be empty when it reaches your form function, so it might be worth seeing if you can find out why that's happening.


How to solve this PHP fatal error after installing module?

Put the module back. Check its code. Delete the problematic function named in the corresponding error message from it. Go to admin page. Uninstall the module.

Try to reinstall the module in a proper location. Don't name the folder easy_booking-7.x-2.4. Simply name it easy_booking. If the error still occurs, file a bug at https://www.drupal.org/project/issues/easy_booking?status=All&categories=All


Cannot trigger CKEditor WYSIWYG in form API

There are a couple of things that you could try changing:

#input_format and #wysiwyg are not in the list of available properties for a text_format element, so even if they're not causing the error, you should probably remove them.
You shouldn't set the #value of an element like that (unless it's a value type itself). Instead you should use #default_value. In the case of a text_format the #default_value is expecting the text for the text area (since you've already set the format with #format).

I would expect this to work (certainly does for me if memory serves), but if not, check the console for JS errors

return array(
    // ...
    'content'  => array(
        '#type'    => 'text_format',
        '#title'   => t('Content'),
        '#format'  => 'full_html',
        '#default_value' => is_null($article) ? '' : $article->content
    ),
    // ...
);


Is there a recognized practice for keeping security details in files excluded from version control?

We split our settings.php file into two separate files:

settings.php (for configuration that applies to all environments)
local-settings.php (for configuration that applies specifically to the current environment)

"settings.php" is stored in version control, while "local-settings.php" is excluded. Each environment has its own version of local-settings.php, which contains its database credentials and other configuration that applies only to that environment.

At the bottom of settings.php, we include the local-settings.php file.

/**
 * Check for a local-settings.php in this direcory. Include it if one exists.
 */
if (file_exists(dirname(__FILE__) . '/local-settings.php')) {
    include dirname(__FILE__) . '/local-settings.php';
}


creating a custom entity which stores multiple bundles as per user input?

Satyabrata,

Not sure i got the requirement correct. Have you considered using entity reference + inline entity form? You can attach bundles to the main bundle and can create them (sub bundles) from the main bundle using inline entity form .

Hope it helps.


How to consume data about drupal contributed modules?

While it is not an rss feed, there is this page:

http://drupal.org/project/usage

which lists usage stats for all the modules 11899 of them. They each appear to have a page that has a bit more detail on it.


Best practices for copying data (only) back from production site to testing site after exporting views as features to prod?

We have the following:

DEV code base. (dev-code)
DEV database. (dev-db)
PROD code base. (prod-code)
PROD database. (prod-db)

Here is a simple dev flow to change a view, deploy to prod and then continue development:

[dev-db] Create a new view or modify an existing view.
[dev-code] Create a feature module out of that view or re-create an existing one.
[dev-db] Enable the feature module on DEV.
[prod-code] Commit the change and push it to PROD or upload the changes to PROD.
[prod-db] Enable or Revert the feature on PROD.
[prod-db] Export database from PROD (and preferably sanitize it to remove sensitive data)
[dev-db] Import the database dump to DEV.
[dev-code] Continue development!

You shouldn't have any problem if you are following this flow.


Upgrade from Drupal 5 to 6, then from 6 to 7. That's it. No further modules or writing your own code is needed, users and content will migrate just fine. You only need Migrate and other modules if you have some special stuff on your site, like Organic groups. CCK version 7 will be needed in most cases, but that's all in the documentation.

Here's the documentation, follow carefully:

From 5 to 6: https://drupal.org/documentation/upgrade/5/6

From 6 to 7: https://drupal.org/documentation/upgrade


Nevermind, I finally found this documentation on how to get started and how to automatically convert the scss files into css files:

http://drupal.org/node/1548946


In Drupal 7 Views, how can I display a block on every page of a view?

Simple:

https://drupal.org/project/block_views

Also related:

How can I show a block in a view page, excluding it's paginated pages


How to give class name to the text field in drupal

Additional HTML attributes, such as 'class', can be added using the '#attributes' property.

function my_module_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Enter Your Name'),
      '#weight' => -10,
      '#attributes' => array('class' => array('uclass')),
    );
 }

Please note that when you alter existing form elements (e.g. via hook_form_alter()), you probably want to add (attributes) to the existing array rather than writing over it.

Checkout Form API of Drupal 7 to get more detail.


How could I send daily or weekly email in cron() function?

How are you generating your email?  It sounds to me like you need a custom module that implements hook_cron.  It would have to save the email address and send_interval to it's own table (or you'll have to build a query to select the email and interval from wherever you've stored it) in the database during hook_nodeapi with the update $op and/or the insert $op.  I recommend creating a 3rd column in your table with a date for the last time email was sent.  That way if cron gets interrupted it can continue where it left off.  Use a sql query to select all of the rows with column interval == daily and date < NOW() and send emails out.  Then do the same if the date is a Sunday or whenever you want to send weekly emails for those.  As you process a row, update the date field to the current time which indicates the email was sent.

If you're not up for custom development, you may want to see if the notifications module suites your needs.


How to get image url in a twig file from a media entity

With Twig Tweak module (2.4+) it can be done like this:

{{ node.field_media|file_url }}


How to change field values in a view programatically?

Okay, so after a little more googling I found my own answer on a thread on d.o that address this issue with sample code (which I'm condensing a bit):

<?php
/**
 * Implements HOOK_preprocess_views_view_fields().
 */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  //Replace 'VIEW_NAME' with the machine_name of your view.
  if($view->name == 'VIEW_NAME') {

    //This for loop iterates over all fields in this view.
    foreach ($vars['fields'] as $id => $field) {

      //Custom formatting logic goes here....

      //Set the field value (not the surrounding tags) here.
      $vars['fields'][$id]->content = 'my new value';
    }
  }
}
?>

NOTE Make sure you replace "MYTHEME" with the name of your theme or module in order for this work.


Configuration Management Module Keeps Saying 'needs attention'

It means that there is a difference between activestore and datastore for those items.

Below you see that those items are overriden. The ones in data store are old versions. If this is a dev environment and those changes are necessarry, you can write these changes to datastore and push/migrate to prod environment.

The below changes are for example purpose and they are not necessarry to put to prod version, since they are about things like last running of cron, etc.

The below image a real change in activestore. You can write that down on datastore by clicking Write Activestore to Datastore.


Try using the /watch?v= parameter (i.e. www.youtube.com/watch?v=Y9eXzmVzDR8) instead of www.youtube.com/embed/Y9eXzmVzDR8 when adding content to the field.


Alter a path alias depending on a node property

if you don't won’t to create a new token as @Clive mentioned in comment, you can use hook_pathauto_alias_alter in your custom module like the following.

/**
 * Implements hook_pathauto_alias_alter().
 */
function MY_MODULE_pathauto_alias_alter(&$alias, array &$context) {
  if ($context['module'] === 'node' && $context['bundle'] === 'MY_BUNDLE') {
    // Get the node.
    $node = $context['data']['node'];

    // Clean string service.
    $clean_string_service = \Drupal::service('pathauto.alias_cleaner');

    $is_checked = $node->field_SOME_NAME->value;
    //   If your field is checked.
    if ($is_checked === 1) {
      $alias = '/mysite/term/' . $clean_string_service->cleanString($node->label());
    }
    else {
      $alias = '/mysite/' . $clean_string_service->cleanString($node->label());
    }
  }
}


Search results showing nodes which are already under NODE_ACCESS_DENY

You must flush the search cache after you have changed node access records.


Default value for form_system_theme_settings_alter

I think it will only execute if you save the theme settings page. If you want to have the default work upon theme activation you have to have your setting in your theme's .info file. I could be wrong.


Drupal 8 Configuration API - cant access variables

To elaborate on @dawehner's answers, default configuration is not cached.

It is only imported when you install a module. After that, if you make changes to default configuration, the only way to add it to existing installations is to write an update function that adds it manually.

During development, there are modules like Configuration development, that can automate that process, but they will obviously not be present on any productive installations.


Adding Display Suite fields to Search API results

I missed it earlier, but it turns out that Search API just exposed the Excerpt field to view modes.

Updating Search API to 8.x-1.x-dev and a cache rebuild gave me the functionality I need.


a single field from reference entity causing memory error

Should anyone come across this, I had failed to mention that it was an image field. The problem what the image style that I had used. I have the imagecache_actions module for the aspect switcher functionality. Somehow the style I was using had the circular reference. I had to copy another style to that style in features in order to event edit the style. Then I was able to recreate the style properly and the problem is fully gone.


Modifying default workbench view filter via code

The preferred approach to do those things in Drupal 7 is to:

Clone "My content" view to "My content clone view".
Make modifications to "My content clone view"
Disable "My content" (the original view).

I still haven't tried this in Drupal 8, but I think the principle should be the same.

Regards,
Oleg


Twig escapes tags when using raw value in template

You can use the following code below:

{{content.field_myfield.0|render|striptags|trim}}

  render:  The striptags filter strips SGML/XML tags and replaces
  adjacent whitespace by one space.  You can also provide tags which
  should not be stripped:

{{ content.field_myfield.0|striptags('<br><p>')}}

trim: The trim filter strips whitespace (or other characters) from the beginning and end of a string:

{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

{{ '  I like Twig.  '|trim(side='left') }}

{# outputs 'I like Twig.  ' #}

{{ '  I like Twig.  '|trim(' ', 'right') }}

{# outputs '  I like Twig.' #}

The example above used from the twig website.


Domain Access: Subdomain -> same views-path - different view?

Based off @Sugandh Khanna answer, follow these steps:

Make View 2 as an attachment and attached to View 1.
In mobile view, add the css .view-content {  display: none  }
In desktop view, add the css .attachment {  display: none  }


Add a class retrieved from a sibling field to responsive image

What I'd recommend is to simply preprocess the paragraph, get the "round image" Boolean, and use it to add a class to the paragraph. This should be just enough to style the responsive image accordingly.

/**
 * Implements template_preprocess_paragraph__PARAGRAPH_TYPE.
 */
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {

  // Get paragraph.
  $paragraph = $variables['paragraph'];

  if (!$paragraph->get('field_rounded_profile_image')->isEmpty()) {

    // Get Boolean.
    $rounded = $paragraph-> field_rounded_profile_image->first()->getValue();

    if ($rounded['value'] == '1') {
      $variables['attributes']['class'][] = 'rounded-image';
    }
  }
}

And then via CSS (Sass) you'd do:

.paragraph-profile-card {
  &.rounded-image {
    .field-profile-image {
      // rounded image styles
      // ...
    }
  }
}


How to debug "undefined" 404 error in console on front page

Thanks for the tips Clive and Beebee!

By trial and error I disabled or removed various components until I found one that made the error go away. In this case it seems to be a problem with Flexslider and Views that was used in a Views block -- I haven't solved it yet but have isolated it at least!

UPDATE: It seems to be a bug related to the navigation in the Flexslider module (Views integration). If I set the Flexslider style not to include navigation, it is fine.


Multi-site is designed for a shared codebase with seperated content.
It is possible to share a few tables within all multi-sites without complications (e.g. users, roles, session) but espacially sharing  of content and content-types is not quite easy.

I would suggest Domain Access: http://drupal.org/project/domain

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites


Prepopulate entity reference field from url in node create form block

Please check the following issue: http://drupal.org/node/494008


Entity operations and redirect destination (using EntityListBuilder)

buildOperations is to change the render array for the link wrapper.

The method you are looking for is getOperations. Just pick the operation you want and add the query string to the url.


Add date field to drupal entity registration

Goto Strcuture->Registrations->YourRegistrationType and add a new field of type date.

You can use Field Validation Module to make sure that the entered field is between the selected date range of the content type on which you have the registrations enabled.

Note : You could also use the tokens module to make sure that this datefiled in registration type has default value of the starting date of the date field in parent content type.


How to show a list of users based on taxonomy?

First a little clarification of term meanings.  Taxonomy is a module that manages groups of terms gathered in Vocabularies.  You have probably created a vocabulary with the terms you listed in it.

To make your list you will use Views.  I am using D7 and V3, so I cannot give you a button by button instructions, but they are similar.

Add a new view.
Define the settings for fields and add a field for the User:name.  To do this in D7 you must add a relationship to the content author to expose the User Name field.  I don't think this is needed in D6.
Delete the node title field.
Set the path to a unique URL such as Group-Type/%/users.
Create an argument to filter the URL input '%' by a taxonomy term ID based upon the vocabulary you are using for the selection terms.

When you enter a URL such as Group-type/stocks/users, The view should be used to generate a list of Users with that term.

A cautionary thought:  I have not used D6 version of Views so I don't know its idiosyncrasies.  You may have to use the term id (tid) for 'stocks' since Drupal has changed a URL from an alias to a tid by the time the URL is passed to the argument section of the module.


Redirect exclusion rule in .htaccess does not work

You're right, there's interference with other Drupal rewrite rules. If you have clean URLs enabled, you're rewriting each request as an argument to index.php. Add an additional check to exclude this other rule.

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/my_url
RewriteCond %{REQUEST_URI} !index.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


How do I populate report page using a controller?

A controller needs to return a render array for the page content. It is explained in Routing API and page controllers / Route controllers for simple routes.

The only requirement is that the method specified in your *.routing.yml file returns:

A render array (see the Theme and render topic for more information). This render array is then rendered in the requested format (HTML, dialog, modal, AJAX are supported by default). In the case of HTML, it will be surrounded by blocks by default: the Block module is enabled by default, and hence its Page Display Variant that surrounds the main content with blocks is also used by default.
A \Symfony\Component\HttpFoundation\Response object.

It's exactly what DbLogController::overview(), the controller method for the Recent log messages (/admin/reports/dblog) route, does.
  $build['dblog_table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => [
      'id' => 'admin-dblog',
      'class' => [
        'admin-dblog',
      ],
    ],
    '#empty' => $this->t('No log messages available.'),
    '#attached' => [
      'library' => [
        'dblog/drupal.dblog',
      ],
    ],
  ];
  $build['dblog_pager'] = [
    '#type' => 'pager',
  ];
  return $build;

(The Database Logging module also adds a pager, which is helpful when the rows to show could be too much, or they would make the rest of the page rendered too low in the page.)
What is wrong in your code is that it uses an array containing a string as array index, instead of a string. Any PHP version that supports the short array syntax would throw Fatal error: Illegal offset type. (The other versions would throw Parse error: syntax error, unexpected '[' since they don't support the short array syntax.)
The return instruction should be the following one.
    return [
      'table' => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $rows,
        '#empty' => t('No entries available'),
      ],
      'message' => [
        '#markup' => t('Below is a list of all Event RSVPs including username, email address and the name of the event they will be attending.'),
      ]
    ];


Parameter upcasting in Drupal 8 with Form Controller

Your variable needs to be called my_menu, check ControllerResolver


1 -  if its a default view,  you should not be able to delete it.  You should only have the option to Enable or Disable it.  If the enabled view is alter then you only have the option to Revert.

2 - An unaltered default views are not stored in the views_view table of the database (however they are stored in the cache_views table).   If you alter the view,  they are now stored in the views_view table.

So,  if you have a unaltered default view and you make changes to it in the code, then the changes will be visible once you clear the cache.   If you have an alter default view, you must revert it for it to match the code in your module.


Must at least one bundle have the same name as the entity in hook_entity_info()?

No, it's not required. It's not necessary to have a bundle whose machine name is the same machine name used for the entity type. And no, defining bundles doesn't make the entity more abstract in any way.

See, for example, node_entity_info(), where none of the content types (which are node bundles) is called node. Vice versa, in user_entity_info() the only bundle is user.
What you can gather from the implementations of hook_entity_info() done from Drupal core modules is that entities with a single bundle use the same machine name for the bundle and the entity. That is not mandatory, though.

What Drupal assumes is that, if hook_entity_info() doesn't define any bundle, the entity has a single bundle named after the entity type. See entity_get_info().

    // If no bundle key is provided, assume a single bundle, named after
    // the entity type.
    if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
      $entity_info[$name]['bundles'] = array(
        $name => array(
          'label' => $entity_info[$name]['label'],
        ),
      );
    }


Distributed authentication system (different domains, separatate databases)

This might be overkill, but have you considered using something like LDAP?

There is an LDAP integration module and an LDAP provisioning module. Both of which work quite well.


First you acquire the user object by using its return value and then you read the uid, which is also the unique value that belongs to the database row:

$user = user_save($user_obj);
$id = $user->uid;


How to email the results of a filtered view to a user?

If your view is a page, should be as easy as grabbing the page url when the form gets submitted and based on the url (if statement) you attach a view that has a filter of "X". (slight chance that it is doable with rules and webform module)

If it's a block, gets a bit more complex. You would have to check what the filter is set to using jQuery, and then pass that variable to a custom module when the form is submitted. Then module triggers x function based on the view filter value that sends e-mail with view x.

Actually, an even more simpler option, have a hidden field of checkboxes (hide it with css) on your webform that has a box for each filter. Then with jQuery you can autocheck option x if filter is set to x.

Now since your webform contains  field of checkboxes with value x, with conditional rules hopefully you can do an if statement on your field of checkboxes and attach view x to your e-mail. (I'm making a lot of assumptions here, as I've never used webform + rules, or maybe I did once... Anyhow, hopefully this will work with Rules)


Use existing serial field with same counter across content types

Instead of Serial type, I added Integer field, and added the same field (add existing field) in other content type as well. And In the hook_entity_presave, I query for the MAX(field_value), increment and assign for the current node/entity.


Input format to save page links by ID but render by the URL alias?

If you use an wysiwyg editor ie. CKeditor, there are contrib modules that offer you this functionality. For example, take a look at the ckeditor link module.
It let's you search for your nodes and make a link to the node path which is what is saved to your database. Drupal automatically shows the url alias frontend, so if you change your url alias at a later point, you will still have a working reference to your node.

Why is it important to you that you reference them by their current url alias?


Redirect to home page without using deprecated methods

Try using Url::fromInternalUri then instead of fromUri():

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url%3A%3AfromInternalUri/8.2.x

It specifically notes the use of front and none. But you can't pass the URL object or path tokens to RedirectResponse, as this is a Drupal construct. That class expects the following arguments:

http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RedirectResponse.html

string  $url        The URL to redirect to
integer $status     The response status code
array   $headers    An array of response headers

$url needs to be a string, so on your URL object, call ->toString() to get the URL.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AtoString/8.2.x


How to print meta property using custom meta tag module

Telling your custom meta tag to use the property theme formatter should do the trick.

$info['tags']['my_custom_metatag'] = array(
  'label' => t('My Custom Meta Tag'),
  'description' => t('This is a custom meta tag'),
  'class' => 'DrupalTextMetaTag',
  'group' => 'my_metatags',
  'element' => array(
    '#theme' => 'metatag_property',
  ),
);


Adding map with user location into the profile

I'm no expert but try using the Location Module.  It

  "..allows real-world geographic locations to be associated with Drupal
  nodes, including people, places, and other content"

God Bless.


PHP drupal added css file does not appear in page source

From https://stackoverflow.com/questions/1410494/drupal-add-css-not-working, the solution is to use CSS Injector. I tried and it worked.

Update

I maintain a page explaining how to use CSS Injector too add CSS to a page.


You can take a look at the Taxonomy menu module. Some details about it (from its project page):

  Transforms your taxonomy vocabularies into menus with ease!

  Custom Menu per vocabulary
  Uses the default taxonomy term path or custom paths
  Integrate with Views
  Integrate with Pathauto: use URL/path aliases
  Does not interfere with other menu modules

Also look at this post:

How do I direct link a view to a taxonomy menu?


How do I hide the entire parent (top) level in superfish?

Menu block module allows you to choose which level to show, and how deep.

It won't integrate with superfish module, but allows you to build the submenus you're looking for. Moreover, those submenus may be themed to use basic superfish:

function THEMENAME_menu_tree__menu_block__1($variables) {
    return '
'. $variables['tree'] .'
';
}

1 in the function name is the delta of the custom menu_block created.

Although posible, there's no straight way to leverage advanced superfish configuration / styling within a menu_block: APIs are not isolated enough as to theme a menu_block with a complex superfish style in a few of lines.

Just note also that a closer integration of both modules is feasible (I think of superfish using menu_block API).

So, although incomplete, I think menu_block + superfish is the best alternative.


Check in your database

1.If cache_views table is exist or not .if not exist  import this table

CREATE TABLE IF NOT EXISTS `cache_views` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...';


Show only nodes in a view which have the same value of a text field (field_phone_number)

You're on the right track with EVA. To list sibling nodes based on common taxonomy terms or entity reference fields you can just use Views configuration, but if you need to filter based on a different common field EVA is the way to go.

You did everything right except for the last step - you don't need Content ID Contextual filter, you're not comparing nodes, you're comparing Phone number fields! And the argument you set for EVA is the phone number, so that is the information you need to include there.

Add a Contextual filter for the phone field, you can configure it:
    When the filter value is NOT available
    Display contents of "No results found"
    When the filter value IS available or a default is provided
    Specify validation criteria
    Numeric (or whatever is applicable in your case)
    Hide view (if it doesn't validate)

That should list all the nodes that share that field, including the node you're currently viewing.

If you want to exclude the current node from that list you need to add another Contextual filter, this time it will be the Content ID one:
    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
    [ABC]
    More
    Exclude

That one will exlude the current node from that list.


Allow specific HTML tags inside a text field of a custom content type using CKEditor

I can't figure out how to "connect" an editor format to a field and
make it selectable for the one who adds a field to a content type.

The text formats are shown in order here:
/admin/config/content/formats
The format at the top of the list is the default format.  To change the order of the formats, drag the arrow icon on the leftmost side and then press save.
Users can only see formats for which they have permission. The roles with permission are listed in the Roles column of the table at /admin/config/content/formats.  To change the permissions, click "Configure" for the relevant format and add the correct roles.


I serve several Drupal sites on HTTPS, I don't see what Drupal has to do with that, that's the webservers job to handle. You can test the login for yourself in via HTTPS on drupal.org.

For querying the database in a safe fashion, I would recommend Views.
For gathering data with forms, the Webform module. I haven't collected files with Webform, and I'm not sure if that's doable in it's current form. This may require some custom work.

There's a Securing Drupal guide which also specifically mentions getting HTTPS up.


Does Google Analytics module tracks superuser 1 out of the box?

Yes, it does. In fact, the default value for the Drupal variable googleanalytics_track__user1 is 1, which means the control statement is executed by default.

if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
  // ...
}

What the code does is to save in $user->data the module settings, and delete the old settings.


How can I manually send order details email to customer in Ubercart?

You can try hook_cron in a custom module and get all orders using uc_order_status_list the return value may contain the email address of the buyer. If not get the order id, use uc_order_load to load the order. Get the email of buyer.

And you're done.


how to redirect users to a page after login only when a specific menu item is clicked?

You could add the link like this:

user/login?destination=node/add/post

after login they'll be sent to the add post form.


How can I determine if a $form (or $form_state) is an entity create/edit form

You can check if the form is an instance of EntityForm and then get the entity to check the entity type:

if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity_type = $form_state->getFormObject()->getEntity()->getEntityTypeId();
}


How can I sort the search results alphabetically?

You can use the search results of Views, Then you can expose a filter related with you are looking for, and assign the sort condition alphabetically. If you want to expose the sort condition, you can do this with views 3, and with views 2 using the hook query_alter().

Remember that you can use the operator 'Contains' if you want to be more laxed in the search.


how to add #states property to a field element in drupal 7?

Fields always have have nested names like field_something[und][value] or something like that. I guess your query (:input[name="field_ctype"]) is wrong.

I find the easiest way to get it right is using the Firebug/Developer tools Console. Play around with jQuery(':input[...]') until it matches what you're expecting. Also check the name of the form element.


How to override a ctools plugin from another module

I am not entirely sure if this is the best solution but I ended up doing the following:

implemented hook_ctools_plugin_pre_alter()

function my_module_ctools_plugin_pre_alter(&$plugin, &$info) {
      if ($info['type'] == 'behavior' && $info['module'] == 'entityreference' && $plugin['class'] == 'EntityReferenceBehavior_EntityQueue') {
        $plugin['class'] = 'EntityReferenceBehavior_EntityQueue';
        $plugin['path'] = drupal_get_path('module', 'my_module')  . '/plugins/entityreference/behavior';
        $plugin['file'] = 'entityqueue.inc';
        module_load_include('php', 'my_module', '/plugins/entityreference/behavior/EntityReferenceBehavior_EntityQueue.class');
      }
    }

Then I copied the files ('/plugins/entityreference/behavior/EntityReferenceBehavior_EntityQueue.class' and '/plugins/entityreference/behavior/entityqueue.inc') in my module and modified the code of presave function.


The way I do this is as follows...

function MYMODULE_block_info() {

  $blocks = [];

  $blocks['my_block_machine_name'] = [
    'info'  => t('My Block Title'),
    // @see https://api.drupal.org/api/drupal/includes!common.inc/group/block_caching/7.x
    // You can use different caching options.
    'cache' => DRUPAL_NO_CACHE,
  ];

  return $blocks;
}

function MYMODULE_block_view($delta = '') {

  $block = [];

  switch ($delta) {
    case 'my_block_machine_name':
      // Good idea to check user permissions here.
      if (user_access('access content')) {
        $block['subject'] = t('My Block Title');
        $block['content'] = MY_BLOCK_CONTENT_CALLBACK();
      }
      break;
  }

  return $block;
}

function MY_BLOCK_CONTENT_CALLBACK()() {

  $items = [];

  // This is the simplest kind of renderable array.
  $items['VAR_ONE'] = ['#markup' => 'VAR_ONE_OUTPUT'];

  // Here I added a prefix and a suffix.
  $items['VAR_TWO'] = [
    '#prefix' => '
',
    '#markup' => 'VAR_TWO_OUTPUT',
    '#suffix' => '
',
  ];

  // This is where the $items get sent to your my-template.tpl.php template
  // that got registered below.
  return theme('my_cool_block', ['items' => $items]);
}

function MYMODULE_theme() {

  // Here you are registering your template for the block output above.
  $module_path = drupal_get_path('module', 'MYMODULE');

  // Drupal will now look up your modules /theme folder first to grab the
  // template.
  $base = [
    'path' => "$module_path/theme",
  ];

  return [
    'my_cool_block' => $base + [
        // Leave off .tpl.php.
        'template'  => 'my-template',
        // Define variables you want to pass to the template.
        // Here I just pass items, but you can pass any other data as well.
        'variables' => [
          'items' => NULL,
        ],
      ],
  ];
}

And then in a subfolder in your module called theme there should be a file called my-template.tpl.php which could have this in it:

<?php

$items = $variables['items'];

print render($items['VAR_ONE']);
print render($items['VAR_TWO']);

And if you wanted to, you could actually overwrite the "default" module implementation you just made for my-module.tpl.php in your theme as you wish in block--MYMODULE--DELTA.tpl.php.


Drupal 7: How to add tags to a new content type?

From the Manage Fields page of your content type, add a new Term Reference field.  Set the widget to be Autocomplete term widget (tagging).

When you get to the field settings you'll be given the option of which vocabulary to use for the tags (for the default Article content type this is usually Tags I believe).


To verify the boost values are included in your queries, tail the Solr request.log file.  You'll see things like &qf=label%5E5.0 (%5e is a caret ^, which marks the boost value).

Another useful trick for optimizing the scores is to include the score in your themed results output.  You may find the boosts are affecting the scores, but aren't high enough to substantially change the ranking.  This can be added with a small hook:

function hook_preprocess_search_result(&$variables) {
  if (user_access('administer search')) {
    $variables['title_suffix'] = '<code>[score: ' . $variables['result']['score'] . ']</code>';
  }
}


How can I add a span tag inside my menu link?

You can try this code:

{% set tmp = '<span>'~item.title~'</span>' %}
{% set link_text %}{{ tmp|raw }}{% endset %}
{{ link(link_text, item.url) }}


webform submission details not getting displayed

You should set Redirection location of webform in form settings.

Edit your webform node.
Click on webform tab in top of page and it will redirect you to webform configuration of the node.
Click on form settings link in webform
Checked Confirmation page radios in Redirection location field-set and save the form.


How to apply suggested theme hook using hook_theme_suggestions_HOOK?

Finally I found a paragraph in the documentation. When using modules, we need to register the template using HOOK_theme(). So, I added the following function in modules/custom/domain_filter/domain_filter.module

/**
 * Implements hook_theme().
 */
function domain_filter_theme() {
  return [
    'node_add_list__custom' => [
      'base hook' => 'node_add_list',
    ],
  ];
}

Then my custom template modules/custom/domain_filter/templates/node-add-list--custom.html.twig is now applied.


How to get all Taxonomy Term attached to Node?

Use the method referencedEntities() to get all terms:

$terms = $node->field_posts_category->referencedEntities();


I suspect you don't have $node->language set, or perhaps the empty [] is causing trouble.

Try:

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    // Set node language to default, if not set
    $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
    $node->field_myother_field[$node->language][0]['value'] = '500';
    $node->title = 'retest the test';
    node_save($node);
  }
}else {
  drupal_set_mesage('no nodes to load');
}

Using entity_metadata_wrapper

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    $node_wrapper = entity_metadata_wrapper('node', $node); // Get node wrapper
    $node_wrapper->field_my_other_field->set('500'); // Set field value
    $node_wrapper->save(); // Save entity
  }
}else {
  drupal_set_mesage('no nodes to load');
}


How to copy taxonomy terms of a node into a textfield using rules?

Well that was easy then.

Create a rule with this configuration.

Trigger the rule "After updating existing content" and "After saving new content".
IMPORTANT. Create a condition with "Entity is of bundle" and choose the desired Content Type. If you don't do this, not all the fields of the content type are exposed to rules for manipulation.
The Action is "Set Data Value" and as Data choose you text field (node:field-keywords in my case). For value choose your desired terms field ([node:field-business-categories] in my case).

Run a "Published" procedure on all desired nodes with VBO and you are done.

And here is the exported rule.

{ "rules_keyword_field_generation" : {
"LABEL" : "Keyword Field Generation",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update" : [], "node_insert" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "business" : "business" } }
    }
  }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-keywords" ],
      "value" : "[node:field-business-categories]"
    }
  }
]

}
}


send emails to specific addresses based on value of fields

I am a little confused about your question. But here is an example for you to send email using hook_mail. Hope you can get some idea from this:

/**
* Implement hook_mail() function
*/
function test_mail_node_mail($key, &$message, $params) {
   $headers = array(
     'MIME-Version' => '1.0',
     'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
     'Content-Transfer-Encoding' => '8Bit',
     'X-Mailer' => 'Drupal'
   );

   foreach ($headers as $key => $value) {
      $message['headers'][$key] = $value;
   }

   $message['subject'] = $params['subject'];
   $message['body'] = $params['body'];
}

/**
* Implement hook_submit() function
*/
function test_mail_node_submit($node, $form, &$form_state) {
   if($node->type == 'rso') {
     if ($node->field_b['und'][0]['value'] == TRUE){
       if ($node->field_a['und'][0]['tid'] == '10'){
          // mail('example1@mail.com', 'example2@mail.com', 'example text');
          $valid_email = array('example1@mail.com', 'example2@mail.com');
          $params = array(
             'body' => 'Your body text',
             'subject' => 'This is a subject',
          );
          drupal_mail('test_mail_node', 'HTML', $valid_email, 'en', $params));
       }
     }
  }
}


Show 4 input file fields on my node add image page

When you add a field there is an option to set number of items. You can set the number to 4 and you would have 4 input elements on the page.


Not able to set the time for auction products, using the Ubercart Auction module

I think you just need to upgrade to the latest dev version, this is what the same fieldset looks like for me with that version:

This is on a blank Drupal 7.14 installation with only the required modules for uc_auction enabled:

Ubercart Auction - 7.x-1.x-dev (2011-Dec-11)
Ubercart - 7.x-3.1
Date - 7.x-2.5

It would be a good idea to make sure you have the latest stable versions of those contrib modules installed as well; if I remember rightly the date_popup module used to have an issue with setting the #default_value of a date_popup type field, so the problem might just be that.


Community website - User rating based on votes in Node + Statistics

I haven't used User Points Module but for fivestar module or module based on Voting api you can create a view of content and add a relationship with vote results and you will get the aggregation you need i.e average/total number/total score  for that node then you can add a Vote results :Timestamp filter to get the results in between dates. You can add sort and limit to display the way you want.


Drupal Commerce products sales limited by date

What you can certainly do is proceed as you've outlined it and then create a view of all products that don't have their collection day within the next 24 hours. This will display all the products that can be bought in time for your collection preparations.

Approach 2: Set up a rule that checks after an order has been saved or before payment is done whether there is any product that has its collection day within the next 24 hours and if so, display an error message and set the number of these products in the cart to 0.

Approach 3: Set up a rule that runs periodically (say every day) and loops through all the products and disables those that have their collection day within the next 24 hours.

If you want more detailed information on how to achieve any of these, comment.


7 - access callback get currently checked path

Based on my research, I checked first the current_path() function and in it's code it gets the path by $_GET['q'] w/c indicates only getting the values fro the URL so this wouldn't work.

I also checked the access callback and access arguments' functionality and initially I noticed that access arguments are meant for the actual use that you are trying to bypass where links needs to be checked to let Drupal know if it will display a link. The only way is does this is by specifying the access arguments.

In my opinion, the access arguments array standardizes where the "access specifications" would come from like this menu's access specs are basing on the second and third arguments. So developers would know what they're dealing with by looking at the access arguments array and user the access callback just to do mostly logic.

I hope this could help.


Using a Third-Party API to dynamically create pages

You have a few options here, though without knowing the API your using, it's hard to nail down exactly what one you would need.

If it's a commonly used service, there might already be a module that exists for it. As a general rule, if there is a module already created to handle it, that should be the way to go.

You might be able to go slightly out of the box if your API spits out some form of feed and use a module to import that feed (it's a bit older, but as an example, feeds does this.) There's a few other ingestion modules out there that might work for you.

Creating your own custom module is, of course, always an option. I know I've written a few import modules, but I normally only do that when the other options are not viable.


What would cause this error when upgrading Panels module?

For some reason, the "cache_panels" table of panel used for cache is missing.

It's reported as an issue for this module.

To solve this error, first, I strongly recommend to do a backup of the database before make any change (even before do a drush updb or update a specific module as you are trying in this case).

You cloud try one of the following solutions:

Using drush, follow this proposed solution.
Using a SQL query, follow this other solution.

I recommend you to use the first alternative as I see that you use drush.


Adding hundreds of fields to a content type in Drupal 6

The one time I had to do something like that (it was a Drupal 6 site) I exported the content type, edited the export manually (lots of copy-paste and search-replace) and imported it back into my site.

That said, a content type with hundreds of fields is going to be huge. I'm afraid that it's going to be a nightmare for your editors, terrible to maintain, and it might hurt performance as well. If I ever needed a content type with hundreds of fields, I would stop right there and start re-thinking my site architecture.


Composer cannot find drupal/commerce in a specific module

You need to add the Drupal repository to composer.json in your project.

"repositories": [
  {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
]

Note that after you do this and run composer require/update, it will create a vendor directory in your module folder. You'll want to delete this folder, as you only want your dependencies to be added when the module is added to your project, and your project's composer.json should install the dependencies in the correct directory.


.htaccess https rewrite for single domain on multisite installation

First I would try using the [drupal]/sites/sites.php file to do something like this:

$sites['example.co.uk'] = 'example.com';
$sites['example.com'] = 'example.com'; // for demonstration only

Then check out the htaccess module to force HTTPS. These are the  options:


Changing the url which the logo links to

Don't do it.

Linking the logo to the front page has become a de facto standard. Linking it to the contact page would only confuse users who expect to go to the front page, while users who want to go to the contact page would probably not click the logo.

Update in response to the comment below:

In my opinion, a language selection front page is a bad idea. Remember that people come to your site in order to accomplish a task. That task is never to choose a language. Also, consider how you want Google to see your front page.

A better alternative is to serve the front page in a language determined y the Drupal Language Negotiation API and make it really easy for users to switch languages if they want to. Read more about multilingual front pages at HowTo: Different home page (default front page) for each language and Drupal 7: Cracking the multilingual front page nut.

Now, if you still want to change the url the logo and site name link to, enable the THEMENAME_preprocess_page function in your Zen sub theme (you did create a sub theme, right?) and alter value of $variables['front_page'].


line break or second row for single record in view?

There is a module for Drupal 7 and Views 3.x called Views Secondary Row. Sadly, it's not available for Drupal 6 or Views 2.x.

A first-glance at the code of Views Secondary Row makes me think that a backport to Drupal 6 and Views 6.x-3.x might not be too difficult if you have some module-development experience (although I've never written modules to work with Views before, so I'm not sure how accurate that observation is). If you don't want to try your hand at it personally, you could put a feature request in the issue queue.


How to translate metatag token into text?

I was running a very out-dated Metatag version. Once I update to the latest version I was able to run metatags_get_entity_metatags and get all the meta tag the way it supposes too.


Difference between a bundle and a content type

Bundle is a generic term that applies to every entity Drupal or third-party modules define; content type is a specific term that applies to nodes.
Since nodes and content types were introduced a way before Drupal 7, content type was the first concept introduced, which then got expanded into the bundle concept when entities were introduced in Drupal 7.

So, yes, a content type is a bundle for the Node entity.


This could certainly be a bug in the new future. For those who come across this in the future, the follow up is on Drupal.org:
https://www.drupal.org/project/easy_breadcrumb/issues/2931141


Restrict admin to search specific content types

I don't think so; you would have to either:

Create a new role and then limit search configuration for that node.
Use Views to simply create another page for administrators where they can search the title/body, limited to a certain type.
Install Views Bulk Operations and Admin Views which will then allow you to change the default administration pages, and limit the displayed content types if you want.
If you need more complex search, look into Search API with Search API Database Search. These modules integrate with Views and you will be able to cover more complex scenarios.

Solutions 2, 3 and 4 use Views, so you will be able to change the number of items displayed per page.

Hope this helps.


hook_form_alter isn't being called when node fails validation

Forms are cached in Drupal so the form is loaded once (where your form_alter runs) and then it's loaded from cache to be reloaded when there are validation errors.

You should use an #after_build callback, which always gets run.

Just remember to return $element in your #after_build callback or you'll be getting WSODs.


How to upload new versions of an image with the same access path?

You can try the Upload File Replace module, This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.

  This is a small utility module that automatically stops Drupal from
  renaming new files upload via filefield CCK. When 2 files with the
  same name exist, the older files will be renamed.


How to detect the region of a block programatically

You can implement hook_block_save($delta = '', $edit = array()) to execute your custom code.


Show Content Type Fields from a entity reference

To show the Parent info (Company) through Child nodes (Employee) you need to add the Relationship for the Entity Reference field that is connecting the child to the parent.

Once you add that Relaionship you will be able to add the fields from the Company CT. Those fields must use that Relationship to show the Company info, otherwise if you don't select the Relationship for a field it will show the original (Employee) info.

So after you add the Relationship for the Company ER field (that is on Employee CT), you will be able to add the Logo field to your Views, and that field will use the Relationship you've just added.


How to add attribute to element in twig before render?

Here is my solution for adding a placeholder to a custom text field being used for inputting search terms in a form.  I could not use element.attributes.setAttributes() because in my case the key for attributes is #attributes.

{% set attr = form.search_api_fulltext['#attributes']|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = form.search_api_fulltext|merge({'#attributes': attr}) %}
{{ search }}

Here is the same expanded a little for clarity:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{{ search }}

Or add a third merge and merge the field back into the form.  Then output the form as usual:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{% set form = form|merge({'search_api_fulltext': search}) %}
{{ form }}


"@sites" is no longer available with Drush 9. I presume this what is being used with Drupal 8 here.

More information here:
https://github.com/drush-ops/drush/issues/3019#issuecomment-334503217

  Drush 9 no longer supports executing a single command on multiple sites with alias lists (@A,@b,@c) or @sites. Neither of those syntaxes are available in any context. You may still use drush sa @group to see all aliases in a group; that is the only context in which Drush recognizes alias lists.


Schema.org itemprop="url" inside anchor object (link)

So after spending some more time on the matter, I finally found the solution and I am posting it here in case anyone is interested.

Simply put the following code in your template.php file, inside your theme folder:

function YOUR-THEME_link($variables) {
  return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
}

Hope that helps..
Remember to change 'YOUR-THEME' to your theme's name, and don't forget to clear the cache.


Grab Data from non form elements and send as POST using AJAX

Hopefully this answer will help someone else looking for the same thing. I found a solution and it works great.

The way that I solved it was by creating two hidden elements with id's in my form. One hidden element for each table that I have in my form.

Below is how I created the hidden form element

$form['orderTable'] = array(
        '#type' => 'hidden',
        '#attributes' => array('id' => 'orderTable')
);

Below is how I created the container that holds the table and is used to generate the table from the Java Script file.

$form['middle']['order-table'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => array(
                'testing-table',
            ),
        ),
    );

The Excel like table that I used Handsontable has an excellent method called afterChange this gets fired after something on the form changes. So what I did is create another Java Script function that gets fired each time inside of the afterChange function.

 function updateHiddenFields() {
    var orderTable = JSON.stringify(hot.getData());
    jQuery("#orderTable").val(orderTable);
}

What this does if your not familiar with Java Script is turn the data from Handsontable into a JSON string and places it in the value field of the hidden element. By doing it this way all of the data is accessible when the form is submitted just like  I wanted and I was able to use the validation function.


Is it possible to select a row with tableselect.js?

The answer is to forget about tableSelect.js and trigger the appropriate eventHandler when setting the checkboxe's attribute to 'checked'.

Here is the code:

var checkbox = tr.find('td input:checkbox');
checkbox.attr('checked', 'checked').triggerHandler('click');

http://drupal.org/node/1477522


check this one

function ptt_contact_form_blocks_submit($form, FormStateInterface $form_state) {
    $form_state->setRedirect('node/24'); // node/$node->nid
}


VotingApi / Fivestar rating Player per Game

You can set up an intermediary content type containing two reference fields and a fivestar field. One reference field references the game, the other references the player. Then use views as a block with a contextual filter to display the fivestar and the player info on the game node.


hook_theme default arguments not recognised in template

You have to do like

/**
 * Implementation of hook_theme
 */
function my_module_theme() {

return array(

'my_theme' => array(
  'variables' => array(
    'var1' => 'default value',
  ),
  'template' => 'my-theme',
),

);
}

Instead of arguments use variables.

Hope this will help.


How to display all links of the Answers module on a single page?

The Panels module allows you to create "pages" of blended content at an URL or URL with a context argument (like a node ID). For example an arbitrary node, 4 views, a custom text panel and a block. It's extremely flexible and fairly easy to learn. Once you've learned the basics you'll never build a site without it.

Panels module


Looks like the id key isn’t matching the router parameter defined in the routing file. It should be either button_set or rrssb_button_set, depending on which one is right. Get that fixed and clear the cache and it should work.


If you create the view as a content pane (panel pane), you are able to select options used in panels on how to receive the context params, (Like from a Panel context of type Node). When adding the content pane in Panels you also get to select which variables should be sent to the view. This is probably what you are missing.


Clean URLs disabled even though module-rewrite is on

I was having the same problem, I opened the /etc/apache2/apache2.conf file and located this portion of the file

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done.


Check effect of hook_schema_alter() hook

This hook is not used to edit the database as such. It is used to alter the schema when using the drupal_get_schema

  Gets the schema definition of a table, or the whole database schema.

  The returned schema will include any modifications made by any module
  that implements hook_schema_alter().

To do what you want you will have to use the db_change_field and this would go in the .install file.

You can check out the Schema API to get other relavent functions

You have to write db_change_field() in hook_enable() function.

Here is my modified answer:

/**
 * Implements hook_enable().
 */
function comment_alter_enable() {
    db_change_field('comment', 'subject', 'subject', array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        )
    );
}


"safe_value" is a "value", passed through the function _text_sanitize().

You can use php function html_entity_decode or use "value" instant of "safe_value". Differences between value and safe_value


In your view, go to section: SORT CRITERIA.
Add field "Content: Post date"
Sort ascending or Sort descending.


drush 7 won't take a command without a site alias?

You need to specify path or create sym link based on your server os.. Check Drush Installation instructions for more details..

It's documented in Github page to under Install Manual..

  Configure your system to recognize where Drush resides. There are 3
  options:

  Create a symbolic link to the Drush executable in a directory that is
  already in your PATH, e.g.:

  $ ln -s /path/to/drush/drush /usr/bin/drush

  Explicitly add the Drush executable to the PATH variable which is
  defined in the the shell configuration file called .profile,
  .bash_profile, .bash_aliases, or .bashrc that is located in your home
  folder, i.e.:

  export PATH="$PATH:/path/to/drush:/usr/local/bin"

  Your system will search path options from left to right until it finds
  a result.

  Add an alias for drush (this method can also be handy if you want to
  use 2 versions of Drush, for example Drush 5 or 6 (stable) for Drupal
  7 development, and Drush 7 (master) for Drupal 8 development). To add
  an alias to your Drush 7 executable, add this to you shell
  configuration file (see list in previous option): $ alias
  drush-master=/path/to/drush/drush

  For options 2 and 3 above, in order to apply your changes to your
  current session, either log out and then log back in again, or re-load
  your bash configuration file, i.e.:

  $ source .bashrc

  NOTE: If you do not follow this step, you will need to inconveniently
  run Drush commands using the full path to the executable
  "/path/to/drush/drush" or by navigating to /path/to/drush and running
  "./drush". The -r or -l options will be required (see USAGE, below).

  Test that Drush is found by your system:

  $ which drush


I do face similar situation and I am trying with http://drupal.org/project/apachesolr_term module.

  This module provides basic indexing of the taxonomy terms for the
  multi entity branch of the Apache Solr Search Integration Module

I will post back my findings soon.


Sort Filter updates both block and page within single view

The default setting is that it will apply to all displays- make sure you choose only the specific one you want.


How to apply spam filter into signatures?

Presumably the content that passes the spam module filter is posted by bots. In that case, using one of the following modules (maybe in addition to the Spam module) may help (by letting the bots fill in hidden forms):

Honeypot
Botcha


Display terms in relation to the terms of the page

1) Create a view of your products

2) Under Advanced, add a RELATIONSHIP of Taxonomy terms on node

Checkmark ☑ require relationship

3) Add a CONTEXTUAL Filter of Has taxonomy term ID

Select provide default value
Select Taxonomy term ID from URL
Checkmark ☑ load default filter from node page


View with nodes but pull only one field from collection

There is another solution mentioned in the issue that you reference in your answer that I would say is a good solution.

Add a new view mode. You could use the entity view modes module if you didn't want to code it yourself.
Configure that view mode for your field collection so that it only shows the photo and not the caption.
Don't add a relationship to the field collection because it will cause rows per field collection item.
Configure your view to display the field collection as one of the fields. Select the view mode you created. In the "Multiple field settings" part of the field definition configure it to Display 1 value(s) starting from 0 to just show the first one.


Cannot find image properties when uploading

I finally found the answer. There was missing packages in my server configuration...I needed to install those :

aptitude install php-apc php-pear php5-curl php5-gd php5-mcrypt


Problem with JS converting module form d6 to d7

Make sure that the $(selector, context) is valid on the page it's being called. You should be able to do this by doing a console.log($(selector, context)); in the first line of the function.

Assuming the selector and context are valid, the .each() should be executed.

If they are not valid, you may have to replace the element or context being passed into Drupal.smackdown.attachNotice().


If you create the COD payment method yourself you can in the code that would normally process payments ect. add the fee to the order by adding a line item to the order. You could use a custom price formatter instead of showing the line item.

I have answered how add a line item in code here.


What is the best way to preprocess fields with Display Suite

You can customize your field at theme level by using TEMPLATE_preprocess_field() function at template.php

You can get get some field value by node object or by fetching field values itself. You can do something like this to get fields value by node object --

function MYTHEME_preprocess_field(&$vars) { //Replace your theme name MYTHEME here.
  if ($node = menu_get_object()){
    if($node->type == 'PRODUCT_DISPLAY'){//Use your product display name here.
      $vars['node'] = $node;
      $product_id = $node->FIELD_PRODUCT_REFERENCE[LANGUAGE_NONE][0]['product_id'];//Use your product ref field name here.
      $product = commerce_product_load($product_id);
      $manufacturer = $product->FIELD_PRODUCT_MANUFACTURER[LANGUAGE_NONE][0]['value'];//Use your field name of product type here.
      $final_body_label = "Description by ".$manufacturer;

      //Set body label for node from here itself.
      $node->content['body']['#label_display'] = $final_body_label;

      //Or set a variable to use it further.
      $$vars['manufacturer_description'] = $final_body_label;
  }
}

Further you can use your default template for node or page if it fulfils what you want or you can make separate TPL for fields too, which will be named like field--field_image.tpl.php, where field_image is field name of your content or product.

You will get default field.tpl in $base_path/modules/field/theme.


how to filter by YEAR of a date (not the published date) in a view

If I am not mistaken this has to do with the granularity setting of the filter. At the moment you add the filter in Views you can set the granularity (if it already exists you can change it by clicking the filter or clicking the settings link behind it).

Contextual

Make sure to select Date: Date (node) as the contextual filter type. Also make sure this is set to year to make the filter work per year only and select the field you want to filter on.

this allowed me to use /2015 in my url to filter nodes with a date field with a 2015 value.

Exposed

If the problem is with exposed filters, just select the date field, and set the granularity to year:


Advanced Forum - how do I delete a forum?

Structure > Forums > You should see General Discussion listed, hit the Edit Forum link > Scroll down and hit the delete button