Why is a page generated by views listening to block.tpl? I'm working on some custom templates for a page created by Views and I'm struggling to understand why it's using block.tpl (which I thought was used for blocks). Basically I'm trying to get rid of all the extra divs created for just this one particular page, and until I remove the div class content I can't get the desired style I'm looking for.

I did something similar for a block generated by views and used the template name block--view-name.tpl and got the desired effect. I ended up copying that same template file and just called it block.tpl and got the deserved effect on this Views page.

Now I'm left scratching my head as to why this Views page is listening to block.tpl when it's not a block. Also, seeing as it apparently wants a block template to do what I want, I'm trying to figure out the template naming but none of the usual tools are helping (theme developer module, the theme information under the advanced tab when editing the view).

Does anyone know why a page generated by views would be listening to block.tpl? If it helps the view content on the page is being wrapped by the following div:

That block is the main content block.

It is provided by the system module and is the default content area block in the page template.

More information:

system_block_info ( delta is "main" )
system_block_view


How to have custom ajax commands on element using InvokeCommand How can i use custom ajax command using #ajax api , i have the following code working well

        $ajax_response = new AjaxResponse();
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'attr', array('disabled',true)));
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'removeAttr', array('placeholder')));
        $ajax_response->addCommand(new InvokeCommand('#edit-event-trigger', 'css',array("background-color", "")));
        //Return the AjaxResponse Object.
        return $ajax_response;

But suppose if i want to focus() or hide() the edit-event-trigger element , how could i do that ?

These are some examples you can try:

$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'addClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'removeClass', array('show')));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'attr', array('value', '123')));
$response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('.message', "Show this text"));
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.message', 'css', array('background', '#dff0d8')));

Peace.


How to build a newsletter template I'm creating a content type specifically for email newsletters, which will be sent using phplist (client prefers phplist to using a Drupal newsletter module such as Simplenews).

So I'm planning to use a module like ThemeKey or Content Theme to create a new theme specifically for newsletter content type. Like most newsletter templates, the theme will use tables and lots of inline CSS.

I haven't seen any Drupal base themes for newsletters. Before I build from scratch, is there any advice or suggested theme/module I might have overlooked?

I'd write the db queries yourself (don't use views) so that you have full control over the output. Use a custom module to do the queries and write the html. You don't need a whole new theme, because the CSS needs to be inline for email clients to work properly.


Can't uninstall module from Drupal 7 I'm running Drupal 7 from 2011-01-05 and I'm trying to uninstall Views Slideshow: Cycle (7.x-3.0 alpha1) and Views Slideshow(7.x-3.0-alpha1). I disabled them in the modules list then go to the uninstall list and uninstall them there but they still show up in the modules list and I can't re-install it because it says the modules are already installed.

I've tried clearing the cache.

Any ideas?

To remove modules, you have to remove them from your server's modules directory (usually sites/all/modules/). Uninstalling through the interface runs the uninstall code provided in the module, typically to remove custom database data and tables that the module may have created.


How to filter a date range? I'm having troubles figuring out how to filter by date using the date range module from Drupal 8 core.

I, of course, found this post: How to filter a View by Date Range (start, end)?

But this doesn't tell me how to use the filter, it only makes the filter work better. So I used this patch but how to make this filter work?

I'm creating a calendar with cultural events and I want to be able to filter on date and genre with exposed filters. So let's say I have a design event from 05-01-2018 until 05-02-2018 (dd-mm-yyyy).

And I want it to show up when I'm searching for what is going on today or this month that concerns design? How to set up the filter for this?

What is the best and most simple way to do this?

I found a solution for this I have two exposed filters for my begin_date (begin_filter_1 and begin_filter_2) and two exposed filters for my end_date (end_filter_1 and end_filter_2).

When the begin_filter_1 is entered, this input will be copied to end_filter_2.
When the end_filter_1 is entered, this input will be copied to begin_filter_2.

No the filter looks like this

Published Yes

AND

Category - Exposed (Taxonomy Term) = Design
Begin Filter 1 - Exposed >= Begin_Date
End Filter 1 - Exposed <= End_Date

AND

Has Taxonomy Term - Exposed = Design
Begin Filter 2 - Exposed(but hidden via css) <= Begin_Date
End Filter 2 - Exposed(but hidden via css) >= End_Date

As you can see in the second Group I use a different filter to filter on the category. This is because of a bug in Drupal Core:
Complex Filter Criteria no Results


How do I get the host paragraph when a paragraph is referenced in another paragraph? I have referenced Paragraph B in Paragraph A and in preprocess of Paragraph B I want to access host paragraph A. Is this possible with ease. As in case of paragraph references on node we can do paragraph->getParentEntity() ?
 I had tried same but it still get the parent node :(

If you look at the Paragraph class in the module, you will find a public method called getParentEntity that return the parent entity of a Paragraph instance.

So, if you do:

$parent = $paragraph->getParentEntity();

if (isset($parent)) {
  // Your stuff ...
}

You would have the parent entity in the $parent variable. You can chain the method if there is multiple nested paragraphs. I also suggest using the isset method on the $parent variable because I've encounter some weird issues where random paragraphs returns null.


How can I provided simplified custom exposed filter options for a field in Views? On my site, users can input their nationality in a field provided by the Countries module.  About half the users on my site are Japanese, and the other half come from all other countries.

I have a view that allows members to search for each other, and I want to make the nationality an exposed filter.  Since there are 200+ countries in the world, I do not want to expose the entire list of countries (this would be a selection nightmare on mobile phones).

Instead, I would like to provide a select list with three options: All countries, Japan, and Not Japan.

The Views UI allows administrators to select options on select lists and limit the list to the selected options by checking a box.  This is not what I want to do, because there is no way to create a Not Japan option (which should show all members from all countries except Japan).

This answer suggests writing a custom views filter handler, but I'm a bit confused about where to begin.

The Countries module provides its own custom handlers, but (I think) these are overkill for what I need (you have to add a relationship to the country, which allows you to filter by continent, etc.); I simply need to make a version of the basic select list handler with my three options.

It seems that most views handlers extend another.  In the views/handlers folder there is a file, views_handler_filter_string.inc, which I think I can use, but I'm not really sure what the next step is to take.

I've done something very similar to that with the following process:

Implement hook_views_api() in a custom module

function MYMODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MYMODULE') . '/includes/views',
  );
}

Create includes/views/views_handler_filter_MYMODULE_country.inc somewhere with code similar to this (the MYMODULE bit isn't necessary, just a bit of low-tech namespacing):

class views_handler_filter_MYMODULE_country extends views_handler_filter_in_operator {

  /**
  * Get value options for the select list.
  */
  function get_value_options() {
    // Replace $this->value_options with an appropriately filtered list.
    $this->value_options = function_to_build_filtered_list();
  }

}

Register that file with the autoloader by adding this to MYMODULE.info:

files[] = includes/views/views_handler_filter_MYMODULE_country.inc

Finally, implement hook_field_views_data_alter() to force Views to use your new handler, changing the $field['field_name'] condition (and other similar strings based on field_address) to whatever makes sense for your site

function MYMODULE_field_views_data_alter(&$result, $field, $module) {
  // Limit country exposed filters.
  if ($module == 'addressfield' && $field['field_name'] == 'field_address') {
    $result['field_data_field_address']['field_address_country']['filter']['handler'] = 'views_handler_filter_MYMODULE_country';
  }
}


Creating entity in Rules causes PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry My application based on CRM-Core.
I am using several rules which launch on the event "After saving a new crm core contact" and each has a crm_core_activity entity created as the rule's action.

Is it possible that the rules happen simultaneously which causes SQL error - trying to set same activity_id (which is primary key)?

Here is the error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '879' for key 'PRIMARY': INSERT INTO {crm_core_activity} (activity_id, revision_id, uid, type, title, created, changed, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( [:db_insert_placeholder_0] => 879 [:db_insert_placeholder_1] => 1552 [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => email [:db_insert_placeholder_4] => תודה שפנית אלינו! [:db_insert_placeholder_5] => 1465830228 [:db_insert_placeholder_6] => 1465830228 [:db_insert_placeholder_7] => 4e87b796-fc8d-49f4-85f4-9ac944563576 ) in drupal_write_record() (line 7316 of /home/roi/sites/staging/0108-ormil/drupal-7.38/includes/common.inc).

The error happens randomly which makes me think this is a timing issue between multiple rules on the same trigger.

Have a look at issue # 430274, which explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg after only a few secs or mins later on ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the entity is for sure saved ... (so that can't be the reason anymore then why things don't work as expected ...).

Note: it's tough (virtually impossible) to pinpoint what exactly is causing your issue without knowing what exactly those rules look like. Adding a copy of your exported rules to the question may possibly help, but still. However, I'd recommend you to do some Rules debugging, using any of the techniques I described in my answer to How can I display the value of a variable inside a condition?


Prevent view to urlencode contextual filters I have 2 views.

View 1 is a small exposed form which collects some data and has some contextual filters.

View 1 is linked to View 2, so when the form is submitted the form redirects to View 2 and inserts the collected data as contextual filters in the url.

The fields in the url are in the form of module[module_field] but they are printed as module%5Bmodule_field%5D in the addressbar in the browser when View 1 redirects to View 2.

But opening manually the same page with the decoded version module[module_field] works.
How can I prevent View 1 to urlencode the parameters for the contextual filters?

You need to use theme_links() function in template.php file of your theme. The original theme_links() function has this:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You should replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}


Easiest way to post videos directly to S3? I am working on a video sharing site and I plan to use the Video module. Amazon S3 is also being used as the file system. The problem is how to override/extend it so the video file skips the intermediate step of uploading to the server and directly upload to S3 using a separate POST request?

If you're using Drupal 7, take a look at these two projects:

Storage API
Amazon S3

Both of these let you store file uploads on S3 instead of the local filesystem.


Path Replacement Pattern - Views Module I am using PathAuto to redirect user urls to the following pattern. users/[user:name].

I have created a page using the views module which needs to show up as a tab on the user naviagation menu. Currently the PATH property for the page is set to /user/%/seasons.

Here is my issue.

My account is Uid=1, UserName = 'Declan'.

Pathauto renders that as '/users/declan' - which is what I want.

When I click on the 'Seasons' tab, the page is rendered, but the url is '/user/1/seasons'.

Is there any way to rewrite the PATH property in the view such that is will render '/users/declan/seasons'?

Found the answer, the Sub-pathauto module does the job perfectly.


Display fields from a view in node template I'm learning views in drupal 7 and I just created an unformatted list view that is displaying the titles of a few nodes. The preview looks great and so does the view page.

I have a div block in a custom node template that I want now to view this "view" in. What code do I need to put into my node template to access the view function?

I looked at the system view template (views-view.tpl.php) that is generating what I want and I see that there is a $rows variable:

<?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>

But when I place that into my node template it doesnt work (probably because I need a preproccess?).

Am I going about this the wrong way? Is there an easier way to get views into another template file? I considered using a block. But I thought that once I nail this, then I don't have to mess with blocks.

FYI: I saw this post but I am not sure where to put the code that he recommended.

Thanks! I really appreciate it.

Drupal 6

  $view = views_get_view('view-name');
  print views_build_view('embed', $view);

Drupal 7

<?php echo views_embed_view('view-name', $display_id = 'display-name') ?>


Form API submit with AJAX removes wrapper element? I'm using the Form api to submit with ajax which works once, but once it's happened the wrapper element has also been replaced by the new ajax content. How can I make sure the content get replaced, but the wrapper element stays there so it can be replaced again?

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#ajax' => array(
      'callback' => 'fung_filter_form_callback',
      'wrapper' => 'view-cont',
      'method' => 'replace',
)

For now I've got a workaround by returning the same wrapper in the ajax content, but this seems a bit strange - any ideas?

If you don't want to 'replace' element with id 'view-cont', use another 'method', like:

'method' => 'append',

And if you in fact want to replace it, modify fung_filter_form_callback to make it return div with that ID again - that way you will replace original div with another div of the same ID, and will be able to repeat that process.


How to pass the nid from hook_node_view to the submit function? I need one button at the end of one content type view form. This button should redirect the user to another page.

I have something like the following code:

function mymodule_node_view($node, $view_mode, $langcode) {

    if ($node->type == 'my_type') {
            $form = drupal_get_form('redirect_button_form');
            $node->content['redirect_button'] = $form;
            //$node->nid is the data I need in the submit function
    }
 }

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Redirect button text'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $path = 'mypath';
    $options = ****I need the nid here;
    drupal_goto($path,$options );
}

How can I pass the nid from the hook_node_view to the submit function?

You don't need to use form here. Just use l() with the button name and the link path.

function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'my_type') {
   $node->content['redirect_button'] = array(
     '#markup' => l('Redirect button', 'yourpath/' . $node->nid);
   );
    }
}


Don't cache custom Front Page domain I'm working on a module that shows a different frontpage per role. I have three frontpages:

the base www.domain.nl for anonymous users, set in the basic site settings
for users with role_1 they go to sub1.domain.nl\dashboard
for users with role_2 they go to sub2.domain.nl\dashboard

I'm almost there but the frontpage url is set in cache (I think) therefor when I login I get the right frontpage. So I have role_1 en go to sub1.domain.nl. Now when I logout I want to go back to www.domain.nl but I still get redirected to sub1.domain.nl. Even when I close the browser and return to the site I still get back to sub1.domain.nl.

So my question is how can I make sure this response is cleared from cache after loggin out or is not even cached at all? What is the best method to deal with this?

My code till now:

mymodule.services.yml

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\FrontpageSubscriber
    tags:
      - {name: event_subscriber}

src/EventSubscriber/FrontpageSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\TrustedRedirectResponse;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FrontpageSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkFrontRedirection(GetResponseEvent $event) {
    $current_path = \Drupal::service('path.current')->getPath();
    $front_uri = \Drupal::config('system.site')->get('page.front');
    $front_alias = \Drupal::service('path.alias_manager')->getAliasByPath($front_uri);
    $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $isFrontPage = \Drupal::service('path.matcher')->isFrontPage() || $front_alias === $current_alias;

    if ($isFrontPage) {
      $hasRole1 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_1');
      $hasRole2 = \Drupal\user\Entity\User::load(\Drupal::currentUser()
        ->id())->hasRole('role_2');

        if ($hasRole1) {
          $domain_url = 'https://sub1.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }

        if ($hasRole2) {
          $domain_url = 'https://sub2.domain.nl/dashboard';
          $response = new TrustedRedirectResponse($domain_url);
          $event->setResponse($response);
        }
     }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkFrontRedirection');
    return $events;
  }
}

Could be a caching issue within the browser, Drupal or both. For the browser set cache headers in the response, see https://drupal.stackexchange.com/a/278703/47547.

For Drupal caching add a cache context user.roles:

$response->getCacheableMetadata()->addCacheContexts(['user.roles']);

Furthermore it is recommended to execute a redirect event subscriber only on a master request, this helps to prevent redirect loops:

public function checkFrontRedirection(GetResponseEvent $event) {
  if (!$event->isMasterRequest()) {
    return;
  }
  ...
}


Get the status message string I tried to get the string messages and create a condition based on the string, but I don't know how to pull the string value.

This is an example of message.

You don't need to pull the string, you can use the markup object in a string comparision directly:

$markup = \Drupal\Core\Render\Markup::create('Test');

if ($markup == 'Test') {
  // the markup string is "Test"
}

When you want to use triple equals then you have to type cast the object to a string first:

if ((string) $markup === 'Test') {
  // the markup string is "Test"
}


jQuery update - access denied Trying to setup the latest jquery update dev version, needed for the installation of the amazing social_count mobile-friendly count widget, I can't configure the module. When logging as user #1 and going to http://www.example.com/admin/config/development/jquery_update,
all I get is access denied. I tried 'drush cc all' to clear the cache but in vain. Any ideas?

Jquery Update doesn't implement hook_menu but instead uses form_alter with jquery_update_form_system_performance_settings_alter

You can find the configuration options at admin/config/development/performance.


Rate module Thumbs Counter I've installed the Rate Module in order to add a simple thumbs up/down rating system on nodes. By default it displays the average percentage (see below) but all I want is to display a simple counter of up/down votes.

Any ideas?

Copy the file:

rate-template-thumbs-up-down.tpl.php

that you find in the module rate/templates/thums-up-down to your theme's template folder.

Then change these two lines that print out the percentage:

<?php print $results['up_percent'] . '%'; ?>

...

<?php print $results['down_percent'] . '%'; ?>

to this:

<?php print $results['up']; ?>

...

<?php print $results['down']; ?>


Related nodes by taxonomy term in a view block In Drupal 7, I've got a content type called "Asset" with a taxonomy field called "Category". All I need is a Block on the Asset pages that looks at the current node's Category term(s), finds all other Asset nodes tagged similarly, and spits out a list of their titles, links to them, and a few other bits of info from their node.

A Views Block was my first thought... but I'm having a heck of a time making this happen in Drupal 7. Maybe it's problematic because my URL doesn't include the Term ID? Anyway, I've searched and followed a bunch of tutorials (like this one and this one), but to no avail. So, here are my questions:

If Views is the answer, what am I doing wrong?
Is there a Drupal 7 module that can do this for me?

I've done a little tweaking myself, and I seem to have gotten a working solution here.

Create a new block for the nodes you'd like to display
Add a new Contextual Filter: Content: Has Taxonomyterm-ID
Select: "when the filter is not available, provide a default value: Taxonomyterm-ID from URL."
Put a check next to "Load Standard Filter from node-page, useful for related taxonomyblocks"
And you will probably want to limit the vocabulary as well

In order to exclude the current Node you have to add a second Contextual Filter for Node-ID, provide default value as the content ID from URL and at the bottom of the modal pop open 'More' and check 'Exclude'


Multiple "page not found" errors in log I am getting "page no found" errors in my website log. Maybe it is some bots that search for  directories that do not actually exist. I get at least 50-100 daily of these messages.

The log says, for example:

  www.mysite.com 46.29.3.237 - - [14/Jan/2013:17:02:33 +0100] "GET /files HTTP/1.1" 200 683 "-" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"

How is it possible to get rid of that? I am just worried if there is problem on my side or it happens to any site. Thank you.

It's very likely automated programs looking to see if you have the proper restrictions on certain directories.

There's no way to prevent it from happening, but you could either turn off 404 logging or have your server log 404 errors to a different file.


Which version should I install? Should I install Drush 8 or Drush 9 for Drupal 8?

What does the code status failing mean? Is Drush 8 not compatible with Drupal 8?

At the moment, the Drush unit tests have some intermittent failures. I wouldn't worry too much about the failure. I'd recommend Drush 8 for Drupal 8 use.

UPDATE: I looked into the test failures, and it looks like they are related to fact that Drupal 8.1.x is now the recommended version of Drupal, whereas the Drush 8 tests are still assuming 8.0.x.  These test failures have been fixed in the master branch, but not back-ported to the 8.x branch yet.  The failures are caused by problems in the tests, not by problems in Drush; they should be fixed shortly, but will not cause you any problems in the meantime.


Can node refferences be automatically resolved in a view? We are using drupal for data management for a web application. We're using the web-service api to get data from drupal views and use it on our app.

We are completely depended on views fetched via the web service.

When fetching a view, we would like to get all it's references already resolved. So if I have entity A with references to B and C, it would be great to get entity A with the data of B and C as well, not just the node ids.

Can such a thing be achieved via the web-service api?

Update:

After using relationships and a table list that can have reference node fields, I am able to see the aggregated data from B and C. I have the list of A type entities, with data from B and C, but when I request this data from the /webservice/views/MyView api I am not able to see the newly formatted data. I get the same old result with the target_ids instead of the fields that I chose in the table list.

Views relationships are used to bring in data from referenced nodes. From your view's administrative page, expand the Advanced section and add a relationship. Select the appropriate node/entity reference field that bridges your nodes. Now you can add fields to your view and configure them to use your relationship, which will pull in any data from the referenced entities/nodes. At this point your view should contain data you want, making it available to the web service.


Subtotal calculates from original product price, disregards applied per product discounts This seems like a known issue but I actually didn't find a solution for this anywhere.

In commerce, if I apply a discount/pricing rule to a certain product, add it to cart, and go to checkout, table would say eg

Product - 120$ (discounted from original 200$)
Subtotal - 200$

The subtotal is taken from the original product price and doesn't include the applied discount. It would be a lesser problem if that was just display issue. But the tax is then actually calculated from the subtotal, making the order total wrong

Is there a solution for that?

Since this question is now almost 2 years old, I assume this "discount" that they were dealing with was an older version of commerce_discount. The newest version doesn't have any kind of subtotaling problems because it affectively utilizes the price calculation system for discounting.


PHP not being eval'd on a node I created a content type called informational, that has only one field in it, the default body textarea, I added into it <?php echo 'test';?>, and chose the PHP Filter option, in my page--informational.tpl.php all I'm doing is printing that field, and it's printing it as 'plain text' format. I checked in the DB and it's saved as PHP code.

P.S. I'm an administrator of the site, and I have all permissions.

If you use print render($content); and your code is displayed as it is on an Informational page ("echo 'test';") you should check PHP code configuration page (?q=admin/config/content/formats/php_code).
Here you set the roles who can use this text filter (by default is the 'administrator') and you enable or disable PHP code evaluator. Ensure that 'PHP evaluator' checkbox is on.
I hope this will help you.


Is there a standard environmental indicator for Drupal 8 projects? I am developing a Drupal 8 site, and I ran into the need to display all errors.
I added this line to my settings file, according to this answer:

$config['system.logging']['error_level'] = 'verbose';

But, when I'm ready to make my site live on production, I don't want error details being shown to end-users.

I want to conditionally display errors based on which environment the codebase is sitting on-- local, dev, staging, and production. In Drupal 8, is there a way to indicate which environment the site is running on? A variable or something? Or is this something that I manage myself?

A standard way to use different settings files per environment is through the use of sites folders.  Check out /sites/example.sites.php in your Drupal 8 codebase. It gives instructions.

Basically, you'll copy this file from example.sites.php to sites.php.  You don't need to edit it, (but you can if you want to do something unusual).

Then for each site (or environment), you'll have a separate settings.php file in a folder named after the site.

So you might have

/sites/example.com/settings.php
/sites/qa.example.com/settings.php
/sites/dev.example.com/settings.php
/sites/example.local/settings.php

If you are using git, you might want to uncomment this
/sites/example.local/settings.php

if (file_exists(__DIR__ . '/settings.local.php')) {
  include_once __DIR__ . '/settings.local.php';
}

and git exclude

/sites/example.local/settings.local.php

so that each developer can customize his settings.

If you run drush, you can run from the site specific folder on that environment or specify the --uri parameter.

Of course, you could just add conditional code in your /sites/default/settings.php

if ($_SERVER['SERVER_NAME'] == 'example.com') {
  $config['system.logging']['error_level'] = 'hide';
}

If you jut want to change one variable, and you know that on your production environment $_SERVER['SERVER_NAME'] is available and correct, then this is an option.


How to view a user's personal data after the user performs a login? I wonder how to view a user's personal data after the user performs a login.

Example: they have 4 tables in database "it", "business", "hrm", "educ". All the 4 tables have a student data when the 1st column in it table are login only the first column in table are viewed his data in webpage.

You might be able to use the Forena module (disclosure: I'm a co-maintainer) to build custom queries to retrieve the data directly from such database (of which its format can be MS SQL, MySql, Oracle, some PDO compliant database, etc). Think of those custom queries as standard SQL statements that fit your requirements (to retrieve the data). And combine this with the creation of some custom reports.

Those reports can then be shown in an appropriate page (with a specific path), or you could show them in a block, by using Forena's integration with the BEAN module.

PS: I'm assuming this question is about D7.


Conditional addition of css - hook_init? I need to conditionally add css to a page  based on the page content / URL. In the past (D6 and down) I was always advised against using hook_init() mostly because of it's weird load order in the Drupal bootstrap process. It was not uncommon to see the hook fire multiple times on a each page load - this still might be the case.

Looking at the D7 docs for hook_init() the following code example is provided:

function hook_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

The example implies that conditional addition of css makes sense while:

  To add CSS or JS that should be present on all pages, modules should
  not implement this hook, but declare these files in their .info file.

using a modules .info for site wide css additions.

Questions:

What are the options in adding css via drupal_add_css conditionally
besides hook_init?
Has anyone had luck using the theme hook -> hook_html_head_alter():

THEME_NAME_html_head_alter(&$head_elements) {

  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }

}
or use the theme engine for the theme hook:

phptemplate_html_head_alter(&$head_elements)

If that CSS is in your module, then the module should really be implementing the hook.

I don't think you can do anything with CSS and JS in a hook_html_head_alter(); that is really to mess with the render array before it is turned into $head by template_process_html().  Personally, I would use a template_preprocess_html().  You can add your logic there.  For example,

function mymodule_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');
  }
}


How to add PHP to a node without php filter? I have a one-off page on my site (webcam), where i need to run some php to eg. calculate today's sunrise time, add a daylight image at night, etc.

I understand PHP Filter is a security risk, and not recommended if it can be avoided.

My page is actually a panesl page, so not neccessarly a node.

I thought maybe i could do the coding and (some) content in a node template, or what other options do i have? A module? Sounds heavy... In my theme's php?
What are pro's and con's?

It really depends since you're planning to add functionality then the best place would be a module but if you're altering HTML or basically the output and maybe quite a little raw data manipulations then that could be in your theme.

Mostly a basic question that needs to be asked is, do you want the "thing" to be functional when you turn off or change your theme? If yes then that would give a strong idea that you would be creating a custom module.

For adding PHP code with panels, you can create custom panel panes. For nodes, your can use blocks or hook_preprocess_node() to add your code in the node level.


form api ajax stops javascript loading I have set an ajax callback to a form using the form api #ajax. I also have custom jquery in a file which styles part of the page and sets click handlers. I found something funny - my custom javascript only begins working AFTER the ajax has been called on the drupal form. Before I that form api ajax is called, it doesn't work.

Why would this be?

EDIT:

I am attaching my behaviors like this:

(function($) {
  Drupal.behaviors.updateCart =  {
    'attach': function(context) {
    $(document).ready(function () {...

This file is being included inside of my modules hook form alter:

if($form_id == 'commerce_checkout_form_checkout') {
  drupal_add_js('sites/all/modules/my_subscription/js/updateCart.js');
}

Even with the extraneous jQuery ready function within the behavior, it should still work. I guess it depends on what code resides within the javascript function and if all the jQuery selectors actually exist at that point. I would change two things to make it more "drupal"

Per my earlier comment, remove the jQuery ready function from within the attached behavior function
Attach the form javascript using the Form APIs #attached property. See here for more info.


Where is the "sites/all" folder for an ubuntu linux installation? I have installed drupal 7 from the ubuntu repositories.  All works well but I cannot locate the folder to install additional modules.

All the documentation says I need to upload files to the "sites/all" folder. This either doesn't exist or is somewhere I have yet to look.

Any pointers would be much appreciated.

ETA: I had to create the "/all/modules/contrib" subfolders manually, under the "/usr/share/drupal7/sites" absolute path.

It's referring to the "sites/all" folder in your website's root folder.

The location of your site's files will have been set by your web server software (probably Apache, in this case).

Have a look here:  /var/www/

and see if there are any directories in there that look like "httpdocs" or anything with your site's name in it or anything.


Setting $cookie_domain variable for specific folder structure During configuration of Ckeditor I have to setup the cookie domain variable. I have added my site in subfolder like www.example.com/mynewsitefolder, where www.example.com is my current and running site.
First I tried something like $cookie_domain = '.example.com/mynewsitefolder'; but that doesn't allow me to log in.

How can I set it, so it works on a sub-folder?

The short answer is that you cannot set cookie domain to such a value. See http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain

As a workaround, you can use this in settings.php (around where $cookie_domain is set:

$cookie_domain = ".example.com";
// Set cookie_path ourselves as Drupal doesn't.
ini_set('session.cookie_path', '/mynewsitefolder/');

$cookie_domain is eventually used to set session.cookie_domain but there is nothing in Drupal code base to set session.cookie_path and so we directly set that in settings.php itself.


Accuracy of numbers provided by the "Statistics Advanced" module? We use modules Google Analytics and Statistics Advanced, in Drupal 6. It is clear from the numbers that they provide very different readings.

Can anyone give any accuracy analysis for the Statistics Advanced module, perhaps by comparison with Google?

As it relates to Statistics Advanced, you may want to take into account some of the options mentioned on its project page. Such as:

  Only track 'unique' views of content: If you keep viewing a node over and over again, the "x reads" counter won't increase each time. This is applied on a per-user basis as well as a per session id for anonymous users.

Refer to the project page for other options mentioned there.

Disclosure: I'm the (new) maintainer of Statistics Advanced.


How do I put form field sets in jQuery UI tabs? I have created a custom form in a module via Form API. The form sits in a page created by hook_menu, which calls a function that renders the form from a form builder function. Also included in my module is a form submit function.

Currently, my form is divided into field sets that can be collapsed and expanded. It would be a lot nicer if the field sets were in tabs. To acheive this I intend to use jQuery UI tabs with the following code snippet:

drupal_add_library('system', 'ui.tabs');
drupal_add_js('
(function($) {
    $(function() {
        $( "#tabs" ).tabs();
    });
})(jQuery);
', 'inline');

I know I can put the other required markup in #prefix and #suffix properties in the $form array to wrap the field sets in tabs - but where does the above code go in the module? Should I be using hook_node_view or hook_view or something to ensure that jQuery UI tabs are initialised on my form page?

Thanks

If you're adding javascript for a specific form, use

$form['#attached']

e.g:

$form['#attached']['library'][] = array('system', 'ui.tabs');
$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/my_module_init.js',
);

You might also be interested in field_group, which provides jquery tabs etc.. for entity forms


Find the password for user admin from a replicated old version of site I have access to a copy of an old version of a production site on a dev server, but the owner of the website on prod has lost his credentials to admin and doesn't know his ssh login credentials. The only option for me to do his content updates is via the drupal web interface.

I'm able to get into the dev site via drush uli admin, but I need the password extracted from the dev server in order to get into the prod website.

How can this be done?

Short answer: it can't be done.

The password is a salted hash, and unless you have access to specialist cracking equipment, you're not likely to reverse engineer that hash in yours, or even your great, great, great, great grandkids' lifetimes. Even with access to the original salt.

As Pierre mentioned in the comments, submitting a password reset link on the live site is probably the simplest course of action.

Or contact your hosting provider; most will find you a way back into a server you're locked out for a nominal fee, once they've verified your ownership.

Bottom line, you're not likely to recover the password from the hash in the database, so you'll need come up with a creative workaround.


How do I implement cookieless subdomain? Cookieless subdomains are considered beneficial for a number of purposes:

They save some network overhead [1], and
they are required for certain types of caching [7] (e.g. reverse proxy like Varnish).

The most straight-forward way to implement is to create a sub domain of the main domain (A or CNAME host record in DNS), then set up a virtual host on the webserver and lastly configure a CDN with shared sub domains. [2] suggests to configure the cookieless Vhosts in Apache like this:

<VirtualHost *:8081>
  ServerName cdn.example.com
  <Directory /var/www/example >
    RequestHeader unset Cookie
    Header unset Set-Cookie
    […]
  </Directory>
</VirtualHost>

In Drupal, a CDN with shared sub domains can be implemented with the 'CDN' module and a CDN mapping like suggested in [3]:

http://css.example.com|.css
http://js.example.com|.js
http://img.example.com|.jpg .jpeg .gif .png .ico

At this point, CSS, JS, and images are delivered through the respective subdomains; however, according to firebug, these objects still have cookies attached to them, so Varnish can't cache them efficiently (or not at all).

These are some sample cookies I'm getting attached to an image that is delivered through the CDN sub domain img.example.com:

__utma=192369400.1671803289.1403302173.1403302173.1403302173.1;
__utmz=192369400.1403302173.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmv=192369400.|1=User%20roles=anonymous%20user=1;
__utma=164879789.945246956.1281184906.1403129675.1405102008.2582;
__utmc=164879789; __utmz=164879789.1396142298.2568.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none);
__utmv=164879789.authenticated%20user%2CSysop|1=User%20roles=anonymous%20user=1

All these cookies are set from/belong to the main domain www.example.com; I don't know what application/module sets the other cookies, but those including an Drupal user role are clearly set by Drupal. How do I get rid of them on images and what am I doing wrong here?

Some of the other cookies are probably set by the 'Google Analytics' module which are "usually set on a domain-wide basis to cover all subdomains" [6]. However, this module allows to configure ./admin/settings/googleanalytics, if GA is supposed to track one domain, or multiple sub domains (of course I chose "single domain").

Is an additional functionality required to allow Drupal (in my case Pressflow) to actually allow cookieless subdomains? For example, there is an 'Cookieless Subdomain' module at drupal.org [4] (undocumented; dev release; very few users). Do I need this, or is there another way outside of Drupal, e.g. in the Apache or Varnish configuration ([5] suggests that "varnish really isn't made to do redirects")?

[1] developer.yahoo.com/performance/rules.html#cookie_free
[2] webmasters.stackexchange.com/questions/1772/how-do-i-set-up-a-cookie-less-domain
[3] www.drupal.org/project/parallel
[4] www.drupal.org/project/cookieless_subdomain
[5] serverfault.com/questions/275728/varnish-serving-static-files-from-subdomains-for-better-page-load-speed
[6] serverdown.ttwait.com/que/275728
[7] www.ravelrumba.com/blog/static-cookieless-domain/ (Wordpress)

All these cookies are set from/belong to the main domain www.example.com;

Check your $cookie_domain value in settings.php

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
# $cookie_domain = '.example.com';

the leading '.' means the cookies also apply to subdomains.

You could try something more specific, to restrict the drupal cookie domain, like:

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


use block_load to load the same block with parameters? I have defined a "userinfo_Block" block to show special user's info. I have a userlist.tpl.php template file.

What I want to do on this page is using block_load() to display each user's info, but I don't know how to send the userid to the block.

How can I achieve this?

Based on what you've explained above, a custom module is required (I called mine MODULE) and you will have your hook_block info() which will declare the block:

function MODULE_block_info()
{
    $blocks = array();

    $blocks["userinfo_Block"] = array(
        "info" => t("User Info Block"),
    );

    return $blocks;
}

And hook_block_view() which will define the block. Below I have set the block content to the return value of the function userinfo_Block():

function MODULE_block_view($delta = "")
{
    $block = array();

    switch ($delta)
    {
        case "userinfo_Block":
            $block["content"] = userinfo_Block();
            break;
    }

    return $block;
}

Now, the function that creates the block:

function userinfo_Block()
{
    global $user;
//print out user, remember to check for no user
print_r($user);
}


Drag and Drop Sort Custom Entities I am looking for a simple way to sort my custom entities through a drag and drop interface and display them in the custom order in my views.

The best way would probably be to add a weight basefield to the entity type and let the drag and drop interface change the weight on each entity through ajax. Are there any examples on how to do that?

You can created an administration page views with you custom entities and to sort it you can use use the DraggableViews module. You would have to create another view to display your entities.


Embed Views remove pager I have embedded view in a node with following code:

<?php
 $view = views_get_view('articles');
 $view->set_items_per_page(1);
 $view->set_offset(2);
 print $view->preview('page');
 $view->destroy();
?>

I just need to display only one specific row (that's why I'm using offset). I couldn't find a way to retrieve one specific row with any other method.

This code is acceptable but it has pager because that view has more than one row.
Is there a way to remove pager like in Views UI? In Views there is a option to not use a pager but "Display a specified number of items".

I would like to remove it completely from code without CSS.

I ended up having to hide the specific pager with css in the case I did what you are trying to do...


How to create a view to display only child nodes of a parent term? Is it possible to create a view which displays only the child nodes of selected taxonomy term?

I have something like this

-Fruit
--Apple
---Green
---Red

and when I click on fruit (taxonomy/tem/1), I want to display only nodes with term apple, green, red. Now It is displaying nodes from fruit, too, but I dont want it. I have some nodes with term fruit but I dont want to display it when I click on fruit.. only nodes from fruit children terms.

Is it possible to do this?

I dont think that this way is possible,but a situation near to this is possible as:-
1. While creating a view,we have a field known as "filter criteria" field,in that add --*Content: Has taxonomy terms (with depth) (or Unknown) *

Go into the settings of this field*strong text* and choose depth of the field.**
Here Depth means-The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).**
this can be of help if u don't mark any node with the fruit tag,but mark all nodes with the some children tags of fruit.


Database error with migration I am trying to migrate users and a few other entities from a Drupal 7 site to Drupal 8 with the built-in migration modules and Migrate Plus.  I have added a database array in settings.php but something is missing to get the migrations to "see" the right database. I am getting this error.

[Mon May 11 22:22:56.025896 2020] [php7:error] [pid 6389:tid 140003403929344] [client 62419] PHP Fatal error:  Method Drupal\user\Plugin\migrate\source\d7\Role::__toString() must not throw an exception, caught Drupal\migrate\Exception\RequirementsException: No database connection configured for source plugin d7_user_role in /var/www//web/core/lib/Drupal/Component/Utility/Unicode.php on line 595, referer:

I have tried adding

shared_configuration:
 source:
   key: database_key

But it did not work.

Any help is greatly appreciated.

Thanks,
Josh

It's impossible to troubleshoot this remotely but there are a couple of things you can try to get connected to your source DB.

In your group's shared_configuration.source config you can manually add a database key with the same DB setting array properties that the migration module also looks for. For example:

shared_configuration:
 source:
   key: database_key
    database:
      driver: mysql
      username: user
      password: pass
      ...

Use the migrate update module to template out an initial working migration config rather than manually add your source DB. For example, run: drush migrate:upgrade --legacy-db-key database_key ....


Why is my JSON looking like this and what can I do about it? On Drupal 8, I enabled the serialization and restful web services and I created a restful view in order to create a map. The format is WKT. However, the output looks like the below.

Can/should I do something about it? Can this be parsed as is?

I'm assuming you're talking about the presence of \u003Ca and similar...

It's like that because Json::encode uses the JSON_HEX_TAG/JSON_HEX_QUOT/etc flags. It's done to ensure that all strings in the document are RFC4627 compliant.

You shouldn't need to worry about this, any compliant parser will happily translate the hex back to the original characters.


How to create a node programatically with drupal_form_submit()? How to create a node by programatically submitting the existing node add form, and most importantly using it's validation process instead of re-implementing all of the property/field validation logic so we piggyback off of the existing code.

The advantage of this method over node_save is that if you have field validation done by modules like field_validation or your own custom validations that you have previously implemented, the node saving will fail if the data sent does not comply with those validations.

global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'MYCONTENTTYPE',
  'language' => LANGUAGE_NONE,
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['MYCONTENTTYPE'] as $field_name => $values) {
  $form_state['values'][$field_name] = array(LANGUAGE_NONE => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body'][LANGUAGE_NONE][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
$form_state['values']['field_MYFIELD'][LANGUAGE_NONE][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('MYCONTENTTYPE_node_form', $form_state, $node);

// Tell watch dog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message', array('%message'=> $message, '%field' => $field_name));
  }
}


How can I preview the Drupal page as specific users? I just started using Drupal, so I'm still learning myself how to configure it. I have seen some older tutorials where there's a module(?) installed where you can click on "Hello %user%" in the top right corner and select which user you want to preview the page as. Is there a module for this or some built in setting I have overlooked?

The module called masquerade can do it. Not sure if it is the one you are refering to though.

  The masquerade module is designed as a tool for site designers and
  site administrators. It allows a user with the right permissions to
  switch users. While masquerading, a field is set on the $user object,
  and a menu item appears allowing the user to switch back. Watchdog
  entries are made any time a user masquerades or stops masquerading.


How to expose edit link on editable areas for all authorized users? The ideas is that in Drupal 7, on mouse hover on a node (or block) a edit link  appear at top corner of the node (or block), just like  the cog that appears for admin when s/he hovers on editable areas.

By exposing the the edit link on hover, we can create a much better user experience, for users that are not necessarily familiar with Drupal backend. I appreciate your hints.

There are two ways to do this.

The "gears" feature is from the "Use contextual links" permission on admin/people/permissions.  If you give that to the appropriate roles, your users should see that.

Personally, I don't like the Contextual Links feature, mainly because the markup it adds can mess with theme layout when you have other positioning going on. I typically add in my own edit links to pages, usually below the content somewhere. I will sometimes use a display: none on them, and then have a link in the footer menu that shows them all via jQuery.


How to alter the menu overview? I was trying to add another additional column in the menu overview (admin/structure/menu/manage/main-menu). I used the following code:

function mymod_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'menu_overview_form') {
        foreach ($form as $key => $item) {
            if (is_array($item) && isset($item['#item'])) {
                $item['node_url'] = array(
                    '#markup' => 'foobar'
                );

            }
        }
    }
}

It actually adds the indexes but the render output is not changed. How can I add an additional column to that overview?

Thanks

i think you should look at hook_menu_alter()
please Visit:https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7


How to add sub title name in the header using pixture reloaded sub theme of drupal 7.x? I need to add sub title name(with different font) next line of the "site name" in the header.
Am using  pixture-reloaded sub theme. could anybody, please help me out, where should i change and what piece of code i should add to diplay it out.

for example:
site name: Drupal Answers
next line of the site name, i need one more line to display :  Welcome to out job portal.

How can i alter my coding. Please help me out.thanks

The "sub title name" you are referring to is called the "Site Slogan" in Drupal.  In Drupal 7, you can add or edit your site slogan on the Site Information page (/admin/config/system/site-information).

Then, on the Pixture Reloaded settings page, just make sure that the "Site Slogan" checkbox under "Toggle Display" is checked.  You don't need any custom code.


How to programmatically create forums and containers (not forum topics)? I need to create containers and forums using rules.

If I use the action "Create new entity" -> "Taxonomy term" I got that by default the new term created is treated as a forum, not a container. How can I either convert it to be a container or, using a custom PHP script, create directly a container ?

I tought it was some variable of the term to make the difference, but if I use Devel over both containers or forums they looks the same.

I found http://www.unibia.com/unibianet/drupal/how-create-drupal-forums-and-containers-programmatically but it refers to D6, and in D7 I don't know what to pass as $form and $form_state to the forum_form_container() function.

I think I got it.. not in some fields, not (directly) in some DB table.. the difference between forum and containers is in the variables:

$containers = variable_get('forum_containers', array());
$containers[] = 14;
variable_set('forum_containers', $containers);


Get the breadcrumbs for a specific node other than the current I have a list of nodes created by a view. Those nodes tend to have titles that are mostly the same, but since they are in a rather logical hierarchy defined by the menu I'd like to output the breadcrumb to the nodes as well.

I couldn't find a core-function that does that. Anyone an idea how to work around/on that?

Core breadcrumbs in Drupal 7 are implemented in a way that they only work for the current page. So to achieve this with core, you would have to "simulate" a page request and somehow harvest the breadcrumb. This is probably painful and not worth the effort.

In Drupal 8, you have breadcrumb builders that take a route match as an argument. This route match can be any page. So yeah, what you want would be possible in D8. But you are in Drupal 7.

In Drupal 7 with Crumbs module, breadcrumbs are calculated independently of the current page. You can see this in action on admin/structure/crumbs/demo.

E.g. crumbs_get_trail() accepts a $path argument, which can be any path you want. But this gives you a "trail", not a breadcrumb itself.

Unfortunately there is no one-liner to give you the breadcrumb for any page.

But here is what you can do:

  // Create a local version of the Crumbs service container.
  $services = new crumbs_DIC_ServiceContainer();
  $page_info = $services->page;
  $page_info->path = 'node/123';

  // Optional: Set display settings.
  $page_info->minTrailItems = 1;
  $page_info->showFrontPage = TRUE;
  $page_info->showCurrentPage = TRUE;

  // Now choose which piece of information you want.
  $trail = $page_info->trail;
  $breadcrumb_html = $page_info->breadcrumbHtml;
  $breadcrumb_data = $page_info->breadcrumbData;
  $breadcrumb_items = $page_info->breadcrumbItems;
  $raw_breadcrumb_items = $page_info->rawBreadcrumbItems;

This can be starting point for you to play around with.

If you use Crumbs for this purpose, you get the full package: All your breadcrumbs will now be controlled by Crumbs. Maybe this is what you want, or maybe not.

I am not aware of other breadcrumb-customizing modules which provide this functionality.


Cron is 403: forbidden with cron_key and through 'run cron' link I'm getting a 403: You don't have permission to access /cron.php on this server.

This is whether or not I am logged in. Stranger thing is that it is happening on our development server, but not the live server (drupal 7)

If token is valid (and it should be when you use Drupal-generated link), there is one other mechanism that can generate 403: .htaccess - check it for rewrites that might block it. If this will not help, try running cron from Drush. Drush bypasses Apache altogether, so you can know if the problem was Apache related (conf files, .htaccess), or purely Drupal related.


How to find and edit front page I am new to Drupal and working for a customer. He wants me to change the title of the front page. I just cannot figure out how to get there. I have no problem with the rest of the pages on the site.

What you want is to find the content of the variable site_frontpage.

You could:

drush vget site_frontpage
Use devel and it's variable listing
SELECT * FROM variable WHERE name = 'site_frontpage';

This will tell you where the frontpage is controlled from. Often it will simply be a node that you can edit.


How do I add a column to the table shown in the vocabulary listing page? I need to add a column to the table shown in the page listing the vocabularies defined for a site. How can I achieve this?

You would need to override the class generating the list builder output on this page, then fill in the methods with what you want:

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = t('Vocabulary name');
    $header['foo'] = t('Custom Header');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $entity->label();
    $row['foo'] = 'custom_value';
    return $row + parent::buildRow($entity);
  }

See this related question: Can you change the list builder class used by an entity?

So, in essence:

function mymodule_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['taxonomy_vocabulary']->setListBuilderClass('Drupal\mymodule\VocabularyListBuilder');
}

Then, in your mymodule/src folder, create a VocabularyListBuilder.php, and copy in from the core/modules/taxonomy/src/VocabularyListBuilder.php and modify the two methods above for your output (since they'll be basically identical).

You could also do this with a View page as well, but for archival purposes wanted to explain how this works in general for Drupal core. List builder classes are such a cool and useful new D8 thing.


Get Video URL from Media Entity reference field I have an entity reference field to Media Video.

I'm trying to get the uri to the video file in node template.

Most of the solution I found around is regarding Image/File. But not Video.

Tried Twig Field Value module but it doesn't work.

If you use the media type Video installed by core, you'll find the URL in the field field_media_video_file:

{{ file_url(node.field_media.entity.field_media_video_file.entity.uri.value) }}


Remove language prefix from custom URL Our site exists in several languages. I have installed xmlsitemap module and default link looks like sitename/en/sitemap.xml

I need to remove language prefix just for this link. It seems like there's no settings to disable translation for any specific custom link.

May be I can do it programmatically?

Why not just add a redirect in .htaccess or similar, e.g.?

RewriteRule ^sitemap.xml$ /en/sitemap.xml [R=301,L,QSA]


Adding drop-down and radio buttons Is there any module that will help me create a drop-down menu and list as shown in the following picture ?

I want to connect this with registration page.

Try the Double field module

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

  For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea

  Consequently, in all there are 4 x 4 = 16 widget types.


Why is $node->taxonomy not populated when implementing a custom hook_nodeapi? I have implemented a hook_nodeapi in a Drupal 6 site. When looking into the node, I found out the node->taxonomy is not loaded. This means taxonomy_nodeapi is not invoked before my hook even though the weigh of my module is greater than taxonomy.

Edit Adding code:

hook_nodeapi(&$node, $op, $arg = 0) {
if ($node->type == 'articles' && $op == 'load') {
  dpm($node)
 }

I think this may be default behaviors. Invoking taxonomy_nodeapi() directly works for me but I am still wondering as to why this is the case.

I think I am explaining this right, but the issue here is that hook_nodeapi() called with op = load returns a keyed array that is later on merged into the node object.  It doesn't do this in sequence and progressively build up as each module's hook is executed, eg, it doesn't modify the node object itself. Thus it does not allow other modules to look at any other extra load information from other modules until later on.

For example, taxonomy_nodeapi() called with op = load loads up the taxonomy term info and returns it as $output['taxonomy'].  So, it is never available to any other modules until the node_load() where it is then turned into $node->taxonomy based upon that key.  Here, all other modules that add to $node in the same way also add in their extra stuff.

So yes, this is probably best described as default behavior.


Change default / base language for t() Currently when I use t() it shows me originaltext in english and i can translate into french and german. But I want to change the default language to french so when I write t('Salut') I will translate it into english, german, etc. later. But how/where can I do this?

Go to the language configuration page here

admin/config/regional/language

And set the default language to French.


Recommended way to clone functionality to create a site in Drupal 8 I have a Drupal 8 installation with different content types, paragraphs defined, views and taxonomy vocabularies. Ideally I wanted to be able to export some of these features and import them in another site, to deploy sites quickly without having to define them.

So first I tried with the module Features, I have followed the tutorial http://www.beaconfire-red.com/epic-stuff/how-setup-features-module-drupal-8, but this module only brings problems. I have also tried the Configuration Installer module, but also gives me problems. And also changing the uuid in the new installation and trying to import the configuration. But there are always problems and errors. So the only solution I can find is just cloning the database, but I think it's just a dirty solution.

I'm not an expert using drush, but I was wondering if it is possible in Drupal 8, to create a profile installation where you can define the content types, paragraphs and views created to reuse them. Is it possible?

Is there another way to achieve what I need?  How is it possible that there is not an easier way to export just part of the functionality of a site?

If you want to just extract specific functionality, you need Features.

If you just want to clone an entire site, first you need to export the site config with drush. Then, you will need to wipe all UUIDs from config export files using a script, here is an example:

#!/bin/bash
FILES=/path/to/your-site/config/*
for f in $FILES
do
  echo "Processing $f file..."
  sed -i '' '/^uuid:/d' $f
done

From here, you can install a brand new Drupal 8 site, and then drop the config in and do a drush cmi to overwrite the entire config state to the one you exported.

I've used this method a few times to clone entire sites. You don't need to copy the database, in fact I would strongly advise against this.

If you wanted to make an install profile, you could do that too, and one route to doing that is to put your feature modules in a profile, include them as dependencies in the profile info file, and optionally add an installer script to configure the site a little further (default content?). But yeah, you will have to dive in a bit here.


How to add a contact link next to the 'submitted by' user info? I would like to customize the 'submitted by user' section of certain contact types and add a 'contact author' link.

You certainly shouldn't need to hack core for this. There's a few ways to do this, the simplest way is to customise node.tpl.php. For example if you were using the default node.tpl.php you would copy it to your theme folder, rename it "node--yourcontenttype.tpl.php" and then open it up and find the code:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

You can then add the code to generate your contact link, something like this (untested):

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>
    <a class="user-contact" href="/user/<?php print $uid; ?>/contact">Contact

<?php endif; ?>


How to force child page added to book outline to top or bottom; update outline without clearing cache Drupal 8. When you click the "Add child page" link at a book page, you go to "/node/add/content type" where you can create and save the child page. Upon return to the book page (assuming the book navigation block is being used to display the book outline), the newly added child is not displayed (usually) in the outline until the cache is cleared and the page refreshed. Children are displayed in alphabetical order by default.

This is challenging for content editors who enter child pages because they don't see the child they've just entered when returning to the book page, and when they do see them, the children are not listed in the order of entry.

Is there a way to:

Automatically clear the cache upon leaving the add child page? Or disable caching for the book navigation block, at least for users with certain roles? Or something else to allow the editor to see the added child?
Automatically add the child page to the top or the bottom of the book outline? Possibly by passing a weight (in the query string?) to the add child page that's placed in the "Weight" field in the Book Outline tab at the right? (Note that the parent node id IS passed via the query string and inserted into the Book and Parent item fields in the Book Outline tab.) Or something else so the editor will know where in the outline to look for the newly added child page?

To this second question, one might say, "Just have them enter the weight when creating the child page." This works fine until they drag to reorder the outline. When that happens, Drupal assigns weights beginning with -15 to the child pages, so editors aren't sure what weight to enter.

Just trying to make the process of entering child pages for books as simple as possible so there will be fewer mistakes (especially same chapter added twice, or not at all).

As an answer to the first question above about updating a book outline display without clearing the cache:

Add the following to a custom .theme file (see drupal.org/docs/8/theming) to add a tag to the cached book navigation block:

function YOURTHEME_preprocess_block(&$vars)
{
  if ($vars['plugin_id'] == 'book_navigation') {
    $vars['#cache']['tags'] = ['node_type:{content-type}'];
  }
}

Then add the following to a custom .module file (see drupal.org/docs/8/creating-custom-modules) to flush the cached book navigation block whenever a node of the specified content type is changed or deleted:

use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

function YOURMODULE_node_presave(NodeInterface $node)
{
  if ($node->getType() == '{content-type}') {
    Cache::invalidateTags(['node_type:{content-type}']);
  }
}

function YOURMODULE_node_delete(NodeInterface $node)
{
  if ($node->getType() == '{content-type}') {
    Cache::invalidateTags(['node_type:{content-type}']);
  }
}

Credit to @oknate for the second half of this answer. See How do you clear cache on a block when node of certain bundle added or updated? for more detail.


image_style_url() function not giving proper image in drupal 7 I am using image_style_url() function in drupal 7 with custom style. In my custom style I have taken a height:200 and width:200. But its cropping my image with these style not re-sizing it.

$query_bigimg = db_query(" select * from  {node} WHERE  type =  'cont' ORDER BY nid ASC LIMIT 0 , 1 ");
foreach($query_bigimg as $data) {
  $data_nid = $data->nid;
  $_Data = node_load($data_nid);
  $_bigImg = $_Data->field_ua_news_photo['und'][0]['uri'];
  $_styles = 'big';

<img src="<?php print image_style_url($_styles,$_bigImg); ?>" class="big-img img-hover">

Then it is likely the rule you are referencing is not configured to do what you want it to do. It may be cropping instead of scaling or do a scale and crop.

Edit the image style at: admin/config/media/image-styles/edit

Check to see if it is scaling or cropping. Adjust it or create a new one and reference that in your code.


public file name encoding on windows I have to deploy a drupal 7 site built on Linux on a windows machine. Some (image) files are referenced via the public file mechanism. Some of them have special characters in their names, encoded in UTF-8 (AFAIK)

Files directly referenced are correctly handled by apache, for example:
http://localhost/lv/sites/all/themes/bizz/images/1.pr%C3%A9sentation.jpg
But the ones that are referenced via drupal public files cannot be accessed; for example http://localhost/lv/?q=sites/default/files/styles/large/public/2.teint%C3%A9_60_380X448_2.png&itok=RvL-USAY returns a 404

The file exists in the filesystem (as 2.teinté_60_380X448_2.png and as 2.teint├®_60_380X448_2.png [that was the name I got in the zip export file]) I tried 2.teintÃ©_60_380X448_2.png (UTF-8 as latin-1) too, but without more luck.

Is there a way to get drupal finds these files without editing all posts ?

I was wrong, 2.teintÃ©_60_380X448_2.png works, now I only have to write a script that converts all filenames to utf8, and use it as latin-1, great :/


The only email header field that can be replaced is the Reply-to field? Under the heading E-mail header details in the e-mail settings for my webform I have set the option E-mail from address to the component E-mail, from the current webform.

When the webform is submitted and recieved it works to click Answer in the recipient's Outlook client (the user e-mail from the webform is used in the TO field of the new mail).

But unfortunately this does not work when the recipient have enabled an auto reply, such as Out of office. In that case the address used in the auto-reply mail is the site's default e-mail address.

I have cleared all fields where the default FROM e-mail address can be stated (Default e-mail values in webform config, E-mail options in the SMTP settings) and tried with the option Use Reply-To header in the webform config both enabled and disabled.

I have also tried to use the variable $from instead of site_mail in htmlmail.tpl.php.

Is there really nothing I can do to replace the FROM address with a custom address fetched from the webform? Apparently the only header field that the webform can replace is the Reply-to field?

Not long after posting this question I found a working answer here
The problem can be solved programmatically using hook_mail_alter,


Display new tag to the newly added content I am trying to show "NEW!" to the recently added.
I know there is something to do with the Views module, but I couldn't find how to get it done.

How can I achieve this?

You can do it easily by adding new field Node: Has new content in views, it will show NEW status when a new node is added.


Drush not being found although installed [ubuntu 11.04] Utilising an Ubuntu (currently 11.04) box for WebDev in my SoHo, it's primarily for Drupal V7 projects using pure Linux LAMP and not any xamp, wamp models. I have a number of Drupal installs for dev and self-learning etc and hence Drupal version installs and modules change. I installed Drush 4.4 via the Ubuntu Synapatic manager and it installed seemingly ok, but when I try to run Drush from the Dash Home (HUD), nothing appears to load or run.

I'm the only user on the computer so I have all priviledges etc and all my Drupal projects are in var/www/ in order to emulate any future live web models. In order to be more efficient in updating Drupal and modules, I'd rather use Drush for Drupal updates as updating 6-8 projects is too labourious. Can anyone shed some light on why Drush is/or not running and what I need to do to simplify it's loading (a simple desktop link creation would be great). My current Linux experience is some 24 months having crossed over 100% from MS Windows O/S, but my DOS CLI experience was also then poor, so my knowledge was limited (but growing). Thank you.

Your problem is probably that Drush is not in your $PATH.  I did not try to install Drush-4.4 from Synaptic to test whether or not this is the case; instead, I would recommend that you install Drush via PEAR following the instructions on the Drush project page.  If you do this, your $PATH will be set, Drush will be found, and better yet, you'll be able to use the much-improved Drush-5.1 instead of the out-of-date Drush-4.4.

Edit: By "Dash Home", do you mean that you are trying to type "drush" into the Unity Heads-Up Display?  If so, instead run "terminal" from HUD, and then type "drush status" from the terminal prompt.  Then you should be good to go.  I'd still recommend installing 5.1 via PEAR.


How to make labels of fields selectable? Does anybody know if there is a module to make labels of fields selectable,
for instance
Field course:

Abc in DCT
123 today
listening pop

so if I select 123 today, in my content display I would have:

course: 123 today

but I would like to change course: by workshop: at the visualization of the content and have "course" for the other two (Abc in DCT and listening pop). So maybe there is a module that allows label selection, I haven't find it yet.

You'll have to make a custom field formatter with a settings form where you select the label and then output it accordingly.

Like in this tutorial about field formatters


Multilingual "Posted on: ... - By: ..." labels I would like to ask how to translate labels in drupal 7 like "Posted on: ... - By: ...".  I also have difficulties with translation for prev-next buttons text in calendar. I created a multilingual website based on Nexus 7.x-1.3 theme.

The Nexus 7.x-1.3 theme didn't considered internationalization for some of its  templates:
To enable it to translate "Posted on: ... - By: ...", edit the node.tpl.php on line 90.

Posted on: <?php print $date; ?>

By: <?php print $name; ?>

you will need to use the t() function to change the lines to:

<?php print t('Posted on:'); ?> <?php print $date; ?>

<?php print t('By:'); ?> <?php print $name; ?>

I'm not sure about which calendar you mean, in case that you are using the one bundled with Date module (Date popup), I believe those buttons can be translated using the Translate interface (admin/config/regional/translate/translate).


Getting data from submitted form I am trying to get data from a submitted form - as far as I can tell, data is being passed correctly, but I want to look at and manipulate it.

I'm trying to print_r() it with no success - because it happens after form submission and it isn't on the previous page.

This is my submit function so far:

function multi_reg_pagecreate_submit($form, &$form_state) {

$form_state['values']['multi_reg_checkbox'];

}

The checkboxes are generated on the page /multiple-registration, but I have no way of checking my variables once this page is submitted.

Any help would be appreciated

Check your variables by printing them with drupal_set_message().

function multi_reg_pagecreate_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state['values'], true) . '</pre>');
}

Alternatively, you can use debug()

debug($form_state['values'], 'Debugging the form', TRUE);


Is it possible to backup created block as a module? My question seems pretty simple but is very important: IS it possible or any solution to backup created block as a module to avoid duplication work, because there are times need to do something similar for multiple times and sites.
Like:

Create simple block with social media links, icon and some stable text.
Create a view that show five recent content title of custom content
type as customized block for several sites.
and all repetitive and permanent tasks can be done each time.

Thanks for any help and feedback.

Exporting and importing blocks in Drupal 8 are quite easy (thanks to new configuration system). You don't need to create a module for this. In Drupal 8 configuration is stored in yml files. You can export and import it on the following page:

Administration >> Configuration >> Development >> Synchronize >> (import / export) >> Single item

It works for all kind of blocks except "Custom blocks" because they are actually not a configuration but content like nodes, comments etc. As a workaround you can use Simple block module mentioned above.

Note, that in some cases you also need to export block configuration dependency in a separate yml file. For instance for a block that shows five recent content titles you need to export underlying view and all its dependencies. You may also checkout Features module for some advanced configuration package tools.


Creating a Feeds Plugin Child from a custom module and calling the new method I’ve got a module where I need to overwrite a method from another Feeds Plugins class. To do this I’ve followed the developer's guide to Feeds.

So I have implemented hook_feeds_plugins and hook_enable. These are being reached fine. The aim of my new child class is to override the parse method in  FeedsCSVParser

In my code I have this line:

$result = $this->importer->parser->parse($this, $result);

This still runs through the parent class and not the child one I’ve created.  How do I tell my Module to use the new parse method instead?

When i break point this line I can see in $this->importer->parser->pluginDefinition that this array should probably be of the new info I've entered in hook_feeds_plugins, but is showing that previous class instead.

Thanks for any guidance that can be given.

I have the issue fixed however this may not be the best method.  If you know what is then please let me know.

You can set a Plugin with 'setPlugin'

$this->importer->setPlugin('PreviewFeedsParser');

This wipes the config though.  So the following code shows - getting the config, setting the plugin and readding the config.

$this->importer->setPlugin('PreviewFeedsParser');
$this->importer->parser->setConfig($config);
$result = $this->importer->parser->parse($this, $result);


How to create multiple option field for product display? I am trying out the Commerce feature (bulk product creation), but the result is that the product has only one option list with all internal options. I want have more multiple options list with relative options, in the picture below you can see what I want to have in the product display:

How the products have no influence on how they are rendered on a product reference field.

What matters is what data the products hold, you need to be able to create unique combinations for all, and setup the reference field to try to do this. The problem you might be facing is that some products are too similar. To reviewing the product data and the products reference in the product reference field.

It's likely that you have created near identical products forcing the user to pick from a list containing all products, instead of have multiple select boxes.


AJAX autocomplete based on other field value I'm trying to implement an auto complete form with a little twist. I want its auto complete options to be limited by another field (text field to be more specific).

I understand how AJAX API works and should able to create an auto complete filter for a field based on it's own values but I have no idea how to create a an a auto complete filter based on another field in the form.

From what I have found only this question is similar to my problem, it is unfortunately unanswered. I don't want the code, just hint where to look would be useful.

BTW: I have came up with a solution but it's unbelievably dirty hack that requires going into database twice. I could implement AJAX callback for the field I want the filter to be based on, store the value of the field in the callback to custom database table and then in the callback of the field I want to filter get the value and make it work.

BTW2: The field I want to base the filter on will be text field, the other one custom entityreference.

BTW3: I'm almost sure it is possible somehow since the entityreference option limit module does something like that. (It does it with a help of one other field which I don't want (And I didn't understand it at all even though I tried anyway :) ))

I know it's a bit amateur but the question has already been answered I just didn't find it.

It's here:

form auto complete how to restrict results by previous drop down

and here:

Using ajax to filter drupal autocomplete form

BTW: I would delete the question but since I didn't find the answered questions myself I thought that this one might be more discoverable.

//I can't accept my own answer now, sory for that.


Images are not appearing on Front Page I've looked far and wide and am unable to resolve why my article images are not appearing on the Front Page. (Even disabled my CSS to see if that was interfering with it, but no.)

I have created a simple test Article and uploaded an image, yet when it's promoted to the front page, the image does not display.

Only the title, and body displays. When I click on the article, it displays the image, is there a setting I'm missing for this to display?

I resolved it by changing the custom display settings from teaser to full content. Once the image appeared on the front page, I changed it back to teaser and the image now displays correctly on the front page.

I'm guessing it's some bug or conflict with some modules that was causing this.


How to display Articles on another page ? not in home page I had Crated some articles for my project how to display that all articles on another page ?
not on home page.

You are looking for Views module:

  You need Views if

  You like the default front page view, but you find you want to sort it differently.
  You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain type.
  You like the idea of the 'article' module, but it doesn't display articles the way you like.
  You want a way to display a block with the 5 most recent posts of some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.


What conditions may cause "The content on this page has either been modified by another user..."? I'm working on a website which has multiple admins, some creating contents, some editing and some tagging...

I know editing one node at the same time will cause this error, is there anything else cause this error?

  The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

Another cause might me the fact that you save a form, then hit the back button and try to save it again


How to add image field to paragraph programmatically? I am trying to programmatically add an image field value to a paragraph.

The field value of the image is as below

Array (
  [target_id] => 28
  [alt] => test images
  [title] =>
  [width] => 1440
  [height] => 557
)

This is, how I try to set the image field value:

$paragraph->set('field_image',  $para_array);

The image field is not being set. Where am I going wrong and what will be the way to implement it?

You can treat the field like a PHP array to add (and not replace) an image:

use Drupal\paragraphs\Entity\Paragraph;

  $paragraph = Paragraph::load($paragraph_id);
  $paragraph->field_image[] = [
    'target_id' => $fid,
    'alt' => $alt,
    'title' => $title,
  ];
  $paragraph->save();


Expand children menu items with parent link, without javascript I've build a main-menu, and a sub-menu with Menu block. The sub-menu shows up if I'm on the article with the represented link. It works like it should.

Question: How can can I expand all childrens of a parent menu-link without Javascript?

A short wireframe for the overview.

If I understand you correctly then setting the parent link to "Show as expanded" should get you the desired result. You can see the option when you go to Structure -> Menus -> list links (of the correct menu) -> edit (the parent menu item which should have it's child links always displayed).


How to auto resize the height of an iframe with Jquery? Any idea on how to automatically resize the height of an iframe based on its content.

The iframe source is coming from different domain.

Any thoughts on how to achieved it via Jquery or native JS?

Thanks

UPDATE:
This script addressed my needs.

Drupal.behaviors.cnngomobile = function (context) {
    $(window).bind('load', function(){
        var adsIframe = document.getElementById("303799");
        if (adsIframe) {
          var style = adsIframe.contentWindow.document.createElement("link");
          // create <link>
          var host = "http://"+location.host+"/sites/all/themes/cnngomobile/css/style-iframe.css";
          style.setAttribute("href", host);
          style.setAttribute("rel", "stylesheet");
          style.setAttribute("type", "text/css");
          // append
          adsIframe.contentWindow.document.head.appendChild(style);
        }
    });
  };

I have implemented automatic iframe resizing using the cross-domain messaging ability of HTML5's window.postMessage() API.  Required reading: http://davidwalsh.name/window-postmessage, http://drupal.org/node/756722.

Example:

// "Sending" side (iframe)
Drupal.behaviors.yourIframeUpdateBehavior = {}
Drupal.behaviors.yourIframeUpdateBehavior.attach(context, settings) = {
  var data = {
    'bodyWidth':jQuery('body').width(),
    'bodyHeight':jQuery('body').height()
  }
  var domain = '*'; // Send to any domain.

  // Send current document dimensions to any parent of iframe
  parent.postMessage(data, domain);

  return false;
}

// "Receiving" side (iframe parent)
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
  $(window).bind('message', function(event) {
    var frameWidthPx = event.originalEvent.data.bodyWidth+'px';
    var frameHeightPx = event.originalEvent.data.bodyHeight+'px';
    $("#frame_id").width(frameWidthPx);
    $("#frame_id").height(frameHeightPx);
  });
});
// ]]></script>


Show only unread content; remove item once read or option to remove items I require a view which only shows unread content or provides functionality to remove items listed in the view once the node has been accessed. Alternatively a "x" button to remove the items manually for users.

So for example a view would show article's 1, 2, 3 & 4.

Once I had visited article 1 & 4 the view would now only show 2 & 3.

You can filter nodes exactly this way (a node filter called timestamp I think).

I'm not sure what the best way would be to solve the "x" button thing. Maybe add an extra binary field to the contenttype which you set via ajax (triggering a function you defined via "page callback" in hook_menu()) when clicking the "x". Then you have to add this field to your views filter as well.

Edit:

Instead of an extra CCK field you could also insert data into the history-table (uid, nid, timestamp) of drupal and pretend the user has already viewed the node. This way you would only need first views filter.


How to print an image field on all the basic pages only? In my custom type "Page" I've added an image field (field_page_cover_image) and applied image style to it.

<?php
  $field = field_get_items('node', $node, 'field_page_cover_image');
  if($field){
     $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
     if(isset($theme_img)) {
        // print styled image
        print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
    }
  }
?>

I have a requirement show this image (if uploaded) in all basic pages only (in a separate div container). For this I added the above code in `page.tpl.php

This code is working fine in all the pages but when I load search or other pages, I am getting error, as they don't have this field ($field).

I suggest you to use template_preprocess_page and save your image to a variable. You can refer the below code.

function mytheme_preprocess_page(&$vars) {
     $node = $vars['node'];
     $field = field_get_items('node', $node, 'field_page_cover_image');
      if($field){
         $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
         if(isset($theme_img)) {
            //print styled image
            $imagevariable = theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
           $vars['myImage'] = $imagevariable;
        }
      }
}

You can use $myImage variable to print the image in the tpl file :)


Users that exist only on slave cannot login Once I've installed bakery, users that exist only on the slave site can no longer log in. Everything else is working perfectly.

Is this by design?

Bakery doesn't pre-sync accounts, so any accounts that exist only on slave sites (sub-sites) won't be synchronized to the master site. This is because of the nature of needing an authoritative account master, the Bakery master site. During authentication (on a slave site) Bakery sends the user to the master to validate so if the account does not exist there the user cannot be authenticated.

To note, accounts that exist on the master that do not exist on the slave will be synchronized when the user authenticates and visits the slave site (administrators also have the option to "pull" accounts from the master).


How to display the term description on top of view In Drupal 6 the TVI module had an option:
"Display term description"
"When enabled, the term description is displayed before the rendered view on term page."

Unfortunately I can't find this option to display the term description on top of views page of taxonomy term in the Drupal 7 version of TVI.

Is there any other way to display the term discription on top of the view (the view displays all content/nodes of the specific term).
Thank you.

I haven't used Drupal 6 since 2010, so I can't speak to what used to be.

There are a few options here, given the differences in Views for 7/8 vs 6.

You can attach a field in the view header for the term description.
You can create a separate block display, and put that block on any term path.

I usually opt for #2, so I can put the term description and term name in a hero region, and keep the main view output uncluttered. Although you can use TVI in various ways, I stick to creating taxonomy/term/% as the page paths so feeding arguments so it is simple. So for the block, create a contextual filter and feed it the taxonomy term ID from URL.

You could also have the view render the term as a view mode as well, instead of fields. It's pretty flexible.

edit: The reason it shows without using TVI or Views is because the page callback for a term path hardcodes and prepends it: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.pages.inc/function/taxonomy_term_page/7.x .

That is one of a handful of reasons modules like TVI were created in the first place, so you can arrange your own display(s). Since TVI is injecting a View, it does not hardcode anything into the output:

/**
 * Replace taxonomy page callback.
 *
 * If more or less than one term is given then pass the request off
 * to the original taxonomy module page callback.
 *
 * @param int|object $tid
 *   The term tid or the term object.
 * @param null|int $depth
 *   The shown depth.
 *
 * @return array
 *   The build array.
 */
function tvi_render_view($tid, $depth = NULL) {
  if (is_object($tid)) {
    $tid = $tid->tid;
  }

  list($view, $display, $term, $settings) = tvi_get_view_info($tid);
  // Load metatags if needed.
  if (module_exists('metatag')) {
    metatag_entity_view($term, 'taxonomy_term', 'full', NULL);
  }
  if (is_object($view) && $display) {
    $output = t('There was no content found matching this term.');

    if (isset($settings->pass_arguments) && $settings->pass_arguments == 1) {
      // Pass all arguments to views. Exclude /taxonomy/term.
      $args = array_slice(arg(), 2);
    }
    else {
      $args = array($tid);
      if (NULL !== $depth) {
        $args[] = $depth;
      }
    }

    if ($view->display[$display]->display_plugin == 'block') {
      // If it's a block display, views returns a block array which won't work
      // as a page callback so we need to explicitly set the page title
      // and just return the $block['content'].
      $block = $view->execute_display($display, $args);
      drupal_set_title($block['subject']);
      $output = $block['content'];
    }
    else {
      global $language;
      module_invoke_all('entity_view', $term, 'taxonomy_term', 'full', $language->language);
      $output = $view->execute_display($display, $args);
    }

    return $output;
  }

  // Taxonomy is last resort - used if no standard views are found.
  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return taxonomy_term_page($term);
}

This is easily solvable in a few minutes with either solution above.