How do I generate PDF content from a node? We are looking for a way to convert the Drupal pages into PDF on click of a button for D8. Initially we thought we could use Print Module, but that only has a D7 version.

How do you create a button in D8 so that on click, it will convert the Drupal node into a PDF keeping the current theme styling and elements appropriately? We have been unable to find any D8 modules or process that can allow for this.

You can achieve with several solutions

Use Entity Print Module

  Entity Print allows you to print any Drupal entity (Drupal 7 and 8) or
  View (Drupal 8 only) to PDF.

  The module is lightweight compared to other modules like the Print
  module, has full test coverage and is ready to be used in production
  for both D7 and D8.

Use new host of print module (Printable Module)

  This is the new home of the print module. The module makes use of
  pdf_api module to generate PDFs.

Use PrintFriendly Module (it supports localization very good)

  The #1 Print and PDF button for your Drupal site. Printer Friendly
  pages without coding, css, or print.css. Fast, easy, and professional.

  The Print Friendly & PDF button saves paper and ink when printing or
  creating a PDF. It's fast, easy, and looks great when printed. Add the
  button now, and your users will see the difference.

  How Print Friendly & PDF Works The Print Friendly & PDF button
  automatically creates printer friendly and PDF versions of your pages
  without the hassle of having to create a print CSS file. No coding,
  hacking or programming required. Simply install the Print Friendly &
  PDF plugin, activate, and choose settings for full customization. It
  also gives your user the ability to remove images and paragraphs of
  text, so they really only have to print exactly what they want.

And final solution is kind of tricky solution, instead of converting the page to PDF just  provide a print theme style for your nodes, when a user clicks on the print button (or link) trigger  javascript:window.print() action. most of the new OS has PDF printer build-in

By the way, I recommend PrintFriendly Module


Making entities under another entitytype Suppose, I've created    -name
    -machine_name an entity_type myentity with its schema as:

-name
-machine_name

Next, I want to create another entity subentity that will be grouped under myentity.

I've create both the entities, but somehow during the form making, I'm clueless how to retrieve the myentity data under which I'm creating the subentity and save it.

subentiy schema:

-name
-parent (parent == myentity->machine_name)

I'm not sure if your case is closer to the typical bundle/config entity > content entity use case (because you mention machine name, so that sounds like a config entity to me) or content entity > content entity but the way this works is pretty much the same.

You need to define a route that contains the parent entity ID, then create your entity with the reference to that and then display the add form for it.

Examples for the first use case are for example node type/node or vocabulary/term, the second are comments. While the first is usually not seen as a hierarchy/grouping, it's essentially that.

Route from node.routing.yml:

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _content: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE

NodeController::add

public function add(NodeTypeInterface $node_type) {
  $account = $this->currentUser();
  $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('node', $node_type->type));

  $node = $this->entityManager()->getStorage('node')->create(array(
    'uid' => $account->id(),
    'name' => $account->getUsername() ? : '',
    'type' => $node_type->type,
    'langcode' => $langcode ? $langcode : $this->languageManager()->getCurrentLanguage()->id,
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

The only relevant part is passing through the entity reference value ($node_type) to the new sub-entity. There are issues to make the uid/name and the langcode default value handling work by default.


List users/roles who has access to node Asked this question on Drupal.org also, but i think this place is going faster and better :-)

I've installed Content Access and made a view for a Content Type. In the table, users can see content only for them. An admin is giving the rights to view, edit and delete content.

Is it possible to show to users who else has access to a node?

You've tagged the question with Views. Are you asking whether it's possible to build a View to do that? If so, then the answer is no (unless there's some module or plug-in out there which would add that capability).

Views queries the database, but node access permissions can be set in code via hook_node_access(). It's totally possible, for example to write some code that grants a user access to a specific node only if they have the letter 'x' in their name and today is Monday.

You can of course do it with some PHP code, and you could hook that into a View using Views hooks. I'm not sure what the most efficient approach would be, but basically:

Use hook_views_post_execute to process the list of nodes returned by your View.
For each node in your View result, you would need to loop through all users, calling node_access() to test if that user (uid) had access to the node or not.
From the results, build a list of users who had access, and have Views display that list by modifying  the $view object that was passed to your hook function.


Trying to create a view of a node that contains the titles of nodes that reference it I'm looking for output that looks somewhat like this:

Node title!

Node body, this is the body of the "main" node, other nodes reference it!

create comments link, share links, some flag or something...

Child node 1
Child node 2
Child node 3

The problem I'm having is that I can't figure out a way to do this in views that works with how this is going to be displayed.The main wildcard here is that I'm outputting a list of nodes, not a single one. So using something like an attachment wouldn't work, since that gets appended to the end of the entire view's output, rather than to the end of a row's output.

Have you tried the Entity Views Attachment module? Sounds like this is a perfect example for this module...


Add class that surrounds all tables (or any other node,field etc...) using preprocess template? I have been able to find information on adding classes to tables and other items in my pages, however, I cannot find any information on wrapping the entire table for example in a div through the preprocess function.

I added this for example:

function bootstrap_preprocess_views_view_table(&$vars) {
    $vars['classes_array'][] = 'table table-striped';
}

My tables are stripped which is what I was after, however, I would like to wrap the entire table itself in
{TABLE}
, but am not finding where / how to add the class to show before the table?

Adding a picture of where it could be added:

you can override views-view-table.tpl.php template to achieve this.

Like :

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
   <?php if (!empty($title) || !empty($caption)) : ?>

<?php print $caption . $title; ?>

  <?php endif; ?>
  <?php if (!empty($header)) : ?>

        <?php foreach ($header as $field => $label): ?>
          <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
            <?php print $label; ?>

        <?php endforeach; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>

Get a look for override views template here

For other tables Override theme_table and change its return statement Like:

return '
'.$output.'
';


How to display menu bar over slideshow block? On my site, I am not able to show menu bar over the slider block in content. When I click the menu over the slide image, part of it disappear under the slide block.

When I click on the Services menu, it shows odd things. This problem is not persist on IE.

You can increase the z-index property of your menu bar.

If this does not help, add the position:absolute property in CSS class; and also add the position:relative property to the container of the menu bar class.


Views - comprehensive source for studying? Making my first website I've been playing a lot with Views recently but I am still struggling to master both Relationships and Contextual filters. I've watched the video trainings provided in the views' section as well as passed through the docs but I think that's not deeper enough. Could you guys suggest some source for studying on this topic - a book, video series, web page ... ?
Much appreciated :)
BR, Ivan

By all means - start the Taming the Beast screencast series by NodeOne: http://nodeone.se/en/learn-views-with-nodeone-part-1-overview


How to log user in to multiple drupal sites? I have multiple drupal sites on the same server (VPS). Thise sites has separated d7 core and db. All sites has own domains: domain1.com, domain2.com, domain3.com..

When user logs in to one site I need him to log also in to the another site.
This should be done in single sign on so user does not have to log first to one site and then to another.

How to automatically log user in to the both/multiple sites?

You are looking for Multisite Login module

Multisite Login allows a user to login to all sites in a multisite
configuration, even though the multisites do not share domain names.
NOTE: if you are using several sites on the same domain (ex.
politicker.com, nj.politicker.com, ny.politicker.com, etc.), then you
do not need this module. The multisite functionality in Drupal core
has the ability to share logins for sites like these without
additional modules.

also take a look at CAS module.


Problem with JS converting module form d6 to d7 I am converting a module from d6 version to d7 and I encountered some javascript problems.In the following code below .each() function isnt getting fired.But the its going till the .attachVote function for sure. Is this correct way to do it, or am I missing something?????

(function ($) {
/**
 * Create the smackdown object/namespace.
 */
Drupal.smackdown = function() {};

/**
 * Attach the smackdown behavior to nodereferences on the page.
 *
 * @param context
 *   The jQuery object to apply the behaviors to.
 */
Drupal.behaviors.smackdown = {
 attach: function(context, settings) {
    if (typeof Drupal.settings.smackdown !== 'undefined') {
        var field_1 = '.field-' +        Drupal.settings.smackdown.field1.name.replace(/_/g, '-');
         var field_2 = '.field-' +  Drupal.settings.smackdown.field2.name.replace(/_/g, '-');
         if (Drupal.settings.smackdownPerm == 1) {
             Drupal.smackdown.attachVote(context, field_1 + ' .field-item a');
             $(field_1 + ' .field-item a').attr('rel', Drupal.settings.smackdown.field1.nid).addClass('smackdown-processed');
            Drupal.smackdown.attachVote(context, field_2 + ' .field-item a');
            $(field_2 + ' .field-item a').attr('rel', Drupal.settings.smackdown.field2.nid).addClass('smackdown-processed');
        }
    else {
         Drupal.smackdown.attachNotice(context, field_1 + ' .field-item a');
         Drupal.smackdown.attachNotice(context, field_2 + ' .field-item a');
     }
   }
 }
};

/**
 * Attach the smackdown behavior to a particular link.
 *
 * @param context
 * @param selector
 *   jQuery selector for links to attach behavior to.
 */
Drupal.smackdown.attachVote = function(context, selector) {
 $(selector, context).each(function() {
     var $element = $(this);
     // Attach the on-click popup behavior to the element.
     $element.click(function(e){
     Drupal.theme('voting', $element);
     var nid = $element.attr('rel'); // not compatible with clean urls
     var sid = Drupal.settings.smackdown.sid;
     var params = {'cid':nid, 'sid':sid};
     // post nid and context to smackdown/vote
     ajaxOptions = {
       url: Drupal.settings.basePath + 'smackdown/vote/' +  Drupal.settings.smackdown.token,
      dataType: 'json',
      data: params,
      success: function(json) {
        // we put the location into a variable so that it can be changed by other modules
        location.href = json.location
      }
    };
    $.ajax(ajaxOptions);
    return false;
  });
});
};

Drupal.smackdown.attachNotice = function(context, selector) {
 $(selector, context).each(function() {
   var $element = $(this);
   $element.click(function(e) {
    Drupal.theme('notice', $element);
    return false;
   });
 });
};

Drupal.theme.prototype.voting = function(element) {
  var output = "
" + Drupal.t('Voting...') + "
";
 element.parent().css({'background-color':'#ffc'});
 return element.parent().append(output);
   };

Drupal.theme.prototype.notice = function(element) {
  var output = "
" + Drupal.t('You do not have  sufficient rights to vote.') + "
";
 element.parent().css({'background-color':'#ffc'});
 return element.parent().append(output);
 };
})(jQuery);

Make sure that the $(selector, context) is valid on the page it's being called. You should be able to do this by doing a console.log($(selector, context)); in the first line of the function.

Assuming the selector and context are valid, the .each() should be executed.

If they are not valid, you may have to replace the element or context being passed into Drupal.smackdown.attachNotice().


Creating a page dynamically Using Views in Drupal 7 I can consume the output of a restful API. I want to take some of the data and dynamically create pages. For example I get the following return json:

$data = {'title':'This is a page title','alias':'pages/page-alias-name','content':'This is some content'}

I would want to dynamically create a page located at http://www.example.com/pages/page-alias-name which would have a title of $data['title'] and the content would be $data['content']. Is it possible to create pages dynamically like this. How can I go about doing this?

Additionally, if I had identical content stored in an external database that can be read by a custom Views module, can I do this and how would I go about it?

I'm not sure how you are using Views to do this, but with a custom module you could easily do this with a fairly simple hook_menu(), eg, something along these lines:

function YOURMODULE_menu() {

  $items=array();

  $items['pages'] = array(
    'page callback' => 'YOURMODULE_get_some_rest',
    'access callback' => TRUE,
  );

  // any other menu items go here

  return $items;

}

and then:

function YOURMODULE_get_some_rest() {

  $args=func_get_args();

  if ($args) {

    $alias='pages/' . implode('/', $args); // so pages/foo works as does pages/foo/bar etc

    $data = /* get your data from your external service */ ;

    if ( /* $data was found */ ) {

      drupal_set_title( /* title in $data */ );

      return /* content in $data */ ;

    } else {

      return MENU_NOT_FOUND; // we don't have an alias of that name

    }

  } else {

    return MENU_NOT_FOUND;  // just called 'pages' so do something else here if need be, perhaps a list of all pages but for now, we just return not found

  }

}

so after a cache clear, users should now be able to go to www.example.com/pages/alias and Drupal will go out to your external service and grab the content and if found, populate the page with it, otherwise will return not found.

Now, if this data is going to be fairly static, I'd look into caching it so your users aren't delayed while Drupal fetches it.  For that, I'd look into cache_set() and cache_get().

ADDITION:

Drupal's menu system works on a sort of best fit methodology.  For example, if you define a menu item foo, it will obviously match www.example.com/foo, but, if no menu item has been defined for foo/bar, it will also match www.example.com/foo/bar or even www.example.com/foo/bar/baz/bing etc etc.

So, in my example above, I defined pages.  This will match www.example.com/pages which is just an error condition above, but with some programming could list all of the potential pages you have available to you, but also will match www.example.com/pages/alias-of-page or www.example.com/pages/alias/of/page.

Inside the callback, I use PHP's built-in function func_get_args() to deal with the variable number of arguments that can be passed to this function.  When you go to www.example.com/pages, no arguments will be passed to this callback and func_get_args() will return an empty array.  But, when you go to www.example.com/pages/alias-to-page, Drupal will automatically pass alias-to-page to the callback, and func_get_args() will return an array containing it, and when you go to www.example.com/pages/alias/to/page, it will pass three arguments, alias, to, and page to the callback function and func_get_args() will return an array containing all three.

As to your commentary question regarding this inside Views, once again, I'm not sure how your are doing this inside Views, but yes, this would go inside YOURMODULE.module and would stand alone outside of Views (although Views might be a great place to generate the listing on pages by itself).


views query I can't workout I know the query I am trying to achieve. But how to start create it in views using drupal 7 alludes me. This is what I am trying to achieve

SELECT * from Articles where Node IS NOT current Node.

You need to use views contextual filters. Add a contextual filter Content:Nid and provide default value as "Content Id from URL" and select Exclude checkbox in the settings. That's it !!


How to get a node object/id from theme functions when the form is ajaxified? I used theme_radio() hook to change the html code of my radio buttons in ubercart attributes form to get something like that:

The code I used in theme_radio function to display this is:

//We modify only radio input in ubercart attributes forms
  if(isset($variables['element']['#parents'])){

    if(($variables['element']['#parents']['0']=='attributes')&&($variables['element']['#parents']['1']=='8')&&($variables['element']['#type']=='radio')){

      $node = menu_get_object();

      $position = $variables['element']['#return_value'];

      //We load content from field collection
      $field_collection_entity = field_collection_item_load($node->field_colors['und'][$position]['value']);

      //We extract color name from field collection
      $color_code = $field_collection_entity->field_color_code['und'][0]['rgb'];

      $pellet_html = '';
    }else{
      $pellet_html = '';
    }
  }else{
    $pellet_html = '';
  };

So everything works well when I load the page.

The problem occurs when I select something in form. As the form is ajaxified, actually when I click either on colors or sizes inputs, the form reload and my function is no more able to retrieve the node object with:

$node = menu_get_object();

or with:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
  }
}

After I clicked in a option, the color inputs get back to initial state:

So how to retrieve node object/id from a theme function when form is ajaxified??

You can check the form there:

http://www.zanonymes.krown.ch/collections/les-accroch%C3%A9s

You can try to store the node->nid in a hidden field on page load. When your ajax call is executed, you can load the node from the hidden field instead of the menu_get_object.


How to add rel="author" attribute to Drupal 7? In the brave new world of Google, great integration with Google+ is mandatory for all webmasters who want to get as much traffic as possible. If adding the rel="publisher" attribute to a website is done with the Meta Tags module, it seems that there's no official way for supporting the rel="author" attribute. For those of you who don't know about I am talking about, read this article from Google: Author information in search results

Apparently support will be included in Drupal 8. I've seen some discussions about adding this to the Drupal 8 core.

But how to implement this in Drupal 7?

I am asking this as a noob in customizing the insides of Drupal. So, if you have some good ideas, please keep this in mind.

Appreciate your ideas.

The rel=author property is now supported by the Drupal 7 Metatags module dev version.

After installing the metatags module (http://drupal.org/project/metatag), go to admin/config/search/metatags, and edit the front-page or one of the node pages. Under 'Advanced' you will see the author and publisher fields where you can input your google+ page URL. On the following screenshot, I've marked the places you need to change the configuration in pink.

Metatags frontpage configuration page:


Map Proximity - Modify markers I want to build a map that has multiple control selectors above the map. When one icon is selected, it prints the relevant markers all over the globe on the map.

If one of the control selectors appears at any one location it just shows one marker, but if two or more different control selectors are clicked on and they share the same location, the marker is modified and expands.

In essence this is something "like a heatmap" function, but not quite.

Anyone had a similar project that can relate and perhaps set me on the right path?

Maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


Copying over all the elements to a new page I have a website where we post our events. We would love to copy the 2018 event post and then edit it, rather than copying over all the elements to a new page. Is this possible?

If your events are part of a content type, then try this module. It should let you clone a node

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


Page content differs from editor I've inherited Drupal 7 website. I'm having some difficulties figuring out why one of the pages is showing different content then it actually has in the edit page.

This site is multilingual (3 languages), same page is displaying properly on 2 other languages. But on this one language instead of rendering proper content, that I see in the editor, it renders completely different content. This is the only page I'm having trouble with.

To be exact it shows sharing buttons instead of just plain text and hyperlinks content. These sharing buttons aren't supposed to be there in the first place.

This isn't a front page, just regular page created through add content > regular page.

Has anyone had successfully resolved the same/similar problem and could share knowledge?

It depends on how the developer did on the website. It could be very difficult if it is done by a developer who is not familiar with Drupal. For your situation, I can share some possible places of code for your reference.

Drupal developer may do it in:

Preprocess function in theme template.php
Field pre render function in custom module.

PHP developer may do it in:

PHP condition code in node.tpl.php

Frontend developer may do it in:

DOM manipulation in theme js file.


CommerceKickstart; Slideshow content/pages disappear if I add a Product Reference field under Slideshow Content Type I am trying to add the "Add to Cart" button into a Slideshow. The problem is as soon as i add a Product Reference field under the Slideshow Content Type, if i than go to Content>Manage Content the Slideshow Content Type/pages are no longer visible.
At this point to add a new slideshow image/content i have to go to Products>Add a Product.
Somethings not functioning right.
Im pretty sure theres something that im doing wrong but i cant figure it out....

if you want an slideshow that will display products you may want to create an slideshow that will display "product displays" and add to it an relationship with the products entity, then grab from there stuff like "add to cart" button, images, prices etc.

fields in the view may be in form of :

[product_display] - title
[product_ref] - price
[product_ref] - img
[product_ref] - commerce line item "add to cart"


Place custom Block, return Internal Server Error I create a Block Plugin in a module,
it be showing the available blocks but when I try to place the block, it returns in the browser console the follow error:

  AjaxError:
  An AJAX HTTP error occurred.
  HTTP-resultaatcode: 500
  Debug informatie volgt.
  Pad: /admin/structure/block/add/hello_block/bartik?region=footer_fourth
  Statustekst: Internal Server Error
  Antwoordtekst:

I have place the code on the follow place:
DrupalRoot/modules/pagebuilder/src/Plugin/Block/testblock.php

<?php

/**
 * @file
 * Contains \Drupal\pagebuilder\Plugin\Block\testblock.
 */
namespace Drupal\pagebuilder\Plugin\Block
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */
class testblock extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#markup' => $this->t('Hello, World!'),
        );
    }
}
?>

How can i fix this problem?

When developing and encounter 500 errors, you should see if Drupal has logged the error or your webserver has logged the error. Depending on your configuration you might be able to see a full stacktrace explaining the error.

In this case you are missing a ; after your namespace declaration. So

namespace Drupal\pagebuilder\Plugin\Block

Should be

namespace Drupal\pagebuilder\Plugin\Block;

This should fix your error.


Use CKEditor for textareas in custom form I'm using the CKEditor module, and I would like to have the CKEditor in my custom textarea. I tried hard but it just doesn't work...

This some of the code I tried:

    $form['body'] = array (
        '#type' => 'textarea',
        '#title' => 'Item Snippet',
        '#default_value' => $body,
        '#cols' => 80,
        '#rows' => 7
    );
    $form['']['format'] = filter_form();

Use the text_format element type and CKEditor will catch your field:

  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
  );

If you have issues with showing CKEditor in popup use additional #pre_render:

  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => t('Body'),
    '#format'=> 'full_html',
    '#pre_render' => array('ckeditor_pre_render_text_format'),
  );


How do you include a user's default image in a Drupal 7 view that lists people? I have a view in Drupal 7 that lists people (users). It shows the username and the standard user picture field. If a user has a set image, it comes through perfectly. However, for users that didn't set a profile image no image is shown, even though I have a default profile image set in the people settings for the site.

How do I get views to use the default profile picture for people that do not have a profile image set?

Update: I wasn't clear. I know how to use the default image in the no results behavior. The issue is that I can't get the default image to use the imagestyle I use for the other images.

I have just found the answer to this question via Drupal.org. You have to use a URI like this:

public://user_pictures/default.png

in your account settings.

Here, public:// stands for your public files location (often sites/default/files/). What comes after that, is the location of your image within public files. If you do this, the default image is treated like normal user images.


No menus being displayed in SideBar First Im using my own Omega 3 sub-theme and a new superfish menu (I created) to be displayed in the Sidebar First section of each page...no big deal. The menu displays as needed in while Im admin, but the entire sidebar is gone when viewed as anonymous. Thinking it may be an issue with Superfish I disabled the new menu and added the standard navigation menu in its place...same issue.

I kept debugging and noticed a weird issue Ive never seen: no menus are working as blocks in the first sidebar. I can add a static block with simple text or content in it and the sidebar is displayed as needed, but never functions if a menu is the only content in the section.

Any ideas?

Thanks in advance.

First of all, Menu works on the sidebar.

For your case, it's definitely the 'Permission' issue.

Permission for menu items: For example, you have only 'Add Content' item in the Navigation Menu. When you are logged in as an admin you have that menu on the sidebar as you have the permission to add a content. To display this item to authenticated/anonymous users you have to configure permission from 'Admin Menu' > 'People' > 'Permission'. Please check the permission of your menu items and configure as required.

Permission for Blocks: By default menu blocks have no permission restriction. Please check your menu block's permission section from 'Admin Menu' > 'Structure' > 'Blocks' > 'Edit' the specific block > 'Permission' tab at the bottom.

I hope it will help you.


How to set Permission based on roles for Views Data Export Using views data export module, I set the permission for different roles in the Data Export in Views like:

But I can still see the Export button for all users in front page. However if the role doesn't have permission to export then after clicking it they are redirected to Access Denied Page

Is there any way I can hide the export button from all the user roles except the ones that have permission to export?

If it was a link defined in *.tpl.php then I could have done something like

<?php if (in_array('myRole', $user->roles)): ?>
// The export button
<?php endif; ?>

But I couldn't figure out how to do it with Views Data Export (without hacking the module)

This issue has been fixed in the 7.x-3.0-beta8 version. See the issue thread here.


How can I prevent cache on any page where a paragraph appears? I am using the paragraphs module with a custom theme I created. I want to figure out how to clear the cache for any page that a specific paragraph appears on. The custom theme is composed of a bunch of templates (i.e. paragraph--paragraph-name.html.twig) and a *.theme file where I preprocess each of the paragraph types.
THEME_preprocess_paragraph__paragraph_name

I don't want to disable the entire site's cache. Can I clear the cache in this file? In this way somehow?

You probably want to be really heavy handed and use \Drupal::service('page_cache_kill_switch')->trigger();
If you put that in a custom module in hook_entity_view_alter() then you can add a conditional that fires it when your paragraph entity is being built.


How to print a custom user field in comment.tpl.php? I'm trying to print a custom user field (field_avatar) image as a replacement for the user picture. Why? user picture file directory would not accept tokens. This mean, I could run into a scenario where there are 100k files in a directory slowing the website!

From googling answers for hours, this is the best solution I've read.

In comment.tpl.php placed in my custom omega 4 subtheme, I added this code.

<?php  print render(field_view_field('user', $user, 'field_avatar'));  ?>

However, above code prints the default field_avatar picture! not field_avatar based on the comment ID? or UID of the author?

Please shed some wisdom smart ones!

I've got it working! I've used user_load($comment->uid) to load the author relationship.

I placed the code in a copy of comment.tpl.php in my sub theme.

<?php print render(field_view_field('user',user_load($comment->uid), 'YOUR-CUSTOM-USER-FIELD'));?>

Cheers and good luck!


db_insert a lot of records I am struggling to sort out how to insert a lot of records using db_insert

Please see below for the code.

I can't have a for loop in the array. It breaks but I am dealing with looping through a lot of data. 48 (states) X 365 (# days) X 36 years.

What is the best way of accomplishing this?

Thanks!

$query = db_insert('HDD')
  ->fields(array(
  for ($s = 0; $s <= $cnt; $s++) {
    'HDDDAYS' => $time, //Loops through the dates
    'AL'=> $output1[$sts[0]][$dts[$s]],
    'AR'=> $output1[$sts[1]][$dts[$s]],
    'AZ'=> $output1[$sts[2]][$dts[$s]],
    'CA'=> $output1[$sts[3]][$dts[$s]],
    'CO'=> $output1[$sts[4]][$dts[$s]],
    'CT'=> $output1[$sts[5]][$dts[$s]],
    'DE'=> $output1[$sts[6]][$dts[$s]],
    'FL'=> $output1[$sts[7]][$dts[$s]],
    ....
    'WI'=> $output1[$sts[45]][$dts[$s]],
    'WV'=> $output1[$sts[46]][$dts[$s]],
    'WY'=> $output1[$sts[47]][$dts[$s]]
  }));
  $query->execute();

You could define your query fields first, then set your field values in a loop before executing the query.

Example (not tested):

$query = db_insert('HDD')->fields(array(
  'HDDDAYS',
  'AL',
  'AR',
  ...
));

for ($s = 0; $s <= $cnt; $s++) {
  $query->values(array(
    'HDDDAYS' => $time,
    'AL' => $output1[$sts[0]][$dts[$s]],
    'AR' => $output1[$sts[1]][$dts[$s]],
    ...
  ));
}

$query->execute();


Hide some of the fields of user profile of profile2 module I am using Drupal 7 profile2 module for creating user profile and Organic group module for group managemnet.

I have user status field in user profile, and there are two options(radio button) for visibility of profile field like 1. Visible in Group 2. Invisible.

Visible in Group is selected then any group member can see the user status

Invisible then no one can see the user status field

Now I want to know that is there any way to unset the profile field during viewing. Is any hook calling during user view event ?

I have also the code that checks whether user being viewed and logged in user are member of same group or not

hook_entity_view can be used all core and most contrib entities and the more specific hook_user_view can be used when the user account is used - this is, however, not the same as the user profile itself.

You should note that this wont effect fields and entities displayed by views.


Getting an error on field module when saving a node When I'm saving a node using node_save, I'm getting the following fatal error:

Fatal error: Maximum execution time of 30 seconds exceeded in /data/www/www.example.com/htdocs/modules/field/field.attach.inc on line 664

This is not happening every time node_save is called, only for a certain new node and I can't find anything strange about the fields I'm populating. Any clue?

I would check cck fields to find which one causes the issue first and go from there, the error message related to 'fetch entities from cache, if applicable'.


Form API-built form only emails Array, not the form results I am having a special moment here:
I need to send an email with form results. These form results are in two fieldsets. This should be the easiest part of building this, but I'm having a brain freeze. How can I use a foreach loop or something similar to print my form results to the email being sent? Here's what I wrote, which just says 1 instead of the full results array:

     $uppgifter = $form_state['values']['dina_uppgifter'];
     foreach($uppgifter as $key=>$value) {
        if ($value > 0) {
            $params['message'][] .= "
" . $key . ": " . $value . "

";
        }
    }

This line is probably the problem:

$params['message'][] .= ...

If $params['message'] is a string then you want to be concatenating directly to that string like this:

$params['message'] .= ...

When you put empty square brackets [] on the end of a variable PHP treats that variable as an array and essentially pushes whatever's after the = sign on to the array.

The way you're doing it (with a string concatenation of .=) I'm not actually sure what the logic flow would be but it wouldn't be pretty...I'm surprised you don't get a fatal error for this :)


Show activities on users' posted content I would like to provide a view, and something like a newsletter, where the users can see what actions (e.g. commented) are done on their posted content.

I thought I could do this with Activity, but I can only catch the events the users did on their posts.
Do have any idea on how to provide this?

There's a module called Heartbeat that should achieve what you're looking for.

Here is a quote about it (from the module's project page):

  ... displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.


Having trouble rendering a block I've defined a block that returns a string of HTML as follows:

function product_block_view($delta = '')
{
  switch ($delta) {
    case 'groups_images':
      $block['subject'] = t('Category Images in Groups');
      $block['content'] = "
Group images html
";
      break;

    case 'singles_images':
      $block['subject'] = t('Category Images as Singles');
      $block['content'] = "
Single images html
";
      break;

    default:
      break;
  }

  return $block;
}

This block lives in a custom region named 'myregion'.  I am attempting to render this block's view with <?php render($page['myregion']) ?> but nothing comes through. The dump of $page['myregion'] looks something like this:

    array (size=4)
        'product_groups_images' =>
            array (size=5)
              '#markup' => string '
Groups images html
' (length=29)
              '#contextual_links' =>
                array (size=1)
                  'block' =>
                    array (size=2)
                      0 => string 'admin/structure/block/manage' (length=28)
                      1 =>
                        array (size=2)
                          ...
              '#block' =>
                object(stdClass)[116]
                  public 'bid' => string '77' (length=2)
                  public 'module' => string 'product' (length=7)
                  public 'delta' => string 'groups_images' (length=13)
                  public 'theme' => string 'id' (length=2)
                  public 'status' => string '1' (length=1)
                  public 'weight' => string '0' (length=1)
                  public 'region' => string 'findyourflavor' (length=14)
                  public 'custom' => string '0' (length=1)
                  public 'visibility' => string '1' (length=1)
                  public 'pages' => string '<front>' (length=7)
                  public 'title' => string '' (length=0)
                  public 'cache' => string '1' (length=1)
                  public 'subject' => string 'Category Images in Groups' (length=25)
              '#weight' => int 1
              '#theme_wrappers' =>
                array (size=1)
                  0 => string 'block' (length=5)
        '#sorted' => boolean true
        '#theme_wrappers' =>
            array (size=1)
              0 => string 'region' (length=6)
        '#region' => string 'findyourflavor' (length=14)

Any idea what I'm doing wrong that is causing my div to not be rendered by the render function?

You forgot to print the results. Use:

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

Explanation:

During a page request, Drupal keeps all the data it loads in PHP arrays for as long as possible. The reason for this is, that as long as the data is in arrays, it can be changed by other elements. This is the power of Drupal's module system.

The array posted in the question is such a data array, it's called a "Render array". Eventually this array must be converted to HTML, this is what render does: it converts a drupal render array to an HTML string. Calling render often happens at end of a page request.

So calling render gives you an HTML string that should be returned to the user, e.g. by printing it in a template file.


RedirectResponse not able to redirect in hook_entity_view drupal 8 I am trying to redirect users to a page on entity view. I am using RedirectResponse in hook_entity_view. But it is not redirecting to the desired page.

This is how I implemented this.
After fetching my redirect url, I have passed it to RedirectResponse.

return new RedirectResponse($redirect_url);

Thank you

Thank you, I got it working.
Don't need to return the object of RedirectResponse. It works like this.

$response = new RedirectResponse($redirect_url);

$response->send();

It works this way.


Creating user alert node on User Alert module The steps for using the User Alert module are the following:

  Enable User Alerts
  Set the appropriate permissions for selected roles
  Set the User Alert block in the appropriate region of your theme.
  Create a user alert node.

How can you create a user alert node in Step 4?

The module defines a "User Alert" content type; when you go to http://example.com/node/add/user_alert (replace example.com with the domain name of your site), you are going to create a node of that content type, if you have the permission to create nodes of that content type.

/**
 * Implements hook_node_info().
 */
function user_alert_node_info() {
  return array(
    'user_alert' => array(
      'name' => t('User Alert'),
      'base' => 'user_alert',
      'description' => t('A User Alert is a short Twitter like message displayed at the top of the site, alerting users to critical information like an online sale, new blog post, or breaking news. After viewing it, they can click and close the message.'),
      'has_title' => TRUE,
      'title_label' => t('Title'),
      'disabled' => FALSE,
    )
  );
}

Check on admin/people/permissions you have at least the "User Alert: Create new content" permission; that is the permission to create nodes of that type. Then, you need the "User Alert: Edit own content" permission to edit the nodes you created.


Add a Radio-button with other option in comment type I have the following requirement in Drupal 8:

I have to create a comment type with options. In options there will be a Other option on whose click a text field will be opened.

something like below image:

How can i achieve the showing of text box on other option selection in comment type?

I think you need to do this in a hook_form_alter.

I have written some example code that you can use. The code is probably not 100% correct, but it's intended to help you, to get an idea of how to solve the problem.

function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface  $form_state, $form_id) {
  $form['radios_field']['#ajax'] = [
    'callback' => 'MY_MODULE_radios_field_callback',
    'event' => 'change',
    'wrapper' => 'radio-field-wrapper',
  ];

  if ($form_state->getValue('radiois_field') == 'other') {
    // Field to show when options is "Other".
    $form['textfield'] = [
      '#type' => 'textfield',
      '#attributes' => [
        'id' => 'radio-field-wrapper',
      ],
    ];
  }
}

function MY_MODULE_radios_field_callback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setRebuild();
  return $form['radios_field'];
}


synchronize two webform select options In my webform page I have two select options components:

Item number:
20 | 20 ,
35 | 35 ,
40 | 40

Price List:
100 | 100 ,
200 | 200 ,
300 | 300

I need these two select options components synchronized. If one selects Item number (35) the price list also moves to (200).

Is there any module available to do that, or how can I get the synchronization of the two select options.

I do not need to synchronize, but combine (merge) them in one list.
In Webform Views Select  I can also combine by using Rewrite Results,

field "Item Number", exclude from display

field "Price List",
Rewrite Result:
[value] - price [value_1]

Then I can get in a single select option list:
20 - price 100
35 - price 200
40 - price 300


How to loop through field deltas of an object? In Drupal 7 I loaded the node/entity I want with node_load / entity_load and, if necessary, then I took a field with multiple deltas and take the value I wanted with a foreach loop.

In Drupal 8 how can I do the same in a hook?

For example, this loads my first value of a field:

$a_id = $adress->field_a->target_id;

In this case an entity reference field.
But there are more target_ids.

So how to take them?

Entity reference fields have a method called referencedEntities().

Usage example:

$addresses = $entity->get('address');
foreach($addresses->referencedEntities() as $delta => $address) {
  // Do something with the $address entity
}

P.S.
If you only want the field then as @Clive mentioned you can just iterate over $addresses.


How do I get the username from the user ID? I want to print the username knowing just the user ID. How do I achieve this?

You can use user_load or \Drupal\user\Entity\User::load to do this. Below code will provide the solution

 public function content() {
     $account = \Drupal\user\Entity\User::load('uid'); // pass your uid
     $name = $account->getUsername();
     drupal_set_message($name);
 }

$name gives the username of the user.


entity_query: sort: Column not found: Unknown column 'membership__field_year.field_year_value' I am using a entity_query, where I get a fatal error because the sort field is not found. The integer field (field_year exists) and exists in the database in the membership__field_year table in the field_year_value row.

query = $this->entity_query->get('membership');
$query->condition('field_membership_member', $this->member->id());
$query->condition('status', 1);
$query->sort('field_year' , 'DESC');

This is the error I get:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'membership__field_year.field_year_value' in 'field list'

How do I sort on an integer field?

Found the culprit. Apparently I was calling $query->execute() twice.


Where are the "Publishing options" for a node stored in the database? I need to order a column in a custom module by whether the node is published or not. Can't figure out where this is being stored in the database.

It's the status field in the node table (in Drupal 7).


Using hook_form_alter to add a label/placeholder insider a form  tag using Drupal Commerce checkout form there is a default 'address' field (it's dynamic and includes several fields in one that are not easy to separate - such as country, name, address 1 and 2, state, etc.). I turned off the labels for the address field because they are ugly and I'd like to put the labels INSIDE each  tag, as you would normally do with html like so:

HTML 5:

<input type="text" name="user" placeholder="Username">

Where the 'placeholder' property shows what should be entered into the field within the  tag, thus removing the need to have a separate label at all.

Anyone know how to do this (include a placeholder property if you will) with hook_form_alter?

You can specify placeholder attribute in '#attributes' array like this:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['item']['#attributes']['placeholder'] = t('Placeholder text');
  }
}


How can I save multiple images to one image field programtically? I have an image field that I am trying to save multiple images to.  There is one field but when I set up the array, only the first image fid is saved.

$i = 0;
foreach ($photos as $photo) {
// make sure we actually retrived this particular image
if ($photo['Success'] == TRUE) {
    // setup the filename and filepath, then write the file to disk
    $filename = "{$id}-{$number}.jpg";
    $filepath = "public://drealty_img/{$filename}";

    // Create image object
    $file = file_save_data($photo['Data'], $filepath, FILE_EXISTS_REPLACE);

    // add this image to the content entity
    $content->images = array(
        'und' => array(
            $i => array(
                'fid' => $file->fid,
            ),
        ),
    );
} // endif $photo['Sucess']
$i++;
} // endfor $photos

Am I saving the image field incorrectly?  Or is there something that needs to be set up to allow for multiple images to be saved?

I changed the following code:

 $content->images = array(
        'und' => array(
            $i => array(
                'fid' => $file->fid,
            ),
        ),
    );

to

$content->images['und'][$i] = array(
  'fid' => $file->fid,
);

And it worked


Remove status messages from content output? I want to move status messages into a region, but I can't seem to get it to stop being output as part of the main content output.

I tried this:

function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'content' && isset($variables['elements']['messages'])) {
    unset($variables['elements']['messages']);
    //$variables['elements']['messages']['#printed'] = FALSE;
  }
}

While that removed it from the array, it is still being rendered.

at /admin/structure/block, you can find the block "Status Messages" and move it to the "- None-" region, or another region of your choosing.


Expose filter in block to show results on view page I want to make custom search block on home page, in header region. I'm using Exposed filter block in Views module, but results on the page are shown just below the block, in header. I want results of the search to be shown on the other page, like regular search do. Is there a way to achieve this. I'm using Drupal 7.

Create a page view using filter you want.Step 1) Enable the block in your View

Step 2) Put the exposed filter block where you want it to be

Step 3 ) Test the result


How do i run node save in background process I have created drupal website for ecommerce store.

Issue:
After node save i will redirect to thankyou (destination) page for tracking but it takes long time to complete.
Customer may skip if it takes long time to complete the process.

How do i run node save in background process and display thankyou page immediately after placed order.

I want to track order conversions and node save.

Please help me to resolve this issue.

Thanks,
Yadavan

You can instead of saving the node directly, modify the node object with attributes from the form and then add it to a queue so you can use the Drupal queue system to do the actual node_save() operation on it.


Get locations search: Show all markers by default I played around with the get locations module for drupal escpecially with the get locations search part.

Finally I got the thing working but I'm wondering now if it's possible to display by default all markers on the map and not only the result markers after a search.

A blank map till I searched something is very confusing to the user.

Thx for any advice in advance.

EDIT

Okay I try to write a patch on my own. My research is based on version 7.x-1.10 The essential part ist to load the lat/longs of the location nodes and also the min- / maxes into the array in getlocations_search.module line 290:291 which is

$minmaxes = '';
$latlons = array();

For the "normal" map they are loaded in the function getlocations_nids() on line 828 in the file getlocations.module.

Try using Open layers Module which has an option for adding multiple locations n single map...

OpenLayers:

  The OpenLayers core code stores map's object configurations: maps, layers, styles, sources, controls, interactions and components. It combines them to create maps using the OpenLayers JavaScript library on any Drupal site.


Change form title for a custom entity I'm just trying to clone a d7 site in 8.  My first step was to use drupal console to generate a custom entity.  Everything is working fine but I want to change the title of the form to "Create project" instead of the default "Add project".

I don't see "Add " anywhere except for module.links.action.yml, but that is just the local action - it doesn't change the name of the form.

The root of the directory looks like:

config
  schema
    project_entity_type.schema.yml
src
  Entity
    ...several classes
  Form
    ...several classes
  templates
    ...couple template files
  Tests
    LoadTest.php
module.page.inc
module.links.action.yml
module.links.menu.yml
module.links.tasks.yml
module.module
module.permissions.yml

The answer comes from here: https://www.drupal.org/node/2187643.

Note: change "module" in the below code to the name of your module.

The first step is to register an event subscriber service. In module.services.yml:

services:
  module.route_subscriber:
    class: Drupal\module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Next, create your class RouteSubscriber and extend RouteSubscriberBase:

  namespace Drupal\module\Routing;

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

  /**
   * Subscribe to the Route to change page titles.
   */
  class RouteSubscriber extends RouteSubscriberBase {

    private function alterRoutes(RouteCollection $collection) {
      if ($route = $collection->get('entity.project_entity.add_form')) {
        // set the title (or override '_title_callback' below)
        $route->setDefault('_title', 'Create Project Request');
        // unset the _title_callback; alternatively you could override it here
        $route->setDefault('_title_callback', '');
      }
    }
  }

Note that you receive a RouteCollection in alterRoutes and then using the $collection-get() will return an instance of Route.  The documentation for Route can be found here: http://api.symfony.com/2.7/Symfony/Component/Routing/Route.html

If you're having trouble figuring out what your routes are, the excellent drupal console drupal route:debug tool will help you.


How do you programatically determine who submitted a webform? When I add a value element to a new webform draft and I attempt to prepopulate the element with a token listed as available, the element does not get populated.

@beltouche: It should be noted that this YAML source creates a webform that internally stores the displayname property.  As a result the identified user is stored wherever the webform submissions are stored.  I now assume this is as designed.  It seems to me that the prepopulation of a webform using something like {{ user.displayname }} is best accomplished by using a block/webform hybrid content type.  Am I on the right track with this thinking?


Commerce: 1 product but N prices I have a problem/question.

My client need to sell one product but the price of this product (digital, so no shipping cost or other) is based on a field in a table. Explain: X categories and Y places. Each combination of X per Y return a different price for the only 1 product.

How can I set the price of this product at "checkout" ?
In node Z (where categories is 1 and places is 2, for example) I can write the correct cost value (via preprocess_node, or template function or other), but in the cart?

You have two options.

You can create one product for each combonation of X and Y and have those as values on the product. If you reference all the products on the node, commerce can turn the value of X and Y into a dropdown which will trigger an ajax update, changing the other data for the product like this price.
The other options if you don't want to create a product for each combonation (my preferred solution), would be to create a pricing rule, custom code is probably needed here, to calculate and set the unit price on the line item based on X/Y data.


Configuring a basic multisite development environment in Linux While installing Multisite devlopment i followed below instructions    https://www.drupal.org/node/823990#comment-10184088

When i trying to call http://testsite.localhost/install.php throwing error Forrbidden Access to Page and in apache2/errorlog its showing AH01276: Cannot serve directory /var/www/html/drupal/sites/testsite.localhost/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive, referer:

If you followed the exact instructions and you did not change any paths, then you have a typo: /var/www/html/drupal/sites/testsite.localhost/ See the extra 'html' directory? Make sure the paths in the apache config (step#3) match the actual paths in your file system.


Why is a template being looked in a theme and not in my module? I have created a custom module. in that module I have create a custom twig template using hook_theme function

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
    )
  );
}

Then I created a custom block using my module here is the code of the block

public function build() {
    $config = \Drupal::config('mymodule.config');
    $role = $config->get('role');
    return array(
      '#theme' => 'mymodule_settings',
      '#role' => $role,
    );
  }

I created a templates directory in my module and inside that directory I have created mymodule-settings.html.twig file.

Cleared the cache but Drupal gives me the following error.

Twig_Error_Loader: Template "themes/subtheme/templates/mymodule-settings.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/subtheme/templates/mymodule-settings.html.twig" in the Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 45 of themes/basetheme/templates/block.html.twig).

My theme is a subtheme. Why Drupal is looking for the template in the theme and not in my module?

Try like this:

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_settings' => array(
      'variables' => array(
        'role' => NULL,
      )
      'template' => 'mymodule-settings',
    )
  );
}

You are missing to define template.


Trying to enter an argument with multiple words into a Views argument I'm using Organic Groups with Views in Drupal 7  with OG Tokens to create a view which returns all content with a type associated with it, so groups/foo/article would return all articles where the content type is article and the group is foo. This works fine for a group audience where the audience is one word, such as foo, or two run together without spaces, such as FooBar. However when I create a group like foo-bar, the view returns the no content page even when there is content attached the group. The contextual filter that I am using is OG Group: Label.

I've tried putting PHP to explode the results in the 'WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED', following the posts that I've seen but although I can see it printing out the "foo bar", it is not calling the types attached to the group. Is there somewhere else that I can explode this data and remove the spaces so that the group details can be presented in the view, or even look at the query to see what is being passed into it by the argument?

Thanks for your help and time.

UPDATE:
Having run a slightly orthogonal search, i came across the following code:

    $handler->argument = str_replace('_', ' ', $argument);
    return TRUE;

Having replaced the underscore with a dash, the multi-worded OG audience type can be used as I outlined above. Put the code into the "PHP Validate" code on the specify validation code and apply. The original came from PixelClever . I'll mark as answered when the site allows me to do so as I don't have enough user points to do so immediately.

If the arguments are not in a taxonomy term then add a vocabulary to contain them
Under the contextual filter section for When the filter value is in the URL check validation, set it to a Taxonomy term  and pick the vocabulary.
Select the Filter type or term name from the term ID
Check the box for Transform Dashes.

The view should now read the name from the URL and access the term id.


Install.php not found after installing with Drustack I'm highly experienced with Joomla, cPanel, and reasonably experienced with SSL/command-line. I know PHP and MySql enough to figure out how not to break code and do minor changes, and find stuff I need to remove/comment-out.

I installed DruStack 8.3.1 with composer create-project, and then drush site-install with --db-url=mysql info correctly done.
Both were done via SSL with the correct user (no root) and both went fine (no errors, etc). The database was filled.

The site is located at the root of a subdomain (not at a /dupal subfolder).

After those two steps, there is no index.php or .htacces at the root (which I expect for an installed site). Those are located into the /web folder, and I'm at a loss on what to do next.

When I try to access /install.php I get a 404.
If I try to access /web/install.php I'm directed to /web/core/install.php with a 500 internal server error.

I did a good search on install.php + 404 error, without any result that would help me.

Any help is much appreciated.

Please see Usage page of drustack-standard project at GitHub:

  Drupal will be installed in the web-directory.
  Autoloader is implemented to use the generated composer autoloader in vendor/autoload.php, instead of the one provided by Drupal
  (web/vendor/autoload.php).
  Modules (packages of type drupal-module) will be placed in web/modules/contrib/
  Theme (packages of type drupal-theme) will be placed in web/themes/contrib/
  Profiles (packages of type drupal-profile) will be placed in web/profiles/
  Creates default writable versions of settings.php and services.yml.
  Creates sites/default/files-directory.
  Latest version of drush is installed locally for use at vendor/bin/drush.
  Latest version of DrupalConsole is installed locally for use at vendor/bin/drupal.

Therefore setup your web server for DruStack if:

You are running with Apache2, point your DocumentRoot to the web folder
You are running with PHP internal web server, execute php -S 127.0.0.1:8080 -t web

Then access the core/install.php directly to kickstart the installation ;-)


Related Links for Content In the design for my article pages I have related links in a right hand side column.

In Drupal administration when you edit content I want to have a 'Related Links' section, which prints a list of the content currently on the site with checkboxes so a user can choose which pages should be displayed as related.

I'm new to Drupal development, however have experience in working with PHP/mySQL and writing modules for other content management systems.

What steps should I go about to achieve this? And how would I then print the selection on the front-end of the site?

Thanks so much for your time

With References or Entity References (recommended) module, you can add node reference fields to your node type.
It's pretty straight forwad. I'd suggest looking at drupal.org docs about making node types asyou are new to Drupal. You will not need to code anything in most cases. for content display, you can use theme templates and/or Views.


What is this operator:content value mean? What is this operator:content mean?

1) Under Content:Title

2) Click on Content:Title, under Configure filter criterion: Content: Title, there is a operator:content. What does value mean?

The operator shown in the screenshot is Contains. Since that is a filter for Content: title, it will show nodes whose titles contain the string you put in the Value field.

To make a summary, that view will show nodes, where:

The node is published
The content type is Webform
The node title contains style 2


Validation error on term-reference field when ajax'd option is submitted? I get the error "Illegal choice" when I submit a form with a multi-select option that was freshly created via ajax.  Workflow is like this:

User loads node edit form
User needs to select a non-existant job title (job titles are drupal taxonomy terms)
User presses my custom ajax button that (1)takes their new title, (2) adds their new title as a drupal term, (3) updates the form in the browser, (4) selects the new title

When I submit the form, drupal doesn't seem to see that the new title has a corresponding (therefore valid) TID and errors out in the validation.

I tried creating custom validation on the title element, but despite passing that validation, drupal still does its own check, which fails.

Anyone know how to work around this?

Drupal checks the integrity of the form to make sure submitted values match up with the available options when the form was built; it's a security feature. Manipulating the form on the client-side, without informing the backend that something has changed, causes the integrity check to fail.

Rather than work around it (which is possible but messy), I'd recommend using the AJAX functionality already built into the form API.

The AJAX Forms in Drupal 7 page, FAPI AJAX reference and the AJAX Example in the Examples module are excellent resources for learning about this.


D6->D8 Migrate failing to copy any nodes I am trying to migrate a measily 200nodes from a Drupal 6 site to the latest Drupal 8. The web based Migrate seems to be partially working in that I have the users migrated, content types, but none of the content/nodes did. I get errors like

Operation on Node revisions (page) failed

and then

Migration d6_node_revision:page did not meet the requirements. Missing migrations d6_node:page. requirements: d6_node:page.

Or

Operation on Nodes (page) failed
followed by
Migration d6_node:page did not meet the requirements. Missing migrations d6_user. requirements: d6_user.

I am also quite often getting an AJAX timeout after less than 60 seconds. I don't know if one is causing the other or what. It sounds like they are separate problems.

(I am using Krystal hosting in the UK. I can pick whatever PHP I want - I tried 5.6 and 7.2). Webserver is LIghtwave I think.

I don't really know what to do with this as I don't really know what that message means.

Any suggestions for diagnosing more and getting a better understanding of the problem?

PS - Just this evening I successfully migrated a D7 to D8 site - but that was using a different host.

In migrations, programmatically you can make requirements so a migration cannot be ran until another migration has already been ran (migrated).

  Operation on Nodes (page) failed followed by Migration d6_node:page
  did not meet the requirements. Missing migrations d6_user.
  requirements: d6_user.

So what this error is saying is you need to run d6_user first; before you can run d6_node:page.

Why you might ask? Because nodes have authors, so the user's need to be already migrated so the node can set the authors. Otherwise, you would end up with nodes that don't have authors.

  Migration d6_node_revision:page did not meet the requirements. Missing
  migrations d6_node:page. requirements: d6_node:page.

Like wise here, you can't have a revision until a node exists. So you need to run d6_node:page before running d6_node_revision:page


Custom ordering flow I was wondering if it's possible to replace the default commerce flow with my own custom flow.
As far as I know the default flow is following:

Add individual products to cart on Product's detail page or in Products View
Go to cart and proceed to checkout
Add shipping & billing information
Complete the payment

My flow need to be a bit different. I would like to create View of Products (my products are entry-tickets for an attraction) where user can select quantity of each Product he would like to purchase. I know this View can be AJAXified to change total price dynamically according to quantity of each product. When customer selects all tickets and quantities I need to send him to second page of my Multi-step webform where he enters shipping & billing information and finally confirms / fullfils the payment. After successful payment confirmation / fullfilment I'd like to display the third page of Multi-step Webform where is only confirmation and "thank you" message.
I've read through Commerce 2 documentation and I know how to change Order & Checkout workflows, but I'm not sure if I can use Multi-step Webform where the steps are following (as described above):

Step 1: Select quantities of each Product in Products View (10 products in total - ticket types)
Step 2: Fill shipping and billing information
Step 3: Display confirmation message

The general idea is to skip the cart step where I need to go to cart page and instead realize whole flow as a 3-step Multi-step Webform.
Thanks!

To skip the cart part of the checkout flow, I have been using the patch here. This is the leading patch for decoupling the cart from Commerce (it's a bit hard-wired at present).
If you want to customize the checkout flow with more steps, you can write a custom checkout flow plugin.
To add a custom confirmation message, you can write a checkout pane.


preprocess function call - $vars[node_title] does not work as a parameter, while $vars['node-title'] does I am writing a preprocess function. I provided a linkIt function that does the linking for me:

function linkIt($what, $where) {

return '' . t($what) . '';

}
If I call it this way:

$test= linkIt('XXX', $vars[node_url]);

it produces a Drupal error 'Use of undefined constant node_url - assumed 'node_url''. If I call it

$test= linkIt('XXX', $vars['node_url']);

with quotes around node_urlit works fine.
The former syntax is properly evaluated if I do not pass it as a function paramter, for example in

$vars['opis'] = '' . t('XXX') . ''

Why is it so?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

See PHP:Arrays - Manual Chapter "Array do's and don'ts"


Unable to get Video + VideoJS to play MP4s on ANY Android device This is a multi-part question - I'm running Drupal 7.14, w/ Video Module 7.x-2.9 and VideoJS Module 7.x-2.2, configured a Content Type to upload only MP4s, and Manage Display to use Video settings, where the Players for all Formats are set to VideoJs - and I get videos to playback on all modern browsers - chrome, firefox, safari, ie, iphone/ipad, windows 8 smart phone, just NOT any of the android devices.

I actually tested a Samsung Galaxy S1 Tablet w/ Adobe Flash 6.3 installed, and I still couldn't get the VideoJS 3.0 Flash Fallback [that I normally get on Firefox].

Anyways, the other part of the question is where to actually put my .htaccess file in a multi-site installation that I have my mime type set to video/mp4 .mp4? I'm guessing this may have something to do with it on Android?

I've scoured videojs forums, video/videojs module bug tracking, and couldn't really answer this question. Any advice would help. ALso, I don't have autoplay enabled as a setting on Video Module.

Thanks,

Many issues with playback are usually due to improperly formatted/encoded files. Different browsers/devices do not support the same media formats in their implementations of HTML 5 video. This due to mainly patent issues, open-source vs. proprietary and disagreement over which is the "best" format.

To make your video work in the latest versions of all major browsers, you will need to serve your video in both WebM format and MP4 format. To guarantee the broadest range of browser/device compatibility you may also need to include the Ogg format.

WebM: Firefox 4+, Chrome and Opera 10.6+
MP4: Internet Explorer and Safari
Ogg: Firefox 3.5+, Opera 10.5+

Go to http://html5test.com/ using your test devices to see what formats are supported.

Helpful info:

http://www.longtailvideo.com/html5/#media_formats

http://www.longtailvideo.com/html5/formats/


Create a controller and a empty theme page On Drupal 8, I'm looking for a way for creating an empty page (a page without any theme) that contains JavaScript code.
I created a controller via Drupal Console, and I searched for an example on the web, but I found only very simple examples.

Is it possible to create an empty page accessible via a controller and add JavaScript code to this page?

Controllers must return a response (you will get an error if you don't). Your options are to return a render array, an HtmlResponse, a JsonResponse, or an AjaxResponse.

Edit: Or as Kevin posted below, a Response.

By the sounds of it, you are wanting to return JSON, so JsonResponse is likely what you are looking for.


Order won't programmatically mark as completed I am struggling to get an order to be marked as completed in Drupal 7 Commerce.

Customers will go through the checkout process inside of Drupal, gets marked as "Awaiting shipment" (a custom order status), but then a fulfillment team goes through a different program and the order should be getting updated programmatically as "Completed".

However, when I use commerce_order_status_update it doesn't seem to want to get marked as completed.

Here is the code I am working with:

$order_entity = commerce_order_load($orderId);
commerce_order_status_update($order_entity, 'completed', false, true, 'Order updated via warehouse');
watchdog('warehouse', 'Order status updated %o', array('%o' => $order_entity->status)); //Does not equal 'completed'

I know this code is firing because of two reasons:

When I set 'completed' to be different status messages, it works
I see the revision message "Order updated via warehouse", but the status has not changed.

Is there something I have missed? Am I marking the order as completed in a wrong way?

I have also tried EMW

$order_wrapper = entity_metadata_wrapper('commerce_order', commerce_order_load($orderId));
$order_wrapper->status->set('completed');
watchdog('warehouse', 'Order status updated %o', array('%o' => $order_wrapper_status->value())); // Does not update to 'completed'
$order_wrapper->save();

EDIT
I added the watchdog statements that I have used to echo out of the operation was successful.
It should also be noted that there are no Rules modifying the order status at this point. I have gone through my list of Rules and verified that nothing is modifying it, and the order history shows no new revision created from Rules.
Error logs also show no error happening on save process. The operation is successful if I change 'completed' to any other status.

I figured this issue out.

I had a Rule that was firing "before a commerce order was saved" that reset the order status but did not show any errors or log any thing. Not sure why that rule wsn't working correctly, but now that I have disabled it, the status is updating successfully.


Update enabled migration module I enabled a migration module. Now I would like to make some changes inside the yml file. How can I update my migration?
I use  migration plus.

You could do a partial configuration import and then a cache rebuild

drush cim --partial --source=modules/custom/MY_MIGRATION_MODULE/config/install -y
drush cr


What's the coding standard for class constants? I'm trying to figure out the proper naming convention for class constants.

For general constants, the coding standards states:

  Constants should always be all-uppercase, with underscores to separate words. This includes pre-defined PHP constants like TRUE, FALSE, and NULL. Module-defined constant names should also be prefixed by an uppercase spelling of the module they are defined by.

However, object-oriented names don't follow the normal conventions of prefixing the name with the module or using underscores, instead opting for various forms of camel case. And unfortunately, the object-oriented coding standards doesn't mention class constants at all.

So which of the following is correct?

class Foo {
  const FOO_CONSTANT_VALUE = 'bar';
}

or

class Foo {
  const CONSTANT_VALUE = 'bar';
}

or

class Foo {
  const constantValue = 'bar';
}

The correct one would be:

class Foo {
  const CONSTANT_VALUE = 'bar';
}

For example, quoting after Zend Framework naming conventions (however there are many others for different frameworks, just Google around):

  Constants may contain both alphanumeric characters and underscores.
  Numbers are permitted in constant names.

  All letters used in a constant name must be capitalized, while all
  words in a constant name must be separated by underscore characters.

  For example, EMBED_SUPPRESS_EMBED_EXCEPTION is permitted but
  EMBED_SUPPRESSEMBEDEXCEPTION is not.

  Constants must be defined as class members with the "const" modifier.
  Defining constants in the global scope with the "define" function is
  permitted but strongly discouraged.

It does not explicitely say anything about FOO_CONSTANT_VALUE vs CONSTANT_VALUE, but not using class name in constant name is general practice. Which perfectly makes sense, considering that you are in class scope.


Filter nodes by today's date Following what described in Views filter criteria date field is greater than current date, I have used operator >= today with some success. I would like to create "future" nodes and they should be filtered out as well. What I need is for a date and time field to be filtered for today's date only. I have tried many things to include:

operator = today + either value type, machine readable or offset (returns no results)
operator = now + either value type, machine readable or offset (returns no results)
contextual filter: summary links (granularity not adjustable that I can find so returns multiple summary links for a single date & summary + a summary link is not a good UI for the application)
contextual filter: default value - "current date" (doesn't work; known issue with variably effective patch to core which I'd like to avoid) ref: https://www.drupal.org/project/drupal/issues/2325899
date only field (doesn't work due to UTC time & changes during daylight savings)

Figured this out.  Have to add the following 2 filters:

operator is "Is greater than or equal to" value is today

AND

operator is "Is less than" value is today +24 hours

Notes:

Must use "Is greater than or equal to" to include today at midnight and must use "Is less than" to filter out tomorrow at midnight.

It does not matter what value type you select, machine readable or offset.

The value "today" literally returns the time of midnight on today's date.  This means setting operator Is equal to "today" only returns results dated on exactly midnight of today, hence why zero results were returned.

SQL for "today" taken from Views query:

DATE_FORMAT(('2020-03-29T07:00:00' + INTERVAL -25200 SECOND), '%Y-%m-%d\T%H:%i:%s'))

"+ INTERVAL -25200 SECOND" is -7 hours correction for my time zone so time is T00:00:00 or midnight.


How to create a view based on taxonomy term of a node reference I have a taxonomy vocabulary called "Sports" that lists out a number of sports terms (Football, Tennis, etc).

I have one content type called "Team". I have a "Sports" taxonomy term reference field set as I associate a sport to the team. The field is called field_sport.

I have another content type called "Fixture". It has a node reference to "Team". The field is called field_sport_team.

That is:

a Fixture has a Team.
a Team has a related Sport.

Question:

How can I create a view with a contextual filter based on a "Sports" term that returns all related "Fixture" given that the "Sports" term is associated to a "Team" node reference?

Been stuck over the past few days...

Thank you for your help in advance!

OK. I've solved it myself!

I had to set up a relationship with "Team".

Then I added in a  "Content: Has taxonomy term ID" contextual filter. Within the settings there is a relationship option which I set to the one I set above.

Works as I expected!


Query based on multiple keywords I have 5 nodes title with some keywords:

this is my node one with some keywords
this is my second title with some keywords
this is my another title with second keyword
this is my another title second keyword
this was my last node title

My search query is: "second title"

when i search with only title keyword, query return 2,3,4, and 5 well, but when i search second title, query return only 2. So, how can i extend my query to return nodes as 2,4,3 and 5 in the last position (since 5 has only one keyword match).

This is my query:

$query = db_select('node', 'n')
         ->fields('n')
         ->condition('n.title', '%' . db_like($_GET['Keywords']) . '%', 'LIKE')
         ->execute()
         ->fetchAll();

Updated:
search keywords can more then 2 words, but query should return as much words matches.

please help!

thanks.

You want db_or().

$or = db_or()->condition('n.title', '%' . db_like('second') . '%', 'LIKE')->condition('n.title', '%' . db_like('title') . '%', 'LIKE');
$results = db_select('node', 'n')
  ->fields('n')
  ->condition($or)
  ->execute()
  ->fetchAll();


Accordion Menu - Where is the original CSS file of the module? I tried for two hours to RTLize\Flip the module via Firebug & Style.css but without major success. So I figured this is one of case when the flipping should be done at the module's CSS files themselves. So I went to sites/all/modules/accordion_menu but I couldn't find anything that has all the CSS. I found only accordion_menu.css that doesn't have more than 4-5 rows of CSS code. So it's not something I could RTLize\flip.

Therefore I ask, where is the genuine Accordion Menu CSS file (that appear in DOM but not in the style window)? How could I track it down and flip it's CSS?

Thanks,

The Accordion Menu module uses jQuery UI, which is included with core. If the styles you're looking for are in a CSS file, they'll be in /misc/ui/jquery.ui.accordion.css (or possibly one of the more general jQuery UI CSS files).

Bear in mind that jQuery UI is a javascript library, so the styles might be applied directly to the elements at runtime, and may never exist in a CSS file as such.


Webform2pdf and CiviCRM fields: pdf empty I have a Drupal website with CiviCRM. I created a webform and installed webform2pdf to create a pdf and CiviCRM integration module to add CiviCRM fields to my webform. After submission the webform fields are correctly added to the pdf but the CiviCRM fields are not.

Any idea? You think you could fix it or give me any advise?

In a Webform, CiviCRM fields are webform fields. There is no difference as far as Drupal is concerned. The only exception is CiviCRM credit card fields (which you really don't want to store in the webform submission).
The "existing contact" field is another special case, but although it gets processed a bit differently it is still a "real" webform field and ought to work fine.
So aside from the above I can think of no reason why any CiviCRM-related fields would not appear on a PDF.


Creating a block to show content in the same group of the current node I would like to create a block that in node/x displays the links to all the nodes in the same group as x.
I created a view of Content, a relation of Group but no contextual filter allows me to filter by current node's parent group

Add contextual filter "Content: Has taxonomy term ID" and make configuration like below

Provide default value : Taxonomy term Id from URL
Load default filter from node page, that's good for related
taxonomy blocks


Why cache form table gets new entries by anon page views? I am seeing new entries in my cache_form table when anonymous user view a page that had a comment form. The page cache is enabled and set to 30 min. Does this mean that cache page is being bypassed? Or does drupal cahe forms for every anonymous user using a hashed key?

Also I should mention that this happening for forms called and renderd in the theme layer (someone's mistake and I'm trying to correct this) .

Comment form is a form. All forms generate entries in form cache. Form engine uses cache as it's temporary data storage, not as the cache in usual definition of the word.

One thing it always store is a list of fields it actually displayed to a client, so it can compare it with a list of values that come back and prevent hijacking and other abuse - hence one entry per user session per form.


drush sql-sync tries to rsync unknown dump file Since I upgraded drush 5.10 -> 7.0-dev today, sql-sync fails to work with my existing alias file.

Using the command drush sql-sync @limelive @limedev fails.

The %dump-dir paths on both local and remote aliases correctly address existing directories. --debug shows the remote sql dump success:

 Database dump saved to /home/aegir/drush-backups/limetreethornfor/20140411235252/limetreethornfor_20140411_235252.sql.gz

but later reports

rsync: link_stat "/var/aegir/platforms/aventura-2014-04-11-1/Array" failed: No such file or directory

This suggest new command syntax incorrectly diagnosed. What am I doing wrong?

This is a bug in Drush master.  Please put an issue in the queue on Github.


How to set node creation limit by user type in Drupal I'm trying to set the limit on authenticated user for creating particular type of content(adding user limit on content type).

Node limit module has same functionality in Drupal 7 but i'm looking for Drupal 8.

Another new module for Drupal 8: https://www.drupal.org/project/entity_limit

Some details about it, from its project page:

  Entity Limit allows administrators to restrict the creation of the number of entities that users may create. Basically, this module provides options to define a creation limit based on user and role.


How do I get the highest `field_id` value that exists in content of a specific type? I have a content type which, among other things, have a field which contains a unique ID number (this number is used to connect the individual content to related information stored on paper).

When creating new entries I'd like to automatically generate this ID by finding the highest ID already present in the system, and calculating the next ID from that.

I have written a small module (using hook_menu()) which presents the user an interface for adding new content. How can I, from within this module, get the  field_id values of my already existing content? (So that I can calculate which ID a new entry should have?)

Is there any PHP command which can be made to return an array containing all the field_ids from my content type?

Worth to know here is that the system is kinda small (500–1000 entries of my content type, at most). There will also only be a single person entering data at a time. Also, I'm using Drupal 7.

The easiest sulotion I can think about is to use Computed field module and the id field will be computed field.
Then,  in the field read the last value using variable_get() and then update that value using variable_set().


adding css classes into a specific image field is there a way to add css classes only to specific image field?

with the image field name field_news_images:

<img class="thumbnail" src="../images/something.png"/>

There are no options to add the classes in the manage display

As of Drupal 8.2

function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_news_images') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'thumbnail';
    }
  }
}


How to move blog to a custom path in drupal? I want to move default blogs to a custom URL
i.e. blog are by default present at ./blog  but i want them to be at ./share/blog I don't want to use url aliases. I want a permanent move.

For a 'permanent' move you'll need to write a custom module and implement hook_menu_alter(), to copy the settings for the original path over to the new one, and remove the old page from the system:

function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog'])) {
    $items['share/blog'] = $items['blog'];
    unset($items['blog'];
  }
}

That will just do the core 'blog' page, the blog module defines 4 paths (see blog_menu()), each of which you'll need to override if you want make this change fully. You might also need to do some further digging into the code the blog module produces as I'm not sure if any of those paths are hard-coded into URLs or anything like that.


how to do addition of two field values in drupal 7during node_presave? I had made two content types
content type 1 - 'product' with field name 'product_stock' and
content type 2 - 'Add stock' with field name 'stock_value'. It also contains a node reference to product content type.
I want to add the value of product stock and stock value during node_presave.

For Example: product stock = 10 and stock value = 14, then both should be added to give 24.

function my_module_node_presave($node){  // implementation of hook_node_presave
  if($node->type == 'add_stock') {
    $product = $node->field_stock_value['und'][0]['value']; //get data value of field
    drupal_set_message('product :'.$product); // print data value for checking
    $nid = $node->field_reference['und'][0]['nid']; //get nid of reference field
    drupal_set_message('nid :'.$nid); // print nid
    $p_node = node_load($nid); // implemenet node_load and get in $p_node
    $stock = $p_node->field_product_stock['und'][0]['value']; //get data value of field
    drupal_set_message('stock :'.$stock); // print value

    $stock = $product + $stock; // addition of both value
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock; // updating the product field with updated value
    node_save($p_node); // implement node_save
  }
}


Pledge cannot be clicked(no link) Have a look at this screenshot:

After creating a crowdfunding reward, it appears on the event page as for example "Pledge $10 for Test Run".

When I checked the source code, I found that this line should be linked with a link <a href="/drupal/crowdfunding/pledge/2/5"> which redirects to the pledge so that the user can make the payment.

But this link is not clickable from the page. I need to go to "inspect element" in google chrome and then click on the link.

My question is, why can't I click on the link? Why doesn't it appear on the page?

Because there is no link content so there is nothing to click on.

A link should be of the form

Link content

In that example there would be the text "Link content" that you could click on.

For your code I would expect it should be something like this:

Pledge RM10.00 or more

For more information see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

To modify the pledge markup do no modify the crowd funding module. For more information on why it's a good idea not to hack modules see Why don't we hack core?

The correct way is to override the template that prints the markup.

In this case crowdfunding-reward-options-node-view.tpl.php is the relevant template file.

So copy that template file from the tpl directory of the crowdfunding module and put it in your theme. Then clear the drupal cache and the site will start using the template file in your theme instead of the one in the module.
Then modify the markup of the template that you put in your theme to suit your needs.


PDOException: SQLSTATE[42S02] on cache_block after module install I am getting the following error on my (localhost) test system after installing some modules:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'bitnami_drupal7.cache_block' doesn't exist

After receiving the error, I uninstalled and removed the modules I was attempting to install thinking that a fresh module install might fix the problem.  However, it's apparent to me that the install corrupted the database.  Before I even attempted a new install of those modules, I get the above error while performing some other work.  So, I used PHPMyAdmin to peek into the database.  When I try to access cache_block, I get an error stating that it does not exist.  Unfortunately, I do not have a recent back up since this is a test system.  However, I do have a live production system.

Question: can I use the live production system to export the cache_block table structure and then import it into my localhost?  If not, is there an alternative solution to resolve this error?  I'd like to avoid having to reinstall Drupal.

can I use the live production system to export the cache_block table structure and then import it into my localhost?

Yes, that's exactly what you should do. Core cache tables have a common structure so you could even just duplicate cache_bootstrap or another from your local and rename it.

Don't bother importing the data as you'll want to clear caches after recreating the table anyway.

Personally I'd be tempted to also go and find out what caused it in the first place to make sure it can't happen again (and so the site can stay up to date).


Invalidate Internal Page Cache on cookie change I need to invalidate the Internal Page Cache for anonymous users when the value of a specific cookie changes. How can I implement this?

I'm tried to add:

$build['#cache']['contexts'][] = 'cookies:my-cookie-name'

in hook_entity_build_defaults_alter, but that doesn't help.
And the page still returns from the cache.

The Internal Page Cache doesn't support cache contexts. It is a simple reverse proxy designed to serve static database content and the only Drupal specific feature it has is to invalidate cache tags. For more dynamic use cases you have to uninstall this module.

The Dynamic Page Cache will then be the frontend cache for anonymous traffic. It is not as fast as the Internal Page Cache, though, so if it doesn't provide the performance you need consider a third-party reverse proxy which is able to handle cookies dynamically.


Can't pass php variable to javascript in Drupal 7 Can somebody help me with this problem.
In the body of a Basic page:

drupal_add_js(array('my_var' => array('orderid' => '123')), 'setting');
drupal_add_js('sites/all/scripts/printout.js');

In printout.js:

alert("Before");
alert(Drupal.settings.my_var.orderid);

Result:
"Before" was alerted then returned to Basic page, no orderid.
What have I done wrong?

Make sure you call for jquery setting inside Drupal behaviour, you can do like this:

(function ($) {
    Drupal.behaviors.example_name = {
        attach: function(context) {
            alert(Drupal.settings.my_var.orderid);
        }
    }
})(jQuery);

or you can call inside jQuery's .ready() event (less preferable than behaviours approach in Drupal world):

jQuery(document).ready(function($) {
   alert(Drupal.settings.my_var.orderid);
});

These both approaches ensure that jQuery is loaded before calling a variable.

P.S. I recommend using console.log instead of alert for quick debugging, like this:

console.log(Drupal.settings.my_var.orderid);

Then go to your developer console / firebug (depending on browser you use) and you'll see an output in console.


Why isn't my composer installation working? I followed the instructions on docs.drush.org for installing Drush, proceeded by the recommended steps for installing Composer and a new Drupal 8 project. My project (cfbtv) is located at ~/sites/cfbtv and it appears the composer template (whatever that is) installed Drupal in the web directory.

When I try the recommended Composer commands they fail. composer update devel outputs the following.

  Package "devel" listed for update is not installed. Ignoring.
  Loading composer repositories with package information   Updating
  dependencies (including require-dev)   Nothing to install or update
  Generating autoload files

When I run composer require devel, I get this message.

  [InvalidArgumentException]
  Could not find package devel at any version for your minimum-stability (stable).
  Check the package spelling or your minimum-stability.

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

So what is the problem here?
Composer seems to have installed properly, but I'm surprised these commands aren't working. Maybe it works and I'm not using it correctly.

As shown in the example reported in the documentation page you linked, you need to add drupal/ to the machine name of the module you want to install. The given example is exactly for the Devel module.

composer require drupal/devel:~1.0

The name of the packages handled from Packagist has the format vendor/package, so if you simply use the machine name of the module, Composer will not be able to find the package you meant.

Remember to run the commands from the directory containing the composer.json and the composer.lock files, not from the core directory.