How do i create nested tabs in drupal 7 view?

You could use Quick Tabs Module along with Views Module to achieve this result.

A simple overview to achieve this might be:

  Since Quicktabs uses blocks as tabs, If you create a views blocks for each
  single items of a content type and then add them to quick tabs
  manually.

Look through this http://mtt.desk.com/customer/portal/articles/992921-how-to-add-quick-tabs-with-multiple-view-blocks-inside-a-specific-page to get an idea.


Force existing users to complete profile after adding required fields

I fixed this with the Rules Module.

First, I set the necessary fields in the user profile as required. That fixes it for new users that want to register.

Then, a little more complex, I used the Rules module for the existing user, with the following setup:

Event: user has logged in
Actions:

page redirect (to user/[account:uid]/edit)
show a message on the site (to clarify why the user was sent here)

Conditions:

One OR group with the following conditions:
Data value is empty (with site:current-user:field-lastname)
Data value is empty (with site:current-user:field-firstname)
etc.

This works perfectly. The only minor point is that when I add a required field, I also have to add a condition to the OR group manually.


How to Remove read more link from front page

The problem is in the node rendering, not the page rendering. Its a lower/smaller level than the preprocess page. You can use node template overrides such as "node-fonts.tpl.php" where "fonts" is the name of the node type. You will copy "node.tpl.php" to make this then modify it to your liking. This template is found in "[SITE ROOT]/modules/node/". Copy this to your theme folder. When I do this I create a subfolder called "node" to help organize the theme overrides.

If you want an easier solution then I would use ConTemplate (otherwise known as Content Template). This will allow you to control this from the content type admin config (creates a template tab which has options for the teaser and the full node). This also provides details about the available variables and sample data from the last inserted node of the type you are looking at.


drupal 7 parent menu item will not hide for authenticated user

The easiest way with the least amount of programming would be do it with css:

body.logged-in .my-menu-name-or-css-class {
  display:none;
}

The most standards compliant way would be to use hook_menu_alter and unset the menu if $user->uid returns true: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7

However, in this case you're probably looking at maybe saving 10kb of bandwidth by unsetting the menu vs. just using CSS to hide it.


If you want your menu access by everyone set access callback TRUE(not need determine function and it pass TRUE,(maybe this is test and you want in future have condtional menu)).

function test_results_menu() {
  $items = array();
  $items['results'] = array(
     'title' => 'your title',
     'description' => 'menu description',
    'page callback' => 'display_test_results',
    'access callback' => TRUE,
  );
  return $items;
}

function display_test_results() {
  //  TODO Display results
   print "hi";
}

This will be work . please after any change in hook_menu clear your drupal cache.


Login Destination behaving differently on two instances of Drupal

See UPDATE above in main question for the solution.

FYI the problem was diagnosed by attempting to step-by-step trace through the Login Destination module, and then discovering that at one point I found myself in the trigger module code. PHPStorm for the win every time!


Generally speaking you can theme field output like other Drupal output. If you use devel_themer* you can normally see the template used and suggestions available. By default fields use theme('field') which by default has a number of suggestions:

// Add specific suggestions that can override the default implementation.
$variables['theme_hook_suggestions'] = array(
  'field__' . $element['#field_type'],
  'field__' . $element['#field_name'],
  'field__' . $element['#bundle'],
  'field__' . $element['#field_name'] . '__' . $element['#bundle'],
);

For example, the first suggestion allows you to override the template/function used for a particular type of field. In this case we could create MYTHEME_field__addressfield() and it would be used for addressfields only. You can add your own suggestions as well.

There are some field API routes as well though. You can use contrib or custom formatters (some of which in turn provide their own theme functions that you can override). Formatters can have settings that might give the results you want. You can add extra settings with a contrib module if you want to extend a formatter. There are also some field-specific hooks that might be useful:

hook_field_attach_view()
hook_field_attach_preprocess_alter()

* As you say devel_themer is heavy. It massively changes the markup, and often messes up your JS. I only ever switch it on when I need it and then switch if off immediately afterwards, YMMV!


I just came across the same issue, and although this is a rather old question I thought I'd give my solution in case any others find their way here.

Text formats have the option to correct 'faulty' HTML, although it's not the best choice if you'd still like to make sure that actual faulty HTML is corrected, you can turn this off by navigating to:

HOME > ADMINISTRATION > CONFIGURATION CONTENT AUTHORING > TEXT FORMATS > %your format%

Deselect 'Correct faulty and chopped off HTML' and Drupal will stop mangling section, article, figure, and other useful HTML5 tags.


Customize the display of error messages from the webform module

Message are not disabled on home page. Please check for $messages if it is properly rendered in page template file. If you are using a separate template for home page then check it specially.


Problem when downloading large files using Storage module

I would have preferred to put this into a comment, but I don't have enough rep points yet. :/

First, a few questions: What version of PHP are you using?  Does the same thing happen with small files?  Are you using symlinks?  Do your server logs show anything suspicious?

I am trying to fix a similar problem on one of my sites.  PHP 5.4 works fine, but 5.5 is choking when trying to interact with the file, which happens to be linked into a mounted filesystem.  They are on different versions of Ubuntu as well, so I am currently trying to figure out if it is a Linux kernel bug, a PHP bug, or a PEBKAC error.


User picture not showing, after moving from localhost to prodution

You might find that updating the permissions on your files folder is necessary. Depending on your server configuration you may need to run chmod -R 770 ~/public_html/sites/default/files (assuming the path to your files folder) or use 777 as your permissions string.

Beyond that, ensure that when you moved to production you deployed an entire copy of the site including all the files.


Pathauto for a multilingual site not generating alias for non-default languages

Aliases indeed disappear from nodes with non-default language after disabling language prefix in URLs. The solution to that is easy, but you have to do it in code, using Pathauto's hook_pathauto_alias_alter().

Basically all you need to do is:

function yourcustommodule_pathauto_alias_alter(&$alias, array &$context) {
  // Force all aliases to be saved as language neutral.
  $context['language'] = LANGUAGE_NONE;
}

This way you make sure that the language of the saved alias (not of node!) will always be und, meaning it will show for nodes of all languages.

Note: For existing aliases it is not enough to re-save the node. You have to delete the alias first and then have it recreated. Often the easiest is to do it in bulk via Pathauto's configuration interface. First delete all paths, then bulk-recreate them.

For more, see https://www.drupal.org/node/1234924


How can I load a view inpage using AJAX when a node is flagged?

This is actually a pretty common functionality and there is a module for it, Views Flag Refresh:

  Views Flag Refresh allows site administrators to configure which views are refreshed automatically via AJAX when certain flags are selected. This is useful when you have a view that filters by flagged content and you want the view to be refreshed automatically when content is flagged or unflagged elsewhere on the page.

If this doesn't fit your exact needs, there are lots of code snippets in the Flag Javascript API Documentation that might set you in the right direction.


When enabling Clean URLs, test passes, but ticking & updating fails

This has taken me a long time to resolve also. You need to set the relevant line in /sites/default/settings.php to

$GLOBALS['conf']['clean_url'] = 1;

Mine was set to zero. When I updated this, I realized that my server account didn't have permissions to change the settings.php file, and I suspect this is why it was not able to be updated by Drupal.

Hope this helps


Commerce functionality using Domain Access + i18n

The answer to your question: Can a Drupal Commerce catalog show different domain-aware products? is "yes." Mostly because Drupal Commerce simply uses content and Views to build catalogs, so if you can get Drupal to do something, Drupal Commerce is most likely along for the ride.

But I want to dig a little deeper to help you understand the problems you will uncover as you try to build something like this. Drupal Commerce 7 works on 2 levels (the version for Drupal 8 is much different):

1) Node level - Content with a title, a url, and published settings are best kept as nodes in Drupal 7. That suits Drupal Commerce well, since if you want to display a product, you must do it with a product reference field on a node. Most of the content related to specific products (a specific size/color/configuration) are actually injected fields. Injected fields get replaced automatically using ajax when an attribute field (size/color/configuration) is changed. This presents the biggest challenge for domain/translation.

2) Entity level - Lots of things in Commerce are simply implemented as custom entities. This includes products (not product displays), Orders, Line Items, etc. Products are the most likely to give you problems. For example, if you set a product display (node) to be certain domains, and products to be other domains, what do you expect to happen?

The Domain Access module is built to work with nodes exclusively. While some effort has been put into making a generic entity solution, it has many failings, most of which include a buggy and bloated data-entry interface. If I were to build such a thing, it would require a few patches to make it useable and understandable to the "store administrator."

For translation, you have a similar problem. You will need to decide whether you want to be able to translate certain fields (titles, description) or entire nodes/entities (a complete copy of the about us page, including attachments).

Most likely, you will want field-level translation. In that case, product pages that use product-level content (pictures or description that are a part of the attributes, like color/size/configuration) have a difficult problem to solve. The node would need to bring in a translated version of fields, and (optionally) bubble up product-level (read: entity-level, not node level) translated versions. If this sounds confusing, it's because it really is. We have multiple sources of content, all that would require some form of field-level translation.

The good news is, you can confirm this works in a matter of minutes with commerce_kickstart version 1 plus your domain and translation modules of choice. Note that field-level translation is supported by search_api, which means that your catalogs that should respond to domain and language, is possible and works without patches (this was not always the case).

The bad news is, while this is relatively easy to build as a demo, in practice, the resulting mess of products, translations, and page-level content becomes very hard to represent in a administrative interface in such a way that your average non-drupaler would know what's going on. For example, lets say you have a tshirt shop that sells shirts in two colors and two sizes. How do you describe to your store administrator that the color "red" is a taxonomy term that needs to be translated because it's connected to products which are connected to the page they are on? It's 3+ levels deep. Quite an abstract problem.

Your question isn't really suited for a "how to" because there many variations on your request that would completely change how I would set up the underlying information architecture. Something else you might consider adding to your architectural plan would be a comprehensive way to deal with multiple currencies in the face of domain/translation combinations.

// Edit: Here are some module recommendations:

I wouldn't use Domain Access if you are trying to control product visibility with domains. It's too messy. It's much easier to simply create a taxonomy term and then build a custom views condition that compares the taxonomy term with the actively requested domain. I have built one store where this was a take-away after months of development.
I recommend https://www.drupal.org/project/entity_translation for field level translation
You will still likely need https://www.drupal.org/project/i18n for menu and taxonomy (attribute) translation.
I highly recommed you tell your designer you need an interface that helps selecting a domain, a language, and a currency. Or some combination. At the end of the day, there isn't one easy way to do this, especially important to nail the mobile-responsiveness of your visual solution. (Drop-downs don't make as much sense on a phone).


Did you already look into dedicated modules for this? There is

Google AdSense integration and Simple AdSense. The first one is more advanced, the second is simpler, but less flexible.

For both, you just have to copy over some values, and the module will take carte of the rest.


Trying to get a "Is between" date filter to work... it is returning an offset by + 1 days.

The filter type must be "single filter",
operator must be "is between", as demonstrated in this screenshot:


There's an alpha version of Editable Fields for Drupal 7. The module:

  allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

It works for nodes, but not for blocks as far as I'm aware.

There's also the Aloha module:

  This module integrates the excellent HTML5 wysiwyg editor Aloha Editor (http://aloha-editor.org/) to Drupal. Both the module and the Aloha Editor library are under active development but still in the early stages.

But judging from the comments on the module page it might not be ready for use just yet. I did find an article with someone who claims to have got it working so that might be the place to start.


Unable to manually install the http_proxy module

Looking at the files for the 8.x-1-x branch, I noticed that those files are essentially the files for Drupal 7, not Drupal 8. Even the https://ftp.drupal.org/files/projects/http_proxy-8.x-1.0.tar.gz archive contains file for Drupal 7.

One of the differences between the versions for Drupal 7 and Drupal 8 is that for Drupal 8 the http_proxy.info file should be replaced from a http_proxy.info.yml file.
Since Drush uses the content of that file to understand if the directory contains a module, and to retrieve the information about that module, without any .info.yml file with the information about the http_proxy module Drush is not able to find it in the already downloaded modules. That is why it keeps saying it doesn't find it.

So, to answer your question: No, you don't need any particular trick to download and install modules on Drupal 8. It just happens the module has not been really ported to Drupal 8, and Drush gets confused.


When do I need a contextual filter vs. a relationship?

Just think of it terms of SQL:

a 'relationship' is a JOIN on another table
a 'filter' (contextual or not) is a WHERE clause.

'Contextual' just means the parameter comes from the current context, e.g. part of the URL, something in the session, etc


Yes and no.

user_load() leverages a per-request cache.  This is implemented as a static cache in the entity controller (see the DrupalDefaultEntityController class).  So, if the same user is loaded multiple times during the same request, the subsequent loads will come from the static cache.

In a base install, entities are not cached between requests.  But, fields attached to entities are cached in the cache_field bin.

Data for views may or may not be cached, depending on your global Views settings and overrides for a particular view.

If you have the Entity Cache module installed, then entities are cached between requests in whatever backend you have defined.  There are almost no reasons to not have this module installed on a site.  It provides huge performance improvements, especially with non-SQL cache backends.


Unable to send email. Contact the site administrator if the problem persists.

This error is due to email sending failed.

You can use SMTP Authentication Support module for sending email.

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

You can take the picture as reference for SMTP configuration.


Because of RFC2822 (Internet Message Format), section 2.1.1 (Line Length Limits):

  There are two limits that this standard places on the number of
     characters in a line. Each line of characters MUST be no more than
     998 characters, and SHOULD be no more than 78 characters, excluding
     the CRLF.

Why they chose 77 and not 78 for Drupal, I don't know, but I'd bet my house the decision was originally based on that standard.


Are user browser information and ip address available as tokens in Rules?

Use [current-user:ip-address] token for IP address of the current user.

For browser related token you have generate it using token_generate API.

  function token_generate use to generates replacement values for a list of tokens.


I think it must be a bug, since the computed module is in alpha for drupal 8 at the time of this writing. With the help of Matt, we were able to print a simple 'hello' message by manually creating a new node. This new node will have access to the new computed field. I was using the devel module to generate content for nodes, which for some reason did not have access to the computed field. So if you are experiencing the same problem, set up your computed field, and then manually create a node, or edit and resave a node your previously created manually. That worked for me.


More template suggestion for views exposed form

create exposed form filters template following this naming standard:
views-exposed-form--{view-name}--{display-name}.html.twig

to get the view-name you can get from Backoffice (Structure > Views > search for your view > then get machine name and repalce the underscore with dash - see image bellow)

so we get this template:
views-exposed-form--media-gallery.html.twig
put your static HTML(we will replace in next step) there and clear cache you'll find the new tempalte.
if you want to print the exposed fitlers just put {{form} in your tempalte

  views-exposed-form--media-gallery.html.twig

{{form}}
but if you want to print each exposed fitler serpately follow this steps :    (Structure > Views> search for your view > Edit > click on filter name under the FILTER CRITERIA > scroll down and copy Filter identifier input value > go back to the template and print your exposed filter one by one  {{ form.$fitler name }}

  views-exposed-form--media-gallery.html.twig

{#1.print 1st exposed fitler form element + label #}
{{ form.field_thematiques_target_id }}

{#2.print 2nd form element + label #}
{{ form.field_type_media_value }}

{#3.include all other form elment ex submit button but to prevent
duplication remove other one #}
{{ form|without('field_thematiques_target_id','field_type_media_value') }}


I'd suggest that you enable the Devel module on your drupal site (hopefully not a production version ;-).  Once you've enabled that module, you can use the dsm() function, within php tags in your templates to inspect in detail the variables that are provided in each template!

So enable the Devel module, then add the following to your template file:

<?php dsm($view->field['field_NAME']); ?>

Clear your cache and go to a page that contains a view... What the dsm() function should do is output your object in the 'Help' section of your page:

Just click on the object and start inspecting all the fields it has available.  You'll see that what it's returning with the 'field_alias' property is just the nid of that node...

Since you didn't specify what you're trying to get with the additional field, I can't be any more specific, but hopefully digging around will let you figure out how to get to the field property/properties you need.  Let us know if you figure it out!

p.s.  Since the 'title' field template is called for each row displayed in your view, you will get that 'field' object multiple times - once for each time the template was called.


User fields that are visible, but can't be manually edited

Between the hooks used from the field API, there is hook_field_access(), which allows to define which users has access to a field when the entity is being viewed, or when the entity is being edited.

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return user_access('edit field of interest', $account);
  }

  return TRUE;
}

There is also a module that uses that hook: Field Permissions.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes
  Role-based field permissions allowing different viewing patterned based on what access the user has
  Author-level permissions allow viewing and editing of fields based on who the entity owner is
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed
  Field permissions overview


got it myself
i create a facet block with price field and a search block of index type which will show the facet in every where the search page will shown .i restricted it for only front page .Then it works for me.


Odd problems with Drupal 8.7.7 and drupal/jsonapi 2.4.0

Composer is showing those error messages because you are updating to Drupal 8.7.7 and the JSON:API module is a requirement the composer.json file contains. (That is why the error message says locked at 2.4.0, required as ^2.4.)

Since the module is now part of Drupal core (as the project page and the release notes for version 8.x-2.4 say), updating to Drupal 8.7.7 would cause the module version to be updated to 8.7.7. (The version of every Drupal-core module is the Drupal version.) That is not allowed from the composer.json file which, with a restriction like ^2.4, just allows versions that aren't higher than 2.

Editing the composer.json file to accept any version of that module would avoid those error messages.
There would still be the problem of having two versions of the module installed in two different directories. I would rather uninstall the module before updating Drupal, but I am not sure how it would possible to preserve the module settings.


Extracting UID information from a URL and sending email to this user

You can solve your problem using Out of the box Webform Module.

  Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.

You can read uid value from URL .. Webform has support for tokens. You need to create a field to collect UID and configure default value.

For Example:
%get[key] - Tokens may be populated from the URL by creating URLs of the form http://example.com/my-form?foo=bar. Using the token %get[foo] would print "bar".

Your URL should be http://example.com/my-form?uid=value .. You will configure default value as %get[uid]
Webform has Email support out of the box.
You can see user submitted results in webform you created.
It automatically creates schema for you, and it has lot more features...


Creating custom node aliases inside a simpletest

It turns out that

$edit = array(
  'title' => 'asdf',
  'path[alias]' => 'qwerty',
);

was correct, but that I needed to add the permission 'create url aliases' to the drupalCreateUser array.


I think it would work if you create a view that displays users as rendered entities, not fields.

You can then tweak the way user entities are rendered and show all fields.


Dynamic view listing nodes in proximity dependent on taxonomy term in url - which is not attached to the node itself

This is a broad question and becomes difficult to answer clearly. There are too many things to do and too many details to resolve. It looks a bit like you are trying to eat an elephant with too many missing teeth. I agree that you will need to create a custom module and by the description you gave, you will need knowledge of php for server side (pre display) and Javascript for client side action (after display). The first thing to do is get do some exploring in the structure of Drupal and how it operates.  From my own experience I know that a couple months of exploration has made a tremendous difference in my ability to solve a problem like this. Do you have any programming experience? If not start with php basics. Then move on to Drupal.

There is an excellent video tutorial series at buildamodule.com.  It charges for some of its content, but it covers a lot of ground.  Building a module will require php/mysql expertise (book:Beginning PHP and SQL by W. Jason Gilmore), an understanding of Drupal operations (book: The Definitive Guide to Drupal 7 publisher:Apress) and a solid knowledge of the key modules (book: Drupal Building Blocks by Earl & Lynette Miles).

You'll know your ready when you find yourself looking forward to writing a custom module.


Why is my custom block template applying to all blocks?

As stated in Drupal 7 Template (Theme Hook) Suggestions, it suggests the file name structure to be like block--sidebar_first.tpl.php.

==EDITED==

In my themename.info file I declared

regions[sidebar_first] = First Sidebar

Copied the core block.tpl.php file, renamed it to block--sidebar_first.tpl.php, added "BLOCK NAKO" text.

Then I Flushed Caches. The image below is the result.

As you can see the footer region blocks doesn't have the override that I only set for blocks within the sidebar first region.


No idea what was causing this but clearing the browser and site caches seemed to have fixed this issue.

Thanks to all those that replied.


There might be a shortcut to this but I don't know it...

// Get the bundle settings.
$info = field_info_instance('node', 'field_name', 'content_type');

// Get the field render array
$build = field_view_field('node', $node, 'field_name', $info['display']['teaser']);

// And print it
print render($build);

Moving the display building logic to a preprocess function would probably be a good idea.


Can you use basic FAPI without drupal_build_form?

From https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7.x :

  This function should be used instead of drupal_build_form() when $form_state is not needed (i.e., when initially rendering the form) and is often used as a menu callback.

It still does a drupal_build_form under the hood, though, but at least you don't have to do it. Mind you, it may or may not work in your specific case, depending on where / how you create and call your form.


It depends on how the nodes are imported really. You should be able to use hook_modules_enabled which is the last hook invoked when a module is installed and enabled. You might need to tweak your module weight to make sure it's invoked after the import of the nodes.


Enable/open comments on all posts of a content type

Or directly into the database with :

UPDATE `node`
SET comment = 2
WHERE comment = 1

and

UPDATE `node_revision`
SET comment = 2
WHERE comment = 1

Where : Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write).


Is there a way to schedule Automatic Source Code and Database Backups?

You can use Backup and Migrate module. It is available for both, Drupal 6 and 7.

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.


It is because how you get them,contextual filter usually get from url and when you have 2 , you should have 2 parameter in url , as example  it should something like "mysite.com/3/reza",
this is one step, another step is that you  specified in your contextual filter that which arg is for this filter(put your default value in raw value form url,then you see path componet), (in my sample 3 is arg(0) and reza is arg(1) ) and if you  observe this note it work for you correctly.


How to alter sort handler to keep existing order intact in views

As I understand you want to be able to use a secondary sort after overriding the default sort by clicking on a column header.

This can be achieved from the front-end using jQuery plugin TableSorter as described here:
https://drupal.stackexchange.com/a/125188/22915

Note this won't work for views with pagination.

It can also be achieved with some custom PHP code. Add the following to a custom module and change the CAPITALIZED words accordingly.

/**
 * Implements hook_views_query_alter().
 */
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name === 'YOUR_VIEWS_NAME' && $view->current_display === 'YOUR_VIEWS_DISPLAY_NAME' && count($query->orderby) == 1) {
    $query->orderby[1] = array(
      'field' => 'YOUR_SECONDARY_SORT_FIELD',
      'direction' => 'ASC',
    );
  }
}

This code snippet will make sure that, no matter what column you use as main sorting, you always use a certain field as secondary sort. In your case this would be the Clinic/Hospital field (use system name in code).

Note: if the secondary sort field is not a sortable column, you can't use the query alias. So YOUR_SECONDARY_SORT_FIELD needs to be something like: 'field_data_field_name.field_name_value' instead of 'field_data_field_name_field_name_value'.


advise for managing and troubleshooting modules

Unchecking the module does not uninstall it, it is just disabled. The schema related to the module is only removed when it is first disabled and then uninstalled.

If disabling and then enabling can solved your issues then do it.

But disabling and then enabling a module would not do any thing harmful except to remove and then add its record in system table and would invoke few hooks like hook_menu, hook_theme etc.


Activate the following Übercart modules:

Shipping
Shipping Quotes
Flat rate

Go to http://yoursite.com/?q=admin/store/settings/quotes and click on "Add flat rate quote". Fill out the from and submit it. The next form should be the conditions form. Create the necessary condition(s), for example, 0 < order:order-total AND order:order-total < 100 as a data comparison. To enter the total values (i.e. float numbers) click on the "Switch to data selection" button near the bottom. Repeat this for all of your total ranges.


How does the internal entity cache work?

node_load_multiple() is using entity_load() and should not interfere with the rendering of your node because it only handles the loading from database, not rendering.

The node controller is the DefaultEntityController which implements a static cache, which (as of code) does not respect conditions used by loading. This might interfere. Are you using special conditions here? how does the $conditions array look like?

Are you using views to render that specific page? then it could be problem with contextual arguments and caching see: How to get Views caching working with contextual filters?


How to process a multiple values field (comma separated) in a Rules Action?

The rules action calls sms_send, whose first argument is:

  The destination number.

i.e. singular. So the module doesn't have support for sending to multiple, comma-separated numbers in one go through rules. It is in alpha to be fair, so it's not likely to be fully-featured yet.

Two ways you could get around this limitation (there are probably more):

Create a custom rules action which splits the incoming string by comma, then loops over and calls sms_send on each. If you choose this method, contributing the code back to the project would I'm sure be greatly appreciated.
Restructure your workflow so the existing rule is invoked once, in a loop, for each phone number.


This is an existing module which does part of what you want to do. The module is Menu item visibility. I recommend looking at how it works and extending it (it says it's extendable) to add the extra pieces you are requesting: visible per page, or visible on PHP code. It probably has hooks you can use to complete your business logic.

In fact, this issue talks about adding "per page" or "php code" conditions essentially.


How can I create template for specific page in module?

As I understood, you need something like this:

/**
 * Implements hook_menu().
 */
function doom_menu() {
  $items['doom'] = array(
    'page callback' => 'doom_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

/**
 * Implements hook_theme().
 */
function doom_theme() {
  // Get the path to this module and define theme dir.
  $module_path = drupal_get_path('module', 'doom');
  $theme_dir   = $module_path . '/theme';

  // Themable elements. This will look for "sample-template.tpl.php" file
  // in the "YOUR_MODULE_DIR/theme" folder. That file can be anything.
  return array(
    'sample-template' => array(
      'template' => 'sample-template',
      'variables' => array('content' => NULL),
      'path' => $theme_dir,
    ),
  );
}

/**
 * Menu callback.
 */
function doom_page_callback() {
  // Get your template and display ONLY the contents of that file.
  print theme('sample-template', array('content' => t('Optionally, pass dynamic content here.')));
}

And the sample-template.tpl.php file:

<div id="sample-template">
  <?php print $content; ?>
</div>

This should give you the idea. If you still want to theme the HTML header/footer from the front end theme, you should be able to create page--doom.tpl.php file there and customize what is displayed. In that case, just return the output instead of printing it in doom_page_callback().

Hope this helps.


How to add and delete a user to another group using the Group module?

Found the solution. When using the group module, there are methods which work well. I used a hook_group_membership_insert($group_membership):

function [my_module]_group_membership_insert($group_membership) {

   $grouptest = group_load($group_membership->gid);
   $grouptest->addMember($group_membership->uid);
}

The same exists for deleting a member, just use the following function:

$grouptest->removeMember($uid);


You need to get the data structure right, then everything will fall in place using Views.

Apart from city, cinema and movie content types, I'd suggest creating a session content type, too, which would link a movie with cinema, adding the time and hall number information. To maintain relationships between individual chunks of data, you want to use the CCK's node reference module (it is part of D7).

Roughly, you'd go with content types like so:

city (name)
cinema (name, city_ref, hall_count)
movie (name, description, picture, rating)
session (movie_ref, cinema_ref, hall_number, date_time)

It always depends on your requirements, but in this particular case I'd recommend using a separate content type for cinemas instead of taxonomy. Each cinema's node would serve information about the cinema, number of halls, and it would also reference the city it's located in and would be referenced by the screening nodes.

On the other hand if you have no other information about a city other than it's name, it should be safe to set it up as taxonomy.

To make it all work together, i.e. display listing pages, or allow users to search for movies and session times, you'll have to pick up the Views module.

Implementation of a "movie description and all it's showtimes" page would be the movie node page with a view attached (via Views Attach for D6 or EVA for D7) that would list show times for the movie passed as node ID from URL.

For the "cinema timetable with movie names and times", you'd do the same thing, but since you're displaying information about multiple movies, you would also use Views relationship (session -> movie_ref) to fetch in the movie nodes to be able to use their names as a views field.


Is there any rule when to use panels and when to use templates in drupal 7

Simple rule:

If you want to add some other blocks, content panes, or other information that is related but not included in content; you need to use Panels.
If you want to display the content in a custom way and all information you want to display is already included in content, then you don't need Panels, use a template.


A lot of the bootstrap process happens now implicitly as services are requested.

If nothing requests the database service then Drupal won't open the connection to it and so on.

The minimal amount of code to do a custom php file that bootstraps Drupal and does some queries can be seen in statistics.php:

$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$views = $container
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    $container->get('request_stack')->push(Request::createFromGlobals());
    $container->get('statistics.storage.node')->recordView($nid);
  }
}

Depending on what it is for, you could also do a normal controller and return a cacheable JsonResponse with the right cache tags and contexts, then Drupal will automatically cache that in the internal and dynamic page cache. Which, depending on your queries, might not be much or not at all slower.


How can I put form elements into a table and have a submit at the bottom?

You should use theme_table.
It will help you.
:)


How to turn a menu tree into an associative array?

You can load up the menu tree with MenuLinkTree::load, which will give you an array of menu links to work with. From there it's just a matter of looping through and getting what you need, e.g.

$tree = \Drupal::menuTree()->load('main', new \Drupal\Core\Menu\MenuTreeParameters());
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url_obj = $item->link->getUrlObject();
  $has_children = $item->hasChildren;
  // etc...
}

The link is a MenuLinkInterface, each item itself is a MenuLinkTreeElement.

It would be preferable to inject the menu.link_tree service if possible, rather than getting it from \Drupal.


This is the way i set the 'fullpage' view_mode of a node as default:

<?php
/**
 * Implements hook_entity_view_mode_alter().
 */
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // Set default view mode.
  if (isset($context['entity']->nid)) {
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'YOUR_CTYPE' && $view_mode == 'full') {
      $view_mode = 'fullpage';
    }
  }
}

It actually sets the view_mode to 'fullpage' when in full mode (default), but you could ommit that part (&& $view_mode == 'full').

Remember that 'fullpage' is the machine name of my view_mode and 'YOUR_CTYPE' is the machine name of your content type.

Not sure if this will work with Display suite though...


Is there an alternative for hook_views_ajax_data_alter in drupal 8?

Mybe you can try implementing an AjaxResponse Event Subscriber and alter the commands onResponse :
an example of this is here : https://www.linkedin.com/pulse/how-alter-ajax-commands-view-response-drupal-8-dalibor-stojakovic/


How do I create different user registration pages?

Basically you have to create only one registration page. And you have to create two roles.
Normal User and Merchant User
Add these roles field on user registration page using Auto Assign Role module.
Configure permissions for the respective role. Like Normal users can buy product and Merchant users can create product
If you are using Commerce Kickstart then you will have permission for adding product and other permissions.


Go to "Manage Display" tab in content type page. Hide label there


How can I display the content of user profile using the Views module?

Wow what a coincidence this question was posted for drupal 6 just this morning.

To list content owned by a user you can:

Create a View that lists content
Create a Block Display within that view
Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".
Place that block on the user profile page using some mechanism for Block placement, like the drupal core block system or the context or panels modules.


Remove `/node` from front page when using a template file (page--front.tpl.php)

I used Global Redirect and it seems to do the trick. I'll still accept someone else's answer if anyone can give any insight on what might of been the solution to my original issue.


How to create dynamic panel column content?

By "dynamic", do you mean "only that panel pane changes and the page doesn't reload"?

If so, check https://www.drupal.org/project/jquery_ajax_load and this tutorial http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding .

If you don't need that functionality, then enable the panel page that overrides /node/%node and put your fields in the left side and your menu in the right.


Validate and submit function for my fom aren't working

Add the following lines to your custom_form function:

$form['#validate'][] = 'custom_form_validate';
$form['#submit'][] = 'custom_form_submit';

Clear the cache afterwards and you will be good


How can I create a table in which columns and rows get added dynamically?

I forgot that famous tagline from a recent president, but in French I would sound something like "Mais oui, c'est possible" ...

The question here seems like a variation of something I recently ran into, related to processing log messages. One of the challenges with recent log messages (watchdog), is that there might be quite a few PHP notices, warnings, and errors that are filling up your logs. So a good practice is to identify / address these problems in your site (which will reduce the required resources for your site also and will result in a faster site).

However digesting these messages is quite a challenge. That's why I've come up with my own "custom" report, as illustrated in this screenprint:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (like severity, User name, etc). And the red numbers are hyperlinks to get a drill down report of the specific messages for which I want more details (= to display the actual watchdog entries).

Some more details about the above table:

Think of the columns (with headers starting with "Msg Type:...") as your "Task XX". While each row (= different message) is like your "User1", "User2", "User3".
If there wouldn't have been any errors with (say) "Msg Type: Ajax" or  "Msg Type: page not found", then the corresponding column wouldn't have been created.
Some columns (like "Msg Type: Error" or "Msg type: PHP") contain a value for multiple rows.

Refer to my answer to "How to gets analyts and generate visual reports from sessions?" for more details about creating reports (tabular displays) as in the above screenprint.

Just in case anybody wonders "How did you do that?" (without checking out my answer in the above link): There's a module for it ... it's called Forena ... And the clue in this specific case is to use Forena to create a "Crosstab table".

Bottomline: no need to re-invent the wheel ...

Disclosure: I'm a co-maintainer of the Forena module.


Which variable to set for programmatically making a field required?

Get the form_id of that form and write an alter function for it in your custom module.

function hook_form_form_id_alter() {
 $form['that_field_name'] = array(
   '#required' => TRUE,
    // add other features you want to add
 );
}

Follow the below link for more details:
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


How to display the average rating of a node as stars in a view?

This is what I came up with:

Create a Views template for this specific field and put it in your theme (or module if you have Views templates already there and enabled via the Views api hook).

In my case it was called views-view-field--top-content--page-1--value.tpl.php for just the included and now enabled top content View.

In there, do the following:

<?php
  $data = $row->{$field->field_alias};
  $path = drupal_get_path('module', 'fivestar');
  print theme('fivestar_static', array('rating' => $data, 'widget' => array('name' => 'basic', 'css' => $path . '/widgets/basic/basic.css')));
?>

And if all is well in the world of copy and paste, you should now have a View with basic stars displayed instead of the number.  If you don't like the basic stars, just look in the widgets directory and you can take your pick of any of the other styles there.


How does forum determine new replies for each user?

Drupal has a history table to record when any user viewed any node.

So it knows when you last viewed the node, and which comments have newer timestamps. So it marks those comments with newer timestamps as new or updated.

UPDATE: There is also a constant NODE_NEW_LIMIT set in the node.module file which defaults to 30 days ago. That means nodes changed before 30 days are always marked as read.


Here you can replace $sql with $result.

<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);

// Retrieve a 2-column result set as an associative array of field 0 => field 1.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is a perfectly valid method:
$result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>


Moving functions in block module to inc file

Like tenken said, use include_once at the top of the ".module" file like this:

<php
include_once drupal_get_path('module', 'module_name') . '/module_name.functions.inc';
?>


hook_query_alter, AJAX, views_get_view : have to submit twice

It was some kind of mess with the $_SESSION variable, which I used for independant reasons.

I corrected my code this way :

  if ($view->name == 'rechercher') {
    $view->query->add_table('field_data_field_cp');

// Old code
// $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' .
// $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');

// New code
    $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' . $view->exposed_data['field_commune_value'] . '%', 'LIKE');
  }

... and everything seems to be fine, AJAX and all.

Thanks to Clive for the help.


How to make a change that affect several site at once?

You should be able to do this by uploading the schedule to one site and then exposing an RSS feed for the other sites to pull it down.


You should use jQuery Update module. Here is a quote about it (from the module's project page):

Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
Updates:

Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD


I had a similar issue while using Feeds, Feeds XLS and Feeds Tamper. I solved it by copying the images in the path mentioned before importing using Feeds.

I am not sure but I think you should first run a script that copies the images onto the path mentioned in the Image field and then import nodes using Feeds.

For example, if your path to images is 'sites/default/files/myimages', you should first copy the images to 'myimages' folder and then run Feeds because Feeds/Feeds Tamper simply populate the file path AFAIK. These modules do not actually save the images.

Let me know if this helps.

Regards,

Supriya Rajgopal


Allow users to view others contents with autocomplete Entity Reference field

Generally if a user cannot see another user's content then it is either because there is a content access module installed that is restricting access or the content is unpublished.

By default in Drupal you cannot see unpublished content unless you created it or you are an administrator with access to all content.


How to find out which context reaction is firing?

About a year ago I was working on a project where the breakpoints module would periodically send us into refresh loops.  I don't remember the particulars - only that the issue was due to the cookies not being cleared properly.

Breakpoints relies heavily on cookies to determine which display to use and when the cookies aren't cleared the module receives somewhat mixed messages.  I use Chrome for my development and found the extension Edit This Cookie very helpful.


Is Drupal contact form securely encrypted?

No. No form, in any website, is inherently "secure" or encrypted. If your requirement is to serve and submit the form over TLS, you'll need to set that up on your server/host as a separate task.

Once you have, Drupal will happily serve any page over https, and submit forms in the same manner.

The only thing you might want to consider from a Drupal point of view is to un-comment the lines in the default .htaccess which force-upgrade all requests to https. If your server isn't Apache that'll have to be done elsewhere.


Drupal 7 skip loading the template for ajax requests

How are you generating the ajax response?

If you simply want to return a string eg a file name you can just return it as plain text or as JSON using hook_menu and a callback function eg:

function mymodule_menu() {
    $items['my/custom/path'] = array(
      'page callback' => 'mymodule_callback',
    );
    return $items;
}
function mymodule_callback() {
  //Do stuff like get filename from DB.
  print 'filename.jpg';

  //to return JSON use drupal_json
  //drupal_json(array('filename' => 'filename.jpg'))
}


I would check a couple of things.

For sanity, make sure that your after_build function is being called by adding a drupal_set_message().
The labels will only change in the Edit form if your values are literally '1', '2' and '3'. Once you save the form, however, drupal will save the original value, not your new label.

function mymodule_after_build($form, &$form_state) {
  $form['field_some_options']['value']['#options'][1] = 'hiyo';
  return $form;
}


Try adding 'type' => 'external', to the options array index.
By default, the type is considered to be a reference to a file hosted on your Drupal site; by using 'type' => 'external', you are specifying that data is a reference to a file hosted on a different host.


Drupal form won't save with TinyMCE (Firefox only)

The main fix is linked to in comment #6 of the TinyMCE bugtracker here => http://www.tinymce.com/develop/bugtracker_view.php?id=3152

The source fix is in comment #4 but that won't help many since you need to have an environment to actually compile TinyMCE.


There is an archive view that comes bundled with Views (Check out admin/build/views page, views name Default Node view: archive (default)), just clone and modify it as per your need and it should work.

Also check this links containing discussion about the same requirement:

How to create monthly archive block
How to create a monthly archive block for a Drupal blog with Views
Views Archive Drill Down (Year//Month/Day) Block


Your hook_node_view() is incorrect, check the documentation and example implementations. The first argument is a $build array. That's the new $node->content: What your code is adding to $node->content should be added to $build.

Also, never render things yourself: Just put your render array ($node_statistics) in $build['content_statistics_list'].

It's also recommended to implement hook_entity_extra_field_info() and expose that key as an extra field. Then it can be shown/hidden based on the view mode.


The Userpoints module has Views integration to make this happen:

Create a new view using Userpoints Transactions as the base table.
Add a Relationship, Userpoints Transactions: User.
Select your fields: User: uid & Userpoints Transactions: Points.
Filter on Userpoints Transactions: Timestamp with the Value Type set to An offset from the current time... so you can input your strtotime() offset (e.g. by rolling week, "-7 day").
Enable the Use aggregation option.
Lastly, for the Aggregation Settings on Userpoints Transactions: Points, set the Aggregation Type to Sum.


How to set value of file field with entity_metadata_wrapper

Well I just found out a simpler and less ugly looking way to set image.

$image_file = A FILE OBJECT; //Lot of choices here : new stdClass(), file_load, etc
$wrapper->FIELD_NAME->file->set($image_file);

Just as taxonomy or node/entity reference, the file field name point on a loaded object, thats how I find out.

:: EDIT a posteriori ::

Here how I would have do it with OP question.

// Get the file
$file = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg');

// Wrap' it like one of your French girls
$wrapper = entity_metadata_wrapper('node', $node);

// And set the photo
$wrapper->field_photo->file->set($file);

// And save the node
$wrapper->save();


Drupal Console is for creating boilerplate code (also known as scaffolding) rather than for general administration and day-to-day work.  You can see an overview of the features of Drupal Console:

How does Drupal Console help?

To delete a node you would be advised to use drush which is a general purpose DRUpal SHell. Drush doesn't have a command to do this out of the box but there are a number of different approaches outlined in this post,
Can I delete nodes of a given content type with Drush?


Import a PDF from within a page (Feeds / Mailhandler)

I was able to do this using curl to get the source code then preg_match to pull the URL. I haven't actually gotten the pdf, though, because it's using a form to generate the pdf. However, that's a different issue, so this question is answered.


How to display all product prices on the page at once with Drupal commerce?

If themeing is considered "involving code", then you could create a view block.

Using Contextual Filters and Relationships, a View will be able to list all the referenced products on a node (including their fields).

Start by creating a View listing all the nodes that have a product
reference field (ex: Product Display).
Add a Contextual Filter for the Nid that defaults to use the Nid from the URL
Next add a Relationship (Product) using the product reference field of the Product Display node
Then add another Relationship (Line Item) for the Commerce Line Item of the referenced product

After that is all setup, you can add fields that use the Line Item relationship to get product titles, calculated prices, etc.


Why 'Failed to start the session' when RedirectResponse is sent?

There are two problems. First, you can't send a response from custom Drupal code. Second, you can't run non access code in an access hook, because access results are cached.

For redirects in Drupal 8 see these change records: drupal_goto() has been removed and hook_init() removed.

A different approach might be to let the 403 exception happen and then catch it in an exception event subscriber to do the redirect, see How to redirect an anonymous user to the login form after a 403 error?


Deleted content type shows in the "Add content" menu

I had the same problem which I just managed to fix - thanks to  Mołot's comment which made me think of menus.  It looks like creating a content type adds an entry to the Navigation menu but deleting it doesn't delete the entry.  I just disabled that menu item and now it's gone from the Add Content page.


How to make profile2 completely replace or override the core profile?

I wouldn't recommend doing this as profile2 is designed to compliment the core profile module.

The simplest way of explaining this is that the core profile module handles your account while profile2 handles all the extra information not required in order to be a Drupal user.

On a large sports team website that I run we use profile2. When users go their user page they see in order:

Their picture (a field of the core profile module)
Their email settings (core profile module)
A heading titled "Personal Information" (profile2 module)
All their personal information (First Name, Last Name, DOB, Address, Contact Number) (profile2 module)
Another heading title "Medical Information" (profile2 module)
All their medical info (Injuries, Allergies, Medications, Emergency Contact) (profile2 module)

When they go to edit their profile, the main tab is titled "Account" and allows them to change their username, email address, password, email settings, and profile picture. Profile2 adds "Personal" and "Medical" tabs where users go to complete the other two profiles.

Our club contact list gives all users access to the main profile which contains the username, picture, and email address. Only club executives and coaches have access to the personal information profile and only coaches have access to the medical information profile.


I followed this guide on Google Fonts to get it to work with my downloaded font. In your case that would be editing your info file to declare that you have fonts assets:

name: Subboot
description: Bootstrap Subtheme
type: theme
base theme: bootstrap
core: 8.x
libraries:
  - subboot/fonts

then edit the libraries.yml in your subtheme, ex. subboot.libraries.yml to add in the following:

fonts:
  css:
    theme:
      //your.domain.com/path/to/font {}


<?php
class MyEntityController extends ControllerBase {
  public function mymethod(AnotherEntity $anotherEntity) {
    // @todo The methods don't exist in core, so it's not clear what object they
    //   should be called on.
    //$form->setParentEntity($anotherEntity);
    //$form->setRedirectRoute(array(
    //  'route_name' => 'some.route',
    //  'route_parameters' => array('somearugment' => $anotherEntity->id()
    //));

    $myentity = $this->entityManager()->getStorageController('myentity')->create(array());
    return $this->entityFormBuilder()->getForm($myentity, 'default');
  }
}
?>


How to hide webform Results tab in webform?

You can hide webform Results tab by restricting user's permission access e.g. uncheck the following checkboxes in permission section :

1. view all webform results.
2. view own webform results.


How do you make sortable tables with a pager with data from a custom table?

You use the so called extenders.  In your case, the code would be similar to the following one.

$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  // ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);

// Initialize $query with db_select().
$query = db_select('your table name');

// Add the fields you need to query.
// ...

// Add the table sort extender.
$query = $query->extend('TableSort')->orderByHeader($header);

// Add the pager.
$query = $query->extend('PagerDefault')->limit(25);
$result = $query->execute();

See HowTo: Convert a module to DBTNG, Dynamic queries: Table sorting and Extenders.


Drupal cannot create sites/default/files even though permissions seemed to be set to standard

I disabled SELINUX by changing to disabled.

$ cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

I would love to understand SELinux better or how to tune it in regards to Drupal.


Conditionally remove / blank out field values in View using Views PHP

Try to use Views Conditional.

Views Conditional is a simple module that allows you to define conditionals with fields in views.

Conditions include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

Views conditional allows you to output text based on the result of the condition.


CSS not applied on install, but loaded properly

When you installed it, for Installation Profile, did you select Standard? or did you select Minimal?

It seems like you selected Minimal, which I highly do not recommend, Standard is the way to go. Delete all the tables in your DataBase and go to http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/install.php and install again.


How to properly check the menu for emptiness in twig?

This is tricky as you would expect {% if drupal_menu('main') is empty %} to work for checking if the menu exists or not. In reality, you'll want to use the render filter for twig. So that would become:
{% if drupal_menu('main') | render %}

I tested this code in my theme's page.html.twig file and it works. e.g.
{% if drupal_menu('main') | render %}
  {{ 'Main menu is not empty'|t }}
{% else %}
  {{ 'Main menu is empty'|t }}
{% endif %}

There is a very long winded issue here with regard to this:
[meta] Themes improperly check renderable arrays when determining visibility
There are also some related issues for this.

2447049: Add a render filter to twig
Checking for empty fields in Twig templates is complicated


Update a Referenced Node with a value from the node referencing it

Thank you both @GiorgosK and @4k4, for pointing me to the right direction! Here is the solution:

use Drupal\node\Entity\Node;

function my_module_entity_insert(Drupal\Core\Entity\EntityInterface
$entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() ==  'iamoriginal') {
   if (!$entity->field_my_reference->isEmpty() &&   !$entity->field_number->isEmpty() &&
 !$entity->field_hide_me->value) {
  _my_module_update_parent($entity, 'add');
 }
 }
}

function my_module_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'iamoriginal') {
$original = $entity->original;
if (!$entity->field_my_reference->isEmpty() && !$entity->field_number->isEmpty() &&
  $entity->field_hide_me->value != $original->field_hide_me->value) {
  $operation = ($entity->field_hide_me->value) ? 'sub' : 'add';
  _my_module_update_parent($entity, $operation);
}
 }
}

function _my_module_update_parent($entity, $operation) {
 $ref = $entity->get('field_my_reference')
   ->first()
   ->get('entity')
   ->getTarget()
  ->getValue();
 if ($ref->hasField('field_number_of_originals') &&        $ref->hasField('field_total_value')) {
$total = $ref->field_total_value->value;
$count = $ref->field_number_of_originals->value;
$number = $entity->field_number->value;
switch ($operation) {
  case 'add':
    $total += $number;
    $count++;
    break;
  case 'sub':
    $total -= $number;
    $count--;
    break;
}
$ref->set('field_total_value', $total);
$ref->set('field_number_of_originals', $count);
$ref->save();
 }
 }

If a user adds a new node of the post type "iamoriginal" then the value of the field_number is added to the refrenced node's field_total_value and +1 to the field_number_of_originals. If he later wants to disable the original node ,he gives a value to the field_hide_me and the previously added values to the referenced node are abstracted. Thank you again for your help!!!


How to display 'Terms and conditions' before starting a download, possibly using Rules?

It should be possible to implement a procedure that fits your requirement, using a combination of the Rules and Flag modules. Here is how you could do so:

Create a Flag (using the Flag module), related to your "terms and conditions" page (=TOC). The actual perpose of your flag is to have the user "flag" the TOC-page to confirm something like "I agree to the terms and conditions".
For any of the relevant download pages, try to have a path for each of them that starts with something like downloads/. It can be any path you like, just make sure it's something that uniquely indicates "this is one of the download pages for which we want to make sure the user agreed to the TOC as on the TOC-page".
When the user then requests the download page to be viewed (opened), add a rule that is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work for this case also:

Change node to downloads (as in my assumptions above in "2.").
Add a Rules 'Condition' like "If this user did NOT flag the TOC-page yet".
Change the "Message" (in the Rules 'Action'- to something to indicate that the user must first "accept the TOC" (by flagging the TOC-page, as in "1.".
Add an extra Rules 'Action' to issue a redirect from the selected download page to ... you guessed it ... the TOC-page!

Haven't experimented/tried creating this Rule (= variation of the rule in the answer I mentioned above), but pretty sure it'll work. Hopefully you'll be able to complete the rest of the puzzle in my answer on your own (if not let me know where you get stuck and I might enhance my answer for it also).


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')) {
  // ...
}


How should I store a simple, time dependent, repetitive data type in drupal

I think Webform is what you are looking for. You make a form that user(s) can fill in and submit.

You can track the submissions over time, export them etc. There are lots of features you can do with webforms.

This is not a complete how-to for your question but you can take it as a start point. This way you don't create a node for each submission, but the form itself will be a node of type Webform.


According to the FAPI docs textareas do support #ajax, yes.

I'd imagine the problem is because you'll be using a WYSIWYG editor on that field. Such an editor will replace the textarea with an iFrame, and the AJAX events aren't bound to that iFrame (or its inner textarea), so won't get fired when you change the text.

If that is the case, I don't think there's any easy way to overcome the problem except to turn of the WYSIWYG editor for that field.


For product type 'donation' allow customer to choose "price" and add allocation field

Did you try Commerce Donate module ?! I think it should solve the issue you are looking for !

Check the Screenshot below.


For those that find themselves here trying to make User Emails Optional, use hook_validation_constraint_alter. You're not extending core's, you're creating a new constraint and using it instead of core's. In my case, I replace core's with... an empty function to achieve what I want.

Something like this in .module

function optional_account_email_validation_constraint_alter(array &$definitions) {
  $definitions['UserMailRequired']['class'] = '\Drupal\my_module_name\Constraint\OverrideUserMailRequired';
}

Then a copy of the two UserMailRequiredValidator.php and UserMailRequired.php files changed to your liking.

The module administerusersbyrole has a working example of this.

I'll see if I can get around to putting my custom module onto drupal.org in the coming months.


How can I display a Google map with Search API Views and Search API DB

Have you ever tried these two modules?
https://www.drupal.org/project/gmap
https://www.drupal.org/project/location

With these two modules, you can create google maps and put your location data into a referenced google map.


How do I add block configuration information for themes using features?

Yes, but not directly you need to use the Context module to do it.


Why are there two database tables to handle taxonomy terms structure

taxonomy_term_data is the base table for the taxonomy entity type. It holds ID, property and bundle data for that entity type.

taxonomy_term_hierarchy holds the parent/child relationship between taxonomy terms (which of course can be multiple in nature).

You can't store the data for anything more than a one-to-one relationship in the same table, hence the split into two.


How do I remove the trailing time zeros after the Date

Go to 'yoursite/admin/config/regional/date-time' and click the button, '+ Add Format' to add a new date format.

Enter a name for this new format and add your date format in the Format string box.

Example: D, M j, Y will output Fri, Dec 22, 2017. Click Add Format

Go to your Webform > build and select the date element you want format with your new date format. In the Advanced tab, select your new date format in the SUBMISSION DISPLAY > SINGLE ITEM > ITEM FORMAT box and save.

You should also be able to select the new date format in Views.

Its best to clear the cache at yoursite/admin/config/development/performance


Why are the edit/delete/reply links missing in the Comment module?

It ended up being layout builder. Enabled full content and layout builder, cleared cache and it worked.


Set the table width to 100% with css. If some other rule is overriding this, you may have to increase the specificity or add !important.

If you need more control of your table columns, there is a cool module for responsive tables: https://drupal.org/project/responsive_tables. Haven't yet tried it myself.


hook_tokens() implementation no longer being called

hook_tokens() is invoked only when token_generate() is called. Since that doesn't necessarily happens when a node is viewed (or similar events), but it happens when a module calls token_replace(), hook_tokens() not being invoked could not mean your code is wrong.

Assuming that the code you show is not causing any PHP error, that means that a module that was before calling token_replace() is not calling that function anymore, or it is calling it in very specific occasions.
For PHP error I mean:

The code is calling a function that doesn't exist anymore (e.g. _workbench_access_get_user_section_names())
It is calling a function that is returning a value of a different type from what it previously returned (e.g. _workbench_access_get_user_section_names() returns a value that is not an array)

There isn't any change in the token subsystem from Drupal 7.41 to Drupal 7.51 that could cause your code not to work anymore. The only reason for your hook_tokens() implementation not to be invoked in a change in the code of the module your hook implementation is using, or a change in the code of a module that was generating token when viewing a node (or a similar event).

To test your implementation of hook_tokens(), you should directly call token_replace() passing a string containing a token your module defines and a node object. If the token is not replaced, then you can check for errors in your code; if the token is replaced, then your code is working perfectly, and your hook_tokens() implementation is not invoked simply because no module is replacing tokens in a string when you are expecting it to happen.

I would use the following code, to put in a file in the same directory containing the index.php file that comes with Drupal.

/**
 * @file
 * Test page to check the hook implementation of a custom module work.
 */

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Load a node to use as context for the tokens.
// Change the argument for node_load() to match the node ID of
// an existing node.
$node = node_load(1);

// Change the string to the token name for the token that needs to
// be tested.
$token = 'publisher_one';

$result = token_replace("[$token]", array('node' => $node), array('clear' => FALSE));

if ($result == "[$token]") {
  // The token has not been replaced.
}


I resolved the issue by adding 2 more tables

'field_config_instance'=>$main_database_prefix,
'field_config'=>$main_database_prefix,


Say you have two fields, title and link, in your view. Click the title field and exclude from display so it doesn't show. Then click the link field and rewrite results. Under rewrite results I think you can check BOTH "Rewrite the output of this field" and "Output this field as a link". In rewrite results text box, put in the replacement pattern [title] and in link path [link] (you can get a full list of replacement patterns below).

If that doesn't work just do a simple href in the rewrite results text box:

[title]


How to hide "Counter" and "Date" on certain page/node?

You need to interact with the theming layer (template.php in theme)

As you want to alter an element within a node, you may use function template_preprocess_node(&$variables) to alter, remove or disable that element. You will need to do a conditional test first ($variables['node']->nid) and check $node->nid against the nid of your specific node page. You can then look for the element within $node.

You may also just use Drupal 7 Template (Theme Hook) Suggestions, if the element you wish to hide is a standalone element (ie not embedded in a larger render array), in which case you will copy over the base theme's node template and just comment out/alter the bit in question - for node it is node--[type|nodeid].tpl.php.

When working in the theme layer remember that your theme always has the last say so you can safely make alterations knowing that you cannot cause problems for any other modules or base themes in the process.


Custom js added with drupal_add_js doesn't actually get added if I enable "Aggregate JavaScript files" or "Cache blocks"

Is the site in D7 or D8/9?
Because in 8+ you should use  #attached instead of drupal_add_js/css


As you mentioned, you'll need to add a custom validate function. Since this checkbox can be checked or unchecked on the fly, you will also need to use some javascript to toggle the "required" class on and off the textbox. This will make sure it looks right to the user. Of course you'll need to make sure you have a required class style in css.

This is just freehand, and just one way it could be done. You would need to adapt this to your fields.

create a custom module. In your .module file

<?php
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //where CONTENTTYPE is the machine name of your content type
  if ($form_id == 'node_CONTENTTYPE_edit_form') {
    $form['#validate'][] = 'my_test_validate';
  }
}

function my_test_validate($form, FormStateInterface &$form_state) {
  $checkbox = $form_state->getValue('field_my_checkbox');
  $textfield = $form_state->getValue('field_my_textbox');

  //if the checkbox is checked
  if ($checkbox['value'] == 1) {
    if (trim($textfield[0]['value']) == "" || empty($textfield)) {
      $form_state->setErrorByName('mytextfield', t('Text field blah blah is required'));
    }
  }
}

In a js file somewhere in your module or theme you could have something like:

(function ($, Drupal) {

  Drupal.behaviors.myForms = {
    attach: function (context, settings) {
      //add a click listener to toggle whatever styles you want
      $('#edit-field-mycheckbox-value').click(function(){
        $('#edit-my-textfield-0-value').toggleClass('required');
        $("label[for='edit-my-textfield-0-value']").toggleClass('form-required');
      //etc
      });

    }
  };

})(jQuery, Drupal);


Is it a great idea to upload php instead of writing phps in drupal interface

I think the solution is to put PHP codes in hooks... And anyone could say that it's insane to create a module just for one or two lines of codes... But most of time, drupal users has to do somthing like this several times in drupal. So why not combine all these hooks in one module that we might call whatever we want. So then just well-comment the code for good reading.

The little snag is : is there hook for each actions where we can add php code ?


Ah, seeing that this is a follow-up to How to check if entity id exists or valid?, I think I know what the problem is.

If you ensure upcasting through the route, then Drupal throws a not found exception automatically and shows the 404 page.

So, you need to define your route as /entityform/{your_entity_type_id} and in the controller, type hint the argument YourEntityTypeId $your_entity_type_id. Then Drupal automatically loads the object, gives it to you and returns a 404 page if not found.


Using hook_element_info_alter() would be one option, not sure it's the best.

The existing class sets 2 pre render callbacks, which you can override in your own class:

function MYMODULE_element_info_alter(array &$types) {
  $types['html_tag']['#pre_render'] = [
    [\Drupal\mymodule\HtmlTag::class, 'preRenderConditionalComments'],
    [\Drupal\mymodule\HtmlTag::class, 'preRenderHtmlTag'],
  ];
}

...

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\HtmlTag as CoreHtmlTag;

class HtmlTag extends CoreHtmlTag {

  public function preRenderHtmlTag($element) {
    // ...
  }

  public function preRenderConditionalComments($element) {
    // ...
  }

}


You can set the field to display in this page:
admin/config/content/webform

For whatever reason the e-sign field doesnt appear for me under form builder it appears when i go to form components under type there should be an option called E-sign.


By default do panel pages render inside main content area?

No, Panels should 'takeover' the page based on your ctools page manager assignments.

See /admin/structure/pages to confirm you have the path set in page manager ("Pages").


template.php function for adding field CSS classes

Using yourtheme_preprocess_field() won't work for forms because theme_field() isn't called. Instead, theme_form_element() is executed, which builds the form element wrapper.
If you want to use/override the input itself override the corresponding theme function, e.g. theme_textfield() and so on.

Another way could be using hook_form_alter()/hook_FORMID_form_alter() if you want to override the attributes for a specific form only.


Render view for specific user, drupal_mail

To render a view programmatically as a specific user, you need to adjust the global $user variable.

//Run script as a sepcific user
global $user;
$original_user = $user;
drupal_save_session(FALSE);
$user = user_load($uid);

//Your code goes here
....

//Return global variable to its orignal value
$user = $original_user;
drupal_save_session(TRUE);


How to utilise watchdog or how to debug webform error

Thanks for taking the time to looking into the issue Jay Chand and Ziftman.

Turns out that if you go into the admin panel in CiviCRM there is a debugging option where you can turn on callback on errors and thus gain more insight into error messages such as the one I mention above.


Overwrite menu.twig only for specific node types

Menus do things a little differently then, so you have an option or two...

/**
 * Implementation of hook_theme_suggestions_alter().
 */
function mymodule_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'menu' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

This will give you give you the following suggestion in this order:

menu--MENU-NAME.html.twig
menu--node-type--page.html.twig
menu--node-type--%.html.twig
menu.html.twig

With this the menu--MENU-NAME template still takes preference over the node type, so we need a trick to add suggestions after.

/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  $key = array_search('menu__'.$variables['menu_name'], $suggestions);
  if ($key !== FALSE && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    array_splice($suggestions, ++$key, 0, array('menu__node_type__%', 'menu__node_type__'.$content_type));
  }
}

menu--node-type--page.html.twig
menu--node-type--%.html.twig
menu--main.html.twig
menu.html.twig

Targeting your placement within the array of suggestions can be helpful, but it can be over kill, so you may just want to keep it simple and place your new suggestion at the end of the list and have the highest override

/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

You can even throw $variables['menu_name'] into the mix with:

$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__%';
$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__'.$content_type;


Hooks for altering Views block output in Drupal 6

You could use hook_views_pre_render to alter the results of the View before Views passes the data of for rendering.


First, create a new term view using the fields row style / unformatted list of fields (it is important that the tree style not be chosen now). Then:

Add relationship for taxonomy term: parent term
Add field term id (do not use relationship) and exclude it from display
Add field term id with relationship, exclude from display
Add any fields you want to display, like term name, term description, etc...
Change style / format plugin to Tree (Adjacency model)
Set Main field to Term ID
Set Parent field to Term ID with parent relationship

For details refer
https://www.drupal.org/node/1493366

https://www.drupal.org/project/views_tree (Compatibility and Usage)


Here's the piece I was missing:

/**
 * Implementation hook_ctools_plugin_api().
 *
 * Makes module compatible with context 3.
 */
function MY_MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'context' && ($api == 'plugins' || $api == 'context')) {
    return array('version' => 3);
  }
}


/* @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$route_provider->getRouteByName('abc.xyz');

RouteProviderInterface::getRouteByName() returns a \Symfony\Component\Routing\Route object if it exists, or throws an exception if it does not.

You can use RouteProviderInterface::getRoutesByNames() if you don't want an exception.

$exists = count($route_provider->getRoutesByNames(['abc.xyz'])) === 1;


How to implement 'phonetic typing' for performing a language conversion of a field (using CKEditor)?

Finally I found a module called Indic Script.

  This Module enables IME (Transliteration Input Method) for Indian Languages in Drupal Text Fields and Text Area Fields So that users can create their content in their own Language within Drupal without installing any additional software.

  6.x-3.0 and 7.x-2.x version has the integration for CKEditor (CKEditor.module and WYSIWYG.module)

  Indic Script module supports Type writer (TW) as well as Phonetic typing
  for the following languages.

  Tamil, Tamil Tw, Tamil 99
  Hindi, Hindi Tw, Hindi Remington Tw
  Malayalam, Malayalam Tw
  Bengali, Unijoy, Bengali Tw
  Gujarati, Gujarati Tw
  Kannada, Kannada Tw
  Oriya, Oriya Tw
  Punjab, Punjab Tw
  Telugu, Telugu Tw & Telugu Apple Tw

I've tested this module. Here is the screenshot of this module usage with CK field

I hope it helps someone.


How do I get the requirements in a module's composer.json merged into the consolidated composer.json?

I think I've figured it out.

This is supposed to happen automatically. If the module is enabled with drush under Drupal 7, it does.  If you use other means to enable, the module, this might not happen.

In case the root composer.json for some reason is missing
the requirements for a specific module, using drush to disable and then again re-enable the module fixes the problem.  E.g.:

drush dis composer_manager -y
drush en composer_manager -y

This seems to be all that is required.

It should be emphasised that this is only valid for Drupal 7. Drupal 8 is a completely different beast.


How to select multiple values from a list block and perform search?

Assuming it's a view, you have to do a couple of things after constructing the view.

Click on the Filter Criteria as seen in the screenshot below:

Click on Expose this filter, Grouped filters and Allow multiple selections in this order (they will only appear if you click in this order). Please see the screenshot below:


Custom menu link does not show up under "List links" but is in the database

Simply go to the menu and add that link in the menu and it would start showing up.


Printing raw field value to use in path to files

$catid = print $content['field_cat_id'][0]['#markup'];

Try removing the print.


You can use the Views Field module, to embed a view into. Here is a quote about it (from the module's project page):

Allows field tables to be used as base tables with Views.
On a field settings form, you may select:

to expose the field table as a base table
the columns of the field table to expose (e.g., entity_type, entity_id, and delta)

Multiple "exposed" field tables may be related by a multi-column join using the primary key columns. This module provides a programmatic interface to trigger this relation. A user interface is provided by the combination of the Field Group and Field group views modules.
One use case is to generate a table using columns from one or more field tables. As the field tables are treated as standard base tables, the Field API handling of the "field" is not invoked. Thus, by default, the raw value in each column of the field table is displayed.
By relating field tables, the individual columns of each table function as if they were part of a single table.


Node reference - show parent node when viewing child

Create one content type view with views module,

Set relationship >> Content: Reference node (field_reference_node)

In contextual filter >> Content: Nid (relationship field_reference_node)

Pass NID of child node within argument will result all node referenced with parent content.


Migrating into a multi-value nested custom field

Turns out the answer on that page is correct, just out of date. Instead of Iterator, it needs sub_process. It also needs a nested array

To create the nested array, I start with a temporary field with the two items it needs

tmp_single_published:
  plugin: get
  source:
    - field_published_by
    - field_published_at

I then plug it into another array and process it.

published:
  plugin: sub_process
  source:
    - '@tmp_single_published'
  process:
    uid: '0'
    at: '1'

This worked for me


Views Group by date plus showing newest node

In terms of the database there is two ways to make this happen.

Using GROUP BY (=aggregation)

group by user and day.
add additional sort criteria so that the photo you want to display is the first in this ordering.
mysql automatically displays the value of the first row in the group for each field that hasn't another aggregation function applied (and isn't grouped by).
Example to display the first photo per user and day (pseudo-SQL): SELECT node.*, DAY(created) AS day FROM node GROUP BY user, day ORDER BY created

Reformulate the problem and filter using joins

The first photo from each user per day can be reformulated as: The photo of each user (per day) that hasn't got an older one on this day.
In SQL this can be realized using joins
SELECT n1.* FROM node n1 LEFT OUTER JOIN node n2 ON n1.uid=n2.uid AND DAY(n1.created)=DAY(n2.created) AND n2.created<n1.created WHERE n2.nid IS NULL

In theory both ways should be expressible in views. But both are rather hard:

views doesn't support ungrouped/unaggregated fields in queries using aggregation. So to work with that you'd need to patch views.
Views provides no way to add additional conditions to relations.

The simplest way to achieve this is perhaps by using views to create the query without aggregation (like in 1.) and then use hook_views_query_alter() to add the grouping:

function yourmodule_views_query_alter(&$view, &$query) {
  $query->groupBy('node.uid')->groupBy('day');
}

NOTE that this won't work as is and without testing. You'd need to take a closer look at the $query generated by views to do this right.


How to properly test access permissions when generating links?

You can check the access for any url-path in your module using menu_get_item():

$menu_item = menu_get_item('mymodule/mypage');
$access = $menu_item['access'];
if ($access) {
    $mylink = l('My Page', 'mymodule/mypage');
} else {
    $mylink = '';
}

Put this code e.g. in some preprocess function in your module, change $mylink variable to sg that is available in your .tpl.php, so you only need to print this variable in your tpl.php.


Please check this link  as there is no way translate the views you just can filter the content of specific language of logged-in user. for enabling translation you check out the Internationalization Views module.

  Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet. Requires Internationalization 6.x-1.5 or newer.


Possible to theme the form's elements with own twig?

I found out a solution which I ended with using {{ element.[machine name] }} instead of {{ children }} on my custom template which is cloned by form.html.twig. The result of the code look similar below:

            {{ element.name }}
            {{ element.mail }}
            {{ element.subject }}

            {{ element.body }}

            {{ element.submit }}

If you have other suggestion, I am happy to know! :)


You're using an undefined twig.lexer tag there.

It looks as though you want that tag to work as a service_collector like twig.extension, but calling setLexer instead of addExtension.

For that, you probably need to add a line to your twig service definition, below the other tag:

- { name: service_collector, tag: 'twig.lexer', call: setLexer }

(Note: I don't know if this is actually good architecture. The service_collector tag is normally used when there can be multiple extensions, and multiple lexers would just replace each other. But it should work.)


i have set-ed 1 day time for cron

Presumably you mean you've set the "poor man's cron" value at admin/config/system/cron to 1 day - that value controls how often Drupal will run cron itself as a reaction to people actually visiting pages; it's not full-automated, hence "poor man's".

Assuming the value is being persisted (i.e. you don't have a global conf override or something for that var), then Drupal will respect it, and only run cron itself when more than a day has passed since the last run.

If it's still running every 10 minutes, then you have another process somewhere doing that - not Drupal.

Check your crontab/pingdom account/your usual alternative to find the culprit. If it's being invoked via URL, not drush/other script via crontab, then you can enable/inspect access logs to get an idea of where the request is coming from. Pingdom's IP ranges are public, for example, so you'd be able to determine if it's coming from there easily enough.


How can a form remember the selected tab after submit?

You should be able to see which vertical tab was selected at the time your form was submitted. If not, you can certainly use js and a hidden field to keep track of it. Once you have it submitted your form then you can easily set the #default_tab of your vertical tabs based on the value in your the recently selected tab. Something like this:

$form['information'] = array(
  '#type' => 'vertical_tabs',
  '#default_tab' => isset($form_state['values']['selected_tab'][...) ? $form_state['values']['selected_tab'][... : "some_tab",
);

Another option would be to use a pure js solution. By storing the currently selected tab in local storage and then selecting that tab when the form loads should work as well. In this case you may see your form "flash" as the selected tab is selected but that may or may not be a problem depending on your form and desired UX


how do I specify a render cache context as universal?

There is no universal cache context. This is the default for a render array if you don't specify any cache context.
Render contexts are merged upstream. Additionally you can configure required cache contexts which are added to all render arrays before they are rendered.
Out of the box Drupal requires these three contexts:
core.services.yml
parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

You can override the parameter in /sites/default/services.yml (use default.services.yml as template).


For grouping the content by date field, you may try the following:

Add one extra date field in the fields section. (This field will be used for grouping)
In Format -> settings, select that date  field for grouping


For settings.php $conf, how can I tell what a variable in Drupal 7 is named in Drupal 8?

Unless the module's documentation tells you the name directly, you'll have to look for it manually.

You can search with drush:

drush config-list (cli)     List config names

Choose one of the names and display its whole content:

drush config-get (cget)     Display a config value, or a whole configuration object.

If you are using a lot of modules, that list may grow fast so you can narrow it down by inspecting the module to get an idea of how its data is structured.

Drupal 8 modules can ship with documentation in a .yml file in their config/install directory, which may include default values for configuration. It seems unlikely there would be a hardcoded default value for the equivalent of the googleanalytics_account variable, but you would at least be able to find the code fetching its value, something like this: \Drupal::config('googleanalytics.account');. *

There's also the new State API, meant to store information which could be different depending on the environment (dev vs production), or any other information you would not want to synchronize with different instances of the same system, like the last time automated jobs ran. If the module uses that, look instead for lines like this: \Drupal::state()->get('googleanalytics_account'). *

Once you've found what you think may be the correct key name, you can retrieve its current value using drush:

drush state-get key

The names used here are quick guesses based on the Drupal 7 names, the real code may use entirely different names.


You can clone down the project via

git clone --branch 7.x-2.x http://git.drupal.org/project/custom_formatters.git

When in the directory do a git diff 7.x-2.4..7.x-2.3 and review the output.

If you don't want to scroll through your terminal, try git diff 7.x-2.4..7.x-2.3 > version-change.diff and pop the output into a diff viewer.

I wish cgit had this built it, but the diff viewer in it only supports per commit (as far as I know)


In the context of the question, Field Quiz simply provides a new field type/widget, so you have to edit the content type and add a new field using that type. It will be available after enabling the module.


What will happen at worst if I change the "Number of values" of CCK field

Changing it to unlimited isn't going to cause an issue. It's a standard warning message for any change on that setting for a field.

So really the only time you would be concerned is if you took an already unlimited field and set it to a static value, which could potentially remove values if the delta of that field on a node exceeded the static value.

Edit: But always be sure to take a backup before doing those kinds of changes, and always do this on a development environment.