Remove and uninstall module in a single patch One of the modules I maintain contains a sub-module. The sub-module doesn't do much; just provides views integration for the main module, i.e. only have implementation of hook_views_data. I would like to move this implementation to the main module.

If it was D7, I would have followed the steps below:

Remove the module files.
Write an update hook in the main module, to remove the entry from the system table.
In the same update hook, would delete the variables (if present).

For D8, I have written an update hook for the same in the module (Reference : #2781805 : Social stats field are not available in views):

/**
 * Implements hook_update_N().
 *
 * Removes entry of social_stats_views module.
 */
function social_stats_update_8001(&$sandbox) {
  // Read the configuration.
  $module_data = \Drupal::config('core.extension')->get('module');

  // Unset the modules you do not need.
  unset($module_data['social_stats_views']);

  // Write the configuration.
  \Drupal::configFactory()->getEditable('core.extension')->set('module', $module_data)->save();
}

I did not add anything else (like removing config, etc.), as the module only implemented a single hook.

I still see the following error after executing the update hook:

  User warning: The following module is missing from the file system: social_stats_views in drupal_get_filename() (line 236 of core/includes/bootstrap.inc).

Is there a bullet-proof way to remove the module?

You can use ModuleInstaller::uninstall():

\Drupal::service('module_installer')->uninstall(['social_stats_views']);

In D8 there is a lot of housekeeping to do. You can see this in the code of uninstall():

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Extension!ModuleInstaller.php/function/ModuleInstaller%3A%3Auninstall/8.2.x


Webform/SwiftMailer - TypeError in encodeString() - must be of the type string, array given I got into an issue while using a combination of SwiftMailer and Webform on Drupal 9. I found nothing helpfull while Googling and it took me a few days to figure out the issue. Hence I am sharing my findings with you.
My context:

Drupal 9.1.3
Webform 6.0.2 - with an Email Notification Handler
MailSystem 8.x-4.3 - Module: Webform / Formatter: Swift Mailer /
Sender: Swift Mailer
Swift Mailer 8.x-2.0 - set up to send SMTP emails

The problem:
The website encountered an unexpected error. Please try again later.
TypeError: Argument 1 passed to Swift_AddressEncoder_IdnAddressEncoder::encodeString() must be of the type string, array given, called in /home/www/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php on line 378 in Swift_AddressEncoder_IdnAddressEncoder->encodeString() (line 32 of vendor/swiftmailer/swiftmailer/lib/classes/Swift/AddressEncoder/IdnAddressEncoder.php).

How the problem manifested:

the error above was displayed on the website's footer
none of the AJAX driven features of the website didn't work - the ones from the admin interface, nor the ones in the front-end

The cause and my solution:
In the Webform's email handler configuration -> "Send from (website/domain)" section -> "From email" field, I used the [site:mail] token.
In EsmtpTransport.php line 378, the $address parameter had a value of ["email@example.com" => string(0)].
By modifying the "From email" field to "Site email address" solved my problem.
Hope this helps.


Host blocked website due to sending spam from website My hosting provider has blocked my Drupal website due to:
sending spam using local e-mail sockets /var/www/vhosts/site domain/httpdocs/sites/all/themes/chaymae/css/mailer.php.php

I am currently not using the mentioned theme, but this is a standard theme in Drupal.
I also have installed the BOTCHA module on the website and it's active.
Can anyone help to solve this problem?

Your hosting provided blocked your website, because it was used for sending the spam from using PHP scripts which were suspiciously uploaded to your Drupal installation folder (by using some vulnerabilities).

Why this happened?

There could be many issues, including contrib modules or Drupal core vulnerabilities.

Please follow Drupal Security advisories to be up-to-date.

If your Drupal version is 7.32 or below, there is Highly Critical issue (SA-CORE-2014-005) which people call Drupalgeddon. See FAQ and Drupalgeddon project for more details. Also my GitHub repo (drupageddon) for educational purposes (to understand how it works).

What to do

To prevent that from happening, first of all, check Status/Reports in Administer page to see if you've any Security warnings and your site needs some upgrades.

Then you may consider to log-in to the website (ssh) and scan for suspicious files.

You should look into these tools to help you with restoring your Drupal security:

Security Review
Site Audit
Hacked!

  If you use drush (and you've alias set-up to your environment), check for Hacked! module. It can find which core files or modules were hacked, but it could find only modified one, not the one which are extra.

If you're using drush, other trick can be to generate your make file (drush generate-makefile) from your current Drupal site (however this is probably not necessary, but it keeps track of your old version of modules), then run drush up. This will upgrade your Drupal core and all contrib projects and apply any pending database updates. How would that help? It'll actually upgrade all core/module files by replacing old directories with fresh version of stable release files (so any extra files which aren't part of the module would be automatically removed).

Finding suspicious files

To fix your infected website installation, you need to find files which were hacked and malware files in your Drupal installation folder.

You actually found one at (which is a good start):

  /var/www/vhosts/site domain/httpdocs/sites/all/themes/chaymae/css/mailer.php.php

which needs to be removed as soon as possible. Probably you have more of them.

If there is no access to shell, transferring over FTP (ncftpget -R) and checking locally would help. Or find other way to backup your whole site and test it locally for any extra files or hacked files.

If you don't use git, I would suggest you to download your Drupal site into folder and create git repository, so you can track the changes.

For example:

git init
git add -A .
git commit -m 'My original files.' -a

Then upgrade all your core and modules and review the changes (git diff), and commit all again.

Here are few commands which can be useful to find suspicious files (in your webroot):

grep -R return.*base64_decode  .
grep --include=\*.php -rn 'return.*base64_decode($v.\{6\})' .
find . -name \*.php

Above results doesn't mean necessary suspicious files, but you need to use your common sense to identify which files aren't Drupal. Usually these files are obfuscated.

Please find the following repository with common php-exploit-scripts to give you some idea what you could deal with. See also: What does this malicious PHP script do?

Unblocking your site

Once you find your problem and identified malware files, then remove these files from the server and upgrade your core and modules to the recent secure version and inform your hosting provider that you've removed malware so they can unblock your site.


Block the node which I am currently in I am discovering one problem on my page - as a content I have some recipe. Under it, I've created a block which is displaying "Simular recipes". And now, this block is displaying some simular recipes AND the one which is in the content page above.
So, I would like to ask if someone can help me how to do filtering to make this block not showing me the recipe which is in the page. Basically, need to block the node which I am currently in.
Thanks in advance.

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


select paged nodes by using selectNode of drupal 7 service module? i'm developing a mobile apps call the drupal service, i'want to get paged nodes of relative taxonomy_term, selectNodes seems can help

http://domainABC.com/my_services/taxonomy_term/selectNodes/

But how do i call page 2 of the nodes of the taxonomy_term (suppose 25 nodes per page)?

i looked the source code (taxonomy_resources.inc) but still don't have idea to do ,

    function taxonomy_service_select_nodes($tid = '', $pager, $limit,  $order) {
      $result = taxonomy_select_nodes($tid, (bool)$pager, $limit, $order);
      foreach ($result as $nid) {
        $node = node_load($nid);
        if ($uri = services_resource_uri(array('node', $nid))) {
          $node->uri = $uri;
        }
        $nodes[] = $node;
      }
      if (empty($nodes)) {
        return services_error(t('No nodes were found with tid @tid', array('@tid' => $tid)), 404);
      }
      return $nodes;
    }

'actions' => array(
        'selectNodes' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/taxonomy_resource'),
          'help'   => t('This method returns all nodes with provided taxonomy id.'),
          'access arguments' => array('access content'),
          'callback' => 'taxonomy_service_select_nodes',
          'args'     => array(
            array(
              'name'         => 'tid',
              'type'         => 'string',
              'description'  => t('The vocabulary ids to retrieve, separated by comma.'),
              'source'       => array('data' => 'tid'),
              'optional'     => FALSE,
            ),
            array(
              'name'         => 'pager',
              'type'         => 'int',
              'description'  => t('Whether the nodes are to be used with a pager (the case on most Drupal pages) or not (in an XML feed, for example).'),
              'source'       => array('data' => 'pager'),
              'optional'     => TRUE,
              'default value'=> TRUE,
            ),
            array(
              'name'         => 'limit',
              'type'         => 'int',
              'description'  => t('Maximum number of nodes to find.'),
              'source'       => array('data' => 'limit'),
              'optional'     => TRUE,
              'default value'=> FALSE,
            ),
            array(
              'name'         => 'order',
              'type'         => 'int',
              'description'  => t('The order clause for the query that retrieve the nodes.'),
              'source'       => array('data' => 'order'),
              'optional'     => TRUE,
              'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
            ),
          ),

The callback function

function taxonomy_service_select_nodes($tid = '', $pager, $limit,  $order) {
  $result = taxonomy_select_nodes($tid, (bool)$pager, $limit, $order);
  foreach ($result as $nid) {
    $node = node_load($nid);
    if ($uri = services_resource_uri(array('node', $nid))) {
      $node->uri = $uri;
    }
    $nodes[] = $node;
  }
  if (empty($nodes)) {
    return services_error(t('No nodes were found with tid @tid', array('@tid' => $tid)), 404);
  }
  return $nodes;
}

Anyone know?

(post)

The url link should be

http://domainABC.com/my_services/taxonomy_term/selectNodes?page=1

parameter:

tid=1

problem fixed.


Show specific articles when clicking on tag I'm working with a page view that contains articles and a block view that contains tags. I would like to display all the articles tagged with the tag I click.

So when clicking on the CITY tag I only want to display the articles tagged with CITY, does anyone know how I can achieve this?

Thanks

Give the page view a contextual filter for the taxonomy term field in question and click "Specify validation criteria", then choose the "Taxonomy term" validator, select your vocab, and select "Term name converted to Term ID" for the "Filter value type" setting, like this:

Then in your tags view, for your term name field, select "Output this field as a link" and set the "Link path" to be the path of your page view, with the term name on the end for the contextual filter, like so ([name] is the term name field in my case):

- Note that if this is a content view instead of a taxonomy term view you will have to add a relationship for your taxonomy term field before you can use the term name field. In your case the relationship should be "Content: Tags".

This would be the same for other entities, for example if your view was a user view and the user had the  tags field on it.

Alternatively you could use the term ID contextual filter and term id field instead of using term name and the convert term name to term id option.

I prefer the term name as it looks nicer than term id in the url, but if you have really long term names or they have strange characters in them or anything the term id might be preferable.


Does Ubercart have an external API? Does Ubercart have an external API that a 3rd party site could query? Specifically from a fulfillment point of view? We need to be able to query the system for items to ship, then update the order's status and set a tracking number after the item shipped. All this is done on a completely different server/company, so needs to be done via a publicly exposed API (like a REST or SOAP service). Does Ubercart do something like this?

Ubercart does have an API (see http://www.ubercart.org/docs/api and http://api.ubercart.me/ ), but I don't see general REST or SOAP support related to fulfillment.

Some options may include miniRESTapi or as noted UCServices and Bee Colony for Drupal 6. There are some vendor-specific SOAP implementations for CyberSource, but I do not know how well-supported they are.


Performance for file serving and storage I intend to allow users to upload images to my website, but I'm concerned that Drupal's default handling of files might not be cut out for storing and serving potentially thousands of files without bogging down. Should all files be stored in the same directory? Should I use something like amazon instead of the same server the website is stored on?

What are the best practices for serving images, potentially thousands or tens of thousands, through a Drupal 7 site? Is it reasonable to expect Drupal to perform well if I just leave it the file handling as is?

If you are storing them the public file system, Drupal does not really interact with them other than to provide the URL.  The .htaccess rules check if the request is for a real file.  If it is a real file, the web server service it up.

So for individual files, it is more about can your webserver handle the load.  You probably want to look at using a static file caching service in front of your site.  CloudFlare does a good job and its basically free. Some alternates are to have a varnish server or a caching Nginx server in front of your server.

Drupal has been used for a lot of sites with a lot of users, files and the like.  E.g. I know that Story Corps uses it internally to manage the thousands (millions) of interviews  they have.

Just be aware that if you need to have a large volume site, you will need to plan for a large volume system setup.  This is true of ANY web software you use.


Alter Views query limit using views_query_alter I want to alter the limit of view using views_query_alter hook.

My code is :

function track_click_views_query_alter(&$view, &$query) {
  if($view->name == "click_list_days"){
  $w_count = count($query->where[0]['clauses']) - 1;
  $w_clause = array();
  for($i=0; $i <= $w_count; $i++) {
      $w_clause[] = "(".$query->where[0]['clauses'][$i].")";
      if($i > 0)
          unset ($query->where[0]['clauses'][$i]);
  }
  $w_clause = implode(" AND ", $w_clause)." Group By track_click.article_title ";
  $query->where[0]['clauses'][0] = $w_clause;
  }
}

How can I alter the limit of this views query? I didn't understand which query object i have to alter.

If it's only about the number of results to return, I think you could simply implement hook_views_pre_build() and do the following:

function track_click_views_pre_build(&$view) {
  if ($view->name == 'click_list_days') {
    $view->set_items_per_page(YOUR_NUMBER_OF_RESULTS_HERE);
  }
}

Or inside hook_views_query_alter() you should be able to do:

$query->set_limit(LIMIT);


Disable product when out of stock I would like to disable a product as soon as it's stock drops to 0 in Drupal commerce.

I think this might be possible by using rules, but then I don't know what will happen to the product display. I figure that when there are no more active products attached to a product display, the display will still appear in my views but without any product information attached to it. In this case I would also like the product display to be "unpublished".

I can't unpublish the product display immediately after a given product is out of stock because there could be more products added to a single display...

Can some one help me to achieve this through rules or is there some other method that I could use?

I'm using Drupal Commerce and the stock module for it.

Seems really odd that the maintainer would say that this was impossible and a fringe case.

Seems to me like this is a very normal use case, in fact one that we use on every single Ubercart site we have in production. I actually thought this was a setting in the module config page and was surprised to see that it wasn't.

Anyway, here's what I did. I disabled the included rule because I despise rules and added this code to my module:

/**
 * Implements hook_commerce_checkout_complete().
 */
function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $order_wrapper->commerce_line_items->value();
  if (is_array($line_items)) {
    foreach ($line_items as $line_item) {
      if (in_array($line_item->type, commerce_product_line_item_types())) {
        $product = commerce_product_load_by_sku($line_item->line_item_label);

        // Subtract the sold amount from the available stock level.
        $qty = (int) $line_item->quantity;
        module_load_include('inc', 'commerce_stock', 'commerce_stock.rules');
        commerce_stock_adjust($product, -$qty);

        // Disable the product if we have no stock left
        $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
        if ($product_wrapper->commerce_stock->value() <= 0) {
          $product_wrapper->status->set(0);
          $result = $product_wrapper->save();

          if ($result) {
            watchdog('commerce_stock', 'Product %sku stock level reached 0, status set to 0.', array('%sku' => $product->sku));
          }
          else {
            watchdog('commerce_stock', 'Failed attempt to disable product %sku', array('%sku' => $product->sku), WATCHDOG_ERROR);
          }
        }
      }
    }
  }
}

It's just a copy of the default rule that ships with the module with the extra code for disabling the product added in.

I guess you could leave the default rule active and remove the 3 lines that adjust the stock level in my example, but then I'm not sure what would be called first, the rule or my hook so you would have to test that yourself.


Drupal 8, don't automatically execute the view after the first load of the view page I created a view page from the admin interface. Then when I go to the view page url with my browser, the view is displayed and show automatically some results.

Now, I want force the user to click on the execute view button for display results. I mean, the user go to the view page url, only exposed filters are displayed, he must click on the view submit button for display results of the view.

It's possible to configure that from the view interface configuration (I didn't find..) or I must use a custom module ? (and how?)

Thanks you :)

I find from the view ui how configure for "force" the user to submit the view for show results ! In the view ui, to the right (in the advanced settings), click on "exposed form style" and choose "Input required" :)


Why drupal includes *.profile file on every page? I developed an installation profile that contains many various hooks. After an installation process, it is still included on every page, and all my installation hooks are executed. Please explain me why it happens, and by which way I can avoid including *.profile file after the installation.

This is a new feature of Drupal 7: install profiles behave like modules.

See #509398 : Install profiles should be modules with full access to the Drupal API and all it entails

Code that you don't want loaded during run-time should be moved to hook_install().

Edit - Xio asked about uninstalling a profile.
variable_set('profile', 'standard');
might work.


Alternative to RedirectResponse I have a module that returns a redirect response in hook_node_insert().

$url = 'announcements';
$response = new Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url($url, [], ['absolute' => TRUE]));
$response->send();

I have another module that implements hook_node_insert() for the same content type. Since I have written redirectResponse in the first module, the hook_node_insert() implementation in the second module is not getting called.

Is there any other way to do it? Drupal 7 has $_GET['destination'] and it works for Drupal 7.

Generally speaking, directly redirecting from a hook is something you should not do because it would not allow other hooks to be invoked, and it would stop what Drupal is doing.
In the specific, hook_node_insert() would also be invoked when a node is programmatically created from a module, for example in a hook_install() or hook_cron() implementation, or from a Drush plugin. In those cases, redirecting inside hook_node_insert() would just break Drupal core or third-party modules.

If you want to redirect users, the proper moment is after a form has been submitted. It is also preferable, because you can tell Drupal where you want to redirect users, and Drupal will do it after all the involved hooks are invoked.

You just need to add a form submission handler to the node edit form. Inside that, you redirect users with $form_state->setRedirect($route_name) or $form_state->setRedirectUrl($url) where $route_name is the name of the route (a string), and $url is a \Drupal\Core\Url object.


Change default messages from Poll? We're running the core Poll module on our site, and we'd like to change the default messages that it generates. I'm meaning stuff like Your vote could not be recorded because you did not select any of the choices.

I looked at the poll content type, but there weren't any settings for it there. It's apparently not listed under modules, because it's core, I suppose.

How can I change these messages from their defaults?

You can use the String Overrides module.  More options are described in the handbook page Change default strings (text).


Access multiple values by index in a view I have a multi-value field. When I output this field in a view I use Rewrite results and reference this field as [field_product_image]. This outputs all the images of the field.

How could I output only certain element of this array, e.g. second image using rewrite results (this is essential)?
Neither of these works:

[field_product_image:0], [field_product_image_0], [field_product_image-0]

For that you need to check the Group multiple values and then set to show 1 values  and set starting from 1. see the below screenshot for clarification

if you check the rewrite output of this filed you can see the token for that filed, for your case it would probably

  [field_product_image_1]

So if you want to retrieve the image separately from the array, you have to do the above steps for each image, for example if you want the 3rd image, then you have to set starting from 2 and its tokes is [field_product_image_2], if you want 4th image, then you have to set starting from 3 and its token is [field_product_image_3].

Below screenshots will help you to understand easily.

I added each filed separately to retrieve each image

and its tokens and above method is for Drupal 6, you can do it in the same way for D7.


override MenuLinkTree Block I want to override the block menu behavior, but i don't know how to do that, because the menu block are created dynamically.

I know add some block with the block plugin, like this :

/**
 *
 * @Block(
 *   id = "system_name_block",
 *   admin_label = @Translation("my Block"),
 * )
 */

But i don't find how the core deal to create dynamic block for the Menu link tree.

I ever know that i have to override this class to get the espected behavior :
Drupal/Menu/MenuLinkTree.

But Now i've to know how to create dynamically some block to use it.

The menu block is defined in the core module system.

Here you can see how the menu tree is set when creating the object:

core/modules/system/src/Plugin/Block/SystemMenuBlockTest.php:

namespace Drupal\system\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuActiveTrailInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a generic Menu block.
 *
 * @Block(
 *   id = "system_menu_block",
 *   admin_label = @Translation("Menu"),
 *   category = @Translation("Menus"),
 *   deriver = "Drupal\system\Plugin\Derivative\SystemMenuBlock"
 * )
 */
class SystemMenuBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;
  ...
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $menu_active_trail) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->menuTree = $menu_tree;
    $this->menuActiveTrail = $menu_active_trail;
  }

How to use your own menu tree in a menu block you can see in this test:

core/modules/system/src/Tests/Block/SystemMenuBlockTest.php

Example from SystemMenuBlockTest.php. A menu that was created before is put in a block config:

$block = Block::create(array(
      'plugin' => 'system_menu_block:' . $this->menu->id(),
      'region' => 'footer',
      'id' => 'machinename',
      'theme' => 'stark',
    ));


How to add a image style to an image in a template file? I need to change these lines (belong to a tpl.php file) to include a image style called "adaptative_image_style" to the generated image.

<?php print l(theme('image', $image_attributes), $ad['url'], $link_attributes); ?>

I think I should use the function to theme_image_style($variables) instead but not sure how to implement it.

Based in Clive's answer I get it working with this code:

  <?php
  $image_attributes['style_name'] = 'adaptative_image_style';
  print l(theme('image', $image_attributes), $ad['url'], $link_attributes); ?>

The docs page has it pretty much covered but here's an example if you're struggling:

$style_vars = array(
  'style_name' => $style_name,
  'path' => $image_path,
  'alt' => $alt_text
);

$image = theme('image_style', $style_vars);

$link = l($image, $url, array('html' => TRUE));


Translate message from tabledrag.js I try to translate the message that is used in the following JavaScript code.

Drupal.t('Changes made in this table will not be saved until the form is submitted.')

I use the String Overrides module; I tried also translation using settings.php. None of the methods work.

Does anybody have an idea on how to translate the sentence? I do not want to use big modules like localize.

Drupal loaded only the needed strings on every page which we are included.
Those strings are added in javascript itself.

I think this is fixed by across the script files before they are actually added to the page.

So, you should be able to translate that string into the translate interface.

For more help, You can see this link,

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

Hope it will be helpful.


Blank search should show all results I remember that, in previous versions of the Search API and Search API Solr, by default not entering any search term would return the entire list of items.

I have tried with new empty Drupal 8.5.1 using Search API and Search API Solr, using the default configuration, with MariaDB and Postgresql, using the default view pages /search/content and /solr-search/content, but it shows an empty list and the message Please enter some keywords to search. message.

Does somebody know how to change it to the previous behavior to get again the whole list of elements when no search terms are used?

After trying everything that I could figure out, I have uninstalled the module, deleting all the views and installing it again and it works. No idea about what was happening sorry, but it work.

Finally thanks for some help I could understand what was happening :D The Filter Criteria Fulltext search was a Required, if you remove the checkbox then you will get the full list of items by default.


Drupal daylight savings issue My drupal installation is still displaying summer time after the daylight savings switch yesterday. Wrong dates include the following pages:

Views displaying nodes with created/updated fields
Drupal reports
page

My timezone is set in drupal config to Europe/Bratislava. I have tested the raw date() function in the web server, and it returns the correct time.

It seems that dates are saved correctly by timestamp using a time() function; the problem is displaying. Can anybody tell what is wrong? Is it a bug, or something else?

I have already found a problem. Drupal variable date_default_timezone was set to 7200 for Europe/Bratislava timezone. In fact, the correct value for winter time is 3600 for this timezone.

Solution was to resave the timezone settings under the Drupal "Date and time" configuration within the administration menu. It will then adjust the date_default_timezone variable.

I am just curious, why is this switch not happening automatically?

Try out Daylight saving time module.

  This module intended to work with Daylight saving time. It replaces
  system time offset and has preferences for each user and full site.

  Used to display correct time of creation of documents etc.


Profile Completion e-mail to user in Drupal Hi in drupal(6) how to send reminder e-mail to the user whoever did not complete the profile information?

Is there any module available to do this? i think we can do using rules/trigger. but not exactly. I need similar to that what cron job do in php. Help me out.

Use Rules, I actually have the below working for an Intranet site I manage.

ON - Choose your event, maybe "User has logged in"
IF - "Content Profile's field 'field_NAME' has value"
DO - "Send a mail to the user"

Replace the field_NAME with the field you would like to check, In the IF I just check for a NULL value on a required field.

return array( 0 => array('value' => ''), );


Include images in Aggregator feed Drupal 7.  I'm bringing in an RSS feed, and for the most part it's working.  It's not, however, bringing in the images with each entry.  I tried adding an  to the list of allowed tags in the admin screen, to no avail.  The lines come across as this:

<media:thumbnail url="http://www.bjtonline.com/uploads/tx_bjt/FINAL3_Flexjet_thumb_b.jpg"/>

Any ideas?

As I've not gotten anywhere with this, I'm working around it.  I'm only interested in bringing in the most recent article from a site that's on our own servers - so I'm writing a script that will import it into the node table and I'll use Views for the block.

I'll set the script to run nightly. Thanks for the help guys.


How do I override the login function I have inherited an outdated Drupal 6 site with hacked modules. I did update core and all the modules that I could.

This php code is from a block for logging in. This redirects an authorized user to be directed to node-20.tpl.php.

<?php  global $user; ?>
<form action="<?php print "/{$base_path}user/login/?travelagents"?>" method="post" id="user-login">

CLIA number or Agent key:

      <input type="text" maxlength="60" name="name" id="edit-name" size="22" value="" tabindex="1" class="form-text required" />
      <input type="hidden" name="pass" size="20" value="password" />
      <input type="hidden" name="form_id" value="user_login" />

      <input type="submit" align="middle" name="op" class="form-submit" id="edit-submit" tabindex="2" value="Log in" src="/<?php print path_to_theme() ?>/images/login.gif" alt="Submit" />
</form>

My client asked me to override the login for users without authentication (ultimately allowing anonymous users to login and see what authorized users see). The other requirement is that authorized users with their unique ID must still be able to use the login box and get redirected appropriately.

I have been able to create a way to automatically login using 00407606 (a special functional generic ID) in the value=field and if I change the text field to hidden a user can click the submit button and be logged in automatically and redirected appropriately. But applying this removes the ability for registered users to input their unique ID and login normally.
This login is not the username-password of Drupal, it is a unique 8 digit number in a created table in the database.

Is there a php solution to do this? Is there some code in logintobbogan I could mimic/use? Am I looking for a javascript solution?

Hey if you have any idea about drupal form alter then go with http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_form_alter/6.

hope this will help you.


How can I add a custom "Date" field as a field in a view? I created a custom Content Type called "Event". In it, I use a custom "Date" field (from the Date module). When I try to create a View that displays all of the Events sorted by their Date, I can do this. However, when I try to add a field for "Date" so that I can display it in the output, "Date" is not shown in the list of fields. Is this because not all content types have a "Date" field? How can I get around this?

I'm not sure why you're having trouble.  I just did this and it worked.  Here's what I did.

Add a "Date" field (widget: select list) to Content Type A.
Create a view that shows items of Content Type A.
Click Add next to Fields and search for the label for my "Date" field.

You should try looking through/searching your list of fields again.  It should be there.  (Even when a view is filtered to a specific content type, the Views module will often allow you to select fields that are not associated with that content type.)


Skip to Main Content link not working? The theme I'm using (AT Panels Everywhere subtheme for Adaptivetheme) has the following skip navigation link:

Skip to main content

but that link goes nowhere when I hit Enter when that div becomes focused as I tab through on the keyboard.

I tried adding the "content" anchor tag like this:

<?php print $content; ?>

but it still doesn't work. I'm still forced to tab through every link on the page.

What am I doing wrong?

Try changing your code like this

Skip
<?php print $content; ?>


Is it possible to use ajax inside the html output of a computed field? I tried making a simple computed field that outputs some html that can be latter modified with Ajax. If we consider a typical hello world example, the computed field output would be a link saying 'say hello' and when you click on it the AJAX adds the text 'hello world' in the div below the link. This is based on a javascript/ajax example inside 'Drupal 7 Module Development' by Matt Butcher. It works inside a normal page, but inside a computed field it gives an error.

Here is the code for my computed field. It just creates a link which is ajax enabled and a second div where ajax content will be inserted.

drupal_add_js('misc/ajax.js');
$link = l(t('Say Hello'), 'hello_world_link_callback/ajax/', array(
           'attributes' => array('class' => array('use-ajax'))));
$output = '
' . $link . '

';
$entity_field[0]['value'] = $output;

Implementation of hook_menu() to create the AJAX callback function:

$items['hello_world_link_callback'] = array(
    'page callback' => 'hello_world_link_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
);

Here is my callback function:

function hello_world_link_response($type = 'ajax') {
    if ($type == 'ajax') {
        $output = t("Hello World!");
        $commands = array();
        $commands[] = ajax_command_append('#saying-hello', $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
    }
    else {
        return t("Hello World in a new page.");
    }
}

When I click the link it crashes to a white screen with this text:

[{"command":"settings","settings":{"basePath":"/drupal/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme_token":"fN8xkldpLQAwubNZ1n0BzdQPnF577BDw6sfuzoVrcmw"},"overlay":{"paths":{"admin":"node/*/maestro\nnode/add/*/maestro/*\nnode/*/edit/maestro/edit/*\nmaestro/trace/*/*/*\nnode/*/edit\nnode/*/delete\nnode/*/revisions\nnode/*/revisions/*/revert\nnode/*/revisions/*/delete\nnode/add\nnode/add/*\noverlay/dismiss-message\nuser/*/shortcuts\nadmin\nadmin/*\nbatch\ntaxonomy/term/*/edit\nuser/*/cancel\nuser/*/edit\nuser/*/edit/*\ndevel/*\nnode/*/devel\nnode/*/devel/*\ncomment/*/devel\ncomment/*/devel/*\nuser/*/devel\nuser/*/devel/*\ntaxonomy/term/*/devel\ntaxonomy/term/*/devel/*","non_admin":"admin/structure/block/demo/*\nadmin/reports/status/php"},"pathPrefixes":[],"ajaxCallback":"overlay-ajax"}},"merge":true},{"command":"insert","method":null,"selector":null,"data":"","settings":null},{"command":"insert","method":"prepend","selector":null,"data":"","settings":null}]

Any ideas?

Updated based on comments from tenken

I've altered hook_menu to be a callback only and set the delivery callback to be an ajax response. I've also split the hook_menu into items for the cases with and without ajax. So the hook_menus now look like this:

$items['hello_world_link_callback/nojs'] = array(
    'page callback' => 'hello_world_link_response',
    'access callback' => TRUE,
    'access arguments' => TRUE,
    'type' => MENU_CALLBACK,
    'page arguments' => array(1),
);
$items['hello_world_link_callback/ajax'] = array(
    'page callback' => 'hello_world_link_response',
    'access callback' => TRUE,
    'access arguments' => TRUE,
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
    'page arguments' => array(1),
);

The callback function is unchanged from above with the exception that it now returns the AJAX commands, rather than calling 'ajax_deliver'. So it returns:

return array('#type' => 'ajax', '#ajax' => $commands);

This code is now working for me, so it had nothing to do with the fact that it was a computed field. This code is also covered here.

Well, it's not Crashing with a white screen. You are using ajax_deliver which returns the content of your response as plain text and stops further page rendering.

A Crash would be a WSOD and no output. Check your hook_menu definition and be sure its setup as a non-menu item ... just a callback. You do this by setting the type in the $items array. You may also want to set the delivery callback value to be an ajax response.

Lastly, your link goes to hello_world_link_callback/ajax/, but that is not the URL you have defined in your hook_menu function. It may be a best-fit match for Drupal on a lookup.... but I doubt it.


how to set smtp for drupal I am working on Drupal 6  my php.ini settings are:

SMTP = localhost
smtp_port = 25

in module in am using

function article_mail($key, &$message, $params) {
  switch ($key) {
    case 'invitation':
      // note: data can be passed to this function in the $params array
      $message['subject'] = t('EMAIL SUBJECT');
      $message['body'] = t('MESSAGE BODY');
      break;
  }
}

and in code i use

$params = array(  'myVar' => 'data you would like in your message and/or subject',);
drupal_mail('article', 'invitation', 'sanjaydev@xolva.com', language_default(), $params);

but it gives

  warning: mail(): Failed to connect to mailserver at "localhost" port
  25, verify your "SMTP" and "smtp_port" setting in php.ini or use
  ini_set() in C:\Program Files (x86)\Apache Software
  Foundation\Apache2.2\htdocs\benthamdirect\includes\mail.inc on line
  193. Unable to send e-mail. Please contact the site administrator if the problem persists.

Can anyone suggest where I am going wrong?

Try the SMTP module to send mails via SMTP:

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


Filter values of a cck field with a view When I create a new node of a certain type, I would like to filter a certain field depending on a view. For example I would like to filter through the top 3 latest news stories (as the view will filter though a news story content type which will display the 3 latest news story only so the sort criteria would be by the date).

Thanks in advance!

If you want to show the latest 3:

Set the Fields you want to display, most likely Node: Title
Under Basic Settings set the limit to "3"
Add a Sort Criteria Node: Post date - ascending
Other Filters you'll want to add are: Node: Published - Yes & Node: Type

Hope this helps!


How to access $variables in a module function where $variables is not passed to it. (D7) I have a custom module that retrieves a view.

I would like to set a page variable that sums up a bunch of fields as im iterating through them.

So how to i access the $variables variable if it isnt an argument of my function?

Call your function from inside your module's preprocess_page() hook.  Eg, in your custom module, let's say your function that calls your view is mymodule_call_view().  Let's further assume it returns the value you want to set your page variable to.  You could do it this way:

mymodule_preprocess_page(&$variables) {

  // any other preprocessing you are doing goes here

  $variables['variable_you_want_to_set']=mymodule_call_view();

}

Then, when drupal is building the page, it would call your preprocess function, which would call your function that iterates through the view, etc...


How to remove form elements before submitting the form? All form items in Drupal must be created with Form API, otherwise form values in $form_state and in $_POST variables are empty after submitting the form.

But sometimes I need to have in form some other items, not created with Form API.  For example  I want to use external jquery plugin like Pickadate (similar like datepicker). This js plugin adds some HTML form elements into  object. And many other js plugins creates their own form elements on client side.

But when I use these plugins, form sent empty values after submitting. So before submitting the form, I need to remove these custom elements from form. I don't need values from these elements, they just help to pick the value selected by user.

Is there any workaround, some event, that can help me remove these elements right before submitting the form?

There are two ways, actually:

Wrap them into a proper modules. You will avoid conflict with Form API by cooperating with it. See Datepicker's code to get idea how to do it.
Create onsubmit javascript event and remove elements with jQuery.


I can't get the correct current language in node URLs In D8, I have a website set up with 5 languages, using file path, like so:

 website.com/en/link
 website.com/en-us/link
 website.com/fr-ca/link
 etcetera.

I've made a view of blogs and resources. It includes a filter to current language selected for page and Not Specified-- this is to include articles that are intentionally set to Not Specified, so they show up for ALL languages. ( I don't want to have to turn 1000 blog posts into 4000 duplicates)

Problem is, the view is showing the link to items ONLY in the default language (EN)
Regardless of what language I view the website in.

I'm using a hidden "Link to Content" field within a custom field for each item. I've UNchecked 'use absolute url'.  I'm not sure what else to do. It doesn't make sense to me that it would be ignoring the site's current language.

If it's relevant, the link within the custom field is written like this:

 {{ title }}

I also added in a "Content: Translation language" field, to verify I was looking at the correctly filtered language. the URL uses default language regardless of whether the item's language is specified or not.

Update: I've also ensured the bottom middle column in Views is set like this:

 Rendering Language:Content language selected for page

This did not solve the problem. As a further test, I've also unchecked 'not defined' in my filter. While filtering to only nodes of the current language selected for page, I Still get URLs to the default language.

Also, the view has been translated into all relevant languages. Not sure how to change how the {{ view_node }} renders though. I assume it should be programmically pulling the current language when generating a URL. This {{ view_node }} is where the language is appearing. It seems like it should not be, though. The node alias shouldn't contain the language, I thought.

After narrowing down the issue, I think I've stumbled into an actual existing, known issue: Entity Links fields does not have translation support.

https://www.drupal.org/project/drupal/issues/2877994

I still need to figure out how to apply a patch, but I suspect this is actually a duplicate of the above issue.


If end date is empty show "Now" or "Current" or something else In some of the content type I have a field date with collects start date and end date.
The end date is not required and is empty as default value.

When I show date in teaser or node or view it will show start and end date but I want a condition

if (empty($end_date)) {
 print "current";
} else {
print $end_date;
}

of course I can set it in the node.tpl.php, for the teaser and the node, and with alternative text if empty in the views with field setting.

Now would like to know if there is any way to do it with the API. Something I can do in the template.php and not in every single node--CONTENT-TYPE.tpl.php and in every single view.

I'm looking for something like

function my_module_date_api ($something) {
if (empty($end_date)) {
     print "current";
    } else {
    print $end_date;
    }
}

Thanks in advance

Have a look at Custom Formatters module.

"The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module."


How to tell if the current revision is the original? I want to display a different "Submitted by" message for content that has been updated, and thus has multiple revisions.

How can I tell if I'm on the original revision, or if there are multiple revisions?

NodeStorage::revisionIds() will let you retrieve all revisions of a node which will let you compare against the current node's version.

 // Retrieve all vids.
 $nid = 123;
 $node = Drupal\node\Entity\Node::load($nid);
 $vids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);

 // Does the original node's vid match the current node's vid?
 return (reset($vids) == $node->vid->getString());


How can i change the confirm page text in simplenews how can I change this text or translate it:

Are you sure you want to add s*****@y*****.com to the sizing mailing list?

You can always unsubscribe later.

this is the page after click on confirm link in email ?

I've tried string override module but it can't change that .

A grep on the simplenews module shows the text is coming from simplenews.subscription.inc file from following code.

on around line #582

/**
 * Generate the confirm subscription form.
 *
 * @see simplenews_confirm_add_form_submit()
 */
function simplenews_confirm_add_form($form, &$form_state, $mail, $newsletter) {
  $form = array();
  $form['question'] = array(
    '#markup' => '<p>' . t('Are you sure you want to add %user to the %newsletter mailing list?', array('%user' => simplenews_mask_mail($mail), '%newsletter' => _simplenews_newsletter_name($newsletter))) . "<p>\n",
  );
  $form['mail'] = array(
    '#type' => 'value',
    '#value' => $mail,
  );
  $form['newsletter'] = array(
    '#type' => 'value',
    '#value' => $newsletter,
  );

  return confirm_form($form, t('Confirm subscription'), '', t('You can always unsubscribe later.'), t('Subscribe'), t('Cancel')
  );
}

since it is a form, you can simply implement hook_form_alter() to override 'question' field markup from your custom module, something of following sort

function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'simplenews_confirm_add_form') {
      $form['question'] = array(
       '#markup' => t('Your Custom Confirmation Message Here'),
      );
  }
}


New custom content type not showing up in 'Create content' menu I have created some new content types but they automatically don't show up in the 'Create content' menu - what do I have to do to get them there. I am currently logged in as user 1 so it shouldn't be a permissions issue.

I think you are facing the same problem I've experienced. Probably you disabled the navigation menu link "Add Content" and its respective sub-menu items. Then, they won't show up at the path node/add.

See this Q/A: No content type problem


How to make a better backup I backuped my website with Backup and Migrate.
I made some tests and restored a few times successfully.

Then I created some fields (one of them is named field_date), and made some tests; I was not satisfied so I restored again.

Then I wanted to create a field named field_date, which should not be in the database after restore to previous state, but I got the following error message:

DatabaseSchemaObjectExistsException: Table field_data_field_date already exists in DatabaseSchema->createTable() (line 630 of /var/www/includes/database/schema.inc).

How is this possible? None of my backups works to turn the site to the initial state. Is this bug in the module I used for the backup, or is this feature and I should use more reliable backup utility?

When restoring, you first need to drop your old database (or all tables within). The restore can only replace the tables that existed when you created the export, it doesn't know about any tables that you created later on.


Display search results in a view I read everywhere that it is possible with Views 3 to display search results in a custom view by adding a contextual filter "search: term" to the view and pointing the view's path to "search/node/%". There even used to be a module that added this contextual filter to earlier Views versions: https://drupal.org/project/views_handler_argument_search

Also, see #9 here: https://drupal.org/node/266683

However, I don't have any "search" contextual filters or relations in my view. Was this feature removed again?

Edit: I don't want to search the view once I'm in the view (exposed filters would be the answer in this case). I want to use a view to display the search results of the search form that would be present anywhere on my website. Also, I want to use the indexing feature of Search module instead of using exposed filters. Unfortunately, Apache Solr is not an option.

Create a page view called search (Add the fields to display)
Add a path "/search"
Add the contextual filter "Global: null"
Add a filter "Search: search terms", expose the filter.
Expose the form in a block to use the search form elsewhere on your site.


What module will show me all sql queries being run on the loaded page? My site is running slow and I suspect its a module, but not sure which one. Is there a module that can display all the sql queries being run on a loaded page? If there isn't maybe there is a command line tool that others use to monitor this data?

The Devel module has a query log option, which when enabled will show every query that's been run for a request at the footer of the page.

You can enable it at admin/config/development/devel once the module's installed.


Drupal commerce: there is a way to apply discount to products with some taxonomies elements? I would like to know if there is a way to apply discount to products with some taxonomies values, something similar to "bulk views operations" Or another way where a non developer or not a site-builder it's able to create new discounts.

Thanks

Oskar

The biggest issue here is that in your taxonomy term comparisons, Rules is going to be looking for taxonomy term IDs. In core Rules, there is no way to show a select list or something similar in the Rules UI for selecting a taxonomy term. There may be a contributed module that adds this functionality; I didn't look.

If you know a term ID, you can use a different condition based on whether the term reference field is single or multi value:

Single value: Data comparison
Multi value: List contains item

Since you're going for usefulness to non-developers / site builders, I'll assume you need something better than that. It appears you might be using Commerce Discount, but I don't know if that's why you've added the tag or not. It offers a simplified interface for building product pricing rules and depends on the http://drupal.org/project/inline_conditions module, which includes a simplified taxonomy term check for product entities.


Unable to add a submit button to a drupal Block I am adding a submit button (in the callback function 'clearbutton_submit()') - when I click on the button - nothing happens.

What am I doing wrong here?

function cacheclearbutton_block_info() {

$blocks['cacheclearbutton_uppercase'] = array(
// info: The name of the block.
'info' => t('CacheClear Button Block'),
'region' => 'sidebar_first',
'status' => 1,
);

return $blocks;
}

/**
* Implements hook_block_view().
*
* This hook generates the contents of the blocks themselves.
*/
function cacheclearbutton_block_view($delta = '') {
//The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'cacheclearbutton_uppercase':
  $block['subject'] = t("uppercase this please");
  $block['content'] = block_content();
}
return $block;
}

function block_content() {

$block_contents = array();

$block_contents['clearbutton'] = array(
    '#type'         => 'button',
    '#value'        => 'Clear Cache by Module',
    '#submit'       => array('clearbutton_submit'),
);

return $block_contents;
}

function clearbutton_submit($form, &$form_state) {
    cache_clear_all();
    drupal_set_message(t('Setting a message from the submit handler'));
}

A small change needed as below

  Key was to chnage the type from button to submit
  But I guess making a separate function to get the form will be better

function block_content() {

  //calling the form in the block
  $block_contents = drupal_get_form('_cacheclearbutton_clear_cache_form');

  return $block_contents;
}

// A separate function to return the form to clear the cache
function _cacheclearbutton_clear_cache_form() {
  $form = array();
  $form['clearbutton'] = array(
    '#type' => 'submit',
    '#value' => 'Clear Cache by Module Test',
    '#submit' => array('clearbutton_submit'),
  );
  return $form;
}

function clearbutton_submit($form, &$form_state) {
  cache_clear_all();
  drupal_set_message(t('Setting a message from the submit handler'));
}


Create native Excel XLS and XLSX files from scratch and export directly to a PDF file We are considering migrating a Cold Fusion application to Drupal and I am wondering if the below 2 capabilities that are current Cold Fusion application is doing can be done within Drupal 7.

The ability to create native Excel XLS and XLSX files (NOT HTML tables that Excel has to convert each time it opens) from scratch. This includes the ability to use native Excel functions, formatting, and multiple tabs/sheets. CFSPREADSHEET makes this a relatively simple task for us.
The ability to export directly to a PDF file. CFPDF and CFCONTENT makes this almost as simple as wrapping the desired output in a set of tags and it’s done in many cases.

PHPExcel. It uses PHPExcel library and supports native Excel export, import. We are using it in our project and it does it well.

  The PHPExcel module allows developers to export/import data to/from real Excel files.

Print. It allows you to generate the printer-friendly, PDF, EPUB and Email versions of any node. It supports following libraries:

dompdf
mPDF (only in the 7.x-2.x branch)
TCPDF
wkhtmltopdf

I'd recommend using the dompdf library, since I'm using it an it does the job well.


Uploading videos with the Media uploader I am trying to create a video gallery. I was originally trying to use the Media module with shadowbox to display them, but I have not been able to figure out how to get a thumbnail for the media. What I came up with was the Video module. The video module allows me to create a thumbnail, however I wanted an uploader similar to the media module one, which allows me to upload it, get it from the web, or use a video that is already in my library. Is there an ad-on module for Video that will allow me to upload videos like this?

The video module is strictly for videos that your users upload. You need to configure the transcoding (ffmpeg on your server or use the external Zencoder service).
If you want to embed Youtube or Vimeo videos you can use video embed field module.

I've combined the two to allow video uploads and video embeds. However I really prefer the video embed field since dealing your users uploading a ton of large video files isn't trivial.


How can I manually send order details email to customer in Ubercart? I have a cron job to read orders from the Ubercart database table, and manually send the order email to the customer.

Usually, when customers checkout in Ubercart, they will get their order email straight away. But in my situation we don't want to automatically send the order to customer because we have some process that needs to be completed before we programmatically send the order email to customers.

How can I manually send the customer's order email 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.


Render a region in a panel What I want to do is to render a region in a panel -> add content -> new custom content.
I tried <?php print render($page['region_name']); ?> but it didn't work.

I'm using panels to be able to create more complex layouts and the Context module to show blocks (with menus) on different pages. Thats why I need to render a region in a panel: to put menus on selected pages.

This code is not to supposed to work inside panels. Regions are what you add to your themes and they are ready to use on your theme templates.Panels are used to override your theme templates, its allows to have regions as per the panel layout you choose.$page will not be available to your panels. Using new custom content you can add plain text,html,php but regions will be available here.


Views on custom data source I have an app that has a front end in tons of custom AJAX and fancy JS controls.

These controls all pull from URL which return JSON in a specific format.

I would like to remove all the selection code from the existing system and integrate with drupal:

Can views be linked to tables which are not directly managed by Drupal?
Can Views have their output overridden to support JSON instead of HTML?

I have googled and found a few projects but none seem to be very active -- I am using D7 maybe D8 for this project :)

Any pointers, hook suggestions, etc?

After using hook_views_data() to declare your custom tables/fields, use a custom Views handler to override or reformat the output.


How do I delete files attached with media entity? Background:

drupal 8.4.2

custom media solution

Issue

I can not delete files permanently which created as media entity.

Reproduce

Created an image media entity.
/admin/content/files claims status permanent and used in 2 places.
After deleting newly created media entity from UI /admin/content/media.
/admin/content/files says status permanent and used in 1 places.

Even cron run after 6 hours (as described in file settings) file still exist on the server.

Is there any safest or best way to delete those unused file permanently?

You have to delete old versions of entities (articles etc.) where you used the files for the files to get the "used in 0 places" under /admin/content/files. After that status should be changed to temporary with option make_unused_managed_files_temporary set to true.


display select list as an image list I want to make my site more user friendly and so I would like to replace select list with an image list.
Is it possible to display ordinary select list as an image list?
Is there a module that would allow me to do so or do I need a custom code for this fetaure?

There is in fact a module that can do this. It's the Select with style module.


How do I make changes to the user registration function? Just to clarify: I don't mean customizing the registration page. I've already managed to customize it to display what I want. What I'd like to know is if it's possible to make any changes to the function that inserts the info to the database after the user submits the form. The site I'm working on has a phpbb3 forum and I'm looking for a way to get a user registered in both after registering in the main site. I'm aware of the phpBB SSO module but that handles signing in, not registration. Also, I haven't been able to get phpBB SSO to work, either. Thanks.

I'm using phpBB3 instead of Drupal's Forum module because this is a migration from an already existing site that used phpbb. The client wants it this way and getting everything to look and function like their original site would take too long.

You can use

hook_user_insert

to add additional code to the new user account creation process.

More information on the User API


I have a block that I need to show in two regions. How do I show the same block twice? I have a multiple blog site that is created using views. One half is the mens other is the womens. I created specific regions to be shown on only on specific gender--page.tpl files. I just realized I cannot show the same block twice. How will I get this to work. I am also finding that the block may have to be another view as well.

One solution is to use MultiBlock. Another would be to use Panels which would also have value if you wanted to have different layouts for the gender specific pages.


Profile fields shown during registration I want to have one profile with some fields shown during registration and other fields not shown during registration. I can't seem to do this.

I am using the Profile2 module (drupal.org/project/profile2)

From what I can see, a profile selected to "Show during user account registration" will show all fields associated with that profile during registration. And a profile that is not selected to show during registration will not show any fields during registration.

I am not seeing any options within a profile to make a given field override the selected setting for the profile.

So currently I have two profiles for the users - one with the fields I want shown during registration and a second profile with the fields I don't want shown during registration.

The result is two profile links for the user, which is not what I want.

How can I make a given profile field override the profile's registration setting?

Thanks for your answer, CR47. I am currently unable to select your response as the answer or even add comments because of a JavaScript problem. I will select your answer as soon as the error is resolved.

https://meta.stackexchange.com/questions/188125/dreaded-error-stack-overflow-requires-external-javascript-from-another-domain

The field permissions module should help with this.  You can set individual permissions on fields of user and node entities.  If you set a field permission to be visible to only authenticated users, then it won't show on the sign up page.

Here is an example with screenshots:

These are the fields I have in Profile 2

When editing the field for "Will not be visible" I scroll to Field visiblity and permissions and select custom.  Then check the types of users that can see/edit values for themselves and others.  By default everything is only checked for admin.

Then when going to create an account you can see the "Will not be visible" field is not visible.


how do 404 pages work? How does the 404 page you can define in /admin/config/system/site-information work?

I found Drupal\system\Controller\Http4xxController->on404(), but how does that display whatever path I definied in basic site settings?

I'm trying to deliver a 410 when a page is deleted. I hve a database table with deleted paths, an InboundPathProcessorInterface to call a custom controller. Now I want to output the exact same thing as a 404, just with another status code.

Alternativly, how do I get the content of a given system path (i.e. node/123) to output in a Symfony\Component\HttpFoundation\Response?

For the configured custom path:

CustomPageExceptionHtmlSubscriber::on404

   public function on404(GetResponseForExceptionEvent $event) {
    $custom_404_path = $this->configFactory->get('system.site')->get('page.404');
    if (!empty($custom_404_path)) {
      $this->makeSubrequestToCustomPath($event, $custom_404_path, Response::HTTP_NOT_FOUND);
    }
  }

If no custom path is configured the subrequest is built for '/system/404' pointing to the controller you've mentioned:

DefaultExceptionHtmlSubscriber::on404

  public function on404(GetResponseForExceptionEvent $event) {
    $this->makeSubrequest($event, '/system/404', Response::HTTP_NOT_FOUND);
  }

To customize other status codes than 403 or 404 extend DefaultExceptionHtmlSubscriber and override on4xx().


Override menu item weight (bring it to same level as 'user' link) that has user/% path and has to be in user-menu I need a menu item living in the user-menu, has path like 'user/%something' but i dont want it to have "My account" link as parent (that has path 'user')

i can only change that through the administration but this is not an accepted answer...

Any thoughts?

thnx

pff got it

had to

hook_menu_link_alter

and changes this link's plid like:

/**
* Implements hook_menu_link_alter().
*/
function YOURMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/some-path') {
    $item['plid'] = '0'; // instead of '2' (My Account menu item)
 }
}

drupal is a pain sometimes... but we love it anyway


Login block is missing from my theme The default login block is not listed in my theme's blocks, if I switch to Garland, it's there and if I type the direct path to the block I can access it, but I can't seem to save it to my block page... does anyone know how to resolve this issue?

Go to /admin/structure/block
Go to your theme (top tabs)
Move your login Block
WIN!


How to overwrite modules by default with DRUSH? I am using a module list from Drupal 7 to populate a Drupal 8 site.

Some modules are now included in core, so there are a lot of confirm overwrite messages like this:

 Install location C:\drupal-8.0.1//modules/imagecache_actions already exists. Do
you want to overwrite it? (y/n):

What is the command for default Y or N ?

Now I use this command:

 drush en module -y

But I would like to set default answer to "overwrite yes" if module is already enabled or already exists and downloaded so I don't have to manually enter Y everytime

Overwrite
Allows the project to be installed in a directory that is not empty. If not specified this is treated as FALSE, Drush make sets an error when the directory is not empty. If specified TRUE, Drush make will continue and use the existing directory. Useful when adding extra files and folders to existing folders in libraries or module extensions.

projects:
  myproject:
    overwrite: TRUE


On a module Issue page, how do you tell what version the patch has been applied in? Much of the time, take this field collection migration issue for example, when I find an issue with a drupal module, there has already been an issue filed, and in some cases the issue has a status of Closed (fixed).  In the sidebar there is a version mentioned.  It seems likely that that version is the one you set when you file the issue, specifying which branch of the code you saw the issue in.

When the issue has been Closed (fixed), does that mean that if you grab the specified version, that the code will include the patch?  Is there any way of knowing when a fix has reached the stable branch?

As mentionned by Eyal a patch is always applied to the -dev version of the module. That's already a good stuff to know.
So yes, if a patch is committed you can download the -dev version specified in the issue (or apply the patch separately if needed).

Usually the patches included in a new release are listed in the changelog:
.

note:
normally once a patch is committed the issue status becomes "closed (fixed)" and you will ind this kind of details in the latest issue comments:

In the sidebar of the presentation page of the module the "View pending patches" can be helpful to check if the issue you are looking for is still opened or fixed. There is also the "Views commits" link for a quick overview. this page provides a detailed list of the patches implemented (issue date, version , description, id).

--

The official doc https://www.drupal.org/issue-queue/status could also help you to understand the process.


AJAX Populated Views Exposed Filter I'm re-building a travel website and need the trip search form to have the "Arrivals" select populated using AJAX once the departures has been selected to remove any empty search results.

I have followed all the tutorials I could find online, namely: Views AJAX Dynamic Dependent Exposed Filters & AJAX populated filter breaks when Views Dependant Filter module added, applied patch #106 from https://www.drupal.org/node/1183418 and nothing seems to work. I'm also not getting any error messages which makes it harder to debug.

I've attached my custom module code to the bottom of this post.

Any help or ideas are appreciated as I've been stuck on this for over a week now.

    function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-trips-page') {

        if($form_state['input']['field_departure_tid'] === 'All')
            $form['field_arrival_tid']['#disabled'] = 1;
        }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_arrival_tid' ) {
                $field_id = $form['#info']["filter-field_arrival_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_arrival_callback($form, $form_state) {
    return $form['field_arrival_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

Try to change:

if($form_state['input']['field_departure_tid'] === 'All')

in

if($form_state['input']['field_departure_tid'] == 'All')

And inside _form_alter function add this string to see the content of field_departure_tid

var_dump($form_state['input']['field_departure_tid'])

because if I don't wrong remember field_departure_tid is a number not a string.


Drupal 7 hook_block_info and hook_block_view permission wise display I have a module that has permission hook for normal access and for administrative access. I want to display two different blocks to different set of users. Say,
the "admin" will only get to view one block and a "site owner" will see the other display.

So, till now what I have done is, declared 2 hook_block_info() as,

    $blocks = array();
//Block for the Normal Site Owners
$blocks['payouts'] = array(
    'info' => t('Listing of Payouts'),
    'cache' => DRUPAL_NO_CACHE,

);
//Block for the Administrators
$blocks['commission_payments'] = array(
    .....
            .....
);

When I declare the hook_block_view() I use user_access() to restrict the user's to see it.
But is there any way I can restrict the user's to view the block infos in the region settings ? Is there any array parameter for hook_block_info that can achieve this? I suppose the 'page' parameter will only handle the page where to display the block.

An easy solution is just to check the user role in hook_block_view():

function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'payouts':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'commission_payments':
      if (in_array('Site Owner', array_values($user->roles))) {
        $block['content'] = t('Hello Site Owner');
      }
      break;
  }

  return $block;
}


A flexible front page layout tool I want to build a front page in which the site administrator has a lot of control (through the UI) over the layout. Panels is the only thing that comes close, but I still don't think it can do everything I need (and admittedly, I'm not a big fan of panels).

requirements

The front page will have a couple of sections; I'll call them "news", "products" and "store" in this example. The administrator must be able to control the order of the sections on the page.

Each section will contain a selection of news nodes for the news section and a selection of products for the products section. (The nodequeue module would be an obvious choice here.) The order of the nodes can be controlled by the administrator too. Also, the admin must be able to choose if a node is rendered full width, or if two are rendered half width, placing them side-by-side.

The "store" section must contain a maximum of 4 blocks (not nodes). The admin must be able to make a selection out of 6 or 7 blocks and gain control the order.

question

I'm sure I can make this work all by myself, but I'm curious: Which module (or combination of modules, if any) would you use to accomplish this? Needless to say, I would like this to be as easy and user friendly as possible, preferrably with as least different forms and interfaces as possible.

EDIT:
I realize there is a more generic question here, so I copied my answer over there.

A combination of the following modules can get you quite far:

Display suite
Block reference
Entity reference
Field collection
Bean
Inline Entity Form
Multiple Selects

How?

Create a node type "frontpage".
Add a multiple-value block reference field with "Multiple Selects list" widget.
Set up some bean types to allow different kinds of fancy boxes that can be placed on the frontpage.
In addition you can have Views blocks to be used in the block reference.
One of the bean types could have a multiple-value entityreference to e.g. reference a bunch of products (and have them sortable). I generally prefer this over nodequeue.
Use Display suite to define how each bean and the frontpage itself should be displayed.
Use Display suite custom field templates to have decorated boxes around each bean/block in the blockreference, or each product, etc. Check hook_ds_field_theme_functions_info(). This stuff is powerful and awesome!
Tell the client / content editor to use the contextual links to edit individual beans.

This should give you some material to play with ..
More detailed questions should be discussed in dedicated stackexchange questions, since this is quite broad.


Site offline notification How to turn off the notification about the site being offline, when in maintenance mode?

  Operating in maintenance mode. Go online.

Before I give you the answer, I would suggest that you do NOT implement this.

This  message is an obvious but friendly reminder that your site is in maintenance mode. Turning off this reminder may leave you scratching your head later, wondering why anonymous visitor John Smith can't access your site. The reason may be obvious to you now but it may not be so obvious as time goes by.

This code snippet removes the 'Operating in Maintenance Mode' message, but preserves other messages. Place this code in template.php and then clear the cache:

function mytheme_preprocess_page(&$vars) {
  if (variable_get('maintenance_mode', 0)) {
    $message_count = count($_SESSION['messages']['status']);
    if($message_count > 1) {
      array_shift($_SESSION['messages']['status']);
    }
    else {
      unset($_SESSION['messages']['status']);
    }
  }
}

Edit: Updated the code, this should do the trick. Added a condition that unsets the 'status' element if empty.

One last thing: The maintenance message also appears on the administration pages. You can remove this message too, but as stated earlier, this is dangerous.

The default theme for the admin pages is 'Seven', which has its own template file. You could copy the above code into Seven's template.php. Or even better, copy the code into a new function in your custom module, mymodule_hide_maintenance_message() for example, and simply call that function within mytheme_preprocess_page.


How to edit e-mail settings for project issue content type I am using the project and the project issue module on a Drupal 7 instance and ran into some trouble with the notification settings.

Apparently, the poject issue module saves for every content type a variable which contains information which e-mail sender address should be used for e-mail notifications on new issues etc.
The variable is named project_issue_reply_to_NAME_OF_CONTENT_TYPE.
How can I change this value for an existing content type?

As the variable is of type blob I can't change the value easily in the database.

suggestion 1 :

drush vset project_issue_reply_to_NAME_OF_CONTENT_TYPE test@example.com

suggestion 2 :

in a custom hook_update_N() :
variable_set('project_issue_reply_to_NAME_OF_CONTENT_TYPE', 'test@example.com');


blocking access to admin content view When blocking access for a editor role to the view admin/content, all sub-items of the toolbar content item are not visible to this role.
How to solve this ?

You can add a new menu link to act as the parent of all the items, a menu link that the users will have access to, then move the Content sub items underneath it. Or you could just move them out from underneath the Content menu item, but that'll probably make a messy toolbar. The toolbar just shows part of the Administration menu, all items under the Administration menu link.


How to use a webform key more than once. We are using webform and on submit sending the result to an API. We have a drop down that loads on context. We need use form_key twice, one for each dropdown but Drupal will now allow us to, is there a way to use form_key on two fields?

Why do you need form_key twice in the $form on the page? Simply add a custom submit handler to the form and create whatever custom $form_state or values you want to pass on to the remote API ... and let webform store the data as it wants seperate from what you send to the API.


using xhprof in drupal 6 to monitor a cron task and display in the XHProf runs page I'm trying to profile a specific cron task in drupal 6 to check the function calls made and what consumes the maximum time and decided to use the XHProf module  which I've never used before. I've got the module successfully installed and able to get the page loads profiled and listed in admin/reports/xhprof.

But to get my cron task to be profiled and listed in it I'm pretty clueless and tried out a few things from what I could gather from PHP.net but beyond coding

xhprof_enable();
echo "
ENABLED
";
// the code block I wish to profile
$xhprof_data = xhprof_disable();
echo "
";
print_r($xhprof_data);
echo "
";

by checking the internet. The $xhprof_data does contain the necessary info array. But I'm not able to get the slightest hint of how this data that's printed could be formatted and displayed like the page loads which get profiled out of the box. Any help on this is greatly appreciated.

I haven't used the D6 version before but rummaging through the code I think something like this will work:

1st bit (taken from xhprof_shutdown_xhprof())

$namespace = variable_get('site_name', '');  // namespace for your application
$xhprof_data = xhprof_disable();

// Path to save file. Leave empty to use a default
$xhprof_data['path'] = isset($_GET['q'])?$_GET['q'] : '';
$class = variable_get('xhprof_default_class', 'XHProfRunsFile');
$xhprof_runs = new $class();
$run_id = $xhprof_runs->save_run($xhprof_data, $namespace);

2nd bit (taken from xhprof_display_page())

drupal_add_css(drupal_get_path('module', 'xhprof') . '/xhprof.css');
$html = xhprof_display_run(array($run_id), NULL);

// Do what you need to with $html to get it out to the screen


How can I implement a non-CRUD function in hook_service_resources()? This question is similar to this question but I don't understand how the URLs are modified enough for the answer there to make sense to me.

The module adds retrieve and index operations by default.  I am attempting to extend privatemsg_services_resources with an additional option, unread.

I have added unread to the function as shown below, but I cannot figure out how to access it via URL.

function privatemsg_services_services_resources() {
  return array(
    'privatemsg' => array(
      'operations' => array(
        'index'    => array(
          'callback'        => '_privatemsg_services_get',
          'access callback' => 'user_is_logged_in',
          'args'            => array(),
        ),
        'unread'    => array(
          'callback'        => '_privatemsg_services_unread_count',
          'access callback' => 'user_is_logged_in',
            'args' => array(
              array(
                'name'        => 'uid',
                'type'        => 'int',
                'description' => t('UID of the user to check the number of unread messages for.'),
                'source'      => array(
                  'path' => 0,
                ),
              ),
            ),
          ),
        'retrieve' => array(
          'callback' => '_privatemsg_services_get_thread',
          'access arguments' => array(
            'get private messages from remote',
          ),
          'args' => array(
            array(
              'name'        => 'thread_id',
              'type'        => 'int',
              'description' => t('ID of the thread to be retrieved.'),
              'source'      => array(
                'path' => 0,
              ),
            ),
          ),
        ),
      ),
    ),
  );
}

When I go to www.myexample.com/drupalgap/privatemsg, I get the value for index.

When I go to www.myexample.com/drupalgap/privatemsg/THREAD_ID, I get the retrieve value for THREAD_ID.

When I go to www.myexample.com/drupalgap/privatemsg/unread/UID or www.myexample.com/drupalgap/privatemsg/unread, I get the message ["Invalid parameters passed."].

However, if I comment out the function for retrieve and then rename unread to retrieve (to test my code for unread), after clearing the caches, going to  www.myexample.com/drupalgap/privatemsg/UID gives me the number of unread messages.  So the code is OK, I'm just setting up the resource the wrong way.

How can I call both retrieve and unread from the URL?

The key is to use the actions array instead of the operations array when creating non-CRUD resources.

Here's an example for DrupalGap: http://drupalgap.org/node/187

FYI, all calls must use POST when using actions.

When using operations, the calls are directed based on the HTTP method (GET, POST, PUT, DELETE).

Don't forget to attach the X-CSRF-Token header to your POST calls. Its value can be retrieved here: ?q=services/session/token

Since this is for DrupalGap, and you're passing along an argument to your service resource, I'd recommend following these instructions, that way jDrupal can be utilized and your function(s) can easily be re-used:

http://drupalgap.org/node/203


How to add product thumbnails to Checkout? I am wondering if anyone can help me figure this out. Using Drupal 7, and Ubercart 3x.

I'm trying to add the product thumbnails to the checkout pane as they show up in the "View Cart" pane. The table seems largely the same minus the fact that on the checkout page itself, there are no thumbnails of the products. I'm okay with PHP and poking around haven't been able to find how I could add this. Thanks!

You can override the theme function uc_cart_review_table to accomplish this.

function YOUR_THEME_uc_cart_review_table($variables) {
  $items = $variables['items'];
  $show_subtotal = $variables['show_subtotal'];

  $subtotal = 0;

  // Set up table header.
  $header = array(
    array('data' => theme('uc_qty_label'), 'class' => array('qty')),
    array('data' => t('Products'), 'class' => array('products'), 'colspan' => 2),
    array('data' => t('Price'), 'class' => array('price')),
  );

  // Set up table rows.
  $display_items = uc_order_product_view_multiple($items);
  if (!empty($display_items['uc_order_product'])) {
    foreach (element_children($display_items['uc_order_product']) as $key) {
      $display_item = $display_items['uc_order_product'][$key];
      $image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart');

      $subtotal += $display_item['total']['#price'];
      $rows[] = array(
        array('data' => $display_item['qty'], 'class' => array('qty')),
        array('data' => $image, 'class' => array('image')),
        array('data' => $display_item['product'], 'class' => array('products')),
        array('data' => $display_item['total'], 'class' => array('price')),
      );
    }
  }

  // Add the subtotal as the final row.
  if ($show_subtotal) {
    $rows[] = array(
      'data' => array(
        // One cell
        array(
          'data' => array(
            '#theme' => 'uc_price',
            '#prefix' => '' . t('Subtotal:') . ' ',
            '#price' => $subtotal,
          ),
          // Cell attributes
          'colspan' => 4,
          'class' => array('subtotal'),
        ),
      ),
      // Row attributes
      'class' => array('subtotal'),
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => array('cart-review')), 'sticky' => FALSE));
}

With the code $image = uc_product_get_picture($display_item['#entity']->nid, 'uc_cart'); you can read out the product image and add it to the table.


Why does advancing/retreating the month remove all events from the calendar in FullCalendar? http://bit.ly/1jrzpIx

Visit the link noted above.  See the calendar.  See the calendar events.
Now advance to the next month using the arrow buttons near the top left.
Now go back to the current month.  Observe that the calendar events have disappeared. This is not expected behaviour.
Now change the view so that you are in week or day mode.
Now return to the month mode and observe that the events have re-appeared on the current month.

Objective: Fix this calendar so that it retains its current functionality but does not lose the events when the months are paged through.

More information: This is Drupal v. 7.26.  (latest)

And you can find the Drupal FullCalendar module here: https://drupal.org/project/fullcalendar

And here is a bug report that I think deals with this issue, at least they seem to be related. My post is near the bottom of this thread. I've turned off AJAX so I don't think that's the problem.

https://drupal.org/node/1864992

Here is an answer on StackOverflow on (maybe) how to fix it. I don't know how to run the eventsRender method after fullCalendar instantiates in Drupal.

https://stackoverflow.com/questions/2665469/fullcalendar-cannot-display-the-new-event-when-switch-month-back

Here is another one (maybe):
https://stackoverflow.com/questions/20195156/when-switching-months-i-want-to-stop-fullcalendar-from-removing-events

Looking at your calendar now it looks like you have it fixed.  I was gonna' offer the solution that I was told:  Make your site's short date format to use "2014-5-19 17:30"  Unfortunately it had to be in military time, not 12 hour or it didn't work.  That is only an issue when looking at the "upcoming events" that I have listed at the bottom of my calendar in another block.  I was going to go the ajax method if I can get 12 hour time to work with ajax, using the fix offered for Ajax at the drupal posts on this issue; haven't tried it yet.

So what solution did you get to work for you?

Dave N


How to display a newly created node (created using a form) in the view using ajax (without page reload)? I have created a "Share update" form using form API. Below the form, I am displaying a view "feeds" of all the published nodes of content type "updates". On submit, the form saves the data entered in the form as a node of content type "updates". It reloads the page and displays the recently saved node in the view below the form.

I want the node to appear in the view list without page reload. How to do that?

My form API code looks like this -

function add_update_page($form, &$form_state) {
  $form = array(
   '#prefix' => '
',
   '#suffix' => '
',
   '#title' => t('Latest update:'),
   '#description' => t('Add status update'),
  );

  $form['update'] = array(
    '#title' => t('Share an update...'),
    '#type' => 'textarea',
    '#resizable' => '0',
    '#format' => 'update_feed_text',
    '#label' => t('Share an update...'),
  );

  $form['submit'] = array(
    '#id' => 'update-submit-button',
    '#type' => 'submit',
    '#default_value' => t('Share'),
  );
  return $form;
}

function add_update_page_submit($form, &$form_state) {
  $update = $form_state['values']['update'];
  $node = new stdClass();
  $node->type = 'updates';
  node_object_prepare($node);
  $node->status = 1;
  $node->uid = $GLOBALS['user']->uid;
  $node->language = LANGUAGE_NONE;
  $node->created = time();
  $node->changed = $node->created;
  $node->title = 'Automatic status update';
  $node->body[$node->language][0]['value']   = $form_state['values']['update'];
  $node->body[$node->language][0]['summary'] = "";
  $node->body[$node->language][0]['format']  = 'filtered_html';
  node_save($node);
  drupal_set_message($form_state['values']['update']);
  $form_state['redirect'] = '<front>';
}

I have looked up everywhere, but the proposed solutions are incomplete, making it harder to follow the logic.

As mentioned by wwwWRX you should use the #ajax property for your submit button and with in your function make a few changes. Before that you would want to remove your view from the block because we would be putting that here using code.

the submit button would become

$form['submit'] = array(
    '#id' => 'update-submit-button',
    '#type' => 'submit',
    '#default_value' => t('Share'),
    '#ajax' => array(
        'callback' => 'add_update_page_submit',
        'wrapper' => 'update-list',
        'method' => 'replace',
        'effect' => 'fade',
    ),
  );

Add one more element to your form of the type #markup like below

$form['update_list'] = array(
 '#prefix' => '
',
   '#suffix' => '
',
  '#markup' => views_embed_view('views-machine-name','block_name', $arg);

);

you should replace views-machine-name with the actual machine name of the view and block_name with the name of the specific block in the view and $arg would be the argument passed to the view which can be left blank if you dont have one.

with in the function you need to make a few changes towards the end.

you need to get rid of $form_state['redirect'] = '<front>';

and add

return views_embed_view('views-machine-name','block_name', $arg);

That should do it.


Cannot apply custom CSS via theme settings With Drupal 7.x and the Whitejazz theme, I want to apply custom CSS styles to some elements. This theme has the option to include custom CSS styles by specifying the path to the CSS file (in Appearance > Settings).

I created the folder and uploaded my file, specified path, but this doesn't work for me, even after clearing the cache. I can apply my styles using the CSS injector module without a problem, but I want to find out why I can not set this using the theme settings.

I think the problem is that you forget to add a reference statement in your theme's info file.
like this:

stylesheets[all][] = css/layout.css

After that, need to clean the cache.


How do I overwrite the view output for each vocabulary? This is the Drupal 8 version of the following question: How do I override a taxonomy/term/% list with a view?

In short: You can edit the default, global taxonomy/term/% view, but you can not set custom taxonomy view. For example, /my-custom-category/% will show the default, global view output (not the customized one).

As you can see, the most elegant solution for Drupal 7 was using the Taxonomy Display module. However, it hasn't been ported.

How would you tackle this problem in Drupal 8?

Ok, it seems that I have found a solution. A Drupal 8 & 7 module called "Taxonomy Views Integrator" provides ability to set custom view for each vocabulary and/or terms. So far seems to work fine. Link to module - https://www.drupal.org/project/tvi


Delete duplicate user Somehow I've got 2 users in my users table with the same email address (mine!).  I need to delete one of them.  One is user ID #1, the other is user ID #144.

When I use the advuser module to search for my email address, only one user (#144) shows up.  I select it and try to delete, but it's not successful - the confirmation screen says "No selections have been applied."  I'm guessing it's trying carefully to not delete user #1.

Additionally, I can't seem to change any account details in my own (user #1) account, it complains that "The e-mail address me@foo.com is already taken."

Not sure what to do next - am I safe to just do DELETE FROM users WHERE uid=144;?  Or will that create dangling references elsewhere?

I'm using D7, but I had this extra user before I upgraded from D6 too.

Instead of deleting the user and risking something going bad, why don't you try just to change his e-mail address in the SQL table? If you change #144's mail won't you then be able to edit, delete his account through the usual UI way?


Sub level menu in sidebar (but in specific pages) How can i display sub level menus in sidebar?

For example: I have a Menu 1 (M1) with SubMenus (SubPage 1, SubPage 2, SubPage 3, SubPage 4) and I want that submenus displaying in sidebar just when clicked in Menu 1 (M1) and other submenu associated with menu 1.

And, when clicked in Menu 2 (M2), I want to display just the Submenus associated to Menu 2

Example image

:

Thank you in advance

This is exactly what Menu block does. You can set up blocks showing menu items according to the start level and depth you desire/configure. Those blocks show only up when there are menu items in that range so you even don't need to configure your blocks to only show up on certain pages. See the documentation for further information.

To be more concrete, your menu (main_menu for instance) should looks like:

Page 1

Subpage 1.1
Subpage 1.2
...

Page 2

Subpage 2.1
Subpage 2.2
...

Page 3

Set up a menu block that shows the second level and configure that block to show up in second sidebar. With this configured you'll see a menu showing Subpage 1.x when on Page 1 or on one of its subpages. The same counts for Page 2. When on Page 3 you won't see the menu in the second sidebar.


Views: Relationship with filtering? I have a content type shortcut with the fields field_namespace and field_active. Additionally, I have a Taxonomy term vocabulary named namespace that is used in field_namespace.

Example content:

Title       | Namespace   | Active
------------+-------------+-------
Shortcut 1  | Namespace A | True
Shortcut 2  | Namespace A | False
Shortcut 3  | Namespace B | False

Now, I have a view displaying a list of these Taxonomy terms as a table. A column of this table display the number of Shortcuts tagged with the particular term. Example:

Namespace   | Shortcut count
------------+---------------
Namespace A | 2
Namespace B | 1

I built this using a Views Relationship with Taxonomy term: Content with term. I used this relationship to add the Field Shortcut: Nid with the Aggregation Type COUNT DISTINCT.

What I now want: The Shortcut count shall only consider Shortcuts whose field_active is True, i.e. the output shall be:

Namespace   | Shortcut count
------------+---------------
Namespace A | 1
Namespace B | 0

So the COUNT DISTICT aggregation shall be somehow filtered by the value in field_active.

Is there an UI way to do this? If not, which hook is appropriate to do it programmatically?

After having asked a friend, I can now answer the question myself.

The solution is pretty straightforward: At FILTER CRITERIA, I simply add field_active, with the operator "Is one of" checking the value "On".

I thought, FILTER CRITERIA may only be fields actually displayed, but this is not the case. It works for all fields being in any form used in the view.