Should the Drupal 8 sites/default/files/config folder be stored in git with its hash suffix? New question title: "Should the sites/default/files/config folder be stored in git with it's hash suffix?"

" Reason I ask this is that this might cause 2 issues:

May be a hindrance when comparing code bases of sites, the diff comparison program would not be able to compare the contents of the config folder directly, if the suffixes are different.
If the site is a open collaboration project, where the code is put on github or bitbucket publicly, then the config hash suffix which is normally secret would be visible to the public and therefore the folder can be determined but the intent was to use the hash to make the folder harder to guess for security reasons.

Original question title: "Why does the Drupal 8 config folder have a long gibberish-like name, e.g.: config_wNOLcm... etc?"

Answer to the question about the 'gibberish' is:

  This sequence is a random hash generated during the installation of
  your Drupalvsite. It is used to add some protection to your
  configuration files. Additionally to the default restriction enforced
  by the .htaccess file within the subdirectories of the config
  directory that prevents unauthorized users from seeing the content of
  the directories. As a result, would be really hard for someone to
  guess the folder's name.

Credit: Drupal 8 Configuration Management, First published March 2015, page 29

Some general references:

https://www.drupal.org/node/2360331#how-do-i-version-my-

In the site install process, Drupal will write the configuration directory path to settings.php.
Any other deployments of the site would then make use of the directory defined in settings.php.
The hash itself is not information that needs protection, but it helps make the configuration harder to find in case it were not properly protected from public access.
If you're making your entire configuration public in a repository, it is important to check that it does not contain any compromising information (e.g. API keys).

The configuration should be protected by .htaccess (which core does by default) if it is in a publicly accessible directory, making it impossible to read and not just difficult to find.

It is possible to move the sync directory to another location.
Pantheon places it in sites/default/config, with an .htaccess file to protect it.
Alternately, setting up your repository so that Drupal is not in the root folder (as Acquia does) will allow creating a configuration directory that is outside of the document root.

/
|-- docroot
|    |-- core
|    |-- modules
|    |-- ...
|
+-- config
     +-- sync


Can't Rewrite the output of this field in views 7.x-3.3 I don't know if I am missing something, but when I check the box for Rewrite the output of this field or anything under the style options to customize the HTML nothing happens. I check it, save it, open it again and the boxes are unchecked. Anyone know what’s going on?

Edited for clarity. I create a new view, with the following settings: Page, Format:Unformatted list, Show:Fields, Fields is Content: Title. In the settings for Content: Title I check to create a label.
I click under “Style settings” Customize field HTML, Customize label HTML, Customize field and label wrapper HTML or even Rewrite the output of this field, but nothing happens. If I save the checkbox goes back to unchecked

SOLUTION Got it. Views 7-3.3 does not work with jQuqery 1.7+. It prevents the box from expanding after clicking the checkbox

Source: http://drupal.org/node/1494860


Is there a way to add a wrapper class to my blocks? While views does a great job of placing blocks and content on a page, I am trying to make my website responsive. It is true that the blocks are responsive. I am just trying to make it so that the blocks take up a percentage of the screen rather than go below another block when the screen shrinks. I found a way to do this using CSS, but I would rather use standard Drupal methods so that my users can edit content. There is a nice module that lets you define a class on each block, and I am using it. I am just wondering if there is something similar so I can define a wrapper of several blocks. I am using Drupal 7.

If I understand you correctly, you can use the Theme Developer module to inspect the block itself.  You will be able to take the default block template out of the main theme directory, rename it accordingly, and then edit it to have your class.  This is not the best way to achieve this result, but it will work. Make sure to disable the module when you are done using it.

In addition to that, the block themselves will have their own independent ids "#block-block-17".  A little more painful to work with, but if you don't have that many it could be another solution for you.


How to customize my front page with background image? I have site for which I need to design a custom front page using my sub-theme with page page--front.tpl.php.

I need to place a background image and on title at left alignment and little bottom thre image background buttons and in that bottom center need to place on caret with hyperlink which will take you to rest of the half page.

Any suggestion?

Try eiher of hese searches:

Specific to sub-theme topics.
Specific to front.tpl.php.

Pick any of the proposed answers that fits best your needs. Such as a solution that is based on using something like firebug to find the CSS file that allows you to adapt your background to fit your needs.


Webform show result table on webform node tpl I am trying to display results of a certain content type (webform: event)

So my idea is that i would embed the table into the the tpl (node--event.tpl.php)
I tried many different ways and the closest i can get is the following code

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 4));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '
';print_r($row);print '
';
        print '
';print_r($data);print '
';
    }
}

This works but just for a single node, in this case node 4, I would like to show this of the current node.

Try the Webform Report module, it looks perfect for what you need.

Or, Why not use views?

It would be easier to use webform 7.x-4.0-rc3 and create a view table for webform submission data. You can easily grab the separate values and arrange them into a table.

You also have the ability to create a reference so only the results from node 4 are being shown.

EDIT:
use $node->nid; , so...

$nid = $node->nid;

module_load_include('inc','webform','includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> $nid));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '
';print_r($row);print '
';
        print '
';print_r($data);print '
';
    }
}


Attach a form input to a node that will be submitted by multiple users I'm trying to create a content type that serves as a "Contest". Each contest needs the ability to upload an image by the user. Basically, I'm looking for the best way to attach a form field (file upload) to each Contest and be able to monitor all submissions, and by a user basis, for each individual contest, separately.

I've looked into Webform and Entityforms, but kind of running into road blocks. Does anyone have any suggestions?

You can achieve that by the Webform module. or
Try the Simple Contest module

Simple Contest module provides contest system for Drupal websites.
Features:

contests are nodes. multiple contests of multiple contest type can be    run same time
Two winner types : Users & Node, that means winners can be "user" or    node"
multiple winners can be chosen by ranking/weight
Supports both automatic and manual winners selection
Winner chosen rule will be based on View. so it is up to you to    decide how the winner will be selected
Modules integration with Views, Token, Rules, Userpoints, Date    Repeat, Commerce Coupon, UC Gift Certificate & UC Coupon
Token integration and customized E-mail notifications

Please note the this module is in dev version. So try that in local (test) environment.


Send message notification when license expired I have a commerce site where I sell subscription using the Commerce License module. I want to send email notification to users whose licenses will expire soon.
I'm trying to do that by creating a custom module. I have 2 code snippets, one to notify users when the license expires, the second to send email using the Message Notify module.
I don't know what variables I should use to have the licence owner's.
This is my custom module and the code works well for me.
    /**
     * Implements hook_cron().
     */
    function license_notif_cron() {
      $expires = strtotime('-1 day');
      $query = new EntityFieldQuery();
      $query
        ->entityCondition('entity_type', 'commerce_license')
        ->propertyCondition('status', COMMERCE_LICENSE_ACTIVE)
        ->propertyCondition('expires', 0, '<>')
        ->propertyCondition('expires', $expires, '>');
      $results = $query->execute();
      if (!empty($results['commerce_license'])) {
        $license_ids = array_keys($results['commerce_license']);
        drupal_set_message('licensce expires soon');
        //send message
      }
    }

This is an example of sending a message. I am not interested in hook_node_insert(); I already created a new message type (licence_expire_soon).
/*
 * Implements hook_node_insert().
 */
function foo_node_insert($node) {
  $message = message_create('foo_message_type', array('uid' => $node->uid));
  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_node_ref->set($node);

  $options = array(
    'rendered fields' => array(
      'message_notify_email_subject' => 'field_rendered_subject',
      'message_notify_email_body' => 'field_rendered_body',
    ),
  );

  message_notify_send_message($message, $options);
}

To glue the bits you have together you need to relate your to-be-expiring-soon license with a uid which can feed into message_create. So something like this in your hook_cron call...

//...after assigning $license_ids

foreach($license_ids as $license_id) {

   //...@TODO: checks on previous alert messages

   $uid = db_select('commerce_license','cl')
     ->fields('cl', array('uid'))
     ->condition('license_id', $license_id)
     ->execute()->fetchField();

   //...@TODO: code for executing message_notify_send_message and sending message to $uid
}


Order a text field numerically in views I need to reorder my views results before display it.

This is my query

SELECT
commerce_product_field_data_field_magazine__field_data_field_numero.field_numero_value AS commerce_product_field_data_field_magazine__field_data_field, node.nid AS nid
FROM
{node} node
LEFT JOIN {field_data_field_magazine} field_data_field_magazine ON node.nid = field_data_field_magazine.entity_id AND (field_data_field_magazine.entity_type = 'node' AND field_data_field_magazine.deleted = '0')
INNER JOIN {commerce_product} commerce_product_field_data_field_magazine ON field_data_field_magazine.field_magazine_product_id = commerce_product_field_data_field_magazine.product_id
INNER JOIN {field_data_field_tipo} field_data_field_tipo ON node.nid = field_data_field_tipo.entity_id AND (field_data_field_tipo.entity_type = 'node' AND field_data_field_tipo.deleted = '0')
LEFT JOIN {field_data_field_numero} commerce_product_field_data_field_magazine__field_data_field_numero ON commerce_product_field_data_field_magazine.product_id = commerce_product_field_data_field_magazine__field_data_field_numero.entity_id AND (commerce_product_field_data_field_magazine__field_data_field_numero.entity_type = 'commerce_product' AND commerce_product_field_data_field_magazine__field_data_field_numero.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('magazine')) AND (field_data_field_tipo.field_tipo_value IN  ('rivista', 'dvd')) ))
ORDER BY commerce_product_field_data_field_magazine__field_data_field ASC

and it works fine but I need the same view with a different ordering

ORDER BY ABS(commerce_product_field_data_field_magazine__field_data_field)

because the result's now order like

1 10 11 2 3 4 ..

but I need

1 2 3 4 10 11 ..

How can I achieve this changing of ordering?

ps_ I can't change the text field type to int because I have some value like '5-6'

Can you use views instead?
The Views Natural Sort module may help you

Otherwise, in drupal 7 you can go with

$query->orderby( 'CAST(n.title AS SIGNED)', 'ASC');

Check also  CAST Mysql documentation


How to make a specific template according number of nodes in a content type? I have a content type article and I need a specific template for showing articles according the number of nodes.  If I have 2 nodes (content type article) I need to make a template, if I have 3 nodes (content type article) I need to make another template.  How do you suggest to make that?

I don't know how to swap template files with panels I only know how to modify the layout based on condition, sorry. here's a small little snippet i quickly wrote to display a different template based on the number of nodes inside of the content type. This should really be done with a custom module but I don't have time.

Make sure templates are in template folder under your theme and named correctly.
Copy paste snippet below into your template.php file.

function YOURTHEME_preprocess_node(&$vars) {

if($vars['type'] == 'article'){
     // set content type
     $content_type = 'article';

     // Count number of articles in article
     $query = "SELECT COUNT(*) amount
               FROM {node} n ".
              "WHERE n.type = :type";
     $result = db_query($query, array(':type' => $content_type))->fetch();

     // get number of articles
     $articleCount = $result->amount;

     //specify template based on number of articles
     // one - is equal to _ and two -- is equal to __ for template file
     // No need to add `.tpl.php`
     if($articleCount == 1){
         $vars['theme_hook_suggestion'] = 'page__template1';
     }
     if($articleCount == 2){
         $vars['theme_hook_suggestion'] = 'page__template2';
     }
     if($articleCount == 3){
         $vars['theme_hook_suggestion'] = 'page__template3';
     }
     // ect.... you should make a dynamic loop here this is just basic logic.
   }
}

Modify code to your liking
Clear Cache


Fuzzy image display on new content type I'm having issues on our Drupal 7 site. We have created a new content type that includes a hero image. The problem is that full sized images that we upload aren't displayed on the page (despite calling for "Original image" in the manage display settings.

Instead, the page is displaying the image in Drupal's "large" image style, then scaling up on the page and creating a blurry image.

Here's a test page: https://claremontmckdev.prod.acquia-sites.com/content/history-0

Based on the markup on your test page reflecting an html5  element and the code snippet calling for a "picture_sizes_formatter", I suspect your site has the Picture and Breakpoints module) installed which automatically serve images based on predefined/configured breakpoints.

Go to the Picture Mappings configuration page Config >
 Media > Picture Mappings (/admin/config/media/picture) to examine existing mappings and add new ones.

You should be able to add a new picture mapping for a wider breakpoint to serve the original image, thus limiting serving the large image to a narrower desktop viewport.

Once you've added an additional mapping (and possibly a wide breakpoint), don't forget to clear the caches before reloading your test page.


Authenticate using OAuth I'm working on wrapping my mind around decoupled Drupal 8 while using an AngularJS app for the frontend. What I am trying to do is to allow a user to authenticate with my D8 site using their username and password, and then provide them with an OAuth token which will allow them to continue to make requests.

What is the correct flow in order to allow this type of authentication?
Is this the correct way to go about things? From what I understand basic auth isn't nearly as secure as OAuth, so I'd rather stay away from that.

I've been messing around with the simple_oath module and jDrupal, but they don't seem like they are quite "there" yet. Any suggestions?

Part of the problem I'm having, is figuring out where the OAuth modules end, and where my module needs to begin.

[Edit] I've heard conflicting things about cookie/session authentication. My end goal is to turn this into an app. Does cookie/session storage work with a mobile environment?

Thanks!

I think you're desire to use Oauth is justified. However, if you have no other options, you can use Cookie authentication. I have used it before and have heard of people using it as well. Here are some things to keep in mind and you'd be good to go with Cookie auth with your mobile application:

You will have to increase the session timeout time to a long period, say, 1 year or more. This means that after the period, the user would have to be asked to login again. Alternatively, you can refresh the Cookie with each request. You will need to:

Change session settings in PHP settings
Change session settings in Drupal settings

You will have to authenticate the user and then have a mechanism to persist the user's Session ID using a Set-Cookie header.
You will need to have a mechanism to handle sign-in failure when the session cookie has expired. When the session expires, you can send the user to the sign-in page again (maybe with the username field pre-populated) and ask then to sign-in again.
Since leaving a session long open poses to be a security threat, you might consider using other mechanisms like CSRF tokens.

Note: If you are in the mood for experimentation, you can also look into JWT authentication. Also, if you expect to have a huge user-base, you might consider a service like Firebase for storage.

Hope it helps. Happy coding!


Create a public profile page for specific roles only Here is what I am trying to do.

I used profile2 to create an employee profile type that only users with the user role of employee could fill out.

What I want to do with views ( which I am not even sure if its possible) is have views create a profile page for each employee with a path of about-us/[user:full-name] (a field I created for the employee profile) and only create it for employee user.

Any help would be appreciated, thanks.

It seems that what you are looking for is to modify the URL structure. In my mind, View is for the layout. Since I assume you have a content type for Profile2 profiles, you can simply install PathAuto and configure it so your URLs have that structure.


Node is flagged, flag has node reference field, how to show list of referenced nodes to author This is a little convoluted, so I'll try to be as clear as possible by using concrete examples.

It's basically a "relevant job suggestion" system. It works like this:

A "candidate" user creates a "CV" node.
An "employer" creates "job" nodes.
There is a flag set up that is attached to CVs.
This flag has a node reference field.
When an employer flags the CV, they choose a job node to reference (suggest)

I want to display a view of all job nodes suggested for that candidate - visible only to them (the author of the flagged node).

I hope that makes sense. I think the part I'm struggling with is getting the relationships & contextual filters right, so any pointers there would be appreciated.

I would have an entity reference field for the user where their CV node is referenced. (Using rules on node creation). Helps in many ways.

In views, the contextual filter would be getting those CV nodes using the entity reference filter.

Then in the relationships, you would pick the appropriate flag and it should display the relevant job postings.

I'll test this tomorrow as its very similar to something i did before. I might be off on the contextual filter but i think you should definitely use entity reference from the beginning.

Edit: I'm actually quite certain you should be able to do this without entity reference or rules. Filter the view using Job content type. Then two relationships, one for node authored and flag.


How do I create a view with mixed languages, showing the node's original language by default? I have a site with mixed languages, Spanish and English. Some content was originally created in English, then translated into Spanish. Other content was originally created in Spanish, then translated into English. The remaining content is either in Spanish or English and is not translated.
How do I create a view that shows all of this content in the original content (non-translated) language, showing a view with a mix of English and Spanish? Then if the user chooses English or Spanish, it will show only those languages.

To show only the "original" nodes in any language don't include any language filters so all languages are shown. This will show all your content, translated or not in both languages.
It's not clear from your question what you mean by "that shows all of this content".
If you want to show only the nodes that were originals, and not a translation of another, add the Source translation Filter from the Content translation Category. Set it to Include untranslated content: Yes if you want only the nodes that haven't been translated yet.
Set it to No if you only want to show nodes that already have a translation node.
I'm guessing you'll want the No selected, or you won't need the Content translation Filter filter at all.
Then add the Content: Language Filter and Expose it to allow visitors to filter the language. Select only the two specific language options and the Limit list to selected items if you only want those to be the options your visitors see and are able to choose (so they don't see options like "Site default", "Current", etc).


Use background images without knowing programming? I'm trying to set up a site using Drupal 7, and have very little knowledge of the stuff under the hood.  If the answer is to edit some css, please give VERY simple instructions.

Is there a simple way to put background images in the Acquia Marina theme?

Or, are there similar looking themes that have this facility built in?

Thanks!

You should change the body background selector in the css file of the template, for example

body{ background: url("path to image");}

More info how to use background css


Callback on 'save' on 'new node form' doesn't fire UPDATE:
Approach showed bellow has the same results -> doesn't work.

$new_form['#submit'][] = '_fmu_new_firm_under_user';

Separate button with only that callback doesn't work either. And what's weird, even if it has only the '_fmu_new_firm_under_user' callback it actually works the same way as 'save' button -> it saves the node and doesn't fire my callback.

$new_form['actions']['submit_and_create'] = array(
    '#type' => 'submit',
    '#value' => t('Vytvořit firmu'),
    '#submit' => array('_fmu_new_firm_under_user'),
  );

Original message

I've created a page with a 'myContentType_node_form' and attached a callback to the save button. The problem is that the callback is not fired when I press the button. To be more specific the default callback is fired - the node is saved - but my callback is not fired.

function _fmu_register_new_user_firm_callback($uid, $control_hash) { //a callback function for a menu item
      include_once(drupal_get_path('module', 'node') . '/node.pages.inc' );
      $new_form = node_add('fm_firm');
      $new_form['uid']['#value'][] = $uid;

      $new_form['actions']['preview']['#access'] = false;
      $new_form['actions']['submit']['#submit'][] = '_fmu_new_firm_under_user';

      dsm($new_form);
      return $new_form;
  }

function _fmu_new_firm_under_user($form, &$form_state) {

  $user = user_load($form['uid']['#value']);
  $user->fmu_users_firm[LANGUAGE_NONE][0]['target_id'] = $form->nid;
  user_save($user);

  dsm($user);
}

DSM of the form before returning it:

actions (Array, 16 elements)

    #type (String, 7 characters ) actions
    submit (Array, 23 elements)
        #type (String, 6 characters ) submit
        #access (Boolean) TRUE
        #value (String, 4 characters ) Save
        #weight (Integer) 5
        #submit (Array, 2 elements)
            0 (String, 16 characters ) node_form_submit | (Callback) node_form_submit();
            1 (String, 24 characters ) _fmu_new_firm_under_user | (Callback) _fmu_new_firm_under_user();
        #input (Boolean) TRUE
        #name (String, 2 characters ) op
        #button_type (String, 6 characters ) submit
        #executes_submit_callback (Boolean) TRUE
        #limit_validation_errors (Boolean) FALSE
        #process (Array, 1 element)
        #theme_wrappers (Array, 1 element)
        #defaults_loaded (Boolean) TRUE
        #tree (Boolean) FALSE
        #parents (Array, 1 element)
        #array_parents (Array, 2 elements)
        #processed (Boolean) TRUE
        #required (Boolean) FALSE
        #attributes (Array, 0 elements)
        #title_display (String, 6 characters ) before
        #id (String, 11 characters ) edit-submit
        #ajax_processed (Boolean) FALSE
        #sorted (Boolean) TRUE
    preview (Array, 23 elements)
    #theme_wrappers (Array, 1 element)
    #process (Array, 2 elements)
    #weight (Integer) 100
    #defaults_loaded (Boolean) TRUE
    #tree (Boolean) FALSE
    #parents (Array, 1 element)
    #array_parents (Array, 1 element)
    #processed (Boolean) TRUE
    #required (Boolean) FALSE
    #attributes (Array, 1 element)
    #title_display (String, 6 characters ) before
    #id (String, 12 characters ) edit-actions
    submit_and_create (Array, 3 elements)
        #type (String, 6 characters ) submit
        #value (String, 15 characters ) Vytvořit firmu
        #submit (Array, 1 element)
            0 (String, 24 characters ) _fmu_new_firm_under_user | (Callback) _fmu_new_firm_under_user();

You would be better off using hook_node_submit which would fire when any node is submitted.

You can make it specific to your node by the following:

function MODULE_node_submit($node, $form, &$form_state)
{
    if ($node->type == "NODE-TYPE")
    {
        //do stuff
    }
}


Creating a "tag blacklist" for users on a view I'm looking to allow users to create a "blacklist" of certain tags on a site. My plan was to do this through adding a "Blacklisted Tags" field on the user entity, but I'm open to other solutions.  If an item is tagged with a tag they've blacklisted, it won't appear in a view.  Is there a way to do this using default views functionality? If not, what's the simplest way to achieve this?

I guess using the ER field on user profiles is the easiest way, it all depends on your requirements.

If you need users to interactively "mark" tags on tags pages or through some other places you could use Flag modules and let them flag tags to blacklist them by simply clicking on the "Blacklist" flag link.

Either way you can build Views that show only content that hasn't been tagged with those.

Add the Contextual filter for the Blacklisted ER field (Default value...) then under More check the Exclude. This way your list will not show any content that has blacklisted tags.

Of course, your Contextual needs to be configured properly but there are many answers here you can find with all the options listed.

Flags views take some more steps to configure but the logic is the same.


Need a solution to search by sales person based on unique territory I've been researching for hours for a solution, but I can't find a module or example of someone else needing this feature.

I have a list of 20-ish sales people, each person is assigned a range of zip codes. Some of them are entire states, but there are a few sales reps where the state is split between 2-3 people. I need a way for the user to enter in their own location and show which sales rep would be their point of contact.

Anyone have an idea of how I would go about doing that? Location module?

Thanks!

Found something that might help you Locator tutorial and use Location Map if you want to display the results in a map.


All custom fields are missing in views 'add field' and 'add filter' forms (Drupal 7) I'm experiencing some very bizarre behaviour on a live website.

I've just added a new date field to a bunch of content types. I now need to add this as a filter criterion to a view. The problem is that when I go to add the filter, it doesn't show any custom fields at all in the Add Filter list, and this is the same for Add Field. It happens in all views.

The really strange thing is that I've copied the live database down to my local dev machine to debug, ensured that I have the live tag checked out, and on my local machine it works absolutely fine.

I've tried clearing caches, logging in as a different user, disabling a new custom module (which shouldn't make any difference). I just don't get what could be causing this, because the code and db are exactly the same in the live and local environments.

Almost certainly I'm overlooked something small. Can anyone think what it could be? Has anyone seem this weirdness before?

Thanks

To add to james-geldart's answer, I solved this same problem permanently (or for a few hours so far at least) by deleting every row of the table cache_views in the site's database.


Drupal 6 Pager not working I am using pager_query and theme_pager function as below.But unfortunately the pager is not getting displayed.Please help.

function advanced_product_search() {
    $output = "";

    $sectors = $material_types = $resource_types = array();
    $where_array = array();
    $node_data = array();
    $product_query = "SELECT n.* FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid ";
    $product_count_query = "SELECT COUNT(DISTINCT(n.nid)) FROM {node} n
        INNER JOIN {term_node} tn ON n.nid = tn.nid ";

    $product_query .= " WHERE n.type = 'product' ";
     if(isset($_POST['keyword']) && !empty($_POST['keyword'])){
        $key_word = check_plain($_POST['keyword']);
        $product_query.= " AND n.title LIKE '%$key_word%' ";
        $product_count_query.=" AND n.title LIKE '%$key_word%' ";
    }

    if(!empty($_POST['sector'])){
      $sectors = $_POST['sector'];
    }

    if(!empty($_POST['material_type'])){
      $material_types = $_POST['material_type'];
    }

    if(!empty($_POST['resource_type'])){
      $resource_types = $_POST['resource_type'];
    }

    $terms = array_merge($sectors ,$material_types ,$resource_types);
    if(!empty($terms)){
      $count = 1;
      $terms_list = "";
      foreach($terms as $tid){
        if($count < count($terms)){
          $terms_list.="$tid,";
        }else{
          $terms_list.="$tid";
        }
        $count++;
      }
      $product_query.=" AND tn.tid IN ($terms_list)";
      $product_count_query.=" AND tn.tid IN ($terms_list)";
    }

    $product_query.=" GROUP BY n.nid ORDER BY n.changed DESC ";
    $product_count_query.=" GROUP BY n.nid ORDER BY n.changed DESC ";

    $product_array = array();
    $product_query_result = pager_query($product_query, 5, 0, $product_count_query);
    while ($node = db_fetch_object($product_query_result)) {
      $node_data = node_load($node->nid);

      if($_POST['accredited'] == 'on'){
        if(empty($node_data->field_right_way_accredited[0]['value']) || !$node_data->field_right_way_accredited[0]['value']){
          continue;
        }
      }

      $product_array[] = array(
        'nid'=>$node_data->nid,
        'title'=>$node_data->title,
        'price'=>$node_data->sell_price,
        'image'=>$node_data->field_image_cache[0]['filepath'],
        'url'=> $node_data->path
      );
    }

    $output .= theme('ssa_product_search_template', $product_array);
    $output .= theme('pager', NULL, 5, 0);
    return $output;
}

Solved this problem by correcting the fourth argument of pager_query function i.e $product_count_query.

Pager query takes the fourth argument as an SQL query to count the number of matching records.It should a valid sql query.


Standard bootstrap main menu with dropdown? When using bootstrap with drupal what is the standard way to create a main menu?

When I add the main menu block to a region it does not display as a bootstrap navbar.

When I try with superfish I can add some classes but for example the active-trail cant be changed on li.

Your "standard" Bootstrap subtheme launches with your "standard" Bootstrap Nav Bar. For most intents and purposes this is the main-menu... links added to the main menu at admin/structure/menu/manage/main-menu appear there ...

Oddly the navbar isn't available to configure from the blocks page as you might expect nevertheless ... there are some navbar options available under admin/appearance/your-bootstrap-subtheme/settings.


Having trouble with ckeditor toolbar buttons I cant figure out how the full toolbar can be view. I tried to toggle collapsed toolbar of and on however I am unable to see the either advanced toolbar or full (only some buttons I haven't selected at all). Meanwhile I can create the basic toolbar.

Can anybody help me get the full toolbar?

You probably need to configure CKEditor for a specific input format.

You might have an easier time if you install WYSIWYG module AND the ckeditor editor. This setup will integrate better with the Media module for instance. If you install WYSIWYG editor, you then can easily setup the editor per input format.


webform block in a page template , inside a colorbox - validation does not show I created a page tpl for a view where using colorbox inline i`m displacing a webform block and some additional text.

My problem is that the error messages are not showing. The submission is working but the messages are not shown.

Here is a part of my code inside a view.tpl

                   <?php  print $content; ?>

                   <?php
                       $block = module_invoke('webform', 'block_view', 'client-block-15');
                       print render($block['content']);
                   ?>

I activated the webform ajax and no redirect after in order to stay in colorbox after submission.

Thanks

The error messages are printed in $messages on a normal page, have you tried adding that?


Installation error with Composer I'm trying to install Drupal 8 with Composer. Drupal Console is already installed (in case that's relevant), so I go to my localhost folder (working locally) and type:

composer create-project drupal-composer/drupal-project:8.x-dev cmpsprjct --stability dev --no-interaction

Everything runs well with the composer installation in the terminal. When I try to proceed with the installation in the browser I get following error:

Additional uncaught exception thrown while handling exception.
Original

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 806)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 272)
Drupal\Core\Form\FormBuilder->buildForm('install_select_language_form', Object) (Line: 898)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1324)
install_select_language(Array) (Line: 670)
install_run_task(Array, Array) (Line: 548)
install_run_tasks(Array) (Line: 117)
install_drupal(Object) (Line: 44)

Additional

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('html') (Line: 298)
Drupal\Core\Render\Renderer->doRender(Array, 1) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, 1) (Line: 139)
Drupal\Core\Render\Renderer->Drupal\Core\Render\{closure}() (Line: 576)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 140)
Drupal\Core\Render\Renderer->renderRoot(Array) (Line: 66)
Drupal\Core\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 76)
Drupal\Core\ProxyClass\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 1004)
install_display_output(Array, Array, Array) (Line: 264)
_drupal_log_error(Array, 1) (Line: 584)
_drupal_exception_handler(Object)

I have searched in Google and found that a composer update could solve the problem, but it didn't.
Any hints about how to proceed?

Working with Ubuntu 17.04 and php 7.1

Please make sure your webserver (nginx/apache) is using the same PHP version as your cli one. For example, you may encounter this issue if your cli PHP version is PHP 7.1 and your webserver is using PHP 7.0.


Displaying node translations I have enabled several languages on my site and the following modules has been installed: Locale & Content translation.
I have created a simple page in English and have added several translations for this node.
Now when I view node on separate page it's displaying in language which is selected in language switcher block.
But if I view node on front-page (/node) or on taxonomy page (taxonomy/term/%) all translations of this node has been shown.
Is it possible to disable displaying other translations for all pages?

You can use Views, which comes with a front page view you can modify to make it show only nodes for a specific language, and a view for taxonomy/term/%. For taxonomy terms, it is not so straight, as Drupal associates a language to nodes, but not taxonomy terms; it still is possible to show only the nodes associated with the selected taxonomy term, and which are written in a specific language.

If you install the development snapshot of Views (7.x-3.x-dev), some settings have been renamed; the one that you should change is "filter criteria."


User register and login test I am trying to register and log in users via the Services module 7.0-3.11 on Drupal 7.36.

The endpoints are declared from the following code.

$endpoint = new stdClass();
$endpoint->disabled = FALSE; /* Edit this to true to make a default endpoint disabled initially */
$endpoint->api_version = 3;
$endpoint->name = 'user_service';
$endpoint->server = 'rest_server';
$endpoint->path = 'user_api';
$endpoint->authentication = array(
  'services' => 'services',
);
$endpoint->server_settings = array(
  'formatters' => array(
    'json' => TRUE,
    'bencode' => FALSE,
    'jsonp' => FALSE,
    'php' => FALSE,
    'xml' => FALSE,
  ),
  'parsers' => array(
    'application/json' => TRUE,
    'application/vnd.php.serialized' => FALSE,
    'application/x-www-form-urlencoded' => FALSE,
    'application/xml' => FALSE,
    'multipart/form-data' => FALSE,
    'text/xml' => FALSE,
  ),
);
$endpoint->resources = array(
  'user' => array(
    'operations' => array(
      'retrieve' => array(
        'enabled' => '1',
      ),
      'index' => array(
        'enabled' => '1',
      ),
    ),
    'actions' => array(
      'login' => array(
        'enabled' => '1',
      ),
      'logout' => array(
        'enabled' => '1',
      ),
      'token' => array(
        'enabled' => '1',
      ),
      'request_new_password' => array(
        'enabled' => '1',
      ),
      'register' => array(
        'enabled' => '1',
      ),
    ),
    'targeted_actions' => array(
      'password_reset' => array(
        'enabled' => '1',
      ),
    ),
  ),
);
$endpoint->debug = 1;

I am using basic PHP code for the testing purpose. Please have a look at the GIST.

The problem is that, while I run the test page, I can see it registers a new user and outputs the following.

stdClass Object
(
    [uid] => 14
    [uri] => http://vote-app.dd:8083/user_api/user/14
)

But while I try to log in with the same user (as per the code) it outputs the following error.

  Error
  ["Wrong username or password."]

I need some help on this. Am I missing something?

I also checked https://www.drupal.org/node/1491754 and other Drupal pages for this too.

Found the solution. Just for future references for others and me as well :-)

There is an issue in Services module Wrong username and password, just after a creation of a user where someone faced the same problem. User login just registration. So as it stated,

  If you are anonymous user and register a user your register form does not have password field at all. It has only username and email fields. All instructions are sent by email (with token to log in and set the password). So register call actually does not set the password.

This is actually true. If I go to the admin and change the password again then it's working. So the solution is to alter two variables,

variable_set('user_email_verification', FALSE);
variable_set('user_register', TRUE);

This will now allow the users to register by themselves.


Create a Modal to Add new fields dynamically I have to develop a contest page. Every participant may have one or more codes that can use to participate in the event. After that the user must fill a form with their personal data so they can be contacted  in case they win the contest.

How could I add a [+] button that opens a modal window asking me how many code field would I need? If I write 5 for example, we create dynamically 5 code fields to the input.

I managed to create an add more button that add just one more button, but for clients requirements, we need to use a popup that ask how many fields we need.

I am not sure how this can be done entirely with Webforms. One option is to include in this webform all necessary fields, including the ones that would appear as a modal dialog. Even better, group these as a fieldset.

Then in a custom module or theme include some jQuery logic with which would be very easy to create a modal dialog in the same page. There is a dialog widget in jQuery UI and this is a relevant question in SO.


Quiz permissions per user I have installed the quiz module in drupal 7 and I know that there is a permission to allow roles participate in all quizzes. I want that a specific role can participate in specific quiz, not in all quizzes, and other roles can participate in their own quizzes.

Is there anyway to accomplish this through the interface? If not, I would like to know how to solve it by coding.

It seems there is a module for this: OG Quiz. According to its description:

  This modules creates permissions similar to the core Quiz ones on the
  group level. This allows site builders to give Quiz
  creation/correction/taking permissions at the group level instead of
  globally.


getpreventdefault is deprecated - Caroussel stopped working I have a caroussel slide made with a view and it was working fine until today. The block (with a view inside) just dissappeared from the front page.

I aggregated js files in the performance page... maybe that was it. But now I uncheked the option and cleared the cache many times and is still not working.

I'm getting this error from the console: Use of getPreventDefault() is deprecated

Does it has something to do with it?

Jquery update is 1.10

try to use Jquery version 1.7.1, or 1.8

If this doesn't work you can try that function this way:

$(document).on('click', function (e) {
    if (e.originalEvent.defaultPrevented) return;
    // continue
});

If everything was working before, maybe is some other js script added and it is getting the error but the console is not showing it properly


Can the speed of my cron job be improved? Can I improve my cron job speed?

Ex: it takes me 30 seconds to complete a certain cron job. Can I make it do this faster?

Does cron speed depend on the server machine?

Does cron speed depend on the server machine?

Yes, to an extent. Maybe even a large extent, it depends on a lot of different factors.

  Can I make it do this faster?

Probably, but that's as much as anyone can tell you from here. Profile the code, see where the bottlenecks are, and fix them. There's no magic formula


Pass list from Jquery to form I have an AJAX form that I've created into a block exposed on my current page. I will have an interface that will allow the users to select an indefinite amount of content to be used within the submit function of the form.

All the variables that will be passed to my form are node ID numbers, but there could be 1, there could be 50.

I have the Jquery action ready to update my ID numbers but I don't know how to get my ID number from Jquery into a variable, which can then be read when the AJAX form is submitted.

I've been looking at this - How to pass Javascript variable with form on submit?

and this - How to trigger a form and pass variables to $form_state with jQuery?

And I've been looking at the responses to both, but neither seem to give me access to the data I need, or are only speaking about a single variable, I need to pass a list or an array.

Would it be best to write something to trigger the form rebuild when I provide a new ID and allow the ID to be written into the form via that method?

For anyone looking to an answer to this, it really depends on whether or not you're working with an AJAX form or not. Ideally I wanted to avoid just populating a text area with my updated field to be submitted, so thankfully, since it was using the AJAX form, I was able to pass it information dynamically through Jquery.

In your javascript

// whatever your function is to get the information you want to pass
....
Drupal.ajax['edit-save'].options.data._my_vars = JSON.stringify(myList);

// Where 'edit-save' is the ID of my save button in my form
// you can console.log(Drupal.ajax) to see what options you have

Then in the callback for your AJAX request, the return request is stored in

$form_state['input']['_my_vars'] // or whatever variable name you passed above

Then you can check whether or not the response has comeback empty by using

 if (empty(json_decode($form_state['input']['_my_vars']))) {
   form_set_error('save'); // You can set the error to be any form element
 }

and in your callback code you can make your own error handling by doing

if (form_get_error() !== null) {
  // fail code
} else {
  // success code
}

Hope this helps someone else down the line


Redirect taxonomy term page links to a View page's exposed filter I'm trying to make every taxonomy term page link direct to a pattern like this:

  /viewpage?[term:vocabulary][]=[[term:tid]]

So, for example instead of material/bronze where bronze has term id 7, you'd have:

  /viewpage?material[]=7

...and you'd go to a views page where the user could then turn off the materials filter and turn on other filters.

I've tried setting this pattern up using PathAuto at /admin/config/search/path/patterns, which does the opposite of what I want: while it does make links to a taxonomy page point to URLs that look like viewpage?material[]=7, it then intercepts these and sends them to the default taxonomy term page, breaking the exposed filters!

I've tried using Global Redirect, but it doesn't seem able to apply patterns, it seems I'd need to enter the redirects by hand which isn't sustainable.

Redirect Tokens module looks to be designed to do what I want, and even has an example very similar to my case but with users not taxonomy and facets not exposed filters, but on closer inspection a) it only accepts tokens in the "from" field not "to" and b) it only works with global tokens like current user.

I've figured out that it's potentially possible using cTools Page Manager:

Enable and edit the Taxonomy View page
Set it the HTTP Response Code variant
Select 301 redirect then input the new URL...

...but I'm not sure how to inject the [tid] into the new URL pattern. The help text says "You may use keyword substitutions from contexts" but there doesn't seem to be any way to view or edit contexts for a page override.

How can I bulk redirect all current and future URLs of taxonomy term pages to this exposed filter view?

After some trial and error and guesswork I've got it working using Page Manger (part of the cTools module):

Under Structure > Pages, Enable and Edit the Taxonomy View page - if there isn't one, you  might need the Page Manager Existing Pages module
Create a "HTTP Response Code" variant
Select "301 Redirect"
For the default pattern, enter something like:

  pagename?%term:vocabulary:machine-name[]=%term:tid

Test this. There might be cases where the field name stub used in the exposed filter doesn't match the actual vocabulary machine-name and where editing this in Views isn't a good option. For example, I had one field named "colours" not matching its underlying vocabulary "colour". You might also have exposed filters using strings like field_fieldname_tid which you might have reasons to not change. If this happens:

Go back to "Summary" in Page Manager for this override
Click "Add new variant"
Give it a sensible admin title (e.g. the vocabulary name) else you'll hit an error later on as it'll match the default name
"HTTP response code" again, and tick "Selection rules"
Choose an appropriate selection rule (probably, "Taxonomy: Vocabulary", then tick the awkward vocabulary), continue
Choose 301 redirect again, and enter the same pattern as before but with the token %term:vocabulary:machine-name replaced with the string used by the exposed filter, for example pagename?colours[]=%term:tid


Drush suddenly stopped working can't use PM command Suddenly having errors in drush with aquia dev desktop...it's been working fine for a year at least and now this:

C:\aquiasites\fixing\sites\all\modules>drush en color_field -y
Command pm-enable needs a higher bootstrap level to run - you will [error]
need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en color_field' could not be executed. [error]

Any idea what is happening?

Runnin WIndows 7 64

So simple, why nobody saw this including me!.....seems like I can't run Drush from modules directory, only from root, never noticed before, haven't used Drush for a while ...

Not working

C:\aquiasites\fixing\sites\all\modules drush en color_field -y

Working

C:\aquiasites\fixing drush en color_field -y

[solved]


Programmatically Duplicate EntityQueues I'm attempting to create a duplicate of an entity queue that includes all the nodes inside it.

Here is my current code

$entityQueueId = 'hero_images';
$langcode = 'test'
$clones = [];
$subqueue = \Drupal::entityTypeManager()->getStorage('entity_subqueue')->load($entityQueueId);
$nodes = $subqueue->get('items')->referencedEntities();
    foreach ($nodes as $node) {
         $clone = $node->createDuplicate();
         $clone->title->value = $clone->title->value . ' - ' . $langcode;
         $clone->set('langcode', $langcode);
         $clone->setCreatedTime(time());
         $clone->setChangedTime(time());
         $clone->save();
         $clones[] = [
             'target_id' => $clone->id(),
         ];
    }

    $subqueue_clone = $subqueue->createDuplicate();
    $subqueue_clone->set('name', $langcode . '-' . $subqueue->id() . '-' . uniqid());
    $subqueue_clone->set('title', $langcode . '-' . $subqueue->id() . '-' . uniqid());
    $queue = $subqueue->getQueue();
    $queue_clone = $queue->createDuplicate();
    $queue_clone->set('id', $langcode . '-' . $queue->id() . '-' . uniqid());
    $queue_clone->set('title', $langcode . '-' . $queue->id() . '-' . uniqid());
    $queue_clone->save();
    $subqueue_clone->setQueue($queue_clone);
    $subqueue_clone->set('items', $clones);
    $subqueue_clone->save();

The queue does get created, but there are no items within it. In case there was an issue with my node duplication code as a test I just set

$subqueue_clone->set('items', $subqueue->get('items')->getValue());

but that didn't work either. Is there an issue with my code? Or should I go about this in a completely different manner? What's the best way to duplicate an entityqueue while preserving or duplicating the list of the nodes inside it?

I was able to get it to work, but I'm not entirely sure why it works. What I did was after saving the duplicated subqueue I loaded it once again then applied the items before saving for a second time.

    $subqueue_clone->save();
    $newsubqueue_clone = \Drupal::entityTypeManager()->getStorage('entity_subqueue')->load($clone_id);
    $newsubqueue_clone->set('items', $clones);
    $newsubqueue_clone->save();


Why do I get a fatal error when clicking on the permissions tab in admin/people? Steps to reproduce:

Log in as administrator
Click on People
Click on the Permissions tab

This navigates to admin/people/permissions. Here is the complete source code for that page:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2048 bytes) in /.../includes/common.inc on line 6300

Why am I getting this error and what can I do about it?

Notes:

my php.ini file contains the following line: memory_limit = 128M
.../sites/default/settings.php contains the following line: ini_set('memory_limit', '512M');
If I go to Reports/Status report and scroll down to PHP memory limit, it says 128M

If you are running multisite, you probably need to modify your settings.php on each sites.


How to programmatically copy Webform handler config? I would like to copy the Webform handler from 1 Webform into another. I can get hold of Webform settings via:
/** @var \Drupal\webform\WebformInterface $webform */
$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('example_webform_id');
$webform->getSettings();
=> [
     "ajax" => false,
     "ajax_scroll_top" => "",
     "ajax_progress_type" => "",
     "ajax_effect" => "",
     ...

However that doesn't include the handler config that I would need and a way to save its new config as well.
I also tried it via the handler object itself:
/** @var \Drupal\webform\Plugin\WebformHandlerInterface[] $handlers */
$handlers = $webform->getHandlers('example_webform_handler_id');
$handler = $handlers->getIterator()->current();
$handler->setConfiguration($new_handler_config)->save();

for which it appears that there is no save() operation in the handler class:

Error: Call to undefined method ::save()

Any way I can do this programmatically that you may know of?

Ended up using the ConfigFactory service, which I believe is fine to do:
$config = \Drupal::configFactory()->getEditable('webform.webform.' . $webform->id());
$config_key = 'handlers.' . $webform_handler_id;
$config->set($config_key, $new_handler_config)->save();


Drupal7 REST webservices API KEY vs OAUTH two-legged authentication for clientside JS consumer library I'm working on an Drupal7 API, using REST services, and consumer JS library (no server code). I'm not trying to authenticate/authorize the end-users, only to identify and allow access to the 'application' using an API KEY.

The goal is to have the 'developers' create an account, request an API KEY, register domains for this api key, and use this key to 'identify' their application to the Drupal7 API. This is pretty much the same API-KEY model that Google Maps is using in v2.

I've looked into OAUTH 2legged approach, which would have been great if my client library was running on the server side, so the secret key wouldn't be exposed, but in our case, the library is JS only (client side), and it doesn't seem a good idea to expose the secret key.

Am i missing something about OAUTH that will allow this? Any pointers will be welcome.

Thanks!

The solution came from Kyle Browning (thanks!) - the current dev version of services 7.x-3.x-dev has support for the following OAuth authentications methods:

None, OAuth authentication will be disabled by default
Unsigned with consumer key
Consumer Key, also known as 2-legged OAuth
Consumer key and access token, also known as 3-legged OAuth

With this version I ended up using the consumer key for the client libraries as identification token for applications.


block restrict depending on role I use this snippet to restrict block visibility from administrator

<?php
global $user;
if (user_access('access administration pages') || ($user->uid == 6)) {
  return FALSE;
} else {
  return TRUE;
}
?>

I also want to restrict this block from role 6. However, it does not work. Can somebody help?

Thank you

// Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }

Replace "administrator" with the role name you want to check.

EDIT:

If you want to check for role id's use below code.

global $user;
$role_ids = array_keys($user->roles);
if (in_array(6, $role_ids)) {
  // Do something
}

In your case

<?php
global $user;
$role_ids = array_keys($user->roles);
if (user_access('access administration pages') || (in_array(6, $role_ids))) {
  return FALSE;
} else {
  return TRUE;
}
?>


Views related nodes with same Title I am building a booking system for a local theatre company. Each theatre event is its own node, and for the same show on different nights, the first night is created, and the node is cloned, with a different date and time for each show.

On the node event page I want to show a block view of other nodes with the same title, and different show times.

I have created a contextual filter by node ID, and excluded the current node from the view already, now I need to display all other nodes that have the same title.

I'm a bit stumped though, I can create a contextual filter by node title, but I cant figure out which options I need to select to achieve this.

Appreciate any help or advice.

I actually found the solution I was looking for here

I was close with what I was doing, I just needed to do the following...

Add contextual filter by Content:Title
Under "When the filter value is NOT available" Provide Default by Content ID from URL
Under "When the filter value IS available" Specify validation Criteria as PHP Code
Enter the following PHP code...

if (is_numeric($argument)) {
  $node = node_load($argument);
  $handler->argument = $node->title;
  return TRUE;
} else {
  return FALSE;
}

Click Save.


How to provide the ability to upload media to the server? I want to provide the ability to upload PDFs/mp3s etc. to the server.

What is the best way of achieving this?

I've seen the media plugin but it seems that replaces the upload field rather creating a stand-alone media area? Or maybe it does?

I think Media is a great module unless if your client will upload and use the same PDFs/MP3 once a time.

But if your client plan to use at severals places the same Media, so Media module is for you.

Also, give a look at Scald, seems to be a promise module.


get taxonomy term count by vid I have this code which gives me the number of terms on a node

 $count = count($node->taxonomy)

Is there a way i can restrict this to VID. i only want to get the count for a specific vocabulary.

Oh yeah the site is in D5

here is a link to the page http://national.thedelimagazine.com/8947/delis-austin-issue-2012-pdf-version-available

I don't have a D5 system handy, but this would do it in D6:

$count=0;
foreach ($node->taxonomy as $t) {
  if ($t->vid==VID_IN_QUESTION) {
    $count++;
  }
}

and it "should" be the same in D5, but I've said that a lot about D7 and D6 :)  If not,

drupal_set_message('<pre>' . print_r($node->taxonomy,true) . '</pre>');

should give you the object information you need to modify above to count.  If that doesn't work,

$foo=taxonomy_node_get_terms_by_vocabulary($nid, $vid);
$count=count($foo);

certainly is a roundabout way of getting them if you already have the node loaded.


Updating field in external Drupal database I'm working on a project where I have 2 Drupal installations which occasionally need to interact with eachothers database.

So far, I've been able to set up all interactions using db_set_active and db_select/db_query/db_update statements (example below):

db_set_active(.....);
db_select(.....);
db_set_active;

Simple select queries don't pose any problem. And while update queries are being propagated correctly, they have an inherit issue: they don't call the save hooks in the target Drupal installation...

My use case: I'm database updating a boolean CCK field (in Drupal B) from 0 to 1 (through a module script at Drupal A) and Rules (at Drupal B) should trigger on this. Moreover, the field caches aren't cleared so probably going directly through the database isn't a very good way to update the field...

Any other ideas how to update fields from within external scripts? Or maybe how to execute Rules while keeping the database operations?

Thanks

I have achieved the similar functionality with following code. I worked on Drupal 6. But, hopefully it worked for you.

I have two same drupal installation and when creating new node in one installation, I need to create node into another Drupal installation also. So, I customize the node form and added a submit function to node form.

Custom Submit function

function custom_node_export_form_submit($form, $form_state) {

  //Creating node object
  $node = new stdClass;

  foreach ($form_state['values'] as $key => $value) {
    $node->$key = $value;
  }

  db_set_active('domain');

  node_save($node);

  db_set_active('default');

}


Cron timeouts at 60 seconds, but all the related timeouts are set higher We're getting 504 Gateway Timeouts on AWS from a Drupal 7 site at 60 seconds, but everything AFAIK is greater than that. The timeout is specifically during running the feeds_source_import in Ultimate Cron.

We have a NLB with two TCP listeners that forward to the IPs of an ALB. According to the docs, the NLB has a timeout of 350 seconds for TCP connections. https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancers.html#connection-idle-timeout

The ALB is using an HTTP and HTTPS listener, and we have the Idle Timeout set to 300 seconds.

Finally on the servers themselves are running CentOS 7.7, Apache 2.4 and PHP-FPM 7.2.
reqtimeout_module is turned off completely.
Here are some values from php.ini:

max_execution_time = 300
max_input_time = 120
max_input_vars = 4000
memory_limit = 300M
default_socket_timeout = 120

And apparently cron lock time is set to 240 in Drupal Core. https://stackoverflow.com/a/9220479/5004648

Is there anything else we're missing that would terminate the connection at 60 seconds?

Given that we have several feeds, I decided to try to also run the importer manually by visiting: /import/video_importer and also get a timeout. For reference, the feed is pulling only a 128KB CSV file that has 912 lines.

Solved. It was the timeout of the proxy connection to PHP-FPM. It involves going down a rabbit-hole of Apache values and defaults so strap in.

As per ProxyPass the proxy default of connectiontimeout is timeout.

The default value of timeout is ProxyTimeout

The default of ProxyTimeout is the core Apache TimeOut

The default of TimeOut is 60. So there you go.

I set a value of TimeOut 180 in my Virtualhost for the site in question and the import went through.

Now just to wrangle all these values back down to a sensible level now that I know the culprits.


Changing "add new node" button I have a content type "consultation" that has an inline entity reference to 1 node of a content type "prescription". This content type prescription has multiple inline entity references to the content type "medecine".

I'm using the module Inline Entity Form so I create/add all of these nodes in the creation form of "consultation".

I'm trying to change the text "Add new node" in the form to something else. I know how to do this when it's a direct entity reference, but how do I get to the "Add new medecine" for "medecine"?

This is my code so far:

function node_change_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'consultation_node_form':
  $form['field_prescription_med']['und']['actions']['ief_add']['#value'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['#title'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['actions']['ief_add_save']['#value'] = t('Add new medecine');
  break;
}}

In this code:

field_prescription is the name of the entity reference field in "consultation" (to a "prescription")
field_prescription_med is the name of the entity reference field in "prescription" (to "medecine")

You can use hook_field_widget_WIDGET_TYPE_form_alter() to alter the button name

example:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function example_field_widget_inline_entity_form_form_alter(&$element, &$form_state, $context) {
  // Rename the button in specific form.
  if($form_state['build_info']['form_id'] == 'eck__entity__form_edit_sample_sample') {
    $element['actions']['ief_add']['#value'] = t('Add new medecine');
  }
}


Output node.type in page.html.twig gives "EntityReferenceFieldItemList cannot be printed" Not sure if this is a bug, but I wanted to add some debug into an HTML comment in my page.html.twig file. I added <!-- type={{node.type}} --> but I get:

Uncaught PHP Exception Exception: "Object of type Drupal\Core\Field\EntityReferenceFieldItemList cannot be printed." at /www/cn8/core/lib/Drupal/Core/Template/TwigExtension.php line 443

It took me a while to track down since I was sure this would work. Shouldn't EntityReferenceFieldItemList have a toString() function for this purpose?

node.type is a reference to the node type entity. You can get the id of the content type with target_id, as you have mentioned in the comment. For debugging this might be OK, but most times you want to get the label, which is nicely formatted and translatable:

{{ node.type.entity.label }}


Hide a view if there are no results (Spin-off of Remove/Hide the block if the View is empty?. I find the other question a bit confusing, and want to reduce it to the essential question.)

When rendering a view programmatically, and there are no results, there is still some HTML returned from $view->render().

This can be desirable in the following cases:

There is a "No results behavior".
There are exposed filters, which need to be shown independent of the view result.
The view is using AJAX, so it could happen that new content appears dynamically.
Perhaps other reasons?

I want to write generic code that renders a view, but completely hides it if there are no results, and no other reason to show it.

So far I have this:

$view = \views_get_view($view_name);
if (NULL === $view) {
  return [];
}
$success = $view->set_display($display_id);
if (FALSE === $success) {
  return [];
}
$view->set_arguments($args);
// See https://www.drupal.org/node/525592#comment-1833824
$view->override_path = $_GET['q'];

$view->pre_execute();
$view->execute();

if (empty($view->result) && empty($view->empty)) {
  // @todo Also check for exposed filters!
  return [];
}

$markup = $view->render();

$view->post_execute();

if (FALSE === $markup) {
  return [];
}
return ['#markup' => $markup];

So the question is: Which other checks should I add when looking if the view is empty? (the place with the @todo).

How do I check if there are exposed filters?
Which other criteria are relevant?

Considering how many criteria might have to be considered to determine if a view can be hidden, I decided to make this a configuration option instead.

I see two ways to do this:

The component where the view is embedded can have a configuration option "Hide view if no results". This is what I went with.
One could make a symbolic views plugin for "no results behavior", named "Hide view if no results". Then one could implement e.g. hook_preprocess_views_view(), or possibly another hook, to hide the view if the new no results behavior is present.

I could write a lot more details, but for now I want to share the ideas behind these options, maybe this already helps.

I am marking this as the accepted answer. But if someone can come up with something more convincing, I will change it.


How can I alter the breadcrumbs on a search page? I just enabled search on my Drupal theme and when I go to the search page my breadcrumbs show like this:

  home > Search > Content > Search

Is there any way to make it just:

  Home > Search

Thanks!

For ease of use you might want to look at Path breadcumbs:

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

There is also Custom Breadcrumbs which was pretty awesome, but be careful if you choose this route as there is serious discussion about deprecating it in favour of Path breadcrumbs.

Hansel Breadcrumbs is useful, but I have found it INCREDIBLY complicated to get set up and working properly. I would suggest to use it only if you're going to be setting up a lot of complicated rules. If it's just for one or two pages, it's probably overkill and might end up making you hate Drupal (and no-one wants that!) ;-)


View won't render any content/teaser, only shows fields I'm having a couple of articles which I want to display in a view. So I've set up a new view and made the following setting there:

Format: Unordered List | [default settings]
Show: Content | Full Content

All other settings remain untouched as default.

In the views-preview it is displayed nicely, but the whole view doesn't show up on the page when browsing to the path.

I've also tried

Show: Content | Teaser
Show: Rendered entity | Full Content

with no luck.

Only if I set the view to

Show: Fields

the view is displayed.

The article node pages are being displayed without a problem.
I'm working with views for years now, and never had such a problem.
Any ideas where the problem is?

Thanks, Marc

check if this view did not get somehow to disabled list... go views list it's divided into Enabled and Disabled lists check there...


Views grid - align fields I'm using Drupal 7, and I have a content type called Book, which consists of a picture and a title. I'm using Views (grid format) to display Books on a page, and it's working great. The only problem is that the titles always sit directly under the picture, which looks bad if the pictures are of different heights. Is there a way to horizontally align all fields within a grid?

This is what I currently have:

_____   _____   _____
|    |  |    |  |    |
|    |  |    |  |    |
|____|  |    |  |____|
title   |____|  title
        title

And this is what I want:

_____   _____   _____
|    |  |    |  |    |
|    |  |    |  |    |
|____|  |    |  |____|
        |____|
title   title   title

I've managed to achieve this by overriding views-view-grid.tpl.php (and adding a new row to the table for each field), but was wondering if there was a better way?

Update: I'm not interested in solutions that involve changing the layout / picture sizes. This is the second time a designer has given me a PSD that leaves me facing this issue, so I'd really like to find a good solution to this exact problem!

If the images are of different sizes, it might look a lil sloppy. You can use CSS to set a particular height and width for all the images so that they look uniform and I guess overriding views-view-grid.tpl.php just for this is not the best way.


Entity 'changed' column doesn't change upon save I have a custom entity called "release".
Release has "state" and "building percentage" fields, which values may change during the release process.

In both "setState" and "setPercentage" entity method I explicitly do the following:

$this->setChangedTime(time());
$this->save();

However, during the process, the "changed" column in the database always remains the same value.
Am I missing something? What could be wrong?

UPDATE:
Running the "setState" and "setPercentage" in a test script separated, the database gets updated.

UPDATE2:

I got it. "ChangedItem.php" - line 37, I logged there, and this is where it sets back to the request time value:

   // On an existing entity translation, the changed timestamp will only be
      // set to the request time automatically if at least one other field value
      // of the entity has changed. This detection does not run on new entities
      // and will be turned off if the changed timestamp is set manually before
      // save, for example during migrations or by using
      // \Drupal\content_translation\ContentTranslationMetadataWrapperInterface::setChangedTime().

will be turned off if the changed timestamp is set manually before save

This "promise" of the comment is definitely not working. Any suggestions?

Okey I found the final reason:

ChangedItem.php

  $original = $entity->original;
      $langcode = $entity->language()->getId();
      if (!$entity->isNew() && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
         $this->value = REQUEST_TIME;
        }
      }

The conclusion:

In Drupal 8 if you save the same entity TWICE within 1 second (for whatever reason), you won't able to save your own changed time BUT it will be the REQUEST_TIME instead... wtf? ...


Problem creating redirect from page with %20 I've been researching the issue for hours and can't seem to find a working solution to this problem. I've created a redirect from /sites/default/files/OLB%20Registration%20Guide.pdf to /sites/default/files/downl_section/Online-Banking-Registration-Guide.pdf that doesn't work.

Here is the line in .htaccess

Redirect 301 "/sites/default/files/OLB Registration Guide.pdf" /sites/default/files/downl_section/Online-Banking-Registration-Guide.pdf

My first inclination was to remove %20, but still nothing... Does anyone have any insight as to how to create a redirect where the original url contains %20?

Thanks!

If you are using the Redirect module it has an admin page for fixing 404 errors with redirects. Your file should be listed there since it gives you a 404 error.

When clicked on "Add redirect" action link, your old link will be pre-populated on the next page for you to create a redirect.

That should fix the redirect issue.

In case it doesn't try replacing white-space with + (plus) character. In the URLs + can be used instead of white-spaces.


Rule to store user's last post date and scheduled rule based 30 day reminder In this scenario, user's can post 1 node of a specific content type every 30 days (interval changes depending on user role). We are using node_limit to accomplish this; it's doesn't play with rules.

So, the idea is to schedule an email that will remind the user 30 days later to post a new article AND update a field in the user's account to display the last time the user posted. Once the node is saved, the rule should update the user field with the node's post date.

BUT I'm unable to correctly configure the set a data value.

The rule I have created is as follows:

Fetch entity by property
Parameter: Entity type: User, Property: press_update_last_posted, Value: [node:created]
Provides variables: Date (entity_fetched_pressupdatelastposted)

Set a data value
Parameter: Data: [entity-fetched] ..., Value: [entity-fetched] ...

And then of course it would fire up the scheduled email and display a message on the site.

Any suggestions?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the 3 steps below. These steps are based on these assumptions:

content type = article.
interval 30 days.

In this case, a date field is added to the user profile, so that for each user you can indicate an appropriate date for the "next article".

Step 1: Create a field to store the "next article" date

Add a field to the "user" entity with machine name (say) field_next_article. Allow only 1 date (to store when the "next" article is allowed).

Step 2: Create a Rules "Component"

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your next article",
          "message" : "This is a reminder about your next article on [user-to-notify:field_next_article] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.

Step 3: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):

{ "rules_user_reminder_after_30_days" : {
"LABEL" : "User Reminder After 30 Days",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : { "user_login" : [], "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_article" } }
],
"DO" : [
  { "schedule_delete" : {
      "component" : "rules_send_email_notification",
      "task" : "[account:name]"
    }
  },
  { "data_set" : { "data" : [ "account:field-next-article" ], "value" : "+30 day" } },
  { "schedule" : {
      "component" : "rules_send_email_notification",
      "date" : {
        "select" : "account:field-next-article",
        "date_offset" : { "value" : 2592000 }
      },
      "identifier" : "[account:name]",
      "param_user_to_notify" : [ "account" ]
    }
  }
]

}
}

Note that the above rule refers to the Rules Component from the previous step.

The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).


File upload field in CCK field settings Is there a difference in Drupal 7 to add a file-upload field on a "normal" form (i.e. a separate page for a modules' configuration) as opposed to the small settings area for a CCK field (the one that appears after clicking on the cog for the field you'd like to modify under the "Manage Display" tab)?

I have a bunch of configuration options for a custom field using hook_field_formatter_settings_form, but am stuck at trying to figure out how to create a file upload field. I'd ideally like to have the user able to browse for an image and upload it without having the page reload. This is all I currently have:

$element['custom_field_name']['image'] = array(
    '#type' => 'file',
    '#size' => 48,
    '#title' => t('Image upload'),
    '#description' => t("Upload an image."),
);

If it is possible to have a file upload field (that uses ajax) in this area, what else must I do?

Edit:

My file field now looks like this:

$element['custom_field_name']['image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image upload'),
    '#upload_validators' => array(
      'file_validate_extensions' => array(0 => 'png jpg jpeg gif'),
      'file_validate_image_resolution' => array('64x64', '10x10')
    ),
    '#upload_location' => 'public://default_images/',
    '#description' => t("Upload an image."),
);

This is sort of working: it allows me to upload a file and it goes to sites/default/files/default_images, but its only temporary. I've been going through the form api reference and it says I need to permanently save it. I am just unsure how where to put this logic. Do I add a #process key to my file field and call some private function? Or do I create a submit handler? The API reference doesn't go into as much detail as I'd like.

You need to add a FILE_STATUS_PERMANENT to the status of the file on form submit then save the file.

$file->status = FILE_STATUS_PERMANENT;
file_save($file);


how to propose when editing content 2 possible media style for an image field? My content type has an image field.
I'd like to propose to the editor two possible displays for that uploaded image, either 100% width or 50% width
How can i achieve that?

EDIT:
i found out this module :
https://www.drupal.org/project/field_image_style
Is this module stable enough?

How can I make this behavior compatible with the field formatter from colorbox module?

You could add a separate select dropdown textfield with two options, which are the image styles you'd like, and if they select the alternate one, update the field in hook_entity_view.

 function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
   if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article' && !$entity->field_image_style->isEmpty()) {
     $style = $entity->field_image_style->getValue()[0]['value'];
     $build['field_image'][0]['#image_style'] = $style;
   }
 }


How to preserve discount set with query parameters into cart? Using Drupal Commerce, I've been experimenting with applying a simple discount to a product using query string parameters. The goal is to allow a user to navigate to a product display page and see a discounted price based on this syntax:

http://example.com/product_display?code=discount_code

Where 'discount_code' represents some kind of discount to apply to the product.

By writing a custom action that's triggered on the event "Calculating the sell price of a product", it's pretty easy to alter the price of a line item with rules with something like:

function mymodule_apply_discount_via_url($line_item) {

  if ((isset($_GET['code'])) {

    // code to figure out if code is valid

    // code to figure out type of discount

    // code to alter the unit price and add difference as a component

Which works fine - the user will see the discounted price on the product display page. This is nice, because the user has access to all product information along with the discounted price.

However, on "add to cart", the product will appear in the cart at the original price. I assume this is because the pricing rules are run again but without the query parameter.

How can I preserve a discount applied this way through the add to cart step?

My current implementation:

Custom action triggered on "Calculating the sell price of a product":

looks for the query parameter "code" in the url
verifies code is valid and active (uses commerce_coupon)
applies it to the line item on product landing page
saves code as a session variable

Custom action triggered on "After adding a product to the cart"

looks for code as a session variable
verifies code is valid and active
uses 'commerce_coupon_redeem_coupon' to apply to cart order
clears the session variable

This seems to work, though it seems a bit rube goldberg. Still looking for a better way to preserve a discount that arrived as a query parameter, and apply it to a cart order, if there is one.


New workflow can't select content type I'm trying to create a new workflow in Drupal. When I click "Content Types" beneath the "This workflow applies to:" section, it loads an empty modal. I have 6 content types but they fail to show.

There is an existing workflow that has the correct content types set. However, if I uncheck one of them, it won't be available if I try to add it back later.

I made a new, test content type. It will show as an option for workflows but the older, existing options will not.

Does anyone have any ideas as to why the content types won't load inside of the workflow editor?

It seems each content type can only be assigned to one workflow at a time.
Try removing removing a content type from the other working workflow, save it, and then adding it to the new workflow.


How to capture credit card information to manually process later? I developed a Drupal 7 website for a client who hosts a yearly fitness expo. This year he has a competition event that requires registration and a fee.  I am looking for a way securely capture the necessary credit card and customer information to be used later to manually process the transaction.

My client has a Squareup account that he wants to use to process the transactions.  I am open to other solutions as well. While I know what Square is, I don't know anything specifically about it. Does anyone know if they offer a way for me to link to a form on their site to do what I am looking for?

Check out Commerce and Ubercart shopping carts. This is the right and best way to do this as it will save you the PCI headache as well.

However, seems that neither of the two do not have SqareUp payment integration, so you will have to do that yourself. You will have to read their API documentation and make appropriate custom module for integration.


Unable to change date format on node created field On my article content type, I enabled "Display author and date information" but am unable to change the date format.

I'm using Druapl 8.0.0-beta14 with a sub-theme based on Classy. The field's value is already computed by the time the twig template and hook_preprocess_field get to it but was able to chase down the setting of the date format to the defaultSettings method in TimestampFormatter.php using a debugger.

    public static function defaultSettings() {
      return array(
        'date_format' => 'medium',
        'custom_date_format' => '',
        'timezone' => '',
      ) + parent::defaultSettings();
    }

So far, I haven't found a place in the admin UI or yaml files (or a hook, which I know I probably shouldn't be doing too much of in D8) where the date format can be changed. Interestingly enough, this "field" on the node seems to be some sort of pseudo-field, because the value is actually the timestamp on the revision_timestamp field in the node_revision table.

That said, how can I change the date format for this "field"?

One way to do this is using a preprocess hook in your .theme file. There you can do pretty much anything with that variable.

Here an example:

function [theme_name]_preprocess_node(&$variables) {
  if ($variables['display_submitted']) {

    // Getting the node creation timestamp from the node object.
    $date = $variables['node']->getCreatedTime();

    // Here you can use drupal's format_date() function, or some custom php date formatting.
    $variables['date'] = format_date($date, 'medium');
  }
}

In an earlier beta, before being able to alter the 'date' variable, I had to  first pass the string through the create() method of the SafeString class like this:

$variables['date'] = \Drupal\Core\Render\SafeString::create('your dangerous new date string')

This might not be necessary anymore, concidering all the recent fuss around the safe string functions.
Edit: I still need to do that in beta15.


Change node title and node field content I try to change the values of the title and a field of a node.

function module_node_view($node, $view_mode, $langcode) {
  $node->title = 'TEST';
  $node->field_description[$node->language][0]['value'] = 'CONTENT';
}

When I try this, nothing is changed...

I think the $node will be a object and not array. You are trying to access it like an array, hence you get php error.

function module_node_view($node, $view_mode, $langcode) {
  $node->title = 'TEST';
  $node->field_description[$node->language][0]['value'] = 'CONTENT';
}


How do I show specific content on a separate page? I have menu links HOME | Property(links to property content type) | NEWS. In every News there are tags which reference to the property.

I want to link "NEWS" menu item to a separate page which should display only the news list which contains the tags for the property.

For example, i am on a property page say "Property XYZ", so there is a menu item "NEWS", when i click this menu item, a new page opens and this page is showing news which contain the Tag "Property XYZ" in them.

How do I achieve this?

From what i understand, These tags can be taxonomy terms and you can create a view where you can use contextual filter to get the tag name from url and show the related news content.

1)Page "Property XYZ" will have a link as abc.com/news/tag1
2)You can create the view page with path /news/%
3)News content should be already having those tags,so that you can get it from that view.

If this is not what you are looking for please provide more details.

EDIT:
1)https://www.drupal.org/project/pathauto
You can use this module to create patterns according to your need for your each news node path alias.
You can use tokens of the taxonomy tag field to set those patterns.

For eg:
news/[node:title]/[node:field-news-category:1:name]
where field-news-category is the taxonomy reference field where you select tags terms

Now how to put these all these links in the menu is a different thing and that is up to you.

2)when you create a page view
set path as /news/% (% for just a tag) OR /news/%/%
(where first % can be news title and second can be tag)
% is the argument from url which is used in the contextual filter field

In right column of the view go to advanced and add a relationship field Content: Taxonomy terms on node
then add contextual filter field as Taxonomy term: Term ID

There should be a default view as Taxonomy term,which will give you some idea to go about it.
Play around a bit with contextual filters.

This might help,
Url Path Alias is not working with the "raw value from URL contextual filter"


Change the display name of a default field in Contact Form In Drupal 8, I LOVE that there are default fields in Contact Forms for Name, Email, Subject, and Message...but in several of our forms those labels don't make sense.

For example, one form's primary use is to request an appointment, but I would like to use the Message field to ask if they have any other questions. Saying "Message" at the top of the box doesn't make sense, and I would like to still use the field but change the label to "Questions".

Is that possible to do without making another field and hiding the default field?

AFAICT each contact category has its own form ID, which means you can change it with hook_form_alter() in your theme or a custom module. Here's a tutorial about  how to implement it, although there are other resources you can find: Learn how to change an existing Drupal form.

If you wanted to do it without coding then creating a new field and adjusting form and display for each contact category is the way to go.

As Hudri mentioned in a comment you could use Webform for a lot more control, including saving the responses in the database. If you don't need to keep record of the correspondence than Webform is probably an overkill.


How to allow for files of any extension to be uploaded? I'm surprised this hasn't been asked before like this.

I want to allow users to upload files of all file extensions, without enabling each extension by hand. How do I do it?

You can use Allow  all file extension Module

  This module reverts Drupal 7's file upload widget to the Drupal 6
  behavior, and trusts the site administrator to be smart enough to
  allow uploads with any file extension. It also lengthens the allowed
  file extensions box from 128 characters to 2048, allowing you to
  specify a larger number of extensions.

  While I realize this is somewhat insecure and would have liked to add
  more functionality to this module, this isn't something I should have
  needed to do at all, and I don't have a whole lot of time to spend on
  it. If there are any bugs, I'll try to fix them, but beyond that, I
  won't be adding new features to it. If you would like add new features
  to this module, I would gladly accept a co-maintainer (or even
  transfer ownership to someone else).

  Warning: The ability to leave the allowed file extensions box blank
  was removed for a reason. If you leave it blank and allow random users
  to upload files of any type, you'll have an insecure site. As such,
  you are strongly cautioned only to allow trusted users to do this.


How to edit misc/print.css without changing core I want to edit core/misc/print.css that the Book module is referencing, and I don't know how.

If I should move the print.css somewhere and load a new print.css in my theme.info, or is there another way make changes to the core/misc/print.css without changing core?

You don't need to edit any core file, to achieve what you are trying to do. Since you are talking of a theme, you just need to replace the template file used from the Book module. This is what done from the Stable theme, which has its own book-export-html.html.twig.

The only reference to the misc/print.css file is in book-export-html.html.twig; there isn't any core library with a reference to that file, and this makes things easier for a theme.
book-export-html.html.twig contains the following code.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="misc/print.css" />
  </head>

In the template file for your theme, you just replace it with the following, if you don't want to use any print.css file.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
  </head>

If you just need to use a different print.css file for your theme, then you can simply edit the file path, and provide your own CSS file.

  <head>
    <title>{{ title }}</title>
    {{ page.head }}
    <base href="{{ base_url }}" />
    <link type="text/css" rel="stylesheet" href="the_path_relative_to_the_theme_folder/print.css" />
  </head>


How may I allow users to embed a view within a CKEditor text field? I'm working on a site that includes a number of service pages (think practice areas in a law firm site) and each service has a number of identical content components (call to actions, legal disclaimers, etc) that are not always in the same order.

It would be awesome if there was a way for my content editors to add these components within the body field in any order they see fit. I believe the CKeditor Blocks module could accomplish this for static content, but for dynamic content I don't see a solution.

Sometimes the body looks like this;

{{ Paragraph }}
{{ Related Services }}
{{ Paragraph }}
{{ Call to Action }}
{{ Legal Disclaimer }}

and other times it's formatted like this;

{{ Paragraph }}
{{ Paragraph }}
{{ Call to Action }}
{{ Related Services }}
{{ Legal Disclaimer }}
{{ Paragraph }}

Specifically, the service content type has a 'related services' entity reference field and users need to include links to these nodes within the body of the page. Typically, if I knew these links were always presented at the end of the body, I'd just create a contextual view and present the results on the page (panels).

What are my options here? I've given some thought to using Paragraphs, but that introduces more work than I'm interested in investing at the moment.

As far as embedding a view into CKEditor, you can use a formula with Token Embed Views and or Token Insert:

https://www.drupal.org/project/token_embed_views
https://www.drupal.org/project/token_insert


Does my Feature module have to explicitly define the body field in it's components? When a new content type is created in Drupal it is automatically given a title and body field. Now that I am defining my components for my feature to I have to select it as one of the components of the feature module?

... I always do. :)  It should be no problem -- and if for some reason the field doesn't exist on the destination server it will then be created (the Minimal install profile for instance I don't think has the body field by default). If you look in /profiles/standard/standard.install you'll see it creates the fields and basic content types in code, eg:

// Around line 229 of standard.install where $type is
// essentially 'page' or 'article'.
node_add_body_field($type);


How do we make the date field default to today's date? We want the date field to default to today's date when creating a new article.
In the node edit form it defaults to the date set in the content type field settings.
In the field settings form, it says "leave blank to use the time of form submission". If we leave it blank, it saves the form submission time which is then the new default for the node edit form.

How do we make the date field in the node edit form always show today's date for new content?

If already date field created follow the below steps to change the date formate:

Goto particular Content type, which you have created.

admin/structure/types/manage/{CONTENTTYPE_MAHINE_NAME}

click on the 'Manage Fields' form the tab menu
click on the 'edit' button on the date field of the content type. The field settings will open, the link will be

/admin/structure/types/manage/{CONTENTTYPE_MAHINE_NAME}/fields/node.{CONTENTTYPE_MAHINE_NAME}.field_{FIELD_MACHINE_NAME}

Goto bottom of the page

Select the 'Current date' option from the drop down at the section of 'default value'.
To display only the date without time, goto 'Field settings' and select the 'date only' option from the drop down of 'Date type'.