How to: Multilingual site with one front page that makes user choose a language first I want to have a front page like www.mysite.com/frontpage that shows up for every new visitor and helps him select a language and then move on to whatever language homepage the user selected.

You can create a custom block to display the language enable into site and a link to respective page of particular language.

To display the custom block in home page, you can use panels, create different template for the home page (page--front.tpl.php).


How can I exclude certain routes from maintenance mode? I am trying to make certain routes exempt from maintenance mode by adding the option _maintenance_access to the route and setting it to TRUE.
I think (although I'm not 100%) that this works because in Drupal\Core\Site\MaintenanceMode there is the following method which checks for the _maintenance_access option and returns false if it is present -
public function applies(RouteMatchInterface $route_match) {
  if (!$this->state->get('system.maintenance_mode')) {
    return FALSE;
  }

  if ($route = $route_match->getRouteObject()) {
    if ($route->getOption('_maintenance_access')) {
      return FALSE;
    }
  }

  return TRUE;
}

I have followed this guide on drupal.org on how to alter existing routes
Here is my mymodule.services.yml file
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\MaintenanceModeRouteSubscriber
    tags:
      - { name: event_subscriber }

Here is my MaintenanceModeRouteSubscriber class
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class MaintenanceModeRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->addOptions(['_maintenance_access' => TRUE]);
    }
  }
}

But this is not working as when viewing this route (any node) it is still in maintenance mode.

You need to override the service directly.
mymodule.services.yml
services:
  maintenance_mode: # same ID as declared in core.services.yml
    class: Drupal\mymodule\Services\CustomMaintenanceMode # point to your class
    arguments: ['@state']

mymodule/src/Services/CustomMaintenaceMode.php
<?php

namespace Drupal\mymodule\Services;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\MaintenanceMode;

class CustomMaintenanceMode extends MaintenanceMode {

  /**
   * {@inheritdoc}
   */
  public function exempt(AccountInterface $account) {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface && $node->getType() == 'article') {
      return TRUE;
    }
    else {
      return $account->hasPermission('access site in maintenance mode');
    }
  }

}


Send e-mail when webform submission changes Well, I want to send an e-mail when the web form is submitted, and when it is edited, so how can I do this?
The employee fills a form, and submit it, an email have to be sent to the boss, then, the boss approved or denied the form, and e mail is sent to the employee.

If you look here : http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/group/webform_hooks/7 , you'll see that Webform provides some hooks on which you can act.

There's a hook called 'hook_webform_submission_update', which triggers on the update of a submission. Using that one, you can check if the boss approved/denied it, and send out an email.

The plain 'send email on submission' can be configured through Webform itself, so you won't need to use a Webform hook for that. Although you could if you want to.


What function/method should I use for file_directory_path()? In Drupal 6, I am using the following code.

$id = fileowner(file_directory_path());

What is the Drupal 8 equivalent of that code?

You can use the following code.

$real_path = \Drupal::service('file_system')->realpath(file_build_uri(''));

On my test site, it returns '/Library/Server/Web/Data/Sites/avpnet/sites/default/files'.

You can also pass a filename to file_build_uri().

$real_path = \Drupal::service('file_system')->realpath(file_build_uri('file.jpeg'));

With this code, I get '/Library/Server/Web/Data/Sites/avpnet/sites/default/files/file.jpeg'.


Double field module theming Could anyone please help with the Double field module in Drupal 8 and Twig? I am trying to produce the following with no luck so far as I cannot figure out the proper Twig variables to use.

{{ first }}

{{ second }}

I would like to have the raw values in the html above.
-- I'm adding some more info here because my goal is to understand the mechanics of twig in this case and how I can get the field values of the two subitems

I have overriden (as suggested by drupal's theme debug system) the field--fieldname.html.twig template in which I have the following

{% for item in items %}

      {{ item.first }}

      {{ item.second }}

{% endfor %}

which is not printing anything in the value areas and apart from that does not iterate through all the items either.

If you are using default (Unformatted list) formatter override double-field-item.html.twig template with the following markup:

{{ item.first }}

{{ item.second }}

Note that Double field ships with HTML list formatter which may render definition list so you might not need to override anything.


Views filter out nodes based on taxonomy field I have multiple node types on my website and a special View listing all the nodes on the site.

I have a taxonomy field which I have applied to some node types but not others. The trouble is any user with editor permissions can add the taxonomy field to any node type which previously did not have it.

My Views needs to list content only of node types which have the taxomony field included. In other words, if a node type does not have field_taxonomy_example included, my View should list NO nodes of that type.

My problem is I can't find a way to dynamically exclude node types - statically setting them is not an option because new types can be added any time.

Please help :-)

I found a programmatic solution after visiting the Views API page.

Using the following code:

function mymodule_views_query_alter(&$view, &$query){
$types = db_select('field_config_instance', 'fci')
        ->fields('fci', array('bundle'))
        ->condition('field_name', 'field_taxonomy_example', 'like')
        ->execute()
        ->fetchCol();

$query->add_where(0, $query->fields['node_type']['field'], $types);

}

I was able to insert a dynamic list of node types to test my Views again.

Works like a charm.


How to delete folder along with the files from database also? I want to delete selected folder along with all files inside that folder. I tried by using file_unmanaged_delete_recursive() It will delete folders and files but it is not removing database entry of files and not even it is making the Status of the file to Zero. So how can I achieve this?

file_unmanaged_delete_recursive(), as the name implies, removes any files under a directory without concern to managed files (i.e. files tracked in the database).

In order to remove files from the database, you can make use of the file_delete() function in the File API. This function needs the file ID supplied as an argument, so you'll need to perform a query on the database to retrieve it. For example:

$files = file_scan_directory('sites/default/files/my_custom_dir', '/.*/', array('recurse' => TRUE));
foreach($files as $file) {
  $scanned_file_uri = file_build_uri($file->uri);
  // @TODO: query file_managed.uri for match with $scanned_file_uri
  // then delete with file_delete();
}


Drupal incorrectly reporting that permissions need to be set on settings.php I've updated a site to v8.5.3.  Checking the status report I have various messages.  One says:

Not protected
    Protection disabled
   - The file sites/default/settings.php is not protected from modifications and
    poses a security risk. You must change the file's permissions to be non-
    writable.
   - The file sites/default/settings.local.php is not protected from
     modifications and poses a security risk. You must change the file's
     permissions to be non-writable.

I've checked these files and they are set to 444, there are no write permissions set.  Drupal seems to be reporting this incorrectly.

Is there anything else I need to do or am I missing anything?

They keyline here is Protection disabled.

Which means you have to check your settings.php or setting.local.php for

$settings['skip_permissions_hardening'] = TRUE;

which must be

$settings['skip_permissions_hardening'] = FALSE;

instead.

If it's not there already, add it.

Flush cache, done.


How can I get an entity edit path? I made a module, and defined my custom entity there. I set the path for the administrative page using the following array.

'admin ui' => array(
  'path' => 'admin/structure/optimizations',
)

How can I get the edit path for one instance of my entity, for example admin/structure/optimizations/manage/2?

I don't think its a good idea to hard-code the path as with  'admin/structure/optimizations/manage' . $entity->id.
Is there any function to get the edit path for an entity?

You may want to take a look at hook_menu()

Here you can define paths and route variables to where they are needed.

For example:

function hook_menu() {
  $items['admin/structure/optimizations/manage/%'] = array(
      'title' => t('Your Page Title'),
      'page callback' => '_your_callback', // The callback that is building the page
      'page callback' => array(1), // This is the value from the % array key
      'access arguments' => array('administer users'), // A permission to require
      'type' => MENU_NORMAL_ITEM,
  );
}

function _your_callback($val) {

  //Access the % from the URL defined in hook menu using $val.

  ...

}


How do I use a term page display? In Drupal 7, the module taxonomy_display allowed me to insert a content view via views display options under the taxonomy manage display. I am working on rebuilding my Drupal 7 views for Drupal 8, and the way they are built in 7, they depend on this function.

We are using a (term) view to display parent terms as links to navigate to:

either a child term view (parent/% path) displaying child terms as links to the content view when the content is ascribed to the child term.
or  our content view (also parent/% path) when the content is ascribed directly to the parent. We accomplish this in our content view by using no results behavior/global view area to inject the child term view when there is no content ascribed.

With the taxonomy_display module, you then simply go to the term page display and set that to the content view. It will show child terms when there is no content ascribed, and it will show content when there is content ascribed.

The module documentation for taxonomy_display for D7 says that the core function of this has been included into Drupal 8, and refers you to this issue for more information, but there I didn't find information there on how this function is implemented in Drupal 8. It seems that they are referring to the taxonomy/term view in now in core.

My question is, can i still accomplish this structure without the taxonomy_display module merely by what is provided by the taxonomy/term view in core?

Or can I ignore the taxonomy/term view all together and accomplish it a better way?  I'm new to D8, so any help would be appreciated!

Both of the modules mentioned (Taxonomy display and TVI) that make Taxonomy term pages easier to configure rely on Views, so you do need to have the Views sorted out before you can assign different Views to different Vocabularies. These modules don't replace the "Views magic".

If you don't use these modules that override how term pages are displayed the "Taxonomy term" Views that comes out-of-box handles all of the terms equally. BTW "Taxonomy term" Views is of the content type (not the taxonomy term type, the name can be confusing a bit).

But the "Taxonomy term" Views can be changed to handle different Vocabularies differently. This change can be made in the Contextual filter in the validation settings. Then you can clone that page, give it a different path, and adjust the contextual filter validation to a different Vocabulary.

Both of your cases can be handled with the modified "Taxonomy term" views. Using the "Summary" option in the contextual filter for the Taxonomy reference field will list the terms present in the views results. When you click through those links you see the content listed. Although your "No results behavior" solution also works.

You can get the Parent info into your path through another Contextual filter (Taxonomy Name), that you can get after adding the Relationship for the parent term in your Views.

It's all in the Contextual filters and perhaps some Relationships to create your cases. There are a lot of answers here relating to those so you can search and learn from them.

It is also mentioned in the comments you can use the theme templates to override how Term pages are displayed, when you're not using the Views to build those pages, but you'll probably still use Views to build blocks to put in those templates, unless you know SQL and can create better queries manually.


Can the reaction of "Cron Maintenance" in the Rules modules pull data from nodes? Overall Goal: Have an email sent whenever a node has not been commented on for a certain amount of time (ex: 1 hour).

Previous Attempt: Have a node become stickied when a comment is posted.  Then unsticky the node after a certain amount of time.  If a node is not stickied, send an email.  This worked for one evaluation time rather than having evaluation over the life of the node.

How it could be done for continuous evaluations:
1. Use the same concept from previous attempt and have nodes stickied when commented on.
2. Have a Rule react on Cron Maintenance that will unsticky any nodes that have the newest comment older than a given time amount.
3. Then have another rule that runs on Cron Maintenance to send emails to a user that is specified within a node's field when said node is not sticky.

My main issue about this is that any Rule that is reacting on Cron Maintenance isn't letting me pull information from the node table.

Previous Attempt: Have a node become stickied when a comment is
  posted. Then unsticky the node after a certain amount of time. If a
  node is not stickied, send an email. This worked for one evaluation
  time rather than having evaluation over the life of the node.

Activate the Rules Scheduler module (comes with Rules)

Sorry, I missed a step. For your If and Else Statement Add Action of Schedule Component Evaluation and select your component. So you basically re-schedule your component evaluation. Thus, you get continuous evaluation.

Result:


How can I open Poll for Anonymous users? I wonder how I can open my poll for everyone including anonymous users, not just registered users.

Visit admin/user/permissions and check the checkbox for vote on polls for anonymous.


Is there a way to ask migrated users to complete their profile? I hope to migrate users in the database (using Drupal 7).

How will I handle the fact that they have no password, and will need to create one before accessing their profile?

Password is currently on the Join Form and these migrated users shouldn't have to go through the Join form.

Also - what do you suggest for mass email?

Thanks!

You can take help of Mass Password Reset module.

I had same kind of situation when I made a existing website of D6 into D7 & migrated users from there.


Custom submit handler on form loaded via entity.form_builder Using Drupal 8.5.3. Currently working within a custom controller to load and alter a form for menu links. To load the form I am using the following:

// Load the menu link field.
  $menu_link_content = MenuLinkContent::create([
    'title' => 'Example link',
    'link' => ['uri' => 'internal:/node'],
    'menu_name' => 'main',
  ]);

  $form = \Drupal::service('entity.form_builder')->getForm($menu_link_content, 'default', $form_state_params);

Simple enough right? From there I go onwards to alter $form inside the same method in the controller. I can change the $form values from there to adjust which menu items are available.

The problem is that I can't seem to add a submit handler.

I've tried both of these to add a submit handler, to no avail.

$form['#submit'][] = 'group_content_submenu_group_link_add_submit';
$form['actions']['submit']['#submit'][] = 'group_content_submenu_group_link_add_submit';

Any ideas on what I could be missing? I'm open to other approaches as well, but I specifically need to be able to set the parent item that this form should be using to present available parent menu link choices.

As per a comment from another user, the form is already processed after being returned by the form builder. That said, you can still alter values, but not add form elements or alter actions.

The solution for me was to do a form alter on the form before hand, and give it a submission handler, along with a hidden field. Then when I get the form in the code above, I now set the hidden field to contain a relevant value (Group ID). In my submission handler, I only proceed if that hidden value != NULL. This prevents me from doing anything on the core entity form which I do not want to affect.

Thanks for the hint 4k4!


Is there any drupal module to export/import all ubercart products with product details(attributes) I am looking for the module which having the option to import all ubercart products including all information like product images, price, sale price and other attributes. After exporting the information how we can import these to other drupal setup.

If there is no single module to do this then what will be the right approach to do the same.

I would use start by having a look at UberCart Feeds with  uc_feeds_product_importer  they should help you get the job done.


How to run a cron queue programmatically? I have created a cron queue like given below.

function mymodule_cron_queue_info() {
  $queues['aggregator_feeds'] = array(
    'worker callback' => 'aggregator_refresh',
    'time' => 60,
  );
  return $queues;
}

My cron runs when calling drush cron. I need to run the queue 'aggregator_feeds' individually without invoking any other cron queues. Drupal admin panel -> config -> cron : runs all queues as per schedule.
drush cron command too runs all queue. How do I run a single queue programmatically?

Also I need to know how to run all the queues programmatically?

For one of my project, this worked for me :-

$queue_machine_name = 'sync_product_list';
$queue = \Drupal::queue($queue_machine_name);
$queue_worker = \Drupal::service('plugin.manager.queue_worker')->createInstance($queue_machine_name);
$item_id = '123';
$queue_worker->processItem($item_id);


Webform + Translations I have a website where 80% of it are Webforms. Admins can create webforms themselves and registered users can fill them in. ( A PDF will be created etc etc...).

Now I have to make this website in 3 other languages then the default.

I Found already the following module:

https://www.drupal.org/project/webform_localization

Now my initial question:

Imagine you have a webform in the wizard with  a label, and a textarea and a default value as type or static text. What is the best way to get the 'default' values in the context translated?

Example
http://i.imgur.com/pAiQEJM.png

Note:
This is text which got changed for every webform generated on the website.

This is content - not static text; your only options are to translate it manually yourself or use one of the contrib modules like Lingotek or Cloudwords.


Modify label on view exposed filter I have a view with exposed filter to a field as follows :

I want to change the text 'Deployment date from' and 'And' to 'From' and 'To'

Can i do this with hook_views_query_alter or hook_views_pre_render

Finally i got the answer . Actually it should be used like YOURMODULE_form_views_exposed_form_alter only . No need of activities_page_1_ as expected . Am adding the answer below :

/**
 * Implements hook_form_FORM_ID_alter().
 */
function module_name_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  $form['created']['min']['#title'] = t('From');
  $form['created']['max']['#title'] = t('To');
}


Exposed filter : search term with select which 'field' to search by I have a view which displays a list of nodes with exposed filters. Everything works perfectly.

I would like to add a filter like this:

one input text
one drop-down.

The list items represent fields of content type.

The user can write a search term in the input text and select which 'field' to search by. i.e. All, Title, Summary, ...

Is that possible? How I can do this?

I have created a custom module inspired by your question. You can find it here

It is not created/approved as a full project on Drupal.org. But it will approved soon. Download the module, enable it. Under filter add a filter that says Exposed fields Filter then select the fields you want to expose to visitors. Only those field will appear to visitors which you select here.

I hope it helps you for now.


What is the difference between wysiwyg module + ckeditor and ckeditor module? What is the difference between using the Wysiwyg module and the CKEditor - WYSIWYG HTML editor module? Are there benefits on using one over the other?

I've played with both recently and can offer some insight, at least for Drupal 7.

The Wysiwyg module lets you use any number of editors, such as CKEditor. It also integrates with the Media module if you use that. If you don't want to use CKEditor, but, say, TinyMCE, then you'll want to use Wysiwyg.

The CKEditor module is (obviously) just for CKEditor, and has more options specific to CKEditor. For example, you can change the skin CKEditor uses (Office 2003, Karma, etc). You can also set advanced CKEditor config options which you can't do with Wysiwig+CKEditor. It also integrates with some file browser modules like CKFinder. And I believe you can use the Media module with new versions of CKEditor.

One of the big reasons I went with the CKEditor module is that it doesn't strip out JavaScript. I couldn't find a way to get Wysiwyg+CKEditor to preserve JavaScript.


How do I set a range of views results? I have 2 views in a page. The first view displays 3 articles and the second view displays a list of all the articles. The problem is that I get duplicated articles in the second view since it is displaying all the articles.

I need to set a range of the last 3 articles added to Drupal and display them on the first view  and on the second view I need to display the remaining articles. I´ve been looking for something like this is in the filters but I haven´t found something.

Thank you for your help !

You can do this by adding an offset (you can find this in the pager options in your view), in your example "3". The offset "3" will show all results, but skips the first 3. Make sure that the sort criterea in both views are the same.


How to define my own block regions for original, custom front page layout? I want to define my own block regions for the front page

I want to have a grid of blocks, each block containing a list of recent media (pictures, youtube, audio) with a certain tag. See example wireframe as ascii art below

A rule with the blocks is that if an item has already appeared in one block, then it doesn't appear in the others (media items can have multiple tags obviously).

Questions after the drawing.

+-----------------------------------+
! main menu                         !
+-----------------------------------+
! rolling display                   !
!                                   !
!                                   !
+-----------+-----------+-----------+
! tag a     ! tag b     ! tag c     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag a! with tag a! with tag c!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag d     ! tag e     ! tag f     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag d! with tag e! with tag f!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+
! tag g     ! tag h     ! tag i     !
! heading   ! heading   ! heading   !
+-----------+-----------+-----------+
! list      ! list      ! list      !
! of media  ! of media  ! of media  !
! with tag g! with tag h! with tag i!
! & thumb   ! & thumb   ! & thumb   !
! nail for  ! nail for  !nail for   !
! each item ! each item ! each item !
+-----------+-----------+-----------+

Please outline specifically how I would go about doing this. I'm looking for a fairly definitive answer -
i.e. something that won't break something else, and is robust in itself.

Specific questions:

Would I use PHPTemplate and if so how? Would I use this to declare
the regions, and how?
What would the roles of Panels, Views and Blocks be in creating this
layout?
Can I create the layout in panels without writing any PHP code?
Presumably the Views module would provide the content within the
blocks.
How do I tell Views and Blocks where to put the content, i.e. in a particular block?

If you just need it on your front page, doing it in page template is wrong.
You can do in in Panel - create new panel for logged and not logged users; use there blocks; and views' display 'panel pane' for using views which need argument from context.
Yes you can
It can, but sending view argument this way is really painful. I recommend use panels panes.
You set it in panel.


Custom Drupal (Block)Module not showing in Blocks Relatively new to Drupal. I have created a custom Module that is supposed to create a block. I refferenced a successful module that accomplished the same end goal (implementing a custom HTML build).

I have done the "Disable > Delete > Clear Cache > Re-Install/Activate Module" process a few times, with no luck. Any help or insight would be appreciated!

Here is my code for the .info file:

name = History of Alcohol Timeline
core = 7.x
package = Legal Thinking Age
php = 5.2.4
version = 7.x-1.0
project = lta_hoa

Here is my code for the module:

<?php

function lta_hoa_timeline() {

$output = <<<TIMELINE

  ...

TIMELINE;

return $output;

}

function lta_hoa_block_info() {

  $blocks['lta_hoa'] = array(
            'info' => t('History of Alcohol')
        );

  return $blocks;

}

function lta_hoa_block_view($delta = ''){

  // Setup blocks
    $block = array();
    switch ($delta) {
      case 'lta_hoa':
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/jquery.fancybox.css');
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/media-queries.css');
      drupal_add_css(drupal_get_path('module', 'lta_hoa') .'/css/style.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/jquery.fancybox.pack.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/jquery.timelinr-0.9.53.js');
      drupal_add_js(drupal_get_path('module', 'lta_hoa') .'/js/lta_hoa.js');
      $block = array(
          'subject' => t('History of Alcohol'),
          'content' => lta_hoa_timeline()
        );
        break;
        default:
          break;
    }

    return $block;
}

Code looks fine to me, except for the sometimes funky indenting :)

Your function lta_hoa_timeline() just returns ... in example code. If your actual code contains a whole of stuff instead of ... and you have trouble getting that to work/display, it might have something to do with the inclusion of CSS/JS files. At the very least you should see the title of the block appear.
But if ... is your actual returned content, it should work.

Verify that you've put your block in a region, that your theme displays that specific region, and that your block is not restricted to any specific page/role/.. , and you should see your block.
As suggested above, switch to a default theme, put block in a standard region like sidebar left, and turn off all restrictions


How does Drupal ensures that the one time unique URL used to reset user password does not get transferred away inside the http_referer header? For example in case the site relies on and loads some external JS (such as jQuery via CDN). Quite technical but any insights are highly appreciated. Thanks.

At this point in time, it doesn't.

There's an issue to fix this in Drupal 8, after which it will (hopefully) be ported back to 7. Patches are currently awaiting review.


Google Maps Module custom markers and routeplanner On my Drupal site, I have a nice Google maps module with custom markers.

The only thing I want to add is a route planner that makes use of my custom
Markers.

Any suggestions?

Have you already tried https://drupal.org/project/routeplanner ? It's a very simple and lightweight Module to create a route from any address to a fixed point of interest.


Change behaviour of Date at 00:00 Is there a way to change how Date works when saving dates with the time in 00:00:00? I have a calendar view, and I would like to avoid having events showing as all-day when the are saved with a time of 00:00. Is this possible? I have a content type that cousd either start at 00:00 or end at 00:00, but those are not all day events.

You could (a) try changing the granularity of the date field in your content type (b) override the theme function. (ref)


$ is not a function but jQuery is loaded when adding JavaScript to a custom theme I must have something set up incorrectly in my custom theme. jQuery is loading and works fine elsewhere on the same page in a views slideshow using jquery.cycle. My custom JavaScript however reports that $ is not a function.

The info.yml file includes the global-scripts property.

The libraries.yml file contains the following code.

  js:
    js/script.js: {}
  dependencies:
    - core/jquery

The content of js/script.js is the following.

$(document).ready(function () {
    $(window).on('load scroll', function () {
        var scrolled = $(this).scrollTop();
        $('#layer-1').css('transform', 'translate3d(0, ' + -(scrolled * 0.25) + 'px, 0)'); // parallax (25% scroll rate)
    });
});

The first line in script.js returns the error in the console. It is the only error I receive.

I checked the page source and confirmed that jQuery is being loaded before script.js at the bottom of the page below the footer.

Can anyone see what I have done wrong here?

The Drupal js documentation states

  Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript
  files when required, to use jQuery and the $ shortcode for jQuery you
  must include jQuery and Drupal as dependencies in the library
  definition in your MODULE.libraries.yml and add a wrapper around your
  function.

You should also use behaviors instead of document.ready() which is stated earlier in the above documentation.

  However with Drupal there is an alternate better method [to document.ready()]; using the
  functionality of Drupal.behaviors and once(). If used properly this
  will ensure that your code runs both on normal page loads and when
  data is loaded by AJAX (or BigPipe!) - but not jQuery methods like
  load() which should be avoided as Drupal behaviors will fail to load
  for loading functions other than ajax().

So your snippet should look like:

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $(window).once().on('load scroll', function () {
        // ...
      });
    }
  };
})(jQuery, Drupal);

If your selector is something other than window, e.g. a class, you should update it to be something like $('.my-class', context).once().etc. Passing context like this ensures that your js only fires if the element exists in the currently being loaded context, i.e. if a small chunk of the page is loaded via ajax context will only contain that small chunk of the page. .once() ensures the js will only be added to the element once. It will prevent scenarios where you single click an element but it acts as though you double or triple clicked it. Here is the documentation for .once().


Drupal 7 db_error() equivalent? I'm trying to figure out how to get the last database error after a query fails, and I'm having trouble finding the appropriate function. It seems up until Drupal 7 there was a db_error() function that would return the information.

How should I retrieve a database error in Drupal 7?

My code:

try {
    $q = db_query($q);
} catch (Exception $e) {
    $error = db_error(); // this is what I'd like to do
    $transaction->rollback();
    watchdog_exception('my_module', $e, t('Caught an error: ' . $error));
}

I'm aware that I can get some information from the exception, but I'd like to get it directly from the Drupal 7 API.

The Drupal 7 database API piggy-backs straight onto PDO. It doesn't define its own exceptions, or messages; it actually doesn't even attempt to handle any exceptions, it leaves them for the caller to handle directly.

The most descriptive error message you can get is in the exception object.

catch (\PDOException $e) {
  $error = $e->getMessage();


Drupal CMS - Find Content - how to drop the ?destination=admin/content in the edit link? I'm using drupal 7.  When I go to the CMS at the url http://mysite.com/admin/content, the edit link for each of the content records are

http://mysite.com/node/206/edit?destination=admin/content

I want to convert the url to:

http://mysite.com/node/206/edit

How do I do this?

The reason I want to do this is because I want the user to always see the result of his work after he's saved it. Additionally, there are important Call-To-Action requirements on the /node/206/edit page that appear immediately after saving a record.  These CTA requirements are not available in the admin/content area.

Additional Info
I applied a bandaid solution for now.  I went into my admin theme at /theme/nameoftheme/page.tpl.php, then I replaced the statement

<?php print render($page['content']); ?>

with

<?php print str_replace('/edit?destination=admin/content', '/edit', render($page['content'])); ?>

Can someone please provide me with a more elegant solution, so I don't have to use this band-aid solution?

This is a result of the content editing screens returning the user to that. If they edit content from the front-end, the destination is the node.

You can override that default content manager with a View configured the way you want it. The 'Edit' link won't have a destination in the URL, and if I recall, it will return the user to the content after editing.

Also, if this is D6 and they have access to this page it sounds like they have administer nodes access. You might want to tune the permissions differently and setup a view so you can override admin/content path(s) with your View to override the content manager.


Drupal 7 Views Isotope Error I have an ecommerce site using the module views isotope to display the product grid. After a recent upgrade, It looks like my view is broken and I'm getting this warning:

  "Warning: in_array() expects parameter 2 to be array, string given in
  ...(my theme directory)".

The warning can be viewed here: http://biltriteinc.com/?q=supports

What is causing the error?

Error is as stated..

Warning: in_array() expects parameter 2 to be array, string given in goodnex_item_list() (line 212 of /home/biltrite/public_html/sites/all/themes/goodnex/template.php)

Whatever is calling in_array in goodnex_item_list is not passing an array as the second argument and instead is passing a string. You'll have to backtrack from there to figure out what and why.

See: in_array


how can I use jquery autocomplete in drupal 7 I want to use jquery autocomplete jquery plugin, I test below code but nothing happend, I check, the file added correctly and there is not js error.

function imodbdev_form_alter(&$form,$form_state,$form_id){
  if($form_id='movie_node_form'){
      drupal_add_library('system', 'drupal.autocomplete');
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/jquery.livequery.js', array('scope' => 'footer'));
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/imodbdev.js', array('scope' => 'footer'));
  }

}

and  js/imodbdev.js file

(function($) {
    Drupal.behaviors.imodbdev = {
        attach: function(context) {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#edit-title" ).autocomplete({
source: availableTags
});
        }
    }
})(jQuery);

I had install jquery update module and set jquery version to  1.8 .
where is the problem?

update

after sometimes I type in textfield to test , I saw TypeError: c.curCSS is not a function in firebug, I search this error in google and suggestion in upgrade jquery ui  to 1.9.3  but drupal not has version higher than 1.8.

Yes, jQuery UI is available in drupal core.

To include libraries like that you need to call the drupal_add_library() function to load the required js & css.

For exmaple:

drupal_add_library('system', 'drupal.autocomplete');

So where you are adding your javascript, add that first.

For example:

// Add the jQuery UI autocomplete library.
drupal_add_library('system', 'drupal.autocomplete');
// Load the custom js for this module.
drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/js/SCRIPT_FILE.js');

The caps lock parts need to be changed to suit your module.

As for where you would put this, I can't say unless I know where you are putting your code. It could be in your theme or in a custom module.

If it is in your theme then the drupal_add_js() part would be drupal_add_js(drupal_get_path('theme', 'THEME_NAME') . '/js/SCRIPT_FILE.js');

I'm also assuming your scripts are in a js sub-directory.

You also need to make sure that any custom js you have is inside a drupal behavior (or $(document).ready() at the very least). Otherwise your javascript will run to early in the page load before the text field even is on the page, so it will do nothing.

It will be like this:

(function ($) {
  Drupal.behaviors.yourThemeAutocomplete = {
    attach: function (context, settings) {
      // Your code goes here.
    }
  };
})(jQuery);

For more info see https://drupal.org/node/756722#behaviors (the whole page is useful info)


How to redirect to top level domain and not relative value Under admin/config/system/site-information, the startpage is configured as /home. So when you go to www.domain.com, the content of /home is displayed. However, when a form is submitted, it automatically redirects to www.domain.com/home. Is there any way to prevent this?

I resolved it as follows:

in the form submit handler, I simply added:

$form_state['redirect'] = '<front>';

Hope this helps someone...


Create a drop down list of notifications with an unread item count that resets or hides on click I've used the message module to create a notifications system on my site. It works fantastically, however the final task I would like to complete has been less pioneered via contributed modules. This is the creation of a drop down menu item that lists unread notifications. It requires several characteristics.

1. Drop down functionality. Options I have investigated:

A) Menu views. Will allow immediate attachment of an item count badge via menu badges module. Would require addition of custom drop down javascript in theme and one additional module compared to option B.

B) Quick tabs accordion. Don't set a default tab and it behaves exactly like a drop down menu toggle. No additional modules or javascript necessary.

2. A badge that counts the # of unread items in the views list attaches it to the link that activates the drop down. Menu badge provides this for option A and link badge(required by menu badge so it's installation is a given) MAY provide this for option B but I don't know how to go about doing so.

3. Removing/resetting the badge after the drop down is viewed. Rules link may be the solution to this by marking the messages in the list as read + some css that hides the badge after click until it can be updated on next page load. May be possible to use views auto refresh module to do this through ajax, but it seems like this single feature would be a little too module heavy at that point.

I want to achieve this in the most lightweight manner possible, but I'm unsure how to proceed.

Re-written for clarification.

Your question consist of (at least) 3 questions. You should really split them in separate ones. Read on for an answer to your bullet "3." ...

Have a look at my answer to "How to allow users to manage their own Message Stack messages?", which IMO is pretty close to the question here. It can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user'.
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module).

Bonus: by using the suggestion as in item "5.", you probably also solved your bullet "2." (combined with "A.")

Note: no custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).


Views: Link Title using Text URL field (GUID) I've created a feed within aggretator that I am displaying using views. I have a title field and a separate GUID field, which contains the link to each specific item's audio podcast. However, when I opt to display the Title as a link, it simply links to the RSS feed's URL. I would like to make it link to the GUID field, which contains that title's audio URL.

How can I use one field in Views to serve as the link of another field?

Assuming that you know the link and can construct it from the GUID field (either by some/text/[guid_field_machine_name]/maybe/more/text or just [guid_field_machine_name] or what have you):

Using the dropdown arrow to the right of the Fields section of your view, select "Rearrange"
Move the GUID field above your title field and save
Make sure your title field no longer has the link box checked off, because we're going to use a different link box.
Click on the title field to pull up the settings where you unchecked the link box. This time, select the Rewrite options.
Select the link option under the rewrite options. This will show you a text box where you can use fields that appear above the title field in your rearranged list of fields in a link to add to the title field. In this box you should put your GUID url, using [guid_field_machine_name] for the GUID field.

If you have questions, let me know, I can definitely provide more specific directions with a bit more information from you, like what exactly the GUID field contains and stuff.


Sending emails on a specified interval, based on a date field So I'm trying to create a schedule that will send an email to a user on a few dates - on their birthday (in the system), and on whatever registration dates they have for a program (NOT their user registration - this is a separate date field).

So there will be between 2 and 11 date fields per person.

I would like to send an email on a certain interval - say, on their birthday, or a year after one of their other registrations.

How would I go about this? Rules doesn't seem to have any specific "send based on date field value" condition. I'm seeing something about possibly running on drush cron and checking date fields individually, but wouldn't this get resource intensive with a high number of users with up to 11 fields?

How is this (I would think fairly normal) use case usually dealt with?

I've built a similar feature for the Commerce Recurring module, but instead of sending mails, it creates orders. Here's how I did it.

Interval field module would become handy so you can control how often the action happens (sending mails i.e.).

You could create your own cron event or just rely in the Drupal one, here's a the rule used for generating orders, yours would probably be simpler:

  $rule = rules_reaction_rule();
  $rule->label = t('Generate recurring orders on cron run');
  $rule->tags = array('Commerce recurring');
  $rule->active = TRUE;
  $rule
    ->event('commerce_recurring_cron')
    ->action('commerce_recurring_get_due_items', array(
      'number_items' => 5,
      'timestamp:select' => 'site:current-date',
      'provides' => array('commerce_recurring_entities', 'commerce_recurring_entity'),
    ));

  $actions = array(
    'commerce_recurring:select' => 'current-recurring-entity',
    'timestamp:select' => 'site:current-date',
  );

  $loop = rules_loop(array(
    'list:select' => 'commerce-recurring-entities',
    'item:var' => 'current_recurring_entity',
    'item:label' => t('Current recurring entity'),
  ))->action('commerce_recurring_provide_order_properties', array('commerce_recurring:select' => 'current-recurring-entity'))
  ->action('commerce_recurring_generate_order_from_recurring', $actions);
  $rule->action($loop);

  $rules['commerce_recurring_cron_generate_orders'] = $rule;

The calculation of the due entities (commerce_recurring_get_due_items) is a rules action that calls this function, based in Entity Field Query to calculate those entities "due" to actions:

/**
 * Return recurring entities with due dates.
 */
function commerce_recurring_rules_get_due_items($number_items = 0, $due_date = NULL) {
  if (empty($due_date)) {
    $due_date = new DateObject();
    $due_date = $due_date->getTimestamp();
  }

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'commerce_recurring', '=');
  $query->propertyCondition('status', TRUE, '=');
  $query->propertyCondition('due_date', $due_date, '<');
  if ($number_items > 0) {
    $query->range(0, $number_items);
  }
  $result = $query->execute();

  $recurring_entities = array();
  if (!empty($result['commerce_recurring'])) {
    foreach($result['commerce_recurring'] as $recurring_entity) {
      $recurring_entities[] = entity_load_single('commerce_recurring', $recurring_entity->id);
    }
  }

  return array('commerce_recurring_entities' => $recurring_entities);
}


How to calculate field values in Views Calc? In Drupal 7, I have a custom content type containing distance (a decimal field) and time (a date field where only hours, minutes and seconds are entered).

In a view on that custom content type, I would like to show not only distance and time but also speed. (speed = distance / time)

I already tried to create a formula in views calc but:

I didn't find a way to get the hour, minute and second values separately from the date field. When I tried to define DATE_FORMAT (%field, '%i'), I got an error mentioning that i is not an allowed value.
I tried to work with the value of %field directly (because I found out that the field contains 101HHiiss as value) but I coulnd't define something like %field / 1000000 because then I would get an error mentioning that 00 is not an allowed value.

Edit: Sorry, I overread "Views Calc" before I wrote my answer. But maybe it helps you nevertheless.

Views maybe isn't the right place to add your custom code to. You might consider writing a very small custom module. Let Views then maybe display full nodes. And in your custom module you might hook into hook_node_view(), grab your node's fields, do the calculation and finally add the result as a new field to the the node's content, which then will get rendered automatically:

function MY_MODULE_node_view($node) {
    dpm($node); // start with that

    $time = $node->field_time[LANGUAGE_NONE][0]['value'];
    $distance = $node->field_distance[LANGUAGE_NONE][0]['value'];

    // do your calculations
    // ...

    $speed = $result;

    $node->content['speed'] = array(
        '#prefix' => '
',
        '#markup' => $speed,
        '#suffix' => '
'
    );
}

When developing your custom module you might find the Devel module quite helpful. After activating it you can easily check out what's inside a variable and then double click the displayed results for a deeper insight. So you might start by calling dpm($node) right inside hook_node_view().


Replace last item in a Views grid of images let's say I have 1000 image files on my server and I am paging the 10 newest (2 rows with 5 images each) on my frontpage in a views block, formatted as a 'grid'. The settings of my view are:

Format: Grid, Show: Fields, File: Rendered, and then filter by File: Type (= Image) and sort by File: Upload date

Instead of adding a "see more" link I would like to replace the 10th image with a "see more" button which has the same format as the images. Is there a way to only render a grid of 9 images and tell views which image to use as the 10th?

But is there no way to actually get it into the grid in html from the
  Views UI?

As I can see thare is no way for that in views UI.

But here are possible custom solutions:

Solution1

Add "more link" in PAGER section. Than specify link in 'Link
display' section under ADVANCED.
Style your link with css

Solution2
Add new views row in [hook_views_pre_render][1]

Solution3
Add new views row in custon views template


How to get Form API #states selected value onchange? When I'm using #states to set the visibility of a form field I'm checking an input element for its value. Is there then any way to grab the selected value the moment it's selected?

In the working sample below I'm displaying some markup when a select list's value != '_none'. It works good so far. But how do I get the markup to display the value I selected?

Background is: it's a node reference select list and I'm trying to maybe load some fields from the selected node as preview inside the markup. The moment I'm writing this I think it's a stupid idea. I'm in Ajax with #states, right? And there might be no way to call node_load() or anything the like, right?

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'MY_FORM') {

    $form['my_container'] = [
      '#type'   => 'container',
      '#states' => [
        'visible' => [
          ':input[name="my_field_name[und]"]' => ['!value' => '_none'],
        ],
      ],
    ];

    $form['my_container']['markup'] = [
      '#type'   => 'markup',
      '#markup' => /* selected value here */ ,
    ];
  }
}

Drupal #states is nothing more than the page containing JS data, and states.js reading them and adding necessary JS events to hide/show/etc fields. At the moment, there is no #states based method to get the selected value.

Note that it's perfectly OK to add #states to elements that are passed through Ajax. The beauty is that, whenever something containing #states is rendered, Drupal pipes these JS data along with the Ajax response. Since behaviours are run everytime after an Ajax response, states.js can update its visibility rules even for Ajax-changed elements.

I think your solution would be to use #ajax to do this. Your [#ajax]['callback'] will contain just-selected values in $form_state['input'], so you can use them.


Checkbox list for content type in drupal 7 How do you add Content type checkbox list in Drupal 7?

I have content type "Exporter". When I edit an exporter I would like to have a list of regions that exporter is part of. In Drupal 7 how do I add a radio button field that list all regions in the exporter content type.

In Drupal 6 I had to use CCK, but I thought this was supported natively in Drupal 7?

You're right...the CCK module has now been incorporated natively into Drupal 7, so you would use that.

Just visit http://mysite.com/admin/structure/types/manage/CONTENT_TYPE/fields to add the fields to your content type in pretty much exactly the same way you did using CCK in Drupal 6.

EDIT

Sorry I understand your problem now, the node reference and user reference modules aren't part of the default field system in Drupal 7; you just need to download and install the References module and then you'll have the "Node Reference" option in your field type drop-down like you're used to seeing.


Two sites, same codebase mystery Ubunutu Server, two Drupal sites. One dev and one live. Both domain names take you to the same code and database, the ones correct for the live site.
Checked apache virtual host files. Both the dev and live sites are pointing to different directories where they should go, one to the live code, and one to dev.

What setting, and where, could make the dev site point to the live one, instead of where apache's virtual host file says it's pointing?

*I should add, this occurred after a server upgrade.

The answer to this was that the dev site was being redirected to the live site, where the "https" was then crossed out, but the domain name remains, confusingly, the same.


Synchronizing Database Configuration Across Environments I am the sole developer on a Drupal 7 site, and I need advice. I use Git, having a 'master' branch (the published version of the site) and a 'dev' branch (the experimental features for future versions of the site).

Using Capistrano for deployment, I've gotten it fairly easy to deploy the two branches to their respective URLs, but I'm up against this wall where I'm not sure how to merge the 'dev' branch database into the 'master' branch after the new features are ready for production.

With a lot of Drupal's structure stored in the database, like Content Types and Views, what solutions are there for merging database changes from the 'dev' branch's url to the 'master' branch's url? So far, I've been writing down the changes I make and then recreating them on the production site before I merge the dev branch back into the master branch.

You cannot reliably 'merge' database copies. One way or another, everything has to be managed through code.

In Drupal 8 this is handled with the Configuration Initiative, but in D6 and D7 you have to use a tool like the Features module, which provides an interface to create 'features' (which are really exportable content stored in specific modules). You can export things like site configuration, content types, views, etc. into a feature, then push the code from one branch to another, and have that feature's changes "apply" on to the new database.

The Features module has its share of problems, but it does work fairly well for the most part, and is the go-to solution for managing database changes.

In addition to Features, you'll likely also want Strongarm, which lets you use Features to export data from the variables database table.

Alternatively, many people use update hooks to handle their database changes; that's a bit more involved and requires a strong understanding of Drupal development.

You may also want to read through these resources:

Staging Drupal
Drupal Configuration Management With Features


Use body field for views nivo slider instead of title field I'm implementing a Views Nivo Slider on a Drupal site.  It's currently taking the title field for the caption and using the whole text as a link.  How can I configure it to use the body field for the caption so I can just have specific words for links instead of the entire field?

When you set up the view, you can click on the Row Style options (the little gear thingy :) and then it will give you three options, Image Field, Title Field, and Link Field.  The Title Field is the Caption and you can put any field that you've selected in your view (in Fields) you want for it. So, if you've selected Node Body as a field, you should be able to select it there.  But, just as using the Node Title, it will put in the whole body (or at least what part will fit I'd imagine) in the caption.  If you want something else, you may want to consider yet another field in your content type, or some sort of views rewriting of the field.


Webform Protected Downloads I am trying to figure out how to use this module.

I've downloaded it, installed it, etc. However, when I try to set up a webform, I'm not seeing anywhere where I can upload files and redirect to a link programmatically.

Where do I set this up?

I found this online, but I don't see "protected" anywhere.

  Configurations on my site:

  Installed the modules (Webform Protected Downloads, Private Upload)
  Changed 'Default Upload Privacy Setting:' to 'Public' under 'admin/settings/private_upload'
  Created a Webform > attached a file
  Under 'File attachments' selected 'Public'
  Enabled 'Protected' under 'Protected Downloads'.
  Enabled 'view uploaded files' permission for anonymous users under 'admin/user/permissions'

The D6 version of the module doesn't support filefield. You must use the drupal upload module. On the node edit form: Attach a file, set it to private. Switch to the tab "Protected downloads" and specify your settings there.
If you don't see the tab "Protected downloads" then it might be a bug. Consider opening an issue for this on the issue queue for the module on drupal.org.


$form_state->setErrorByName() for a form in a block doesn't work properly I created a very simple module 'testform'. In this module, I generate a form and a block. (via the drush console)

The form contains a textfield ("housename") and a submit button.

In the form Class, I add a condition in the validate handler for display an error when the user submit the form without any data in the textfield.

The form from the form page (no problem)

I load the form page (url path found in the testform.routing.yml)
I click to the submit button without enter any data in the housename textfield
The next page load, the empty housename field is red and there is an error message "the housename field is empty"
=> By this way, all is ok

The form from the block (there is the problem)

I load a page where is displayed the form block
In the block, I click to the sumbit button without enter any data in the textfield
The next page load, the empty housename field is red and there isn't any error message

If I reload the page, the setError message appears

I don't understand why when the form is displayed in a block, the error message doesn't work properly.

This is the code I am using.

The modules/custom/testform/src/Form/DefaultForm.php file

<?php

namespace Drupal\testform\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class DefaultForm.
 *
 * @package Drupal\testform\Form
 */
class DefaultForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'default_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['housename'] = [
      '#type' => 'textfield',
      '#title' => $this->t('housename'),
      '#maxlength' => 64,
      '#size' => 64,
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $housename = $form_state->getValue('housename');
    if(empty($housename)){
      $form_state->setErrorByName("housename","The housename field is empty");
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    ksm("Work...");

  }

}

The modules/custom/testform/src/Plugin/Block/DefaultBlock.php file

<?php

namespace Drupal\testform\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\testform\Form\DefaultForm');

  }

}

This is a known bug. You can see the same problem with the core user login block upon submitting bad credentials. The comments in that issue note that it's a side effect of another issue which has a fix committed to the 8.2.x branch.


Dependency injection for FormElement #process callback Is there any way to inject container services into FormElement callbacks like '#process'? Or do I need to call \Drupal::container()->get(..)?

I noticed https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form, but this is for forms, not for form element types.

Dependency injection for any method of a class is done for the whole class. So if you have a dependency for the method you're adding for any method in the class, you will set that as a dependency for the whole class, not just a single function. However, #process callbacks are static functions, and static functions cannot use dependency injection. They should use the \Drupal::service() method, which is for static functions and procedural code.


Migrate users datas to the profile module I’m able to migrate users datas from a csv file with migrate, migrate_tools, migrate_source_csv and drush

Now, i’m trying to import datas from the same csv file to the Profile module (which provides configurable user profiles).

Here is my configuration file for user import. Obviously, i I add the profile fields in it (here field_profile_last_name, it doesn’t work).

id: user_migrate
migration_tags: null
migration_group: null
label: 'User migration from CSV'
source:
  plugin: csv
  path: /path-to-csv/users.csv
  header_row_count: 1
  keys:
    - weblogin
process:
  # user fields with custom fields : works !
  name: weblogin
  mail: email
  roles: roles
  field_last_name: nom_salarie
  field_first_name: prenom_salarie
  field_password_web_services: weblogin
  status: status
  field_profile_address: adresse1
  field_code: code
  field_date_de_naissance: date_naissance
  field_numero_societe: numsoc
  field_profile_function: qualification
  # profile fields : doesn't work
  field_profile_last_name: nom_salarie
destination:
  plugin: 'entity:user'
migration_dependencies:
  required: {  }
  optional: {  }

How can i migrate datas to the profile module ? What is the entity for this module.

I post an answer to my question. Feel free to comment or edit my answer in order to improve.

I’ve migrated users datas from a csv file. If you need help to do this, you can follow instructions in this questions :
Import users into Drupal with data from a CSV file

Now, i import the profile data in a migration process that maintains the relationships between source and destination identifiers in map table.

So the profile is related to the correct uid.

More information on this here (Process plugin: migration_lookup):

https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/process-plugin-migration_lookup-formerly-migration

The configuration file looks like this. You have to adapt some values as :

uid:
     source: xxx

This takes the value of the xxx property in the source data, and looks it up in the map table associated with the users migration, returning the resulting user ID and assigning it to the destination uid property.

You have to adapt the fields of course and the key to your needs.

id: profile_migrate
migration_tags: null
migration_group: null
label: 'Profile migration from CSV'
source:
  plugin: csv
  path: /path/to/csv/users.csv
  header_row_count: 1
  keys:
    - weblogin
destination:
  plugin: entity:profile
process:
   type:
    plugin: default_value
    default_value: 'profile'
   uid:
     plugin: migration_lookup
     no_stub: true
     # previous user migration
     migration: user_migrate
     # property in the source data
     source: weblogin
   field_profile_last_name:
     plugin: get
     source: nom_salarie
   field_profile_first_name: prenom_salarie
   field_profile_address: adresse1
   field_date_de_naissance: date_naissance
   field_code: code
   field_numero_societe: numsoc
   field_profile_function: qualification
migration_dependencies:
  required: {  }
  optional: {  }


Can I use views_bulk_operations with the D7 core toolbar module? I'm building a site right now where I'd prefer to use views_bulk_operations to administer the standard content overview (admin/content) and user overview pages (admin/people). My trouble is that I also want to use the toolbar module (or something like it) to give my site admins the ability to easily browse to the pages generated by views_bulk_operations (admin/content2 and admin/people2). It doesn't seem possible right now.

Any ideas? Or, perhaps, any alternatives to the core toolbar module? Thanks!

I figured out how I want to do it: http://drupal.org/project/quickbar

The Quickbar module allows me to provide an administration bar at the top of the page, much like the default toolbar, but I get to define what menu is placed in that bar. It will allow me to keep the content admins away from the default content admin pages by simply not providing a link to it.


"SELECT DISTINCT node.nid AS nid" killing MySQL performance? My database server's CPU has been pegged for the last two hours and the site is down as a result. Looking at the process list, I see dozens of queries that all begin "SELECT DISTINCT node.nid AS nid," and from my reading, it appears that this should not be a common occurrence  because these queries are very expensive and this could be the source of my problems.

Is it safe to say there is a view or module making a query incorrectly and if so, how can I can track that query down?

from what I see, you may be running views, and complex views, that perform complex queries. execute() is a database abstraction layer function. I am deducing that you are using views from the image you sent, which lists queries that look like generated by the views module.

Luckily, if my supposition is correct, then your problem can be lifted. When editing the view, you can enable caching. Unless you have a constant flow of new view items, you can make caching time 10, 30, or even 60 minutes. Or more. Making these expensive queries cached will lift the overhead. Also, if you are using panels, you can cache panel panes as well, or whole pages for anonymous users, keeping in mind, that caching on the larger level (page vs a single view) is more preferable.


How to embed a quicktab instance in a page? How do I can embed a qiucktab instance in page? I'm not going to create a region and assign the quicktab into that region. is there anyway to do such thing without using region?

After creating the quicktabs, you can render the quicktab programatically from the template file of that page.

Please put the below code inside your template file:

  $quicktabs = quicktabs_build_quicktabs('myquicktab');
  print render($quicktabs);


Page not found when I try to access my custom module I create a custom module in Drupal 8. It install/uninstall smoothly. But when I try to access that module then I'm getting that message

"Page Not Found." -
Failed to load resource: the server responded with a status of 404 (Not Found)

For debuging I made these entries in my setting.php file.

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$conf['error_level'] = 2;

But getting no luck. Is there any other ways to debug my code in drupal 8.

Here is my routing file code:

custom_module.admin:
  path: '/admin/custom_module'
  defaults:
    _controller: '\Drupal\custom_module\CustomModuleController::custInformation'
    _title: 'Custom Module Title'
  requirements:
    _permission: 'access information'

custom_module.site_page:
  path: '/custom_module'
  defaults:
    _title: 'Custom Module Title'
    _controller: '\Drupal\custom_module\CustomModuleController::custInformation'
  requirements:
    _permission: 'access information'

and link.menu.yml file code:

custom_module.admin:
  title: 'Custom Module Title'
  parent: system.admin
  description: 'Brief description.'
  route_name: custom_module.admin
custom_module.site_page:
  title: 'Custom Module Title'
  route_name: custom_module.site_page
  menu_name: footer
  enabled: 0

& controller file

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for contact routes.
 */
class CustomModuleController extends ControllerBase {

  /**
   * Render a list of entries in the database.
   */
  public function custInformation() {
    $header = array('Name');
        $rows[] = array("John");
    $content['table_brief'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => t('No entries available.'),
    );
    return $content;
  }
}

There are several reason for "Page not found." I'm sharing the some points may be helpful to someone who face same issue.

Check your php log file. if there is some php error in your code, it also cause page not found. It occur in my case.

Check PHP file location, which you mention in routing file. Sometimes php file location not correct.

Most important point, check yml file for indentation, if indentation is not proper it also cause "page not found" issue.

Check recent log message and try to sort out warning/error if any

@Kiran Tej, my issue has been resolved. In my case by mistake I placed the file directly inside the 'src' folder. Please read above points may be it helpful to you if your issue not resolved yet.


How do I delete all the user's posts, using drush? I frequently need to delete all comments/posts of a particular abusive user. It takes a hell of time to accomplish this with a browser. It would be great if someone could tell me how to do it using drush.

You could run something like this via drush php-script:

<?php
global $user;
$user = user_load(1);
$result = db_query("SELECT nid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE u.name = '%s'", 'alice');
while ($row = db_fetch_object($result)) {
  node_delete($row->nid);
}
?>

There's also http://drupal.org/project/user_delete.


Views: Show All Distinct Dates I have a custom content type with a date field that includes year, month, day, hour and minute. If I create a view of all the node start dates I get something like this

2014-10-23 13:00:00
2014-10-24 18:30:00
2014-10-24 21:00:00
2014-10-25 09:30:00
2014-10-25 10:00:00
2014-10-25 13:00:00
2014-10-25 18:30:00
2014-10-25 21:00:00

I want to create a view that lists only the unique days in ascending order. If possible I'd also like to rewrite these as links. Ideally I'm looking to generate something like

Thursday, October 23 2014
Friday, October 24 2014
Saturday, October 25 2014

or even better

Thursday, October 23 2014
Friday, October 24 2014
Saturday, October 25 2014

I've tried aggregating but I have to install extra modules to get the day granularity and even then I can't sort by date ASC. I've tried grouping but that just add extra headers I can't rewrite as links plus it means I still output a line for each node like this

Thursday, October 23 2014

Thursday, October 23 2014
Thursday, October 23 2014
Thursday, October 23 2014

Friday, October 24 2014

Friday, October 24 2014
Friday, October 24 2014

Saturday, October 25 2014

Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014

because the view is only using one field and if I hide it the view doesn't work. I've also used 'Distinct' and 'Pure Distinct' but they don't seem to do anything.

Is there something I'm misunderstanding? I don't get why this is so much trouble to do.

This video https://www.youtube.com/watch?v=Cp2SPiwA2Qg shows exactly wat you want. I ussualy follow these steps:

Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.


Ubercart import catalog I’m using drupal 7 with Ubercart version 7.x-3.8

I would like to now if there is a way to mass import different taxonomy vocabulary from a csv file.

Here is the module that you need to import taxonomy from csv https://www.drupal.org/project/taxonomy_csv


how to differ start date and end date in a table views in D7 i have a date field with start date and end date and configured like start=now and end date=+30days. both dates are displayed well in two columns in a table views seperately. now i want a third column to dispaly like end date-start date = 30days. how? any help please.

You can add a global php field where you have the end date available as a token, you can get the current time using now and then get the difference between the 2 dates in days.


How to resolve Catchable fatal error in entity.inc? Locally (WAMP) I have created a new GIT branch to install Drupal Commerce on my site. Everything went well and I have begun configuring my new shop. But when I decided to pull this branch into my remote test site, I get this error:

  Catchable fatal error: Argument 2 passed to SelectQuery::fields() must be of the type array, null given, called in /home/httpd/mysite/test.mysite.se/includes/entity.inc on line 317 and defined in /home/httpd/mysite/test.mysite.se/includes/database/select.inc on line 1316

Since I can't reach my admin pages (white screen with error message) and Drush stopped working as well, I used MySQL from the command line to import the database on the remote test site. So now both the codebase and the database should be the same on the remote test site as I have locally. Instead I get the above error. Any ideas? I have a feeling that Rules is involved in this, but that's just a feeling.

I have now done everything from the beginning, with the same result. I have installed all the commerce modules and their dependencies (Entity api, Rules, Address field etcetera) in the suggested order. Everything works fine until I export a database dump and add & commit all changes to my new git branch. After pulling that branch and importing the database dump in my test site (or even locally), I get the message above.

I have managed to run cron, which gave me this message:

  User warning: Missing database columns for the exportable entity
  rules_config as defined by entity_exportable_schema_fields(). Update
  the according module and run update.php! i _entity_defaults_rebuild()
  (rad 872 av C:\wamp\www\sites\all\modules\entity\entity.module).

... allthough I am using the latest version of Rules and when I run the database update, the message is that there is no update pending.

I have also seen this warning:

  Warning: array_flip() expects parameter 1 to be array, null given i
  DrupalDefaultEntityController->buildQuery() (rad 308 av
  C:\wamp\www\includes\entity.inc).

Any hints on what I can do to get my site back on track?

In case anyone else has a similar problem, here is how I solved it. I began by using Drush to disable the commerce modules one after another (in the correct order) to detect which module caused the error. I got so far that in the end I had disabled all the commerce modules, plus Rules and Entity token. And still the same error message was showing (the first one in my question).

I suspected that I really needed to flush all cache, but I could not reach any page in the site, and still it was not enough to truncate all the cache tables in the db and to run Drush cc all. So what to do? I finally found a way to flush all caches with this snippet (https://www.drupal.org/docs/7/administering-drupal-7-site/clearing-or-rebuilding-drupals-cache) in a file named for example clear.php in the web root:

<?php
// Define static var.
define('DRUPAL_ROOT', getcwd());
// Include bootstrap.
include_once('./includes/bootstrap.inc');
// Initialize stuff.
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

After saving the above file in the web root, you can just navigate to it whith the browser. In my case I also had to comment out all the memcached rows in settings.php in order for this to work (I got a "Cannot redeclare ..." error message).

When I finally managed to flush all caches this way, the site began to work. I still don't know how I would have done this otherwise. And "Flush all caches" obviously does somehting more than what is accomplished by executing drush cc all + manually truncating all the cache tables in the database.

So if anyone else has a similar problem with white screens and error messages, first try to flush all caches with the method above. And if you use memcached, you will have to comment out everything that regards memchached in settings.php in order to do this.


Webform 'add element' and 'addpage' buttons do not appear I am new to Drupal. I have Drupal 8 and installed Webform 8.x-5.1 module.
I can create a new webform but 'add element' and 'add page' do not appear so I cannot add any elements to the form as I see on tutorials online.
Any ideas?

You need to go to admin/config/development/performance and clear the cache.
Add element and add page will appear.


Feeds doesn't import photos I imported products with the help of feeds via commerce product processor. All products data downloaded correctly except the product photo.

It downloaded from csv file, where there is a full direct path to the picture. At settings of acceptability to this field : photo: URI (field_product_photo:uri)

Import runs without mistakes, but there is no product photo in a product's description. Which is strange because the file is copied to sites/default/files/ it's saving the origin name, except saving in sites/default/files/images and changing the origin name to sku , as it should be by making this products list by hand-labour.

Can you tell me what am I doing wrong?

Thans for your reply. We've already solved the problem. It was bug in sql in file_managed. The total truncate of the table helped.


How to enable both passwords at registration AND email confirmation together? I know how to enable setting the password at registration, and I know also how to set email confirmation after registration. But I don't know how to enable both features to work together.

When I enable the former function, the ladder would stop works.

Is it possible to enable both functions using UI?

I have tried Login Toboggan module but it doesn't have this function, either.

All you need to use is the user registration password module

Let users register with a password on the registration form when
verification mail is required.
By default, users can create accounts directly on the registration
form, set their password and be immediately logged in, or they can
create their account, wait for a verification e-mail, and then create
their password. With this module, users are able to create their
account along with their password and simply activate their account
when receiving the verification email.


Attach jQuery behavior to AJAX loaded content I would like to add some jQuery behavior to a page using the FAPI #ajax behavior (a Commerce product reference add to cart form)

I used a custom module (Commerce Taxonomy Field Product Attribute) to replace the standard text output of the taxonomy term attribute by an image, and hide the radio button of the add to cart form via CSS (display: none). The goal is to let the user click on the image label to select his product's color or size.
See a screenshot without css, and with css

I added some custom jquery that adds a "hover" and "selected" class to the label (on mouse over and clicked event) in order to have a ui feedback via CSS - as the Commerce add to cart form uses radios element, there is no "hand" mouse pointer on hover, which can be quite disturbing for the UI.
--> It works fine the first time the page is loaded but doesn't get attached when a product is reloaded by ajax.

I have a JS file with

Drupal.behaviors.custom_danity_afficheur_produit_label_hover = {
  attach: function (context, settings) {
    //All the code that attaches the click / hover event functions using jQuery.once()
  }
}

I tried loading the JS file at different level :

in the template .tpl.php file
in the add to cart form alter hook in
a function callback on the add to cart form #post_render attribute

None of these work, the AJAX only works the first time it is loaded.

It's not the first time I try to add jQuery code to an ajax loaded content - I managed last time to modify the code and use FAPI Ajax to make it work - but here i don't know how to do it as the product attributes already have an Ajax behavior implemented by Commerce... and as far is i know, it's not possible to attach multiple ajax behavior to an element with Drupal FormAPI

Any help would be much much much much much appreciated :-)

Ok I managed to make it work.

Drupal did try to re-attach the behavior on my content after it was added by AJAX, but my selectors were starting from too "early" in my DOM - as such, when drupal.attachBehavior got called by the system, it couldn't find the right selector.

Example :
My DOM look like this :

        <input ... class="input1" />
        <input ... class="input2" />
        <input ... class="input3" />

My jQuery selector looked like this
    $('#product-add-to-cart .class1 input.input1").hover(...);

As I understand, FormAPI was replacing what was INSIDE #product-add-to-cart .class1, while the context passed to Drupal.attachBehavior only had part of this markup (the input elements..) : hence    $('#product-add-to-cart .class1 input.input1").hover(...); couldn't return anything in this context.

I replaced my jQuery $('#product-add-to-cart .class1 input.input1").hover(…); with
$('input.input1").hover(…); and it works like a charm.


Filter taxonomy term on content type I'm currently running Drupal 7 and have got some taxonomies setup.

I also have different content types which live under the same taxonomy terms but want to be able to filter a term by content type.

What's the best way to do this in Drupal 7? I've looked into the Views module which looks like it's the right way to go.

I've also looked at this article: http://www.braahm.be/posts/tuning-taxonomy-pages-page-manager-panels-views-and-custom-build-modes-drupal-7 and Filter by content type and shared taxonomy terms but they seem a bit over the top for what I want to achieve.

Cheers,

James

Views is the standard option for achieving your goal.  Check out this video series to learn more


Sending test mails locally I can't test sending emails with Drupal 7 on my local host. I have been searching for some solutions for more than 10 days but unfortunately the problem still exists.

Any help?

You can also use Maillog to test emails locally.

  Maillog provides an easy possibility to log all Mails for debugging
  purposes. It's possible to prevent the mails to being sent, so there
  is no need for an extra mail server to test the mail functionality of
  other modules or the drupal core. Additionally you can immediately
  display the mail through the devel dpm() facility.


How to override default favicon.ico? I would like to load my own, but Drupal seems to forcefully load it's own by default behind the scenes.

Turned out to be as simple as placing favicon.ico into the theme root folder (!)


XML Feed invalid in drupal 7 Am trying to create xml feed through views feed generation to get the node content values. I have mapped the fields and i am getting the feed also, but a single space while generating feed in front of the xml feed. i.e before tag "<?xml" I am getting one single space. So that my feed page it's showing white space in Firefox and I can find the space in chrome browser. Is there config issue will be there or any thing else? Can anyone give me solution for this?

I wrote a detailed description about this problem and a possible debugging solution here: https://drupal.org/node/1275042#comment-7814971

In my case, Views Slideshow was problematic, I just created a tiny patch for that:
https://drupal.org/node/2078689#comment-7815015

For convenience, I'm copying my post linked above:

  As merlinofchaos said, this really has nothing to do with Views. The
  "fix" in #6 is NOT actually a fix...

  In my case, I had two whitespaces in front of the <?xml tag, so the
  RSS feed started like this: "  <?xml". I never thought I will find the
  source of the problem with such an ugly solution, but this is quick
  and works - it's really dirty, so use it only on a local development
  copy, do NOT test it on a production site:
  https://drupal.org/node/175137#comment-1526410
  in includes/module.inc file, in the module_load_all() function, after the
  drupal_load('module', $module);, soyarma suggests you to put in the
  following line temporarily: print $module.'|'; This way you'll get a
  list of your modules in the beginning of the output separated by the
  pipe (|) character. When there are unnecessary whitespaces before the
  module's name and the pipe character, then you just found the buggy
  module.

  For example, in my case, Views Slideshow was the source of the problem:
  views_bulk_operations|views_content|  views_slideshow|views_slideshow_cycle (this is just the end of the huge list)

  As you can see, there are two spaces before views_slideshow. This is
  where I should start searching for the source of the problem. I found
  it in views_slideshow/theme/views_slideshow.theme.inc: the code starts
  with two whitespaces, and the PHP block is just after that: "  <?php"
  You can also see it here:
  http://drupalcode.org/project/views_slideshow.git/blob/d9fd60c20add43a7b...

  And YESSS, after deleting the two spaces, http://validator.w3.org/
  congratulated me that my RSS feed is valid. Thank you, soyarma!

  Don't forget to revert the changes in module.inc (don't ever hurt the
  core's code! :) ), and delete the print $module.'|'; line.

  I'll report an issue to the Views Slideshow's queue, and I hope that
  this helped someone.

  ====
  EDIT:
  I reported the bug to the issue queue, and also created a patch, see #2078689: Unnecessary two whitespaces before the PHP code
  block in views_slideshow.theme.inc, which can cause RSS feeds to get
  invalid.


How to create many workbench moderation flows / scenarios I want to manage many content types with the workbench moderation module. Every content type should have its own states and transitions. I tried Workbench Moderation Profile module, but it has many bugs (it's in alpha) that causes many problems for me so I'm looking for any alternatives.

I don't mind developing a custom module, but I don't know how this could be achieved. Are there other solutions here?

I think what you need is Workbench Moderation Types


Feeds : creating a node dependencies at importation The Excel file I'm trying to import is comprised of two part, the first three columns describe a node that might or might not exist currently, and the three last columns are my entity informations. To date I've created a Feeds plugin to provide a custom processor for my entity and I've explored Rules.

What I'd like is to import the three last column into a entity and before saving it, check if a node with the existing account number exists. If it doesn't, create one with the three first columns. After that, I'd store the nid into the entity as a foreign key (my entity has a n-to-1 relationship with the node).

I've tried to use Rules "Before saving an entity" event, but I can't access unmapped columns this way. I've tried adding mapping to non-existing properties of the entity thinking they would be set and simply forgotten once the entity goes out of scope, but I instead get an unknown property error at importation. I've even tried to override the setTargetElement function in my processor, but the error still occurs. It seems to me I've got little choice but to store the unwanted data in the table and duplicate it in the node afterward (exactly what I'm trying to avoid).

Does someone have either a way to create these non-persisted property, have a better way to create and store a node relationship in an entity (Entity reference maybe) or even another solution6

Thanks

I have done something similar with importing images. If the image exists in the files table I just add the fid, and if it does not yet exist I create it.

I created a custom module and implemented hook_feeds_processor_targets_alter, and hook_feeds_dimension_set_target

Aside from that I don't know of an answer that does not require a bit of coding.


Only show view tab for current user profile I created a HTML table view to show the current "listings" the user has created. I have everything set up (I think), but I am looking in how I can restrict access. The view is suppose to be a tab on the user profile page with the title of "My Listings". I need to only show it to the profile owner and also make it so people can't access it via URL itself (bypassing the tab)

I remember this was doable back in the Drupal 6 days, but my memory fails me.

Path: /user/%/listings (contextual filter % is set to UID)

So if user 1 goes to /user/1/listings They should see a tab next to View | Edit that says "My Listings"

But if user 4 goes to /user/2/listings they shouldn't see the "My Listing" tab. But if they go to /user/4 they should see their "my listings" tab.

Thanks for the help.

set your view path to:

user/%/listings

Add a contextual filter of: author uid, and set 'WHEN THE FILTER VALUE IS NOT IN THE URL' to User ID from logged in user.

Add a menu 'Menu Tab'.

For access you have various options. Here is a simple one.

Install Views PHP and set access to PHP, then add this bit of code in there:

global $user;
return $user->uid == arg(1);


Webform tokens - token to return the 'option value' not 'option text' I am trying to pass the value of fields from one wizard page to another page . I can use the [Webform_submission:values:element_key] to pass most values. However on the select list I want the 'option value' not the 'option text'.
Example using the twig
  Example:
   '#options':
     10: Ten
     20: Twenty
     30: Thirty
     40: Forty
     50: Fifty

if the second item is selected I want the value "20" not "Twenty"

Is there a token that will give me the other value?

You need to suffix your token with :raw.

@see https://www.drupal.org/project/webform/issues/2990260


Entity reference - which side of the relationship is it best to put the field in? I an adding entity references to an existing site with a lot of data, and I want to make sure I get it right first time. My question is - is it best practice to put an entity reference in the container content type, or in the contained content type? In other words, is it best practice for the entity reference to be in the album content type, or the track content type (also applies to team/team member, book/chapter or whatever)?

In an ideal world these relationships would be in both content types, but that doesn't seem to be built-in and the relevant module (Corresponding Entity Reference) seems to be in Alpha.  So what is best-practice?

Where you definitely have a 'container' vs 'contained' relationship, I would say the best way to go is to put the reference field on the contained field.  If you put the reference field on the container then every time you make a new item to be contained you have to edit the container as well.

Frequently I find that 'containers' end up with many more child objects than were originally intended, putting the reference field on the child object helps keep it manageable.

Also, when you are rendering the content or using it in views, you can use the reverse relationship.  So if you have books with many pages and each page references the book it belongs to, you could have a view that is based on books but also contains information about the pages.  And yes, that is using CER, so far for me it works quite well.


I want to override theme node.tpl.php file with node--[content-type].tpl.php in my custom module I am making a new custom module. and i have 1 content type called city management(city-management).
I want to override theme node.tpl.php file with node--city-management.tpl.php in my custom module.

Is it possible?

This can be done by providing Drupal with a content type template suggestion through hook_theme. It uses the same 'node--contentname' formalism you are used to in theme templates. This method is IMHO preferred if your module also creates the content type you're theming.


Linked images from the Media module in WYSIWYG having A tags stripped when rendered to template I am using the WYSIWYG module to load TinyMCE 4.x, I am then uploading an image via the Media button in the toolbar of TinyMCE finally I am using LinkIt to link the image to a location.

All of this is fine inside the WYSIWYG editor, but once it is published and viewed on the page the wrapping  tag is stripped.

So in the editor if I view the source I see:

    [[{"fid":"7","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"","field_file_image_title_text[und][0][value]":""},"type":"media","link_text":null,"attributes":{"height":376,"width":640,"class":"media-element file-default"}}]]

However once this is rendered to the template I see simply:

If I then edit this piece of content again and view the source of the WYSIWYG editor the  tag is definitely still wrapped around the Media module's little string of JSON.

In a bid to prevent this from happening I changed the Wysiwyg Profiles and Text Profiles so that they don't remove broken tags or attempt to clean up an HTML or introduce any of their own HTML. Unfortunately this has had no effect.

Is there some way that Media/Drupal/WYSIWYG/LinkIt can be setup so that it will allow images to be linked? I have been unable to find a relevant issue or patch floating about out there on the web either.

I posted this as an issue on the media_wysiwyg module bug tracker over at https://www.drupal.org/node/2357993 and have been working my way through it since. Here is the best result I have managed to achieve so far copied from my responses to that issue.

This issue is mostly caused by the file_entity module. To work round this I have restricted the view modes available to media_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

I have then created an override template for the file entity called file--image--wysiwyg.tpl.php (see https://www.drupal.org/node/1793548) and I have the following code in it:

<?php

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

This has now removed all the annoying links, headers and wrapping <div>s from the output EXCEPT for the media_wysiwyg wrapping  mentioned in comment #4.

As this is just one wrapping <div> and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping <div>.


Symbolic Code for Delete I know about using LANGUAGE_NONE instead of 'und' for an undefined language.  Is there also a symbolic variable for a 'Delete' operation?  In my hook_node_validate, I look at the value of $node->op, which is the operation.  I test it for the value of 'Delete', if the content is being deleted.

Should I be using something other than the string 'Delete'?  I looked in bootstrap.inc, but didn't find anything there.

There's no symbolic code/constant for 'Delete', no.

The button containing that text gets set in the main node_form() function though:

$form['actions']['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#weight' => 15,
  '#submit' => array('node_form_delete_submit'),
);

and making the assumption that no other module is changing the #value of that variable by way of a form alter, you'll be safe checking the clicked button text by wrapping the same string in t():

if ($node->op == t('Delete')) {
  // ...
}


Not show node count view in drupal 7 I have installed node count view module and configured it.

But it's not showing me anything anywhere in my site. And I am not getting the setting of node count view.

Any suggestions about where I can see the 'node counts'?

Visit admin/config/system/statistics and enable the following settings.

These are the standard options I use for showing the node count. They some to work well in my case.


How do I disable the subject? In Drupal 8 I visited admin/structure/comment/manage/comment/form-display and disabled the subject.

1- The subject field is gone, but the subject label for comments is still shown. Is there any option to hide that, or should I change the theme?

2- It looks like there used to be an Allow comment title setting for each content type. Has it been removed in Drupal 8, or is it just me who cannot find it?

3- How can I avoid an empty comment title is automatically filled with the first words taken from the comment?

I find the Automatic Entity Label module to do that.
After making a backup of your Drupal database and folders, require it with composer and enable it.
Now you will see a new 'Automatic label' tab in the comment type management, and by clicking 'Automatically generate the label and hide the label field' you will be able to use tokens to auto fill it.


Add a table class name to a View table Can I add a custom table class name to a View that outputs a table, Or just add the name of the view to the table class name? There isn't a setting in Views to add a table class name, you can only add row class names.

My View name is view-a1. I would like to the name of the View to all table class names.I am trying to do it with hook_preprocess_views_view_table. But I don't know how.

The default twig template uses this markup

The method in the url below worked, it will add a custom hardcoded table class name. I changed the hook in the example to hook_preprocess_views_view_table. What I really want to do it add the name of the View as the table class name. How can I do that?

https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

Views have the CSS class option under Advanced (third column). There you can set the class to be output to all displays of that Views or override for single Displays.

Most themes won't output that class directly on the <table> element, it is usually output on a <div> that contains the table.

That can be enough for styling in CSS, but if you want you can override the twig template or use the preprocess function in your theme for more control.