how to display node page using views I have used panels to override the node pages(node template). I have created a views block, it has an image field and its output has been rewritten so that it is rendered as a image link. Now, I want to configure the views such that it will display the panels page(node page that has been overridden by panels).

What will be the URL of image link so that it points to node page. And also it has to pass certain arguments to the node page. How to do it?

I am using D7

You've got it backwards-- you don't want to use views to display the panel.  Instead, you want to use panels to display the view.

I will try to explain how this works as simply as I can.  Panels overrides the node page display.  Therefore, the display must be changed in Panels.

You can add your views block to the panels display.  To do this, you can use a Contextual Filter.  The Contextual Filter is the "argument" that views needs to display the content.  Panels will provide this argument (the value for the contextual filter) because it is the one overriding the display.

Explaining how views and panels work in detail is beyond the scope of what I can do here but I will refer you to Node One's excellent free videos on learning views and learning page manager/panels.


Extracting Views SQL I would like to create a MySQL view for another application looking at the Drupal Database. I thought I would get a jump start on figuring out the select statement needed by creating a Drupal View, then copying the generated SQL output. After doing this however, it doesn't seem that the actual SQL statement is outputted. From Drupal views it is showing:

SELECT node.title AS node_title, node.nid AS nid, node.uid AS node_uid, node.created AS node_created, 'node' AS field_data_field_ticket_category_node_entity_type, 'node' AS field_data_field_client_username_node_entity_type, 'node' AS field_data_field_ticket_hostname_node_entity_type, 'node' AS field_data_field_ticket_priority_node_entity_type, 'node' AS field_data_field_ticket_source_node_entity_type, 'node' AS field_data_field_ticket_type_node_entity_type, GREATEST(node.changed, node_comment_statistics.last_comment_timestamp) AS node_comment_statistics_last_updated, 'node' AS field_data_field_ticket_owner_node_entity_type, 'node' AS field_data_field_vis_group_node_entity_type, 'node' AS field_data_field_ticket_status_node_entity_type, 'normalizedticket:page' AS view_name
FROM
{node} node
INNER JOIN {node_comment_statistics} node_comment_statistics ON node.nid = node_comment_statistics.nid
WHERE (( (node.status = '1') AND (node.type IN  ('ticket')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

I don't understand what it is doing here: 'node' AS field_data_field_vis_group_node_entity_type Is views doing some additional processing after this to get the data? Is there a way to get a query that when run against MySQL directly, it will output similar results to that of views?

I believe your primary question is:

  Is there a way to get a query that when run against MySQL directly, it will output similar results to that of views?

You're probably getting an error when you try to run the query when copied directly from Views UI.  Change the {node} to myprefix_node, changing myprefix_ to the prefix you gave your tables.  If you didn't supply a prefix than simply replace {node} with node.

To respond to your other question:

  I don't understand what it is doing here: 'node' AS field_data_field_vis_group_node_entity_type Is views doing some additional processing after this to get the data?

Views creates aliases for the columns that are returned by the query so that it can more easily reference it later on.  In this case it is creating a hard-coded value of "node" for each result, which is interesting.  And the hard-coded value has an alias of field_data_field_vis_group_node_entity_type.


Is it possible to combine a Bootstrap theme with an existing custom Drupal 6 theme? Is it possible to combine a Bootstrap theme with an existing custom Drupal 6 theme?

I want to use Grayscale in my Drupal 6 website. But I already have an existing custom theme and I am not sure if I can simply use it. Or whether the styling will interfere with other stylesheets in Drupal.

There is the Bootstrap base theme for D7 (and even an upcoming D8 version), which bridges the gap between Drupal and the Bootstrap Framework, with also quite a few (contributed) sub-themes available for it already.

So if your question was about D7, then it seems such combination that you're looking for should be possible. As you may know already, the Bootstrap base is not available for D6. But maybe you can use the D7-version of it as inspiration to somehow make such combination also work for D6. Ultimately even come up with a backport of the Bootstrap base theme for D6?

Note: as mentioned by Molot's in the comment to this answer, there is "some" D6 backport of it available on github ... Via Drupal.org there doesn't seem to be any D6 versions, however there "is" some D5 version of it also ... Maybe upgrading the D5 version to D6 is another approach to consider? Using Browse code repository only results in D7/D8 versions though ...


Which module hook to use for CRUD operations on custom table? I have used hook_schema() in my module to create a custom table in the Drupal database - the data is unrelated to anything in Drupal.

I would like administrators to be able to insert, update etc. records in this custom table. I had thought to use the function hook_form() for this, but upon closer inspection this hook relates back to nodes. My custom table has no relation to nodes.

Is there a different function I should be using?

You don't need to call any special hooks. You just need to create menu items for insert/edit/delete/list of data.

Here is an example module that create basic crud using custom table.

If you want to create listing with views instead of custom listing callback function you will need to use view_api and hook_views_data in your module for that.


Render parent paragraph depending on dynamic data from child paragraph (e.g. db query) Here's my problem (D8):

There's a content type concert. In a paragraph type concerts_list a list of upcoming concerts (concert nodes) is displayed.
This concerts_list paragraph is referenced in field_right_column of another paragraph of type 2_columns.

What I want to do is: Hide the right column if there are no upcoming concerts in the concerts paragraph.

My issue is that the outer (parent) paragraph is rendered and preprocessed before the child paragraph and the resulting render array only includes #theme, #paragraph and #cache but not the actual render array used to render the paragraph.

How can I access a child paragraph's render array from the parent?
I don't want/need to access the child paragraph's fields since the concerts are no field because the data is simply added to the build array in hook_entity_type view.

When rendering the 2_columns paragraph I need to know whether or not there are any upcoming concerts and if not I'd like to hide the right column.

Is there a better approach to achieving a similar result?

I'd appreciate any hints/tips/...!

Here's the relevant code:

function MODULE_paragraph_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $bundle = $entity->bundle();
  if ($bundle === 'concerts_list') {
    // Get the max number of concerts we want to display.
    $max_concerts = (int)$entity->get('field_count')->value;
    $build['concerts'] = MODULE_get_upcoming_concersts($max_concerts, 'teaser');
  }
  elseif ($bundle === '2_columns') {
    // Determine whether to show one or 2 columns depending on the number of
    // upcoming concerts in 'concerts_list'.
    // It would also be ok to do that in twig but I'd need to get the data
    // somewhere.
  }
}

function MODULE_get_upcoming_concerts($limit = 0, $view_mode = 'default') {
  $entity_type_manager = \Drupal::entityTypeManager();
  $query = $entity_type_manager
    ->getStorage('node')
    ->getQuery()
    ->condition('type', 'concert')
    ->condition('field_date', strtotime('midnight'), '>')
    ->sort('field_date', 'ASC');

  if ($limit) {
    $query->range(0, $limit);
  }

  $nids = $query->execute();
  if (count($nids) < 1) {
    return [];
  }
  $nodes = $entity_type_manager->getStorage('node')->loadMultiple($nids);
  return $entity_type_manager->getViewBuilder('node')->viewMultiple($nodes, $view_mode);
}

I don't understand the code and what you are trying to do, so I answer the question in the title and the last part of the question:

  How can i access a child paragraph's render array from the parent? Or
  is there a better approach to achieving a similar result?

Don't use the render array, use the parent paragraph entity to get the child paragraphs and their field values:

use Drupal\Core\Cache\Cache;

/**
 * Implements hook_ENTITY_TYPE_view() for paragraph entities.
 */
function MODULE_paragraph_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $bundle = $entity->bundle();
  // check if this is the parent paragraph
  if ($bundle === 'gigs_teaser') {
    foreach ($entity->field_child_paragraphs->referencedEntities() as $paragraph) {
      // get a field value from a child paragraph
      $field_value = $paragraph->field_example->value;
      $build['#cache']['tags'] = Cache::mergeTags($build['#cache']['tags'], $paragraph->getCacheTags());
      ...
    }
  }
}

Node query

I think I understand now the issue more. You ask probably the wrong question, because the "dynamic data from the child paragraph" is in reality not data from this paragraph, but from a node entity query. If you want to access this query data from two places in code, then put the code in a function and store the result in a static variable so that it is not calculated twice.


Unable to send e-mail. Contact the site administrator if the problem persists When my web form is filled and submitted, I get redirected to a page that says:

  Thank you for submitting.

but theres a red warning box there that says:

  Unable to send e-mail. Contact the site administrator if the problem persists.

I think its the SMTP server, but I don't know how to fix that.

Try using:

SMTP Authentication Support

with
PHPMailer

If You use Gmail to set up STMP follow this steps:

SMTP server: smtp.gmail.com
SMTP port: 465
Use encrypted protocol:Use SSL
SMTP Authentication -- Your User Name and password
Leave the other options by Default


Configuring drupal in a virtual directory I am running drupal using apache on redhat linux.  Currently drupal is running at the root of the apache site.  However, I want to put drupal in a sub-directory/virtual folder, because it's possible other sites will be on this server in the future.

The sub-folder I want to use is /fr.  I can easily setup apache to use this alias, but how do I configure drupal to know that it's running in a subfolder? I currently have URLs like /agent/dashboard.  If I configure apache for the /fr subfolder, drupal loads but it doesn't recognize /fr/agent/dashboard.

Do I just make a subfolder in the drupal install folder?  I'm not too familiar with apache so I really don't know.  Do I have to redefine all my routes (i'm using Drupal 8).  I really hope not.  I'm looking just for a setting in drupal or apache where I can set this.

Running Drupal in a subdomain and changing the document root of Apache virtual server are two different things.

To change document root you would set new paths in two Apache configuration lines for the given website:

DocumentRoot /home/username/public_html
<Directory /home/username/public_html>

Change the above two records to whatever you like, for example to:

DocumentRoot /home/username/public_html/sub-directory/sub-sub-directory
<Directory /home/username/public_html/sub-directory/sub-sub-directory>

and it wouldn't matter for Drupal as long as the following directive stays same:

ServerName example.com

In other words, whatever document root you set for a website, it will be still accessible through its domain name typed in the browser's address bar, set as ServerName in Apache configuration file, and Drupal will behave accordingly.

However, if you want to just place Drupal in a sub-directory, then you do not have to meddle with Apache configuration at all.


Local site not working I've pulled down a site using dev desktop but none of the styles are working. I think it's a problem with the settings file.

There are multiple sites on this environment. In Dev Desktop, I chose to clone an environment, specified a specific site, and cloned it locally. I am able to view the site and images but the stylesheets are loading. I also can't access the admin area. Drush seems to work fine.

The only error I'm seeing is "The file could not be created." In the past I've had to create a settings.local.php file but that doesn't seem to be working, either.

Any thoughts as to what I'm doing wrong?

The message The file could not be created indicates a permissions issue to me. Make sure that the webserver has the ability to create files in all the places in needs.


Add related field node limit I am using drupal search api with facet api modules.

I am trying to add more than 3 related node in my search index, but I am limited to max 3 nodes.

I have articles, styles, brands, designers, themes content nodes.
I created a search index on articles on the fields page; after adding 3 nodes, the  fourth node doesn't show. The reason I am doing this is to have title of nodes as facets.

I was able to add 4 related nodes on another machine. Is there any limitation to the number of related nodes that can attached to the index?

I found a solution instead of related nodes. I am using default node field attached with articles and have cache mapping of other content types with titles and id. And implemented custom code segment encoding which replaces id with title from mapping.


Commerce line item views and html mail I have a view (commerce line item) with HTML (or unformated) list with several fields.

On each field i unchecked "place a colon after the label" but it does not obey that rule.
So i added custom CSS to fields and its working.
Each label has "strong" html elemement and that is working fine too.

When the order is complete commerce sends email and results are:

Label:
field
Label:
field

instead of

Label: field

Label: field

html strong tag displays fine.

I have tried with HTMLmail and MimeMail with emogrifier installed.

Was fairly easy to fix the issue.

In styling settings of a field in view i used "SPAN" for field.


How do I allow users to remove their pictures from their user profile? Users on my recruitment website are able to upload profile pictures and CVs to their user profile. However, they aren't able to remove uploaded pictures and CVs or replace them with new files. What do I do to allow users to change their existing profile pictures as well as CVs?

If you use Field Permisions module, you should check the permission settings for that field. There are 5 permissions for each field: "Create own, edit own, edit anyone's, view own, view anyone's". It seems that you didn't give the 'edit own value' permission to users.


Not able to map all the product variations fields in commerce feeds importer I have one content type and added one field Product Variations' as product reference with widget 'Inline entity form - Multiple values'. But when I used Node Processor, I am not able to map other fields of the product variations. It only shows SKU and Product ID fields in target drop-down. It shows all the fields from node but not from the product variations.

Because of this I am not able to add more fields in my CSV file except title and sku.
Does anyone have any ideas on this?
Thanks

Another user gave me this to answer my question:

How to use Commerce Feeds to Import Stock for the Commerce Stock module?

The user https://drupal.stackexchange.com/users/8943/watergate suggested this:

If you're using commerce_feeds 7.x-1.3, uninstall it.
Make sure you've updated the standard Drupal feeds to 7.x-2.0-beta1
Download commerce_feeds 7.x-1.x-dev

After I did that, I could use mapping and see all the target fields for my product variation, including those fields enabled when you use commerce_stock.


Panels with 4 or more columns Is it possible to create a panel with 4 or more columns? The sample templates in the Panel module only go as far as 3.

You could also define your own 4-column panel. There are instructions here: Panels 3: Creating a custom layout in your theme, and a more specific tutorial available here: Creating a four column layout for Panels 3 in Drupal 7.


How do I write a template file for a specific input field? I'm currently creating a custom theme for a drupal 8 site and I'm putting a comment section for blog posts like :

<section class="comment-section">
    {{ content.comment }}
</section>

That puts in the comment section, but now I want to style it. I have twig debug enabled and to customize a page or view I usually look at the inspector/page source and there are comments recommending file names such as page--node--1.html.twig and such. Unfortunately for these fields when I look for the textarea or title input the only suggestions are, for example, ../form/textarea.html.twig. I can't use those because they will effect every other textarea on the site, so how do I figure out what to name my file for these specific inputs?

I'm going to put in a screenshot of my elements console in case it has something to do with that:

If you want to add a more specific template name to an input element use a theme name suggestions alter hook:

mytheme.theme

function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#type'] == 'textfield' && strpos($element['#id'], 'edit-subject-') === 0) {
    $suggestions[] = 'input__textfield__subject';
  }
}

function mytheme_theme_suggestions_textarea_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strpos($element['#id'], 'edit-comment-body-') === 0) {
    $suggestions[] = 'textarea__comment_body';
  }
}

You find more information here hook_theme_suggestions_HOOK_alter.

If you don't find the data you need in the elements variables, then you have to add it in the form build process, for example in a form alter hook. In this case the form build has already provided the necessary information in the element id.


Cannot use libraries in sub-theme I'm experiencing a weird problem. I'm making a sub-theme of the Bootstrap theme that's available for Drupal 8. However, after trying all the possible ways of how to attach a library to a page in my theme, no one seems to work. Am I doin'g something wrong?

Here's my libraries.yml file

countdown-timer:
version: VERSION
js:
  js/jquery.countdown.min.js: {}
  js/auction-timer.js: {}

Here's how I am trying to attach it to all pages in .info.yml

libraries:
  - numisvet/countdown-timer

I have already tried the approach of adding '#attached' to the render array or using {{ attach_library('numisvet/countdown-timer') }} in a twig file.

No one of these seems to work, only libraries defined by the Bootstrap theme are getting loaded.

Am I doing something wrong?
Thanks a lot for all replies.

Simply add your library here in your's my libraries.yml file

 bootstrap-scripts:
 js:
bootstrap/js/affix.js: {}
bootstrap/js/alert.js: {}
bootstrap/js/button.js: {}
bootstrap/js/carousel.js: {}
bootstrap/js/collapse.js: {}
bootstrap/js/dropdown.js: {}
bootstrap/js/modal.js: {}
bootstrap/js/tooltip.js: {}
bootstrap/js/popover.js: {}
bootstrap/js/scrollspy.js: {}
bootstrap/js/tab.js: {}
bootstrap/js/transition.js: {}
bootstrap/js/transition.js: {}

Your-sub-theme/js/jquery.countdown.min.js: {}

Your-sub-theme/js/auction-timer.js: {}

**No need to define it separately also place your js file at correct folder path should be eg:Your-sub-theme/js/jquery.countdown.min.js then clear cache **.


How to replace Operations links (dropdown) by icons? I'd like to have something like that (icons as buttons)   instead of text links in dropdown

There is probably a better way, but you could use CSS to hide the text and display an image background over the space instead.


How do I get the menu title via the menu name, Drupal 7 API I'd like to get the title of the menu.

if I do:

menu_navigation_links('menu-name');

I get only the links without the title, which is good but I still need the title.

Any ideas ?

Cheers

menu_load('menu-name');

Returns title, description and menu_name for this menu.
https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_load/7


How to redirect all unpublished nodes of a certain type Problem

I'm running a job site where content appears and disappears quickly. This means I end up with a lot of 404s from Google indexing pages only for them to disappear.

I want to redirect all unpublished nodes of a certain type to a particular page, depending on a value on the node and display a drupal message depending on what just happened.

I'm trying to come with a solution which is easy to maintain and will scale, should the site grow to have thousands of nodes.

Has anyone solved this sort of problem? What kind of solution did you use?

My current ideas

Use the redirect module.

I've created a module which will redirect all my nodes when they're unpublished via either a cron action or a form action using the redirect API.

The problem is this creates a lot of redirects. While it might take a while to become unmanageable, several other questions mention the module scales quite well into the thousands I would like it to be future proof is possible.

One option to solve this was to delete unused redirects however because I run Varnish in front as a cache, it is unable to tell which redirects have been active.

Do it server side

I'm running Nginx, I presumably could set up a location block which would redirect all 404s.

If I put the node information I needed in the URL I could just grab it from there and then redirect each set of nodes.

This is an ok solution, but the pages are redirecting to country so there would have to be 330 location blocks in my nginx config, which isn't particularly slick.

It also makes it impossible to set a message on page load.

Use the rules module

You can setup content viewed redirects using the rules modules but unfortunately Varnish caching breaks this.

I ended up going with the first option and using the following solution to make sure the redirects never got out of hand:

Basically when a job advert goes down it will get given a 301 redirect. Then I remove every redirect for a job advert older than 3 months.

Hopefully this will remove the worst of the 404 problem because: If Google crawls the link in the three months then it will be redirected and change its index.

If a person comes across it in the three months they'll be correctly redirected and if no-one has bothered to try it for three months then I've probably avoided the 404 problem.

The code just involved calling an extra cron job and then altering a version of the redirect_purge_inactive_redirects(); function.

function redirect_purge_job_redirects(array $types = array('redirect'), $interval = NULL) {
  //set interval in code to 3 months in seconds
  $interval = 7776000;
  $query = db_select('redirect');
  $query->addField('redirect', 'rid');
  if (!empty($types)) {
    $query->condition('type', $types);
  }
  //add in condition here to select all redirects
  //for the job adverts.
  //the path for all the job adverts begins with job
  //so I look for that.
  $query->condition('redirect', 'job'.'%', 'LIKE');
  $query->condition('access', REQUEST_TIME - $interval, '<');
  $query->addTag('redirect_purge');
  $rids = $query->execute()->fetchCol();

  if (count($rids)) {
    redirect_delete_multiple($rids);
    watchdog('redirect', format_plural(count($rids), 'Removed 1 inactive redirect from the database.', 'Removed @count inactive redirects from the database.'));
    return $rids;
  }
}


Modifying a Views 3 underlying query I have a View and it's based on a query and I'd like to modify the query that it is based on. What is the best way to do this?

More specifically, the query generated by Views is like this:

SELECT blah, blah, field-repeating-date, field-startdate, blah blah
FROM etc. etc.
WHERE this, that and the other
ORDER BY field-repeating-date ASC, field-startdate ASC

and I'd like the query to be:

SELECT blah, blah, IFNULL(field-repeating-date, field-startdate) AS thedate, blah blah
FROM etc. etc.
WHERE this, that and the other
ORDER BY thedate

in order to be able to mix the two date fields and have them sort properly. The modified query does what I want when entered through phpMyAdmin.

I'm using Drupal 7 with Views 3.

Edit:
I did find a solution, but I can't post an answer for another 3 hours because I do not have a reputation here.

A little googling and I found one solution, I'm not sure if it is the correct way to go.

I created a small module with one function, installed and enabled the module and it seems to work exactly as I need.

The mymodule.module file contains the following code:

function mymodule_views_query_alter(&$view, &$query) {
  // this is the name of our View and Display
  if ($view->name == 'upcoming' && $view->current_display == 'block') {
    // override the ordering
    // this is because the two different date fields are one or the other
    // but not both fields, so we coalesce.
    $query->orderby = array(
      array(
        'field' => 'COALESCE( field_data_field_repeatdate_field_repeatdate_value, field_data_field_startdate_field_startdate_value)',
        'direction' => 'ASC',
      )
    );
  }
}

This gets called in when needed and uses COALLESCE to on the sort order (


Images not appearing into sites/default/files I designed and set up a site for a client at Gregory Lamberson.com, and for some reason when he tries to create new content, the images are not uploading to the correct directory. The old images that I put on the site are showing up fine at /sites/default/files, but when he tries to add a new image, it writes the image into /?q=sites/default/files, and that directory doesn't exist, so the images are not showing up into the site.

Clean URLs are not enabled, so I was thinking that if I do enable them it might solve the problem. However, I am just starting out in front-end development and I could use a second (professional) opinion.

The nodes in question are in Storm Demon & AfterLife Project.

Thanks!

I fixed this problem. Apparently it was a permissions issue with the default directory. I set it recursively to 777 and the client was able to post images without a problem. I just had to make sure to reset the permissions on the settings.php file.


Where files are used if path entered by hand I am brining a 100 or so static pages into my drupal install here. We are pasting the content from the static site into the body of a content type. I am using ICME to upload the images and documents. Unless I directly link from ICME to the document, I've noticed it does not record as being used (/admin/content/files > USED IN). Is there a batch script to run to check if a file is used somehow?

We are adding the files, but only updating the path via code editor find and replace... I do not want to hightlight each image and find the file in Drupal. The files are being recorded in the system as IMCE does that and if we do actually use the ckeditor IMCE link it does show as used. Just to emphasize that.

inline_image_to_field module promises turn your inline images into an image field (image entities).

  This module will take images that are embedded (copy/paste) or were uploaded via the wysiwyg and attach them to an image field.

This way you can have your Drupal installation being fully aware of any such images and take advantage of any file or image entity related modules.

DISCLAIMER: I have not used this module and it is new module with not many installs so use with caution on your DEV environment before commiting to your LIVE environment


Cron fails when calling hook_node_view When running cron manually via GUI the cron starts to run but I have traced down the failure to hook_node_view in one of my modules.

The code is:

if ($node->nid == 47)
{
     //THIS CODE IS HAPPENING, but HOW in hook_node_view when running cron?
     drupal_goto('node/48');
}

When you implement hook_node_view(), don't forget to check if you're really displaying the node using this code:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    //Do something...
  }
}

This should correct your errors.


How to Show Nodes under different flags in a view I have two flags, Flag A and Flag B. I need to have a view that lists the nodes that flagged under A and also the nodes that flagged under B.

Using Include only flagged content option in Relationship, I only get the nodes that are flagged by both the flags. But in my scenario I need nodes that are flagged either by flag A or flag B.

I found out the solution for this question.

Refer:https://stackoverflow.com/questions/1340423/or-operator-in-drupal-view-filters?rq=1

If you are using Views 3 / Drupal 7 and looking for the answer to this question, it is baked right into Views. Where it says "add" next to filters, click the dropdown, then click "and/or; rearrange". It should be obvious from there.


Boosted Varnish for Drupal - what to do with "Control: no-cache" headers? Per the following article http://www.trellon.com/content/blog/boosted-varnish-high-performance-caching-made-easy#comment-8150 we're attempting to use Boost and Varnish on our Drupal 7 site.

As for why we want to use Boost and Varnish, it is to limit the impact of restarting/clearing the Varnish cache.

Anyway, when we install Boost and go to the status report page (/admin/reports/status), there is a message which states:

  Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.

So we disable the core cache. When we do that the following HTTP header gets set:

  Cache Control: no-cache, must-revalidate, post-check=0, pre-check=0

We re-enable the core cache and the headers read as:

  Cache Control: public, max-age=900

As I understand, a cache control header of no-cache tells upstream proxies like varnish "you aren't allowed to cache this."

So essentially we have a dilemma: Boost requires core cache to be disabled, but disabling core cache makes the site un-cacheable by Varnish.
Leave core-cache enabled and Boost won't work.

How do we get them to play nice together? In other words, how can we disable the core cache to make Boost happy but not have the no-cache header set?

drupal_add_http_header() in your own module will allow you to override Drupal's headers.

Not that it's needed - your headers will only be set to no-cache when you hit Drupal directly. Not for boosted statics. It is a good thing. You want to keep HTML from boost in varnish, after all, not the one generated directly.

I'm proposing to leave it be. Files from Boost cache will not generate these headers, so will be cacheable for varnish. You will only skip caching pages generated on direct Drupal hits. But you want to skip them. They may contain messages, for example. Boost does not cache when there are errors and messages, so leaving no-cache in Drupal will let you to use this behavior and make varnish respect it.


Custom Validation on Address Field In addition to the validation that already takes place using the addressfield module, I'd like to check for (and fix) items like:

Building to Bldg
Room to Rm
Circle to Cir
Avenue to Ave

Is there a module that would do this?
Is this best done with a custom module or using JavaScript?

Any chance that this module might be helpful?
https://www.drupal.org/project/field_validation

Don't use JavaScript validation because some people can disable JavaScript in the browser and you're validation will fall!

If you want custom validation will be better if you will use additional validation for your form (custom code)


Redirect (or show the node) taxonomy term page to node, if there's only one node associated with that term So I'd like to redirect taxonomy term page or show the full content of the node on taxonomy page if there's only one node associated with that term.

My solution is handle it in hook_preprocess_page(maybe there is another or better solutions but this is good too)

put this in template.php

first solution(maybe not worked)

function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid;
    if(count($item)==1){
         drupal_goto('node/'.$items[0]->nid);
     }
    }
}

Alternative solution

function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid);
    if(count($items)==1){

         //another solution is set a variable in preprocess and in page.tpl.php or your taxonomy tempalte page redirect it
         $variables['soheil_redirect_tax'] = array('path' => url('node/'.$items['nid']));

    }
  }

if first solution (drupal_goto) not worked in page.tpl.php or your custom template for terms page handle redirect(I mean in page.tpl.php file or taxonomy--term.tpl.php file) with

 if(isset($soheil_redirect_tax)){
    drupal_goto($soheil_redirect_tax['path']);
 }


a non existing subdomain is added to image urls I have some images in my home page and from time to time the URL of these images get changed somehow and a subdomain is appended to it automatically.

For example:
www.mysite.com/sites/default/files/image.png becomes abc.mysite.com/sites/default/files/image.png.

Here are some other facts that might have something to do with this issue:

The site supports two languages (english and arabic which is the default language) and this issue only appears in English Site.
We had a very old drupal 6 site before that was using Subdomains extensively (using the subdomain module) and I noticed that any subdomain appended to the image url is usually a randomly selected one of these old subdomains. So these domains used to exist. But the weirdest thing is that we actually moved to a completely new server a year ago and we created this new site from scratch using Drupal 7. We have not imported any content or modules from the old site and we don't use subdomains any longer. The old server is no longer active. Also we have removed all subdomains from DNS in cPanel.
The issue goes away sometimes after clearing the cache.

What could be causing this weird issue?

This is rather big guess, but I think you have everything configured so that your virtual host is responding to all subdomains for your primary domain.  In Apache terms this would be something like

ServerName mysite.com
ServerAlais *.mysite.com

And, you have old links that are getting crawled from the old subdomains, and the net result are some bad URLs are being cached.

My suggestion would be to add something like this to your .htaccess

RewriteCond %{HTTP_HOST} !www\.mysite\.com [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,L]

Make sure this goes right after the RewriteEngine on in the stock Drupal version.  I don't think the two example rules in the file will work, as they assume just adding/removing the www and don't take subdomains into account (though I am not 100% sure about this; I haven't looked at these closely in a while).  Make sure you clear Drupal cache, too.

Also make sure you back up the file after you change it, so you have the additions the next time you upgrade core.


views of node with weight Possible Duplicate:
  How can I add a “weight” functionalitiy to nodes?

I have views of node for example 10 last of news,I want when create a views of node , I can set this weight, means that create own list.
for example , I chose first node , second node ...

please help me

You should extend your contenttype with a weight field for this and use it as sort parameter. If your drupalversion is 6 you could use the CCK module for that.


Dynamic select list in the form API (dependent dropdown list)? First I want to select State (like Tamil Nadu, Sikkim, Kerala) after selecting state, depended city list will be display another dropdown list ( for example Tamil Nadu -> Chennai, Salem, Karur and Kerala -> Trivandrum, Kochin etc)

Please help me please how to make it, here i have tried some coding but does not work, Please help me

Sstate - Table

$query_state = db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_code]=t($state_record->State_name);
}

$form['state'] = array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' => $options_state,
  '#required' => TRUE,
);

City - Table

$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name'));
$query_city->condition('State_Code','$state_record->State_code','=');
$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach($city_results as $city_record) {
  $options_city[$city_record->District_code]  =t($city_record->District_Name);
}

$form['city'] = array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#required' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="state"]' => array('value' => $options_state)
    )
  )
);

Basically, in your form declaration, you have to add

In your form['state'] :

'#ajax' => array(
  'callback' => '_ajaxfunction',
  'wrapper' => 'divaroundseconddropdown'
);

Then in your form['town'] :

'#prefix' => '
',
'#suffix' => '
',

Now in your _ajaxfunction :

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

Now, back to your form['town'], you simply have to build your $options with the $form_state['values']['state'] variable, which will contain what has been filled in the first dropdown.

Everything is documented here.

[EDIT]

First replace $state_record in your $query_city by $form_state['values']['state']; *You can check if the value is formatted the right by dpm($form_state); in your _ajaxfunction.

Then :

$form['state']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '
',
  '#suffix' => '
',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state"]' => array(
        'value'=>$options_state))));

Close your function, open a new one :

function _ajaxfunction($form, $form_state) { return $form['city']; }


How can show block when mouse over icon in menu How can show block when mouse over icon in menu like this

when i put mouse in any link in this menu its show me block.

How can i do this.

That looks like a "Megamenu" type menu configuration.

You could try using a module like

om_maximenu
menu_minipanels

To acheive that design effect.


Paragraph Component reporting via Views I would like to create a View that allows me to see where Paragraph Components are being utilised.

It would just need to be a basic tabular View consisting of the following fields:

Paragraph Component Type / Name
Parent Node Title
Parent Node URL

Using exposed filters on the View it would then be ideally possible to filter by Paragraph Type so that you can easily see what nodes / pages are using what Paragraph Component Type / Name.

Is this possible through the Views UI? I have tried setting relationships between the node / field / entity, but can't get it to join up.

I think I got it.

Install the Entity Reference module
Go to view and add a relationship in the advanced section
Search for your paragraph embed field and set the identifier as anything as you want
Add your paragraph fields by searching for the fields in the paragraph bundle
Click save and done!


What about Drupal Commons 3 on Drupal 7? What about Drupal Commons 3 on Drupal7?

Its still in alphas and betas for months. Is it worthwhile waiting till it mature? Or is progress already stalled?

At the time Commons 3 on D7 (1.0) comes out Commons 6 will be at least 2.15 (its already 2.11). Should I go with already matured Commons 2.11 or wait for the delaying Version?

As of today Drupal Commons on Drupal.org, Commons Distribution Projects has reached version 7.x-3.22 from the first full release on February 25, 2013


How to add css class on click of CKeditor table button? We are using the CKEditor module provided from Drupal 8 (v8.6.2). There is a need to add a css class to the table when it is added to the Body field (text formatted, long) after someone clicks on the table button without having to modify the table via Source button.

How would we add a css class to the table after clicking the CKEditor table button?

The goal is to be able to do this without a module. If it comes down to it, we can review the module, but prefer to use any out of the box functionality. Another goal is to be able to do this on D8.

You can add copies of:
ckeditor.styles.js
ckeditor.config.js
to your theme directory

You can add a class using jQuery addClass

Be sure to set custom JS path under directory CKEDITOR profile settings.

*This was method under D7

D8
Option 1: You use this editor_js_settings hook to adjust ckeditor settings. A full list of settings can be found [here][3]

Option 2: Target item using jQuery addClass in the themes or custom module sites scripts.js file

Option 3: Create a custom module based on a copy of CKEDITOR module with a class added where you need it, or create a patch for the module to add your class. Classes to buttons are added here core/modules/ckeditor/ckeditor.admin.inc (be sure not to edit this core file)


How to modify display of image form metadata after upload on node edit form? After uploading an image, how do I hook in and change the display so that Title appears above Alternate text?

Here's the answer, which I discovered after some further research:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an an image on a slideshow
  if (isset($context['form']['type']['#value']) && $context['form']['type']['#value'] == 'slideshow') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = '_MYMODULE_image_field_widget_process';
    }
  }
}

function _MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the way metadata form fields are displayed;
  unset($element['title']['#description']);
  unset($element['alt']['#description']);
  $element['title']['#weight'] = '-4';
  $element['alt']['#title'] = 'Description';
  // Return the altered element
  return $element;
}


What Drupal tables to export from broken site I'm on localhost with Acquia Dev Desktop , Drupal 7.34. Php 5.3.29.
I was just playing in the Views when suddenly the site crashed. After few drush cc and restart of Acquia Dev Desktop and trying to access the site again showed me:

Fatal error: Allowed memory size of X bytes exhausted (tried to allocate X bytes) in c:\sites*\database.inc on line 2171.

I tried to increase memory limit to 1024M in php.ini and settings.php. Then I check the PhpMyadmin and I found that the watchdog table has ~6,000,000 records and its 6.4GB so I deleted it. drush cc, disable statistics and dblog modules. But still can't access the site. it just don't open. I copy watchdog table from another Drupal install (actually it was a previous backup) but still doesn't work and now it shows:

Fatal error: Maximum execution time of 300 seconds ...

and the watchdog db increased from 0mb to 350mb with ~777,034   rows.
Can I export certain tables with my views, taxonomy and settings and import them in another Drupal clean install? the Content is not important.
Edit:

Watchdog Message:%type: !message in %function (line %line of %file).
Variables: [BLOB - 294 B]
location: http://nina2.dd:8083/
the file watchdog_variables.bin says:

a:6:{s:5:"%type";s:14:"Strict warning";s:8:"!message";s:40:"Creating default object from empty value";s:9:"%function";s:43:"views_many_to_one_helper->ensure_my_table()";s:5:"%file";s:60:"C:\Sites\nina2\sites\all\modules\views\includes\handlers.inc";s:5:"%line";i:940;s:14:"severity_level";i:7;}

Not at the database table level, no.  There's a contributed module in Drupal called "Features" that lets you export content types, fields, views and some other configuration into a custom created module, but you would need a functioning site to begin using it.


How to upload file from a custom module? I am trying to create one basic module for Drupal 8, where I have added one form with some textfields and multiple file upload element.
Now on "submitForm" I am saving textfields values on database, but I am not sure how I can save image fields. I will be only saving the filename in the database.

Will it be using same function as we have in Drupal 7?

If you upload a file, it stores the file temporarily in file_managed table in database.And you have to set the file permanent status 1 to save it permanently else it will be deleted from the table by cron after some time.
This sample code to load a image and save it to database might help you to understand.

/* Fetch the array of the image file stored temporarily in database */
$image = $form_state->getValue ('image');

/* Load the object of the image file by it's fid */
$file = File::load ($image[0]);

/* Set the status flag permanent of the image file object */
$file->setPermanent();

/* Save the file in database ( "managed_file" table) */
$file->save();

when you select any file from 'managed_file' field type, drupal make a entry in 'file_managed' table, you just have to set the permanent flag as above to decide whether you have to save it permanently or not.


How to send files to Drupal 8 via REST I can create articles via REST without problems. But I can not figure out how to submit files.

How do I submit files (images) to Drupal 8 via REST?

Update:

REST UI - File: /file/{id}

Example image added in article:
/admin/content/files -> /admin/content/files/usage/1

file {id} = 1?

Get file id 1:

curl --request GET --user admin:admin --header 'Accept: application/hal+json' http://d8.local/file/1
A fatal error occurred: No route found for "GET /file/1"

Post image (without entity content):

curl --request POST --user admin:admin --header 'Content-type: application/hal+json' http://d8.local/entity/file
{"error":"No entity content received."}

I can't find out how to create the entity content.

Apply patch to the core: https://www.drupal.org/node/1927648
Install Rest UI using: drush dl restui-8.x-1.x
Go to /admin/config/services/rest and activate File /entity/file/{file}
Under /admin/people/permissions set all necessary permissions
Make sure files folder exists and has proper permissions
Encode image using command tool base64
POST to drupal.url/entity/file/

{"_links":
{
  "type":{"href":"http://drupal.url/rest/type/file/file"}
},
  "filename":[{"value":"input.jpg"}],
  "filemime":[{"value":"image/jpeg"}],
  "data":[{"value":"insert-output-from-base64-here"}] }


Adding of social media links( Facebook, Google Plus) In my site I've already added Facebook Like, Google Plus and Addthis modules.

Facebook like shows up only in the bottom of the article and it won't display if we're in the home page where no node is shown in full view.

Google Plus also won't show for home page in teaser mode

Addthis shows up in the bottom.

So I've gone ahead and copy pasted this code in the "content top" position in Acquia theme from Addthis.com account:

So this will make the buttons display on all url's. I just want to know if I'm doing the right way. When I added this same code to another site using Acquia theme in the same position then this code caused the buttons to show in staircase way. So I removed this code.

My main concern is that this code should not break layout in any browser/version.

Maybe should you try ServiceLinks, instead. Very straightforward to implement.

My two cents.


How to use db_select and apply a condition for another table's data? I know this is probably the dumbest question ever but I'm just not getting warm with SQL.

I am writing this function which loads all users that have a role assigned:

function mymodule_get_users_by_role($rolename) {
  $role = user_role_load_by_name($rolename);
  $uids = db_select('users_roles', 'ur')
      ->fields('ur', array('uid'))
      ->condition('ur.rid', $role->rid, '=')
      // ->leftJoin('users', 'us', '(us.uid = ur.uid AND us.status = 1)')
      ->execute()
      ->fetchCol();
  return user_load_multiple($uids);
}

But I only want those users which's status = 1. I could do it afterwards but I really hope there is a way within the QuerySelect to add this filter beforehands. The commented line just produces a white screen of death so I'ma go with a nope. I dont even know if leftJoin is the right thing to do.

Thanks!

The following query should be self-explanatory.

$query=db_select('table1','t1');
$query->join('table2','t2','t1.nid = t2.nid');

$query->condition('t1.uid','1')
      ->condition('t2.uid','3')
      ->fields('t1',array('uid','nid'))
      ->fields('t2',array('date'));


Getting the role ID from the global $user I'm very new to Drupal, so please bear with me if this is a dumb question. According to the globals API, the global $user object returns roles as an array:

[roles] => Array(
  [rid] => name
)

If I reference $user->roles, it gives me the role names.

Short of looping through like this:

foreach($user->roles as $key => $value){
    error_log("key: " . $key . " ; value: " . $value);
}

Is there any way to return the role ID (rid) instead of the role name? I need to do conditional processing based on roles, but some of our roles are company-specific, and contain special characters. It would be much easier to work with the ID instead.

You can use array_key_exists() to do this:

$rid = 42;

if (array_key_exists($rid, $user->roles)) {
  // Do stuff
}

If you just want an array of RIDs, you can use array_keys():

$rids = array_keys($user->roles);


How do I get the raw URL as a field in Views? In views I need to return the raw url that is provided as the href value to the title field (when as a link) or the Content: link value.  I thought originally I could choose Content:link and strip the HTML in a rewrite, but no go.

I need the full URL so that I can pass it as a parameter in a field rewrite. Thoughts on how to get this only?

As per the comment here http://drupal.org/node/458316#comment-6236984

In views 3.x you can use "Path" field with option "Use absolute link (begins with "http://")" in Rewrite results section.


send user registeration mail in html format I want to send any email of my site in HTML format, I install smtp , mimemail and mailsystem modules, and smpt configured correctly and test it(I check Allow to send e-mails formated as Html), also this is a snapshot of Mailsystem settings

,also in Mimemail settings I set E-mail format in FULL HTML format,also I create mimemail-message.tpl.php in theme folder (and cleared cache).

it seems everything is ok,but when a user register in site, email not send in html format and is only plain text.

How can I send any user email (registertion,canceling,approved,suspending ,...) in HTML format?

I recommend using PHPMailer module.
https://www.drupal.org/project/phpmailer

It is used to send HTML emails with Mime Mail.


Wrong timezone in Views output I'm using Services Views to create a JSON output of my Drupal site's nodes. These nodes has a start and stop date and time regarding an event. On the site, viewing the node, the time is correct, but in my Services view it is shown in UTC instead of my Drupal site's timezone (UTC +2).

I've seen other questions regarding this issue with a DB and site timezone being different, with all the issues it creates - especially in cases just like this.
Eg.:
http://dropbucket.org/node/559 and
Drupal timezone and database and Printing the correct date value in a view

In this case, however, I do have a problem converting the value into the correct timezone and therefore the correct time.

I have the site set to UTC +2 (Sweden/Stockholm), users arn't allowed to have any other timezones, also the date field is set to save the date in the site's timezone, not the DB.

My view wont let me rewrite my output so I can't convert the date inside the view - nor would I like to run PHP in a view anyway.

Is there another way of converting, or at least changing the setting for the date save, so that this won't be a problem?

Cheers,
Daniel

I'm not exactly sure why you are having this trouble... Though in a quick attempt to test (in Drupal 7), it does seem a little screwy.

However, since you don't seem worried about other timezones and no need to convert timezones, it would seem easiest to set the "Time zone handling" on the field to "no time zone conversion"
Then the views should pick up whatever date and time is there to begin with.


How does DrupalGardens.com setup a new website? How does drupalgardens.com creates a new website?

It creates a separate directory for Drupal, containing all core files(modules, themes, includes, ...)

OR

It shares the themes, modules and core files, and just creates a sub-site in drupalgardens.com

The second one is more reasonable, But When I read the source HTML I saw the following line:

<link type="text/css" rel="stylesheet" href="http://[mysitename].drupalgardens.com/modules/acquia/gardens_client/gardens_alert.css?lva62a" media="all" />

That, in my opinion, says that my website is outside of drupalgardens and has a separate directory instead of being a sub-site in drupalgardens.com

Yes, Drupal Gardens sites are multisites. Modules inside either /modules or /sites/all/modules are shared by all sites in a multisite installation. If we installed an entire instance of Drupal for each individual Gardens site it would be a serious waste of disk space.


The missing phpmailer module I updated a site with "Composer update --with-dependencies"
and encountered the following problem:

User warning: The following module is missing from the file system: phpmailer in drupal_get_filename()

Then I ran: composer require drupal/phpmailer.

Terminal returned:

Using version ^3.0@beta for drupal/phpmailer
./composer.json has been updated

And

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

But the Status Report still showed that phpmailer module was missing.

So I attempted running "drush en phpmailer -y"

And it returned:

phpmailer was not found.                                             [warning]
The following projects provide some or all of the extensions not     [ok]
found:
phpmailer
Would you like to download them? (y/n): y
This codebase is assembled with Composer instead of Drush. Use       [error]
`composer update` and `composer require` instead of `drush
pm-updatecode` and `drush pm-download`. You may override this error
by using the --pm-force option.
phpmailer was not found.                                             [warning]
Unable to download some or all of the extensions.                    [warning]
There were no extensions that could be enabled.                      [ok]

What can I do to fix this?

There is a module for that: https://www.drupal.org/project/module_missing_message_fixer

And you can try drush or devel according to the doc here https://www.drupal.org/node/2487215

Use Drush

drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

When done, clear the site's caches (e.g. drush cr).
Also make sure that the CMI folder is cleansed of the broken uninstalled module. There may be some yml files left over and / or some system config. (this is all not the best way to do things as a FYI. However with Drupal 8 being so young, things don't go as planned always).

Use Devel

Enable Devel module and go to /devel/php. This will allow you to run some PHP code and you can execute the following:

$query = \Drupal::database()->delete('key_value')
    ->condition('collection', 'system.schema')
    ->condition('name', 'module_name')
    ->execute();


How to determine if {{user_picture}} is not empty in the comment.html.twig template Trying to determine if {{user_picture}} is not empty in the comment.html.twig template.
{{user_picture}} refers to the Compact display mode for a User Entity.
The below code doesn't work.
{% if user_picture is not empty %}
      {{ user_picture }}
    {% else %}
      <img src="images/default_image" width="42" height="42">
    {% endif %}

Also tried this with no success...
{% if user_picture|render is not empty %}

Researched a bunch, and couldn't find any problems/solutions with this use case. What am I missing?

The comment entity is available and you can get the author and its field data from that, e.g.
{% if comment.uid.entity.user_picture.target_id > 0 %}
  {{ user_picture }}
{% else %}
  ...
{% endif %}


Adding a delete button for webform attachment fields I have created a structure of field like below within code and not used webform UI. The reason of doing this pro-grammatically is because I have hundreds of forms and I wanted to do it once for all.

Here is my code:

            for ($i = 0; $i <= 4; $i++) {
                $form['submitted']['file' . $i] = array(
                    '#title' => t('File'),
                    '#type' => 'managed_file',
                    '#description' => t('Please upload a document or image.'),
                    '#default_value' => variable_get('file' . $i, ''),
                    '#weight' => 100,
                );

                $form['submitted']['remove_name'.$i] = array(
                   '#type' => 'submit',
                   '#value' => t('Remove'.$i),
                   //I NEED A WAY TO PASS $i AS ARGUMENT TO THE CALLBACK
                   '#submit' => array('form_remove_attachment'),
                   // Since we are removing a name, don't validate until later.
                   '#limit_validation_errors' => array(),
                );
            }

And here is the callback:

 function form_remove_attachment($i, &$form_state) {
  //dsm($form_state['complete_form']);
  $clicked = explode(' ', $form_state['clicked_button']['#value']);
  //dsm($clicked, 'clicked');
  if ($clicked[1] == $i) {
     unset($form_state['complete_form']['submitted']['file' . $i]);
  }
  // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
  $form_state['rebuild'] = TRUE;
}

Now what I need is a delete button for each attachment field to allow users to change their mind on regard the attached files. I can add it of course by JS but this way the attachments are not eliminated from $form_state.

Does anyone have some suggestions?

There is an example in the examples module.

There is a module with in that called form_example. If you check the 9th example you would get what you are looking. It has an example of adding and removing fields dynamically and the code is well documented.

change value '#value' => t('Remove'), to '#value' => t('Remove' . $i),

and in function you could get that as given below

function form_remove_attachment($i) {
    $clicked = explode(' ', $form_state['clicked_button']['#value']);
   //$clicked[1] would have the value of $i

    $form_state['rebuild'] = TRUE;
}


How can I change active theme for specific paths or inside module? I'm working on an online game engine website where users can create games online and other can play it.

All pages are displayed in normal theme except game play page which should be in full screen mode inside a minified version of main theme.

I know themekey is useful and I can change theme with it. but I don't want use a complex module for this purpose. is there any API function for changing theme inside module on specific paths?

There are several modules you could use besides themekey:

Sections
Theme Rules (There is a 7.x branch, you'll probably need to check it out with Git)
Theme per path

Some of those are more focused for your task and don't have the overhead Themekey has (although it is a good module, just a bit heavy perhaps).


Create content of different entity by user programatically I am using an OpenSocial site, and writing a custom code that will create a post content by specific user. The post was created but assigning user is not working. How to properly assign userID to a post entity type?

use Drupal\social_post\Entity\Post;
...
    $node = Post::create([
      // The node entity bundle.
      'type' => 'post',
      'field_post' => $post,
      'field_visibility' => 1,
      'uid' => 2, // user = John
    ]);
    $node->save();

Actual result:

POST ID  POST   AUTHOR  CREATED                   OPERATIONS
1        Test   admin   Wed, 04/18/2018 - 10:19   Edit

Expected result:

POST ID  POST   AUTHOR  CREATED                   OPERATIONS
1        Test   john    Wed, 04/18/2018 - 10:19   Edit

The key is user_id, so presumably the correct code would be:

$post = Post::create([
  'type' => 'post',
  'field_post' => $post,
  'field_visibility' => 1,
  'user_id' => 2,
]);

$post->save();

I changed the var name to $post as it's not a node and you don't want to confuse those two things. I also removed the type as the social post entity type doesn't have such a field.


Can't add contextual Filter (taxonomy term ID (with depth)) to a View (User) please help me out here:

I can't find a contextual filter by taxonomy term with depth on a view of users and/or profiles. When I make a view of content it can be chosen.
I'd like to provide a filter for Regions, so Filter for Europe should result in a List of Users from all over Europe and so on.

The users are associated with a taxonomy term.

Thanks for your help or any suggestions.

Christian

In D7, you can only do that with the node table (the content).

If you want to have a working solution for every entity of your system, you have to use this module.

Once installed, don't forget to rebuild the index of your entities, then, in views, you'll have the possibility to add a new relationship ('Taxonomy Entity Index: Taxonomy terms on User') and a filter with depth ('Taxonomy Entity Index: Has taxonomy terms on User (with depth and indexed in taxonomy_entity_index)').


Local install of live site looks different Localhost site looks different than live site.

Drupal 7.37 > 7.5 (Commons), viewed in Chrome on Mac OS X.

Prep Steps:

installed a clone of the website from an outdated repository on my local machine
reconciled the code differences between the live site and the slightly outdated repository site
imported a current copy of the database from the live site.
featurized database configurations
updated most of the modules as well as Drupal core.
checked default theme and settings to make sure they are the same between sites

After noticing the problem:

downloaded theme files into respective locations
installed stage_file_proxy on local dev to load any files I ignored

Thematic Differences

From the moment I imported the database, until now, after all updates have been performed, there is a thematic difference between the live site and my local version. (The difference is slight, but annoying.)

live site is centered and contained, local stretches all the way across in some places but stays left aligned in others
some fonts are larger on local site
navigation menu splits itself to a new line early
live site has blocks on the right, local has one column with blocked content at bottom

Summary of Question

Is this a commonly known problem when certain steps are forgotten and is there another place to address configuration besides in the codebase and the database or is this probably not a theming issue but something else?

Update: I pushed the site up to my remote dev server anyways, to see if the problem was environmental or database and codebase. The remote dev looks perfect. There is definitely an issue with my local dev environment causing this somehow.

Sounds like some CSS files are not loaded on the local site. Or some additional or other CSS files are loaded on the local site.
Clear caches
First thing to start troubleshooting the local site is to clear the caches. Not only CSS/JS caches but all caches.
If the site has the Advagg caching module installed, then sometimes it is not enough to clear its cache by clicking the Administration menu link. Advagg cache might also need to be cleared by clicking the Flush AdvAgg Cache button on this path:  /admin/config/development/performance/advagg/operations
If the above does not help then on the same Advagg page there are more buttons to click, hidden behind the headings containing 'Clear' and 'Delete'.
Look at CSS with Firebug
Firebug is an addon for Firefox. Instead of this you can also use the browsers built in inspector by pressing F12(maybe another key on Mac).
See what CSS is different and if the CSS is taken from different files on live site vs local site.
Panels Page layout
Having blocks on the right vs bottom could also be affected by Panels Page layout. Check for that if the blocks are still wrong after you got all other thematic right by getting all CSS right.


Prevent empty  item in Views (HTML List format) I'm using the HTML List format for my View, which has three fields (nid and title, both excluded and Custom Text).

The content of Custom Text is as follows:

View Project

[title]

Lorem Ipsum

I've noticed that using the
 item in my Custom Text field will result in an empty
 item wrapping my content. As such, the output I get from this is as follows:

View Project

Item 1

Lorem Ipsum

View Project

Item 2

Lorem Ipsum

My question to you is: How do I remove those empty
 tags?

I tried to set wrapping element to none but to no avail. I've also attempted to do it with an unformatted list and create everything in custom text but then I'd have a
 for each row and I do not have access to data-content="#colio_c[nid] that way.

An export of my view is available at http://ideone.com/KyNGO4

It sounds like you want to override the row style output so that it doesn't output the wrapping li tag. There are other posts on here asking about that process. To get started though, in views, expand the Advanced section and click "Theme" - a window will then pop up showing you information on the template files for your theme.


How do I add a taxonomy vocabulary to more than one menus with the taxonomy menu module? I'd like to have two different menus based on the same taxonomy vocabulary, but the taxonomy menu module only lets me choose one menu to add the terms to.

Can I somehow add the same terms to more than one menu?

Try this: https://www.drupal.org/project/taxonomy_menu_block

Otherwise, you can use views to create blocks with links from a taxonomy vocabulary.


Alter value of field before loading I'm just wondering if its possible to alter a field before loading.

Here is the situation.

Im using commerce kickstart.

When I'm in a product page(inner page or product details page), I want to change the value of field_my_field before it load up to the page.

In pseudocode:
If field_my_field == "something" change field_my_field to "my custom value"

It is very easy! where do you want to display the field?

If it is a view, then you can use template_preprocess_views_view if it is a node, you can use hook_preprocess_node function to alter the values. where your content is going to be displayed?


How to configure Views to determine pages never visited by anonymous users? I want to find out and list the pages that never get visited by anonymous users. Google Analytics just shows pages that are visited at least once.

How can I configure views to create a kind of flag for "visited" or the like?

Thanks!

You may want to use the Flag, Rules and Views modules, as further detailed below ...

Step 1

Enable the Flag module, and create a global flag which you label something like "Visited by an anonymous user".

That way, later on, any node that is NOT flagged by this flag, is one of the  nodes that your question is about.

Step 2

Enable the Rules module, and create a custom rule that looks like so:

Rules Event: Content is viewed.
Rules Condition: Current user has role "anonymous".
Rules Action(s): Flag the node being viewed (using the flag from Step 1).

Step 3

Enable the Views module, and create a view of all nodes that are NOT flagged. Those are the nodes that have not been visited at least once by an anonymous user.

Step 4

After you complete (implement) the previous steps, the (Views) results you get are correct as of the date you completed the previous steps. If you do have some type of historical (logging) information available about anonymous users visiting nodes, it would be a matter of using that information to also "flag" those nodes, so that your (Views) results would become more accurate/complete. And if you can make that info available in the format of some view, you could use the Views Bulk Operations (VBO) module, combined with another custom rule to also flag those nodes.


In Views, when using a filter on a datetime field, what is the time zone of the offset? When I use an offset like "-4 hours" in a Views filter on a datetime field, which timezone is used?
More details
In Views, when I add a filter for a datetime field, I get the following options for Value type:

A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.
An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

On my site, users can set their own timezones. (/admin/config/regional/settings Users may set their own time zone)
So there are potentially three timezones in play:

In the database, the strings for datetime are stored in the UTC timezone
The site timezone is set to Tokyo
The user timezone is set to Berlin

So, which of these timezones does the offset use?

For datetime fields, it uses the timezone for the user viewing the page. If no user timezone is set, it uses the default site timezone.
See the relevant comment from Drupal\datetime\Plugin\views\filter\Date.php:

Date-only fields do not have a time zone associated with them, so the filter input needs to use UTC for reference. Otherwise, use the time zone for the current user.

/**
 * Get the proper time zone to use in computations.
 *
 * Date-only fields do not have a time zone associated with them, so the
 * filter input needs to use UTC for reference. Otherwise, use the time zone
 * for the current user.
 *
 * @return string
 *   The time zone name.
 */
protected function getTimezone() {
  return $this->dateFormat === DateTimeItemInterface::DATE_STORAGE_FORMAT
    ? DateTimeItemInterface::STORAGE_TIMEZONE
    : date_default_timezone_get();
}


Using t() with langcode in Drupal 7 I have a Drupal 7 setup with multiple languages (en and fr). In my template files I have a lot of t() texts which im translating using the i10n_client module. This works perfect for translating texts from en to fr IF the t() texts are written in english. However, what if I want to write my t() texts in Danish and being able to translate them to both en and fr? Meaning that the Danish version never will show up as long my Drupal setup only have en and fr as languages.

I tried using the options parameter with the langcode like this:

print t('Min tekst', array(), array('langcode' => 'da'));

But the translate-text interface (provided by i10n_client module) wont show up when I'm on the en site. Only on the fr site where I can translate it from en to fr.

Is this possible? And how?

The string (first parameter) always needs to be in English, from the Drupal 7 API:

  $string A string containing the
  English string to translate.

The langcode just means that the string will always be translated to Danish, no matter what the active language is. So if you'd be surfing the French site, you'd see the Danish string.

I'm afraid you'll have to translate your Danish strings back to English strings.


Can I show the answers to a previous round of questions in webform? I built a questionnaire on Survey Monkey and had 75 people fill it in. I now need people to repeat the same questionnaire (which I am rebuilding in Webform) BUT I have to show the option they previously selected and the average across the entire survey.

I have all previous answers in a mysql database, so what I would like to do is to drop the user-specific answers in.

i.e. Last time you answered ....

Is there any way to get Webform to do this (i.e. with the Markup feature possibly?) or is this beyond its remit? I have people who are willing to help me with this, but wanted to see whether the Drupal community had any ideas first.

EDIT

Perhaps I can give you an example. Say for the first round of the questionnaire you ask people:

How do you feel about cats?
1) Love them
2) Like them
3) Dislike them
4) Hate them.

A week later, you then ask people to repeat that same question, except the question looks like this.

How do you feel about cats?

Last time you selected 'Love them'

In the survey overall people made the following choices:
1) Love them 25%
2) Like them 40%
3) Dislike them 25%
4) Hate them 10%

Please now re-answer.

1) Love them
2) Like them
3) Dislike them
4) Hate them

Thanks for your help. I hope this is a bit clearer!

Your question is not completely clear, but as I understand you want to load a custom set of dropdown options as a webform element.

You can do that from a custom module with the following example code:

/**
 * Implements hook_webform_select_options_info().
 *
 * Defines a custom dropdown form element to be used with the Webform module.
 */
function YOURMODULE_webform_select_options_info() {
  $items['last_time_answered'] = array(
    'title' => t('Last time you answered'),
    'options callback' => '_YOURMODULE_get_options',
  );
  return $items;
}

/**
 * Generate "Last time answered" options for the current user.
 *
 * Used for sample webform element.
 */
function _YOURMODULE_get_options() {
  // Your query goes here
  // Return should be an array with $value => $label structure.
  return array(
    1 => 'Option 1',
    2 => 'Option 2',
    3 => 'Option 3',
  );
}

I also suggest to drop in a custom validator to the webform:

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

  switch ($form_id) {
    // Sample webform custom validation
    case 'webform_client_form_1':
      $form['#validate'][] = '_YOURMODULE_validate_custom_field';
      $first = array_shift($form['#submit']);
      array_unshift($form['#submit'], $first, '_YOURMODULE_validate_custom_field');
      break;
  }

}

/**
 * Custom validation function for webform component.
 */
function _YOURMODULE_validate_custom_field() {
  foreach ($form['#node']->webform['components'] as $element_id => $element) {

    if ($element['form_key'] == 'last_time_answered') {

      // Perform the check here
      if ($element['value'] != 'Sample value') {
        form_set_error('', t('Validation message.'));
      }

    }

  }
}

To use this custom field, create a new webform element (select options) and choose your new list from the "Load a pre-built option list" dropdown.


Node reference field share between two content types I have Two Content types Store and Deals and one Vocabulary named as Outlets. Outlet has many terms. I have added outlets as a term reference field to stores content type, and title field of store content type is added as a node reference field to deals.

1.Store content type
When I am adding a new store I am selecting some outlet terms for it and saving it.

2.Deals Content type
In Deals content type when I am creating a new deal
I am selecting any store in dropdown, which I have added here as a node reference of store content type.
What my concern is now while selecting any store title I want its corresponding outlets to be displayed here, so that if I wish I can uncheck some of them and then save.

Any help would be much appreciated.Please find the screenshot for better understanding.

Top Image is the store content type adding a store carters
Second image is the deals content type I am selecting the store which I have previously added in stores, now while selecting carters the corresponding outlets should get selected

I'm not sure you can do it with Conditional Fields, so I did it with a custom code. You have to :

Hook on your form
Get referenced node
Get its taxonomy value(s)
Check this values in your term reference field.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "page_node_form") {
        $form['field_OUTLETS']['#prefix'] = '
';
        $form['field_OUTLETS']['#suffix'] = '
';
        $form['field_STOREREFERENCE']['und']['#ajax'] = array(
            'callback' => 'MYCALLBACK',
            'wrapper' => 'mytaxofield',
            'method' => 'replace',
            'effect' => 'fade',
        );
    }
}

function MYCALLBACK($form, $form_state) {
    if(!empty($form_state['input']['field_STOREREFERENCE'])) {
        $nr = node_load($form_state['input']['field_STOREREFERENCE']['und']);
        foreach($nr->field_OUTLETS['und'] as $delta => $value) {
            // Add term to default values
            $form['field_OUTLETS']['und']['#default_value'][] = $value['tid'];
            // As it's not enough (I might need help on that one), I force it with the '#checked' value
            $form['field_OUTLETS']['und'][$value['tid']]['#checked'] = TRUE;
        }
        $form['field_OUTLETS']['und']['#default_value'] = drupal_map_assoc($form['field_OUTLETS']['und']['#default_value']);
    }
    return $form['field_OUTLETS'];
}


Redirection to home page I am working on a Drupal site. I have put a "Create an account" block on one of my content pages. After the form is submitted the user is redirected to the home page. I want to reload the same page on submit. Can anyone help me out with this.

Download and install this module http://drupal.org/project/login_destination

It is also possible to keep users on the currently visited page after logging in or out.

Hope it will match your requirement!!!


Hide the page titles of some content types I found following code on this website http://codekarate.com/content/hiding-page-titles-specific-node-types-drupal-6 to hide the page titles of some content types.

Can some one help me rewrite this for drupal 7 ??

function THEMENAME_preprocess_page(&$vars) {
  $vars['original_title'] = $vars['title'];
  if (!empty($vars['node']) && in_array($vars['node']->type, array('NODETYPE'))) {
    $vars['title'] = '';
  }
}

Just wanted to let you know that there is a module that does this Exclude Node Tittle


Execute a view without rendering I'd like to programmatically execute a view (providing arguments) and get the raw results, without rendering it. Is it possible?

When I use $view->preview('default', $args); it converts the results to HTML. I know I can use $view->result to iterate the raw results, but the custom rendered I'm using for some fields are buggy and give me a WSOD (I have no interest or ability to fix the renderer, it's an edge case :) )

I'm using Views 3 with Drupal 7

There is already a function that does exactly what you want:

  $result = views_get_view_result('my_view_name', 'default', $arg1, $arg2, ...);

Read more at its page at api.drupal.org:

https://api.drupal.org/api/views/views.module/function/views_get_view_result/7


How do I remove the trailing time zeros after the Date I'm using Drupal 8.4 Webform Module. I selected the Date element (not Date/time). In the Webform Date Settings, I'm using date picker, Medium date - D, m/d/Y (Mon, 11/27/17). (I also tried Custom, D, M j, Y.

I'm using this field in a View, Format = Default medium date and this is what I get, Thu, 12/14/2017 - 00:009:00 AMFri, 12/15/2017 - 00:005:00 PM
. How do I remove the trailing zeros?

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


Hide "language menu" next to search bar / login menu I have inherited maintanance of quite horrible looking website that is currently running version 6.x of Drupal. I am now trying to streamline / delete / disable as many unnecessary things as we can on the website.

http://sejong.ff.cuni.cz/

One of the features is a multilingual menu next to search bar / login menu. I visited the multilingual settings but I have been unable to find a way to get rid of that menu.

How can I achieve that? (I am new to Drupal so I am not sure if this is something that was custom put to the system or if it is a default Drupal feature)

Head over to relative path admin/build/block/list, to bring up a list of blocks configured for the theme that you're using. Pretty sure you'll find a block titled something like "language switcher" (or similar to that), which is locate in your "header" region (or some other theme region). Change that to <none> (to not show that block in any theme region. Then check if it solved your question.


Change permission on Content Overview page I have granted an admin 'Administer Content' permission under People->Permissions. This gives him the ability to publish/unpublish nodes. But I don't want him to be able to go to the Content overview page where he can delete and unpublish in bulk. This is because I have setup certain workflow rules with node_validate which only let him delete or unpublish nodes under certain conditions within the node edit screen. If he goes to the Content overview page, he can circumvent the workflow logic.

So how do I programmatically take 'Administer Content' permission away when he goes to the Content overview page? I still want him to be able to see the Content overview, but I don't want him to be able to unpublish, delete, or do any of the other bulk operations.

Any thoughts would be appreciated.

This is such an old question, but I had the same question and hiding it in css is not the answer.

The correct answer IS to enable the Actions permissions (VBO) (actions_permissions) module.  That will allow you to set which roles can perform bulk operations.


Member list with Demographic Data - is there a module or how do I build a View? I want to be able to do a Member Directory page that when clicked, displays a sortable view of Users, including First name, Last name, etc.

Is there a module for this or how do I build a View?

Creating a view of type user will allow you to extracts necessary user and profile fields to list in you view.

Go to admin/build/viewsthen click onAdd.
Define view name, description, tag and select view type as user.
Add you display type page or block
Alter/Override views settings
Add fields, the list can expand
Select view's format style as table, and configure this style for fields to sortable.

For demography point of view there are few date specific fields like created, last login.

This list can grow depending on module extending user entity e.g. profile


How to process an http request with a controller? I try to write a custom Restful API to send contents between two drupal site. The present code work except the datas are in a weird format with @ in the json.

My resquest is:

$serializer = \Drupal::service('serializer'); $data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);

$response = \Drupal::httpClient()
        ->post("http://site1.test/api_test/send_content", [
          'headers' => [
            'Content-type' => 'application/json',
          ],
          'json' => $data,
        ]);`

The function which process my request:

public function createNewContent(Request $request) {

   if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {

     $data = json_decode( $request->getContent() );

     \Drupal::logger('test_rest_api')->notice($data);
   }

   $response['data'] = 'Query well received';
   $response['method'] = 'POST';

   return new JsonResponse( $response );
}

The problem is, after the json_decode my datas let a big string and look like:

  @"nid":[{"value":5197],"uuid":[@"value":"8310f782-06ce-4fb8-957d-ec7feecc8929"],"vid":[@"value":63527],"langcode":[@"value":"en"],"type":[@"target_id":"page","target_type":"node_type","target_uuid":"189f826c-e516-4a22-8d4d-f3a2f418aea9"],"revision_timestamp":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"revision_uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"revision_log":[],"status":[@"value":true],"title":[@"value":"Test"],"uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"created":[@"value":"2017-12-19T21:07:57+00:00","format":"Y-m-d\TH:i:sP"],"changed":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"promote":[@"value":true],"sticky":[@"value":false],"default_langcode":[@"value":true],"revision_translation_affected":[@"value":true],"moderation_state":[],"content_translation_source":[@"value":"und"],"content_translation_outdated":[@"value":false],"metatag":@"value":{"title":"Test","og_site_name":"Test","shortlink":"http://site1.test/en/node/5197/sendContent","canonical_url":"http://site1.test/en/node/5197/sendContent","og_type":"article","og_url":"http://site1.test/en/node/5197/sendContent","image_src":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_title":"Test","og_description":"This
  is a
  test","og_image":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_updated_time":"2017-12-19T16:08:36-05:00","article_published_time":"2017-12-19T16:07:57-05:00","article_modified_time":"2017-12-19T16:08:36-05:00"},"path":[@"alias":"/test","pid":16287,"langcode":"en"],"rh_action":[@"value":"bundle_default"],"rh_redirect":[],"rh_redirect_response":[@"value":301],"publish_on":[],"unpublish_on":[],"menu_link":[],"body":[@"value":"\u003Cp\u003EThis
  is a test\u003C/p\u003E","format":"full_html","summary":""]}

I precise the @ are already present before the json_decode. I don't know where I could have made a mistake.

I suppose I can clean it easily but I'm more interested to understand what is this format and how can I convert it properly and quickly.

Ok, my problem was the serialization. To recover my node object in my function of POST, I should deserialize the json with the function:

 $data = \GuzzleHttp\json_decode( $request->getContent(), TRUE);
 $serializer = \Drupal::service('serializer');
 $node = $serializer->deserialize($data, \Drupal\node\Entity\Node::class, 'json');

 $new_node = Node::create(array(
   'type' => $node->bundle(),
   'title' => $node->title,
   'langcode' => $node->language()->getId(),
   'uid' => '1',
   'status' => 1,
   'body' => $node->get('body'),
 ));

 $new_node->save();

Now, I can manipulate my node like I want in my other website.


How do I create a block in a module that can be referenced via an entity reference field? I'd like to be able to reference my programmed block as a field in a paragraphs.
I've

Generated a module with drupal console - drupal generate:module
Used the template for a block from the example module. Only has Plugin/Block/MyBlock.php

I create a new field in my paragraph

Field type Reference
choose other

How do I get the block to be able to be embedded in this way?

To achieve this you may use the Block field:
From module description:

Use Cases
Add blocks to a node's sidebar.
Add blocks to paragraph.
Create a carousel of content and configurable blocks.

install and enable the module
Create a new field of type Block(plugin) in your paragraph type
In case you want only your custom block to be referenced in the field settings uncheck all other blocks in the AVAILABLE BLOCKS config like this for my Hello block for exemple

now you can reference your block in the paragraph.


Module Library JS Some In Header Some In Footer I have read that Drupal 8 by default loads library-defined files into the footer. My module libraries.yml file makes use of the "header: true" property as several JS files are needed to load in the header. However, now I need to add another JS file to the library, but this new file must load in the footer / just before the closing of the body tag.

How do I modify my libraries.yml file to make this JS file the only footer-loading one?

modulename:
  version: 1.x
  header: TRUE
  js:
    headerfile1.js: {}
    headerfile2.js: {}
    footerfile1.js: {}
  css:
    component:
      css/style.module.css: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

Just add it to your *.libraries.yml as an additional library this time without header: TRUE. And maybe better place all your JS files in a subfolder named /js.

headerlibs:
  version: VERSION
  header: TRUE
  js:
    js/headerfile1.js: {}
    js/headerfile2.js: {}
  css:
    component:
      css/style.module.css: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

footerlibs:
  version: VERSION
  js:
    js/footerfile1.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Then attach everything as usual:

/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {

  $attachments['#attached']['library'][] = 'MYMODULE/headerlibs';
  $attachments['#attached']['library'][] = 'MYMODULE/footerlibs';
}

From the docs:

  Asset loading order

  As you would expect, the order in which the files are listed is the
  order in which they will load. By default, all JS assets are now
  loaded in the footer. JS for critical UI elements that cannot be shown
  unless their corresponding JS has run can be loaded in the header if
  needed like so:

js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

  Set the header property to true, to indicate that the JavaScript
  assets in that asset library are in the 'critical path' and should be
  loaded from the header. Any direct or indirect dependencies of
  libraries declared in this way will also automatically load from the
  header, you do not need to declare them individually for them to be
  available. This is the meaning of the phrase 'critical path', once an
  asset is declared to be in the header it is 'critical' for that asset
  and all of its dependencies to load first.


How to get logged user id? I am developing a moule which has one page asking for email frequency; when the user selects and save it, I save it in the user table, but it doesn't work. It works only when I hard code the user ID.

global $user;
$uuid = $user->uid;

function emailf_form_submit($form, &$form_state) {
  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}

It works when $uuid is initialized inside the function.

function emailf_form_submit($form, &$form_state) {
  global $user;
  $uuid = $user->uid;

  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}


Title tag not overriding after using meta tag module I have created a content type for uploading user details. I have changed the title as UPLOAD PAGE using drupal_set_title. I have installed Meta Tag module, now page title remains same but title tag i.e. (title displayed in browser tab) are different. Please guide me. Thanks

Try theme_preprocess_html and modify the title using variable header_title

Sample code:

function mytheme_preprocess_html(&$vars) {
  $vars['head_title'] = 'TITLE';
}

It works for me.


Move aggregated JS file to the footer Is there a method of moving the aggregated JS files to the footer?   I've taken a look at hook_js_alter but that just gives me access to the individual files, not the aggregated ones.

I would prefer to not move the $scripts variable to the bottom of html.tpl.php

Any tips would be appreciated.

Found this excellent code snippet for Drupal 7: https://gist.github.com/pascalduez/1418121

It offers a way to have $script and $head_scripts so that you can specify which JS files need to go in the head. Example, Modernizr should go into the head scripts.

I'm copy pasting below the solution in the link to future proof the answer.

Cheers.

html.tpl.php

<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>

<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>

template.php

// Used in conjunction with https://gist.github.com/1417914

/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}

/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}


How to allow users to attribute accumulating points to nodes? I would want to make a thing in priori simple: allow users to attribute (grant) a selectable amount of accumulating points to nodes.

I tried various modules (Fivestar, etc.), but these modules are about a note (or a score like '4/5') and not of a number of accumulative points.

It would be necessary from a field (for example list of selection), make increase or decrease the value of another field.

Anybody has an idea?

Notes:

Fivestar allows to give a note (for example: 4 on 5), while I wish to give points which accumulate. Points: simple value. Give X points to this node. For example: I give 5 points to this node because I find this a good node.
Multiple users could give a different number of points. The functioning would be close to Fivestar, except that instead of having an overall average there would be a total number of points.
There would be a field of a node which stores the accumulation of points, and possibly one other to give points.

Step 1 - Use the Flag module

I'd definitely use the Flag module for what you're trying to achieve. To allow authorized users (to use such flag) to flag relevant nodes. Maybe you want to limit them to only selected content types also.

Step 2 - Add a field to a Flag to specify the points

However, to also implement those points to nodes that get flagged, you should configure the flag (you only need 1 flag!) by attaching a field to such flag. Such field can then be used to enter, or select, any of the allowed values of points you want to be granted (appointed) to a node that gets flagged by such flag.

However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

  By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.

  Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

Step 3 - Add some 'Total points' field to your nodes

Define some other field in the content types for the nodes you want to use these points for, which will contain the total number of points. And which will get updated each time a node gets flagged with '+X' (or '-Y') points, as explained in the next step.

Step 4 - Use the Rules module to maintain the value of the 'Total points'

The Rules module integrates extremely well with the Flag module. So it should be fairly simple to create a rule to maintain the value of the 'Total points'. Here is a blueprint (to avoid writing an entire manual ...) of this rule:

Rules Event: when a node is flagged (with the flag you created in step 1)
Rules Conditions: whatever you might need (if anything), on top of what is not yet covered by the way you configured the flag.
Rules Action(s): Perform some Rules Actions that use the value of the points as specified by the user who flagged the node, and then adds that to the current value of the 'Total points' field. For an example of such calculation, refer to this answer to the question about "How to add up all items of a field collection field using Rules?". In your case here, you don't need the 'loop' (you're not processing a field collection, only 2 fields for which you want to calculate the sum of it).

Summary

Using Flag (with 1 extra field) and Rules, and by adding a field (for 'Total points') to relevant content types, the above is how you can create something similar to what User Points can do, though with a summary like so:

  provides a technique an API for nodes users to gain or lose points for selected nodes performing certain actions on your site.

And btw ... zero custom code involved ...