Views3 - Is there are feature in Views3 that allows for authenticated users to change the fields in a view? I'm using Drupal 7 to display a particular content type as a table view. This particular content type has the possibility of 15 columns, but I want to give users the option of displaying fields that are interesting to them. Does Views3 allow for users to select which fields he or she is interested in and save that to the profile?

Drupal 6 has a module based on Views - Control field display, which seems to have this feature.

you can allow users acces to the views UI but you couldn't limit that just to "fields". It wouldn't be end user friendly either.

You might want to show all fields in your view and then hide the fields dynamically with css.

If you want it more robust you can use a hook like hook_views_post_execute to remove fields dynamically.


Webform: POST data and send user to external URL I was reading this interesting post: Webform - Submit values from Drupal 7 from to external url

I'd like to know: instead of just sending the data via POST and keeping the user on the Drupal site, how would you send the user to the URL the form values are posted to, so that they would arrive at the new URL and see a new form with the values they submitted?

Thanks.

That post is accurate. You just need to set the #action of the form to be the URL you want to be POSTed to:

$form['#action'] = 'https://some.other.site.com/destination';


Views url paths not using proper url on localhost When running site on localhost and using field rewrite I construct a link like this for example

Set as default

I get a path that is not proper. Something like this

http://localhost/1/addresses/shipping/default/284

and it is missing a site part in url and should be like

http://localhost/MY-SITE/1/addresses/shipping/default/284

I have set a $base_url in settings.php but doesnt help. When I put site online this works fine, but what should I do for localhost?

You need to alter your .htaccess file:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal


Disable all form elements when doing AJAX I have a form where every user input field is AJAX enabled, and I'd like to disable all of the form elements when one of them is changed - is it possible?

Yes, it's possible. For example, you can attach a .js file to your form and extend the Drupal.ajax object.
Every element which can initiate AJAX submission from a form has its own instance of Drupal.ajax. You can find it in the global object Drupal.ajax. And every Drupal.ajax object has the methods success, error, beforeSend etc.
Here is a simple example to demonstrate the idea:

;(function($) {

  Drupal.testAjax = {
    // Our form
    form_id: 'node-type-form'  //Yes, I tested on my extended node creation form
  };

  Drupal.behaviors.testAjax = {
    attach: function(context, settings) {
      // We extend Drupal.ajax objects for all AJAX elements in our form
      for (ajax_el in settings.ajax) {
        if (Drupal.ajax[ajax_el].element.form) {
          if (Drupal.ajax[ajax_el].element.form.id === Drupal.testAjax.form_id) {
            Drupal.ajax[ajax_el].beforeSubmit = Drupal.testAjax.beforeSubmit;
            Drupal.ajax[ajax_el].success = Drupal.testAjax.success;
            Drupal.ajax[ajax_el].error = Drupal.testAjax.error;
          }
        }
      }
    }
  };

  // Disable form
  Drupal.testAjax.beforeSubmit = function (form_values, form, options) {
    $(form[0].elements).not(':disabled')
                       .addClass('test-ajax-disabled')
                       .attr('disabled', true);
  }

  // Enable form
  Drupal.testAjax.enableForm = function(form) {
    $(form).find('.test-ajax-disabled')
            .removeClass('test-ajax-disabled')
            .attr('disabled', false);

  }

  Drupal.testAjax.success = function (response, status) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.success.call(this, response, status);
  }
  Drupal.testAjax.error = function (response, uri) {
    Drupal.testAjax.enableForm(this.element.form);
    // Call original method with main functionality
    Drupal.ajax.prototype.error.call(this, response, uri);
  }

})(jQuery);

This approach may seem a little difficult, but it gives you full control over AJAX in your forms.
Another way is to use jQuery methods like .ajaxStart(), because Drupal uses jQuery AJAX Framework.


Restrict editor user to only edit contents in one specific language I'm trying to create a role for editors where one editor only has access to edit English contents and the other only has access to contents in another language.

I've been researching for quite a while, checked out Content Access too, but I haven't found any solution.

How can I make this happen?

Thank you!

The answered Specified here would help you give-permission-to-translate-a-specific-language
After installing Translation Management Module,

You can create users with their translation capabilities
You can specify that a user can only translate from English to Spanish and another user can translate from English to French while creating the user

Create a new user with user role: Translator (which is created when tmgt module is installed)

Then Choose his/her Translation skills as shown below :


Cache Form table size is enormous Cache table's size had increased to 10+ GB last month, and I had fixed it temporarily by truncating it. Last time I checked it was around 1GB. So in couple of months it will hit 10GB again. How should this be dealt with ?

Note that I have disabled all cron jobs on this site. If this is the reason, which cron should be enabled ?

The {cache_form} table is a little funny, and behaves in a slightly different manner than other cache tables.

If you take a look at drupal_flush_all_caches() you will see that {cache_form} isn't cleared.  This is to protect in-progress forms from being nuked.

The system_cron() function does take care of pruning out old data from {cache_form} along with the other cache tables.

You really should run cron on all Drupal sites.  If you {cache_form} table is ginourmous, then I bet your {watchdog} and {session} tables are, too.  Many other modules run housekeeping activity as part of their own hook_cron() functions.

You may also want to poke around the issue queue.  There have been some bugs with {cache_form}, and you may be running into one.


How to fetch the existing value of a form field in the form? I have a minimal form with a single field to add an image to an entity and a save button. I have used managed_file to add the image.

After adding the image from form the image gets saved in db.

Next time the user opens the form, it shows blank field and after adding a value current one gets replaced. What I want to do is user should see the existing value of the field when reopening the form.

How do I do this?

[Edit]:

Code for my form is:

// Form Definition
function custom_profile_form($form, &$form_state){
  $form = array();
  $form['picture'] = array(
    '#title' => t('File'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded file will be processed.'),
  );

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

  return $form;
}

// Form Validation
function custom_profile_form_validate(&$form, &$form_state) {
  $file = file_save_upload('picture');
  $file->status = FILE_STATUS_PERMANENT;
  $uploaded = file_save($file);
  $upl = file_move($uploaded, "public://");
  $form_state['storage']['fid'] = $upl->fid;
}

// Form Submission
function custom_profile_form_submit(&$form, &$form_state) {
    global $user;
    $user1 = user_load($user->uid);
    $file = file_load($form_state['storage']['fid']);
    $edit = array(
      'picture' => $file,
    );
    user_save($user1, $edit);
}

You can use #default_value attribute of the managed_file to show the existing value of the field.

You can get the value of fid from database and set value into #default_value.

Example:

$form['picture'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => '',
  '#default_value' => 1, //fid from database
  '#upload_location' => 'public://image_example_images/',
);


How to retrieve a shipping service settings field in Views My client needs a very specifically formatted file that displays order details. I'm using Views Data Export for this, and everything seems to be going well except for when it comes to the shipping information. I'm trying to show the Shipping Service name field for the shipping method that was used, but there's one catch: The client needs to use their company's codes for this field, not the default ones that come with the shipping module.

For example, if a customer used FedEx Ground, the field would need to display "FDXGRDCOL" instead of the default "FedEx Ground" name listed on the commerce/config/shipping page. One solution I had hoped would work was by renaming the Shipping Service's rules name in the Settings fieldset (admin/config/workflow/rules/components/manage/commerce_shipping_service_fedex_ground), but it seems that because shipping methods are not entities, I can't access stuff like this. I have attached a photo of this:

Any ideas?

Try configuring the shipping field with rewrite results, checking the "rewrite the output of this field and using a either a custom token or the machine name for the shipping type, and make the machine name the same as the client's code.


Modify default rendering of a custom content type defined in a module I am developing a module for importing, editing and exporting DocBook(XML) documents. In this module I define two new content types: docbook and  *docbook_section*. I have also defined new fields like: author, keywords, etc.

The default rendering of these content types is not quite handsome, so I would like to change and improve it. The classical Drupal way is to copy the template node.tpl.php to node--docbook.tpl.php and customize it. But this modification is done on the current theme, after the module has been installed. I would like to do the modification inside the module, so that as soon as it is installed it has a decent default look, without having to make any external modifications. Themes should also be able to override this template, in order to customize the look.

It may seem reasonable to place node--docbook.tpl.php inside the module, but that way it will not work: the theme/rendering engine will not be able to find and use the template. To solve this problem, I have defined hook_theme() on the module like this:

/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array (
      //'variables' => array('view' => NULL,),
      'template' => 'node--docbook' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'docbook'),
      'preprocess functions' => array('template_preprocess_node__docbook'),
    ),
  );
}

This time it indeed finds the template node--docbook.tpl.php inside the module. Themes can also override the template if they define node--docbook.tpl.php. But I have some problems.

First, I call nowhere the function theme('docbook', $variables), so I don't see where I can assign the variables. Another option can be to assign them on the preprocess function like this:

function template_preprocess_node__docbook(&$variables) {
  $variables['test'] = 'ABC';
}

But this doesn't work either, and in fact, it seems that the function template_preprocess_node__docbook() is not called at all, although it has been listed on 'preprocess functions' as well (at the definition of hook_theme()).

So, I am stuck. Although I have been working with Drupal7 for two years, theme and template processing still seems to me like a huge maze and I am not able to find my way around. Can somebody help me?

This is the way that I solved this problem:

/**
 * Implements hook_theme().
 */
function docbook_theme($existing, $type, $theme, $path) {
  return array (
    'node__docbook' => array(
      'template' => 'node--docbook',
    ),
    'node__docbook_section' => array(
      'template' => 'node--docbook-section' ,
    ),
    'field__field_dbw_author' => array(
    ),
  );
}

/**
 * Implements hook_preprocess_HOOK().
 */
function docbook_preprocess_node(&$variables) {
  //krumo($variables);  //debug

  if ($variables['type'] == 'docbook') {
    $variables['variable1'] = 'hello1';
  }

  if ($variables['type'] == 'docbook_section') {
    $variables['variable2'] = 'hello2';
  }
}

/**
 * Implementing theme function theme_HOOK().
 */
function theme_field__field_dbw_author($variables) {
  //krumo($variables);  //debug

  $output = '';

  . . . . . . . . . . . . . . .

  return $output;
}

See more details on these commits:

https://github.com/dashohoxha/DocBookWiki/commit/0e15266fdfa9000bd32d2ddabce036b21fa55930
https://github.com/dashohoxha/DocBookWiki/commit/0fee64d261f66878166c215559234e01e185e6f1
https://github.com/dashohoxha/DocBookWiki/commit/0fb4ac1ca7da38067c647f362c22d167c62f5ae6
https://github.com/dashohoxha/DocBookWiki/commit/db15d8af013bfc91143029c84e7cd0134400af85
https://github.com/dashohoxha/DocBookWiki/commit/c9250ba89094fc2c8fa83945ffbee0be25d42d84

I would expect these solutions to work as well:

function docbook_preprocess(&$variables, $hook) {
  if ($hook == 'node__docbook') {
    $variables['my_new_variable'] = 'hello';
  }
}

function docbook_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

function template_preprocess_node__docbook(&$variables) {
  $variables['my_new_variable'] = 'hello';
}

But somehow they don't work. Either my understanding and expectations are wrong, or there is something wrong on the implementation of Drupal.


Views exposed filter for children terms when on parent term page I have created a views with multiple exposed filters and I need another filter that is based on taxonomy.

My taxonomy structure is:

term 1

child 1.1
child 1.2

term 2

child 2.1
child 2.2

What I want is the following;

path: site.com/taxonomy/term/1

Exposed filter that can filter shows only;

child 1.1
child 1.2

How I have a filter that shows all taxonomy structure or when using depth it shows all child terms? Like this;

child 1.1
child 1.2
child 2.1
child 2.2

I'm sure there must be a way to only show the related child terms when on the parent term page.

thanks

You could use a form_alter hook in a custom module (or even your template.php file of your theme) to alter the filter values in the exposed view form.

as an example:

<?php
    function mymodule_form_alter(&$form, &$form_state, $form_id){
        //if it is the exposed filter view
        if (($form_id == 'views_exposed_form') &&
        //for the view we care about
        ($form_state['view']->name == 'your_view') &&
        //and the view display we care about
        ($form_state['view']->current_display == 'your_display') &&
        //and on a taxonomy term page
        (arg(0)=='taxonomy') && (arg(1)=='term') && (is_int(arg(2)))){
            //get the childern of the term
            if ($child_terms = taxonomy_get_children(arg(2))){
                //only care about the tids
                $child_terms_tids = array();
                foreach ($child_terms as $child){
                    $child_terms_tids[] = $child->tid;
                }

                //for the exposed filter, alter the available options
                foreach ($form['exposed_filter_name']['#options'] as $tid => $term){
                    //is is a child term?
                    if (in_array($tid,$child_terms_tids)){
                        //leave it
                    }else{
                        //remove it
                        unset($form['exposed_filter_name']['#options'][$tid]);
                    }
                }
            }
        }
    }

    ?>


display results from a form in theme-settings.php I've been working on a way to upload a background image for months and I finally got it to work. How do I display the URL to the image on page.tpl.php? It's a form called background_file. Here's my code that I'm using:

<?php
function tsaudio_form_system_theme_settings_alter(&$form, $form_state) {
$form['background_file'] = array(
'#type'     => 'managed_file',
'#title'    => t('Background'),
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),);
form_load_include($form_state, 'inc', 'system', 'system.admin');}?>

When you upload a file it creates an file ID (fid) that we need to call back, then generate the URL and then insert it.
Place this in your template file.

$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
print '';

To print it out with an image style such as thumbnail:

$fid = theme_get_setting('background_file');
print 'uri) . '">';

Not tested.


Replacing Private message module with nodes I was looking for a quick answer to the problem of allowing members to write each other messages. The Private message module looked like the most complete solution.

However, it has some significant downsides.

I can't find an API for it anymore. All the links are dead.
It uses awful HTML output which is not responsive so refer to problem 1.
It's not integrated with views!

So I wonder if a poor man's messaging system that simply uses nodes and views would be a more versatile, future proof and potentially more performant replacement. Is private messages dramatically more performant(such that it's downsides are worth it) than using nodes and views for private conversations, of which there would be potentially many?

If by API you mean documentation, there is a documentation for the module in the following link: https://www.drupal.org/documentation/modules/privatemsg
For actual API file: https://cgit.drupalcode.org/privatemsg/tree/privatemsg.api.php?h=7.x-1.x
In the same code repository, the module contains views folder with views integration, so I don't understand what you mean by no views integration?
And here is an example on how to theme the new messages block, you should check this file for more theming functions.
Hope that helps.


How can I cast a fivestar vote on a different node I'm new to drupal and trying to figure out how i can use fivestar to implement a rating system.

I have around 15 products and want my site users to be able to rate & review  them from a page named "User Reviews" and NOT from within each product page/node.

Adding the rating axis in the review node is nice and simple but can't figure out how to select the product node to associate the vote with. I want to create a select list field that would list all my products and where the user will be able to select the item they want to review. Then add their comments and ratings and submit it.

Its straight forward to do this when creating a review as a comment on the product node that is reviewed (i.e. select Parent Node as the Voting Target)  but how can I achieve this from a different node and assosiate the nodeId with the nodeId of a product?

I'm using the latest releases of Drupal, Fivestar and Voting API.

How are you generating your page with the 15 products? I think views can display the widget as a field so that might be an easy way to achieve the desired functionality.


How to remove the size of an input? I create a very simple theme with "stable" parent theme.

So far so good.

The size of input is indicated in HTML, and it bothers me a lot for the layout of my forms.

This is an example.

<input (...) value="" size="60" maxlength="128">

I have of course looked in the stable theme, but in the template input.html.twig, it is only indicated <input{{ attributes }} />{{ children }}.

I would like to remove the size indication to fully manage my layout in CSS.

How can I achieve this?

This question is quite old but here a solution

/**
 * Implements template_preprocess_form_element().
 */
function mytheme_preprocess_input(&$variables) {
  // remove size
  unset($variables['element']['#size'], $variables['element']['#attributes']['size'], $variables['attributes']['size']);
}


Pressflow Install - Redirect to database configuration without error I am currently installing the database in the conguration distribution "Pressflow." I have already installed apc and varnish.

During installation, I put the access to the database and when I click OK, I am automatically redirected to the same page. This does not create the database

Make sure that in your settings.php all your configurations are properly set. (e.g $db_url, $base_url ..)


It doesn't run the first time Trying to run cron tasks using 0 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1 or 0 */1 * * * root wget -O - -q -t 1 http://site.name/cron.php?cron_key=secretkey >> /var/log/site-cron.log 2>&1 doesn't work.

Using 0 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1 and 2 */1 * * * root curl -s http://site.name/cron.php?cron_key=secret_key >> /var/log/site-cron.log 2>&1, the second attempt works.

Access log shows both calls, but dblog shows only the second attempt.
There are no errors in nginx log, cron log, php-fpm log.

How do I fix this?

UPD: thanks @zhilevan. I was able to debug cron scripts with his help. This way drush --root=/usr/share/nginx/demo --quiet cron displays errors in cron scripts.

Running cron tasks before clear all your cache.
During development it is necessary to clear the cache very frequently.
Clearing caches is relatively harmless. Sites might slow down for a bit afterwards while the cache fills back up.


Hide the displayed article in a most viewed/popular sidebar In an article panel page, i have a sidebar with the Most Viewed articles as per RAdioactivity module. If the main article that I am viewing is one of the Most viewed, I want to hide that article link in the sidebar but instead display the rest of the Most Viewed articles links. How can I do this using Panels, mini Panels, views?

I figured it out by going to Advanced > Contextual Filter. Choose Content: Nid. Then
under "WHEN THE FILTER VALUE IS NOT AVAILABLE", pick "Provide default value", Type = 'Content ID from URL'. Under "More", check on 'exclude' checkbox.


Buying same product simultaneously in drupal commerce Case: There is a product in stock with 1 quantity. Now two or more buyers try to buy that product simultaneously.

I want to restrict any one from buying that product on first come first serve basis.

Is there any hook available ?

Please help.

Check out Commerce Stock - https://www.drupal.org/project/commerce_stock. The module itself will expose hooks for controlling stock. Or there are sub modules it provides - Simple Stock and Simple Stock Rules - which add an integer field and use Rules to validate purchases.

This runs on Add to Cart, Can Checkout, and prior to purchase.


Set a block region from the block edit page I used Drupal since 4, and it always bothered me that the the block edit page doesn't include block region settings. One must return to the Blocks list to change that. It would be so much nicer if the block edit page included the region options, when using the contextual Configure links on the page.

There is no module dedicated to this on Drupal.org, so maybe there is a good reason for not doing this, like a technical limitation. Or maybe this is not useful to anyone else but me.

Is there a module for setting the block region from the block edit page? I'll create one if there isn't.

Thanks.

In Drupal 7 you have the option to set the region of the block within the block's edit page.

I haven't seen a module for this for Drupal 6 let alone earlier versions. I would strongly recommend upgrading to Drupal 7 for this feature and the plethora of other desirable features of Drupal 7 compared to it's predecessors.

I hope that helps...


How to use Views to obtain this? I want to use the Views module to obtain the number of comments associated to a node, and show it as "1 comment," "5 comments."
How do I do this?

Checkout the Views Group By module, this will do it. Here is a quote about it (from the module's project page):

... enriches Views2 functionality with SQL Grouping and Aggregation capabilities.
A new field group: SQL Aggregation is added, in Views, once you install the module. The field group has one available field: SQL Aggregation: Group By Fields. The field allows to configure many aspects of "group by" SQL clause and "count()" fields.


Change position of submit button on form This is my code:

function feature_contact_form_form_alter(&$form, $form_state, $form_id)
{
if ($form_id == 'contact_form_node_form') {
  $form['field_user_agent']['#type'] = 'hidden';
  $form['field_ip_address']['#type']      = 'hidden';
  $form['buttons']['submit']['#weight'] = -15;
}
}

I am using Drupal 6. I am trying to change the position of the submit button. I am using conditional fields also on this content type. weighting is not changing the position.

I added the form elements submit buttons onto the node add/edit panel in the correct place, which solved my problem.


How to use JQM theme and jQueryMobile plugin with Drupal? I'm developing a mobile web site with Drupal 7 and i want to use jQuery mobile. I've found many plugins, but just one available with drupal 7 (jQuery Mobile module). I have also a jQuery mobile theme (jQM Theme). My problem is that doesn't work (there is just html, no css and jquery mobile displayed).
Is there someone who used this plugin and theme ? Or could you give me an efficient way to create a mobile web site with Drupal 7 ?

Thanks,
Gen

Please make sure you've read the readme properly. The module requires that certain files be patched and you have the libraries in the correct place.

I have had jQuery Mobile theme working but found that it was far from usable so built my own simplified theme.


When adding a new product variation type no catalog options appear I have installed the Commerce Kickstart installation profile and I am currently experimenting with it. The main problem I face is when adding a new product variation type and trying to create a new product using it, the vertical TAB where you select the product catalog, instead of this :

I get this :

So far I have tried reindexing and checking the views filters without finding the root cause of this.

Turns out that when adding a new Product Variation, a new content type linked to this variation is automagically created with the corresponding representations.

All I had to do is adding the Catalog term reference to the linked content type.


How to deal with Bubbleable Metadata when there's no rendering context and no render array Since Drupal 8.0.0-beta12 "all rendering must happen in a render context", as stated by this change record.

This is to avoid bubbleable metadata lost. So far, so good.

Let's say I'm implementing a Commerce payment notification. The important part is a server calls a Drupal URL to notify something. The controller, as far as I know, doesn't need any rendering context because the answer is simple (almost just a status response). Good.

Let's say I want to send an email on this event. I create an EventSubscriber that subscribes to the payment event that happens on this callback. I hook on the event, gather the email data, and call the send function. During sending, Drupal renders the content (is an HTML email!) and I got the error: since there's no rendering context Drupal throws an exception. The point the error is triggered is when Token::replace() is called:

$body = $this->token->replace($this->getBody(), $this->getTokenData());

How to fix this?

Option 1:
Use the BubbleableMetadata $bubbleable_metadata fourth param of Token::replace(). This param docs states:

  An object to which static::generate() and the hooks and functions that
  it invokes will add their required bubbleable metadata.

  To ensure that the metadata associated with the token replacements
  gets attached to the same render array that contains the
  token-replaced text, callers of this method are encouraged to pass in
  a BubbleableMetadata object and apply it to the corresponding render
  array.

But because $body is just a plain string I guess the bubbleable metadata is lost, so what's the point of caring?

Option 2:
Follow the change record suggestion and use RenderContext::executeInRenderContext(). In that case I'd wrap the whole process:

$renderer = \Drupal::service('renderer');
$context = new RenderContext();
$that = $this;
$response = $renderer->executeInRenderContext($context, function() use ($that, $recipient) {
  $that->mailer->send($recipient);
  });

Again, I'm discarding the cacheable metadata.

I guess discarding that cacheable data is ok because the email is totally uncacheable, the whole body and its parts (because the replaced strings with tokens have URLs that would change on every email).

Are both approaches ok? Is one better than the other? Is there a third approach more suitable for this problem? I guess the problem can be summarized as how to deal with Bubbleable Metadata when there's no rendering context and no render array.

Yes, when rendering email data you have to take care that you don't bubble up metadata to the render context of the main response.

There is a third option, and in most cases the best option: The method Renderer::renderPlain, which not only discards bubbleable metadata, but also makes sure your email doesn't contain leftover placeholders:

  Renders final HTML in situations where no assets are needed.

  Calls ::render() in such a way that placeholders are replaced.

  Useful for instance when rendering the values of tokens or emails,
  which need a render array being turned into a string, but do not need
  any of the bubbleable metadata (the attached assets and cache tags).

  Some of these are a relatively common use case and happen within a
  ::renderRoot() call, but that is generally highly problematic (and
  hence an exception is thrown when a ::renderRoot() call happens within
  another ::renderRoot() call). However, in this case, we only care
  about the output, not about the bubbling. Hence this uses a separate
  render context, to not affect the parent ::renderRoot() call.

  (Can be executed within another render context: it runs in isolation.)

And it's always a good idea to build a render array to produce HTML. For example if you have a formatted text field then build a processed text render element: How to safely render node body on a custom variable?


Trigger 'Add another term' using javascript Is there any way to simulate the click event of 'Add  another term' using javascript?
I tried like this

 jQuery('#edit-field-attribute-und-add-more').trigger('click');

but no effect

Try this code

jQuery('#edit-field-attribute-und-add-more').click();


Drupal views filter with latest month with content I am working to show a page that will display a current issue section, by which all the articles from the latest month whatever articles were posted are only shown.

Suppose the last posted set of article are December 2015 and after that nothing is posted, that view must show all articles posted on December, 2015. If the last posted set of articles were on January 2016, it must show list of articles posted on the month of January 2016 like that.

How it can be adjusted in views ?

Try to create a date filter using the create date and set the granularity to month. The setting for the relative date field should be set to be equal to now.


Facet blocks are not shown with Facet API Pretty Paths activate I've enabled Facet API Pretty Paths and the Face blocks are not shown once I select a category.

For example: the Facet Blocks (color and prices) are not shown for the link: /products/field_brand/simple-threads-68

These are:
Drupal 7.44
Facet API Pretty Paths: 7x-1.4
Profile: Commerce Kickstart (commerce_kickstart-7.x-2.38)

Thanks,
Araujo

Ok... I got the 'error'

The Facet blocks are visible for the URL: products
When you install Face Pretty Paths, the URL is modified including the segment of the search result.
I just added the "products/*" to the visibility of the block.

Show block on specific pages -> Only the listed pages: products/*


can i register using same email id for a 3 different profile types This project is related to add social service work details into my website.
I used profile2 module to create a 3 profile types and its create successfully.
we have 3 profile types,
1) Single User
2) Comapny
3) NGO

Can i register on above 3 profile types using same email Id because if single user is chairman of company and they wants to register as comany using same email id so it is possible.
same like if single user is chairman of NGO and also they wants to register NGO using same email Id then it is possible or not.

How i can manage this situation.please help me

You may need Shared Email module for this. It allows multiple email accounts with same email address.


All page access only to administrator in I want to restrict my page access. Only an administrator should be able to see the page.

I followed this tutorial

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'example_user_has_role',
    'access arguments' => array(1, array('adminstrator')), // Argument 1 loads the user, argument 2 is the role name.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function check_user_has_role($user, $roles = array()) {
    foreach ($roles as $role) {
        if (in_array($role, $user->roles)) {
            return TRUE;
        }
    }
    return FALSE;
}

But I was able to access the URL even after I logged out. What is my mistake or is there a better way to achieve this?

I think the name of your access callback is wrong. (example_user_has_role => check_user_has_role). Also, you made a mistake on the role name (adminstrator => administrator).

Anyway, you can achieve this in a more simple way like this (avoiding the argument in the URL)

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'check_user_has_role',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function check_user_has_role() {
  global $user;
  if (in_array('administrator', $user->roles)) {
    return TRUE;
  }
  return FALSE;
}


Disable cache for node body I would like to disable the cache of that specific part of the node content.
Is it possible?

I'm aware I can disable the cache for the node itself using:

$build['#cache']['max-age'] = 0; // users
\Drupal::service('page_cache_kill_switch')->trigger(); // anon users

But I indeed would need to only deactivate for the body content.

Any ideas?

Thanks

The body is not cached on its own, but as part of cached nodes for logged in users or of cached pages for anonymous users. This is what you have already disabled with the code.

You can check this in the cache metadata. Render elements with cache keys get cached. If there is no cache key, then the cache tags, contexts and max-age are bubbled up and merged until they reach an element that has cache keys. This element is then cached including all merged cache metadata that is nested inside.

That means, that cache metadata you set in the body will have no effect on the body to be cached or not, but change, how elements on higher levels like the node or page are cached. For example a cache tag in the body will be included in the tags of the node and the page and if the tag gets invalidated, the cached node and page will both be invalidated.


The block X was assigned to the invalid region footer and has been disabled I am seeing the following:

The block X was assigned to the invalid region footer and has been disabled.
The block Y was assigned to the invalid region footer and has been disabled.
The block Z was assigned to the invalid region footer and has been disabled.
The block W was assigned to the invalid region search and has been disabled.

Here is my code

array(
  'module' => 'W',
  'delta' => 'form',
  'theme' => $admin_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'search',
  'pages' => '',
  'cache' => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'X',
  'delta' => '1',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'Y',
  'delta' => '2',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),
array(
  'module' => 'Z',
  'delta' => '3',
  'theme' => $admin_theme,
  'status' => true,
  'weight' => 0,
  'region' => 'footer',
  'pages' => '',
  'cache'  => -1,
  'visibility' => BLOCK_VISIBILITY_NOTLISTED,
),

);

Any suggestion greatly appreciate it. I have other blocks that have properly worked using this method with the custom theme. But the above in $admin_theme = 'seven'; are not working.

It doesn't work because regions are theme specific. The only way you can have cross theme block export/import is to have the same regions (machine name) defined in your admin theme.


How to programmatically list users with a certain role? What is the preferred way of programmatically generating a list of users with a certain role?

(I know how to do it with a database query, but surely there's a higher-level method.)

In Drupal 7, user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE)
will load the user details for the given user IDs.
In Drupal 6, there isn't that function, but you can use $user = user_load(array('uid' => $node->uid));.


How to synchronize my Drupal site with content pulled from a Wordpress site? I need a solution which asks to another site (running WordPress) for updates (i.e., I want to pull new content posted on a WordPress site into Drupal.

Please note that I need a regular (daily) sync of the contents, not a single import.

How can I implement this?
Can I read the site RSS? Or can I ask in some other way this data?
And how?

Wordpress exports its content using RSS.  The standard way of pulling this content on a regular basis is to configure the core RSS Aggregator module (disabled by default) to pull the content from the WordPress RSS.  It is highly configurable, you can pull daily or by the hour.
Here is a link to an introduction to the Drupal Aggregator - quoting:

Aggregator is a key part of Drupal that is often ignored.
I blame it on the confusing name. No, Aggregator is not an animal in Florida that eats people. Aggregator is a module that imports content from RSS feeds into Drupal.
Because it has a name starting with "A", Aggregator is the first module that people ever see on the Modules page. In this tutorial, we're going to show you what Aggregator does and how to use it.


Drupal Commerce hide cart to non authenticated users I have a drupal 7 commerce install. I have made the views only accessible to authenticated users, but when I am not authenticated, and type in "mysite.com/cart" I still can see the cart (even though it has nothing in it).

I am using the content access module to prevent non authenticated users from viewing my produces, but I don't want anyone who is not logged in, to even know the website doubles as a store. How do I hide the cart page?

A quick fix might be to write a tiny custom module that overrides the access callback for the cart page:

function MYMODULE_menu_alter(&$items) {
  $items['cart']['access callback'] = 'MYMODULE_cart_access';
}

function MYMODULE_cart_access() {
  if (user_is_logged_in()) {
    return user_access('access content');
  }

  return FALSE;
}


how to display data in view for specific content base on permission I want to create the view where content of specific type will be visible according to given permission for current user's role.

For Example:I have created a role and given it the permission for create, edit ,delete Article Content Type. so the view should display all the nodes for article. This should be applicable on multiple content types also.

Summary : View should display only nodes for which user has permission for create,edit,delete.

Create your view, in middle column, in Permissions: View Published Contentclick on it and select Role. Specify the role you want.


Why doesn't adding results in hook_views_pre_render work? In the docs for hook_view_pre_render http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7 it states "Altering the content can be achieved by editing the items of $view->result."

Removing elements from this array is reflected in the final output, but appending to it, rewriting parts of it, or reordering it results in no change to the final output.

Does anyone know what's going on? How do I use this hook to alter or add to the results of the view post-query but before rendering?

Don't know what the deal was with hook_views_pre_render, but adding to the result array works fine in hook_views_post_execute, and accomplishes the same thing.


Saving form data and running custom queries in mysql I'm new to drupal and although I've researched and asked some questions I'm still stuck on how I can achieve my end result.
I have built a php/html/mysql website (www.gbpokerclub.co.uk) but I now want to create it in drupal, mainly so I can easily give different users their own permission levels, and also so I can have my admins do some of the content editing.

Most of that I've worked out but the bit I'm stuck on both practically and conceptually is how I can record data into custom tables and retrieve that into leaderboards and results tables.

At present an admin logs poker game results via a form, this records the venue id, player id, finishing position etc into a mysql table. I have other tables that record venue details, player details, agent details etc. I then have some complex mysql queries that take data from results, player and venue tables, performs some calculations on it and spits out a leaderboard showing who has the most points.

This is currently done using forms to input the data, and mysql queries and php include files to drop the data back into a presentable format on the webpage.

My big question is ..

  How can I emulate this process in Drupal?

the feedback I've had so far suggests I could use content nodes with specialised types, or custom DB tables and views to present it back, or coding a custom module, but I've also been warned against using SQL and to use the database.api instead.

To be honest there seems to be many solutions to the achieve what I need, but I'm ideally looking for someone to tell me exactly which method I should go with and how I should go about implementing the solution.

I hope that all makes sense!
Thanks

Short simple answer is Views to display output of Entity Form inputs.


Programmatically upload a file to a custom file field I am trying to update a node and programmatically upload a file.

$nid = 45343;
$node = node_load($nid);

$image_url = 'http://test.com/misc/druplicon.png';
$file = system_retrieve_file($image_url, file_default_scheme().'://products_images/'.basename($image_url), TRUE);

// We save the file to the root of the files directory.
// $file = file_copy($file, 'public://');

$node->field_custom_file[LANGUAGE_NONE][0] = (array)$file;
node_save($node);

Somehow, it's not working at all. Do I need to add more functions to it?

The following code works for me.

$image_url = 'http://test.com/misc/druplicon.png';
$file_info = system_retrieve_file($image_url, 'public://documents/', TRUE);

if ($file_info->fid) {
  $node->field_custom_file['und'][0]['fid'] = $file_info->fid;
}

$node_ready = node_submit($node);
node_save($node_ready);


Override default register form <?php
/*
** Implements hook_menu().
*/
function custom_register_menu() {
    $items = array();
    $items['custom-register'] = array(
    'title' => 'Custom register',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_register_form'),
    'access arguments' => array('access content'),
  );
    return $items;
}
/*
** Implements hook_form().
*/
function custom_register_form($form, &$form_state) {
  // Display page 2 if $form_state['page_num'] == 2
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
    return custom_register_page_two($form, $form_state);
  }
  // Otherwise we build page 1.
  $form_state['page_num'] = 1;
  $form['egn'] = array(
    '#type' => 'textfield',
    '#title' => t('EGN'),
    '#size' => 20,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['last_digits'] = array(
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 4,
    '#title' => t('Last digits from the card '),
    '#required' => TRUE,
  );
  $form['authorization_code'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#maxlength' => 6,
     '#title' => t('Authorization code'),
     '#required' => TRUE,
  );
  $form['transcation_date'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#title' => t('Transaction date'),
     '#required' => TRUE,
  );
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Forward>'),
    '#submit' => array('custom_register_next_submit'),
    '#validate' => array('custom_register_next_validate'),
  );
  //dsm($form_state);
  return $form;
}
/**
* Validate handler for the next button on first page.
*/
function custom_register_next_validate($form, &$form_state) {
    if(!is_numeric($form_state['values']['egn'])) {
        form_set_error('egn', t('Please enter only numbers!'));
    }
    $egn_length = strlen($form_state['values']['egn']);
    if($egn_length == 10) {
    }  else {
        form_set_error('egn', t('Please insert proper ЕГН'));
    }
    if(!is_numeric($form_state['values']['last_digits'])) {
        form_set_error('last_digits', t('Please enter only digits!'));
    }
    $last_digits_length = strlen($form_state['values']['last_digits']);
    if($last_digits_length == 4) {
    }  else {
        form_set_error('last_digits', t('Please enter 4 digits!'));
    }
    $authorization_code_length = strlen($form_state['values']['authorization_code']);
    if($authorization_code_length == 6) {
    }  else {
        form_set_error('authorization_code', t('Please enter 6 digits!'));
    }

I'm building a multistep form for custom registration on Drupal 7.
The reason that I don't use hook_form_alter is because later I have to create a submit handler to a webservice and other database, but I'll open a new thread later for that.

This is a part of my code (sorry about putting text the down bellow, but drupal.stackexhange is not so friendly for putting text and codes) and you can see that I've created a menu page (custom-register).
On that page there are four fields with custom validators and next button. On the next step it should be displayed the Drupal four fields (username, password, password repeat and email) and after that it should redirect to some register successful message page.

My questions are:

How can I redirect /custom-register to user/register page? I've read about hook_form_alter, but I didn't find a way how to override user/register page.
For the second step of the form after submitting how can I create a new user like on the core user module?

EDIT:

I've managed to alter the default register form with my new form created. :) This is the code:

<?php

    function custom_register_menu_alter(&$items) {
        $items['user/register']['page arguments'] = array('custom_register_form');
        return $items;

    }

Now the next thing is to create the 4 fields (username, password, password repeat and email) and to find a right submit handler to save the user.

You can still use hook_form_alter and have a special variable (in the $_SESSION for example) to define which part of the form do you need to show. Code sample below:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
  if ($form_id === 'user_register_form') {
     switch ($_SESSION['register_step']) {
         case 1:
              // confirm smth
         break;
         case 2:
              // establish the connections to other services, etc.
         break;
         default:
              // show initial form
         break;
     }
  }
}

Hope this is helpful.

EDIT

Some links:

Creating a user programmatically
Custom submit
handlers


Template suggestions periodically not being recognized I have some simple template suggestions setup in my THEME_preprocess_node() function. Example:

function my_theme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_TYPE' && $vars['view_mode'] == 'MY_VIEW_MODE') {
    $vars['theme_hook_suggestions'][] = 'my__template';
  }
}

Then I have the template file (named my--template.tpl.php) setup in my theme. I cleared the cache, and this is recognized right away and works fine.

Then, after about an hour, if I refresh the page that uses the template, it suddenly is not recognized anymore. I clear cache again and it comes back.

Has anyone experienced this before?

Just FYI, I am using hook_theme() in a custom module to specify the theme for this page based on the URL alias.

Turns out I had the wrong hook specified. I copied this from another theme and forgot to update the hook prefix. So I had:

other_theme_preprocess_node

instead of:

my_theme_preprocess_node

Changing that seems to have resolved the issue.


How do I list my profile in the profile list after downloading the Drupal distribution with drush make? I am creating a profile for my site.

So I basically have the following files:

myproject.info
myproject.make
myproject.profile

Evertime I run

drush make myproject.make

the drupal files + modules are copied but during install I only see the profiles: standard and minimal.

How to make my profile myproject visible in the list?

UPDATE:

I copied my profile inside the profile folder of a Drupal installation.
Now my profile is being listed. But I prefer this should be done from a script.

I asume I should edit the make file to copy the new profile inside the profile folder. I am not sure this can be done from within the make file therefore I assume should run a .sh file instead.

I am waiting for some suggestions.

You need a custom sh file that does the drush make, and moves the profile files for you.


Hook_views_query_alter: adding condition with entity reference value I need to filter a table result based the current user.

I added this condition in my hook_views_query_alter

function my_module_views_query_alter(&$view, &$query) {
  global $user;
  if ($view->name == 'preventivi' && $view->current_display == 'page_3')
  {
    // $view->query->add_where(1, $user->uid, 33, '=');
    $view->query->add_where(1, "field_data_field_installatori_reference.field_installatori_reference_target_id", $user->uid, '!=');

    // dpm($view);
    //dpm($query);
  }
}

but I can't find the correct value of target_id to insert in the condition.
Any suggestion?

This comment save my life!
https://api.drupal.org/comment/49458#comment-49458

  Be careful to add the table, even if You added the field in the view
  UI :

I added

$view->query->add_table("field_data_field_installatori_reference");

and then I could access to my field:

$view->query->add_where(1, "field_data_field_installatori_reference.field_installatori_reference_target_id", $user->uid, '!=');


How do I delete all entities of a bundle? I am using Paragraphs module and I can't delete paragraph type until I delete the content of the paragraph. I can use admin/modules/uninstall/entity/paragraph, but this will delete the paragraphs of all types.

There are some examples of removing nodes of a certain content type. In that case node is the entity type and article could be bundle (content type). This is no different. paragraph is the entity and [paragraph type] is the bundle.

For instance this post: https://stackoverflow.com/questions/34593060/drupal-8-delete-all-nodes-of-the-same-type

There are a few alternatives listed, but I suppose this should work:

$paragraphs = \Drupal::entityTypeManager()
    ->getStorage('paragraph')
    ->loadByProperties(array('type' => 'your_paragraph_type')); // System name

foreach ($paragraphs as $paragraph) {
    $paragraph->delete();
}


Hook module and Drop table I would know if it's possible to drop a database table created by a module.
I could see the hook "uninstall" and "disabled" but nothing works.

Can you help me please?

It could sound a stupid question, but have you enabled your module?
Have you launched the uninstall procedure?


Next in position of nodequeue in views I got A Drupal7 setup with module view and nodequeue.
Now i want a pager on the bottom of my content-type that gets me to the next node of this type in my nodequeue position.

Now i found this Get next node in nodequeue when i googled it.
But this solutions wont work for me.

I have done something like that with Custom Pagers module in the past.

I was hoping I could achieve the same thing with views and contextual filters but I can't figure it out.


Value modified with form_alter revert after check_cache Using Drupal 7.x.  Not much experience with Drupal.

I have a core form in which I need to append some data to a field after it's been submitted by the site visitor.  I have found I can alter the submitted data with a form_alter function added to my own custom module.  It works fine as far as that, but after the "prepare", $check_cache reverts values.

Is there a way to make this work?

Is there a way to manipulate the "uncacheable keys" to include my item?

Is there a different way to massage submitted data other than hacking the code?

Any other suggestions?

Submitted form values are stored in $form_state['values'], and can be modified in a custom validation function.

So in your custom module, implement hook_form_alter() and add a validation function:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form_to_alter') {
    $form['#validate'][] = 'mymodule_custom_form_validate';
  }
}

/**
 * Custom form validation handler.
 */
function mymodule_custom_form_validate(&$form, &$form_state) {

  // Append value to submitted field.
  if (!empty($form_state['values']['myfield'])) {
    $form_state['values']['myfield'] .= ' append this string';
  }
}


Organic groups chat - what are my options? I have several organic groups which has members added. I want to a chat system that allows members within the same group to communicate amongst each other.

What modules can i do to achieve this? what are my options? I am running drupal 6.

I think DrupalChat might integrate with Organic Groups. According to Issue#871238 the patch in comment#2 adds this functionality.

The patch looks like it was committed to the dev branch on January 21, 2012. With the release dates of the beta11 version and the latest dev version, it looks like it might already be in those respective releases. If not, try the patch mentioned above.


How to transform select options from views exposed filters to clickable link areas? I have asked more generally in stack overflow

https://stackoverflow.com/questions/49491094/how-to-transform-select-options-to-clickables-link-areas?noredirect=1#comment85985442_49491094

How can I make my exposed filters look like this?

<select data-drupal-selector="edit-field-video-theme-target-id" id="edit-field-video-theme-target-id" name="field_video_theme_target_id" class="form-select"><option value="All" selected="selected">- Tout -</option><option value="9">A*midex</option><option value="11">Bibliothèque</option><option value="10">Relation entreprise</option><option value="8">Université</option></select>

Is it possible to transform select/options to ul/li?

Is it possible to override the template views-exposed-form--videos.html.twig?

It is possible to override the template, you shall just create it in your theme and then clear the cache.

In your new template you can just change the select list to a ul

The template that you want to override may only contain {{ form }}.
Then you must find the preprocess function in the module or theme.


Views Slideshow Contextual Filter, Show Images From Same Node In a Content Type A I have added a image field with a value to add unlimited images.

Created nodes of Content Type A and adding multiple images to the field in all nodes of that content type.

Through Views Slideshow I have created a slideshow which is displaying all images added through that field.

Created a block display and configure that block to appear on nodes of the Content Type A.

Slide show is displaying all images added in different nodes of that content type.

I want views slideshow to display the images in context to the node it is appearing on. Means only display the images which are added on that particular node.

I think this could be achieved through contextual filters, but not sure how to do this.

To add a contextual filter for Content:Node:Nid, configure the 'When the filter value is NOT available' by selecting 'Provide default value, and under 'Type' select 'Content ID from URL'.

Save your view and you are done.

In your case, check for the nid or entity id associated with the attached (associated) images, and relate this to the node id in the URL. If your base table is node, the Content:node:nid will work. If your base table is files, you will need to use File Usage:Entity ID.


How to render field of one type of node to another type node I have two types of nodes: metals and prices.

Metals has two fields:

field_gold

and

field_silver

How to render this fields on node--prices.html.twig (not node--metals.html.twig)

Please, help me!

After you made reference between prices and metals implement hook_preprocess_node like the following:

use Drupal\node\Entity\Node;
/**
 * Implements hook_preprocess_node().
 */
function MyTemplate_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'prices') {
    $price_node = $variables['node'];
    //- Get reference target id
    /**
     * @TODO: change field_reference_metals by the referenced field.
     */
    $metals_node_target_id = $price_node->field_reference_metals->getValue()[0]['target_id'];

    //- Load metals referred node
    $metals_node = Node::load($metals_node_target_id);

    //- Set field_gold from metals node
    $variables['field_gold'] = $metals_node->field_gold->value;
    //- Set field_silver from metals node
    $variables['field_silver'] = $metals_node->field_silver->value;
  }
}

In node--prices.html.twig template add:

   {{ field_gold }}
   {{ field_silver }}

Change MyTemplate by your custom theme/module name.
Change field_reference_metals by the field from your prices content type referred to metals.
clear cache.


in drupal 7, how can drupal link to another remote service, consume the data in the web service such as nodejs? I am using the drupal 7 for my CMS server, at the same time, I have a nodejs based server, I need the drupal link to my nodejs server in order to make drupal consume the data in the nodejs based server, which will expose the restful service interface

Is there such a module that could link to the remote web service like nodejs rest, consume the data in the web service and expose the remote data as a view? and how to establish the authentication between drupal and nodejs?

You can always use the API from Node.js project. And build a module using it to consume your node.js server.


How to send an email with a download link? I had installed Webform Protected Downloads. But there are lot of things I don't like about this module:

Too many steps to download files.
The email's body content is only for plain text. You cannot use any HTML tag.

What options do I have to remedy these things I don't like?

The Functional Overview of the Webform Protected Downloads module seems to be like so (from its project page):

  This module provides protected downloads using webforms. When you create a webform you can select which of the attached files you want to protect. You need to specify the webform field used for the confirmation mail (this must be a mandatory email field) and how long the download should be accessible after the user has submitted the form.
  When a user submits a webform with protected files he will be sent an email with a link to the downloads page. The link contains an individual hash code that will be checked upon page load to verify the access. If verification fails access will be denied. If it succeeds the user will see the default private upload file listing with all protected files that are attached to the webform.

Pretty sure you can build something similar (or close) by using the Rules module instead, which integrates nicely with Webform via the Webform Rules module. By using the Rules module you can, for example:

Perfectly tune the entire content of your eMail to be sent. Have a look at these (working) samples of sending eMails using Rules.
Perform all sorts of redirects, based on the actual URL being used. Have a look at these (working) samples of performing redirects using Rules.

What else would you need?

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


Display Main menu only on login page I am using Webform module and I used main menu to display the form on Login page. I want to display menu only on Login page but Main menu is also displaying on front page. Is their any way to hide displaying main menu on front page.

You have 3 simple options (And even more with preprocessors, but I won't go into that):

Most themes auto output the primary and secondary menu (configured in Appearance -> Global/THEMENAME -> Settings). You can turn it off on the theme settings, and use the Block system (Structure -> Blocks -> Main menu -> Configure) to put it on the pages (2 valid urls):

/user
/user/login

pages only.
(This is exactly the same as 1 except it's not database configuration, it's a code edit) Edit the page.tpl.php and comment out the lines that go something like:

if($primary_menu) { print $primary_menu; }

and again use the block system to output the main menu block on the login page (2 valid urls - see 1)
Or alternatively you can create a new custom menu, stick your form link there, and use the block system to assign it to the login page (2 valid urls - see 1). And leave your Main menu empty.


How to implement content access for groups of users? I am building a Drupal 7 site, and I am quite new to Drupal. I want to assign each authenticated to a group which I define myself, for instance "friends", "family", "coworkers", "mortal enemies" and so on. I want the content access permissions to depend on this group, so that my friends and family are allowed to see all my images with cute kittens, whereas my mortal enemies should only have access to my archive of taunts and elaborate verbal abuse.

Any suggestions?

The Organic Group module will come to your rescue. Read the documentation about how to use the module.
More about the module:

Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.


Link node 1 to node 2 and create list I basically have a content type of companies and another of events. I would like to have a page with a select list of all companies and a select list of all events so that the user can choose what company is attending what event. This will need to allow multiple combinations.

Example: Company 1 will be at Event 1 and Event 2.

There will need to be list of all companies attending the selected event.

This can be done using a combination of Editable Views and Entity Reference.

You will need to create an entity reference field on one of the content types that points to the other. Then create a view of that content type.

Using editable views you can have a select list to add an entity reference on the company node to the event node. If you set up the entity reference field to allow multiple values, you will be able to have one company attending multiple events.

You can also create a view that shows all entities that reference the the event in order to show a list of all companies who will be attending an event.


Upload Image impossible I just migrated a website, and I can't upload any files now.
I checked the file path , it's ok
I checked the files and tmp permission , its ok (775)

When I try to upload an image, it does the 'ajax loading' and then boom everything's gone. It's like I just came and didnt try to upload anything.
I have no js , php or ajax error.

I really don't know what to do, have someone already face this ?

Thank you.

Ok, I've found the answer.
Files and tmp folders were owned by root, so I changed in www-data ( web user ) and everything works now.


More than one pager in the same page I have a Page that contains two views one that list the latest news and the other list the latest event

The problem now is that each view has a pager but when I change the page of one of them both view will change.
i.e If I want to see page number 3 in news view,the event view will also change to page number 3

Is there is a way to make that even programmatically
also I don't want to make it ajax because I need to share the url

Thanks

In Pager options There is a field named Pager ID. Setting a different value for each view should solve the problem.


Disabling Page Cache for Redirect Response I've implemented a conditional redirect on my site via an event subscriber and returning a redirect response. It's working but, I believe due to the page_cache module is getting cached for anonymous users.

This is basically what I'm using to set the redirect response:

public function checkRedirectStatus(GetResponseEvent $event) {
    if(shouldIRedirect()) {
        $response = new RedirectResponse('/redirect/path');
        $event->setResponse($response);
     }
}

The above gets cached whether or not it returns true unless I add \Drupal::service('page_cache_kill_switch')->trigger();.

As this is a fairly high-traffic page I'm concerned about bypassing cache for anonymous users. Are there other options I'm not aware of?

If this is on the REQUEST kernel event, how far-reaching is page_cache_kill_switch?

Thanks for your help!

This doesn't exactly answer your question, but I feel it's relevant information. I did something similar, but I also didn't like using the kill switch. In another iteration I used a TrustedRedirectResponse which allowed me to handle my cache issue differently. My understanding is this is forcing browsers to always bypass cache when executing the redirect, but the redirect itself is cached by Drupal until $entity's (my cache dependency) cache is invalidated.
$response_headers = [
  'Cache-Control' => 'no-cache, no-store, must-revalidate',
];

$response = new TrustedRedirectResponse($url, '302', $response_headers);
// In my case $entity is a content entity where my redirect $url is generated.
// In your case you'd add cache dependencies relevant to determining shouldIRedirect().
$response->addCacheableDependency($entity);
$event->setResponse($response);


Webform element validation custom module I want to add a custom validation to text input, I followed the instruction provided in
https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element

I have a requirement which needs to verify an id entered into a text box, by making a REST API call to another system, the issue  is to make that REST API call, I need another text parameter which is also inputed into the webform.
I have written a custom handler which makes that rest call, but that custom handler work on webform post save option only, how can I pass more than 2 fields to the validate function mentioned in the example given.

function onboarding_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
    // check for desired element
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--surname'){
     $surname= $element['#default_value'];
    $form_state->setValue('SOME_NAME', $surname);
   }
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--proda_id') {

        $element['#element_validate'][] = array(
            'Drupal\dhs_vendor_onboarding\Validate\DhsValidateConstraint',
            'validate'
        );
    }
}

In the validate function:

public static function validate(array &$element, FormStateInterface $formState, array &$form) {
        ksm($formState->getValue('SOME_NAME'));
        $webformKey = $element['#webform_key'];
        $value = $formState->getValue($webformKey);
        $surname= $formState->getValue('SOME_NAME');
        }

I am not getting any value for surname

i was able to get the value of surname from the Formstate, the form state had surname in surname field itself.

public static function validate(array &$element, FormStateInterface $formState, array &$form) {
    $webformKey = $element['#webform_key'];
    $value = $formState->getValue($webformKey);
    $surname= $formState->getValue('surname');
}

this did the trick.


Contextual filter to show only nodes of the same type I am trying to create a View that will be a sidebar block on node pages of various content types. The View is pretty basic, just a linked title. I figured I could use Contextual Filters (what used to be Views Arguments in Drupal 6) so I don't have to set up many Views that will all be the same and just use one for all.

My goal is to get only nodes in the sidebar block View of the same type to show up on a node page. So for example on a single Blog node page, the sidebar View will only show other blog stories. However, that same View on a News content type node page will only show other News stories in the View sidebar block and so on...

I have various content types including "News", "Services" and "Blog".

Here is what I have tried so far.

Set up the basic View, showing linked titles.
Added a contextual filter using Content: Type
"When the filter value is NOT available"

Provide default value >> Content id from URL

"When the filter value IS available or a default is provided"

"Specify validation criteria" >> Validator >> Content >> Checked off the content types I want i.e. Blog, News, Services.

After I save this, no data shows up on any of the node pages.  I also tried playing around with other various options in the Contextual settings but to no avail. My google-foo is also failing as everything I found for something like this deals with Taxonomy and that's not what I am after here.

I don't think you can do it with a contextual filter (without using coding).
Just build a view (with block output) for each of the types and then use a filter criteria "content type = news", etc.

It's pretty easy since you can clone the view, then just override the type and change the block name.


Behavior being fired on backend causes AJAX error I am using jQuery Update to bump up the jQuery version on the front end, and keep the default 1.4 on the backend.

On a custom filter form on the home page, i use jQuery on, and wrap it in a behavior so it still works after an ajax event on that page.

The problem is that for some reason, when editing the page, and adding a new field collection row when Ajax is fired, the jQuery is being called, and an error happens because jQuery on did not exist in 1.4.

  VM787:31 Uncaught TypeError: $(...).on is not a function

Steps to fix...

I am using drupal_add_js but I check that if (!path_is_admin(current_path())) {//jQuery} to make sure it isnt called on the admin pages
I am certain the JS is not on the admin pages, but after ajax, it is called because its in a behavior.

Is there a way to say which behaviors should run on the admin side, and which shouldnt?

Funny how sometimes you write out the question, and it makes you think about it in a different way!

The issue is that the behavior is obviously saved somewhere and called on an ajax event, EVEN if the js is not being called on that page! This was funny behavior to me, but the quick fix (maybe not the right fix) was to check the current path, and not run the JS inside that behavior if the path had "edit" in it.

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    (function($) {

        jQuery(document).ready(function() {

        var pathname = window.location.pathname;
            // If the page does NOT contain edit
            if (! (pathname.indexOf('edit') > -1) ) {

               // All of the JS stuff....

            }
        });

    }(jQuery));
  }
};

I will leave this question open for a few days as I would be interested to see if there's a better way of doing this. Ideally some way to control which behaviors are called on which pages?


Thumbnail: i need to have a fixed width and variable height (in proportion) I need to fix the width of the thumbnail at 200px, while the height has to be resized proportionally; i've seen that i can fix the width x height for thumbnails, but need to set only one dimension....how can i do it?

From the image styles settings for the "Scale" action:

  Scaling will maintain the aspect-ratio of the original image. If only
  a single dimension is specified, the other dimension will be
  calculated.

So if you specify just the width to 200px, the height will be calculated while maintaining the aspect ratio of the original image.


How not render a region on specific page programmatically on Drupal 8 I put a custom block (develop for me) on sidebar first region for every page, every fine, but I want that this block not render on the home page.

On my module, I made this:

funtion mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['sidebar_first']);
  }
}

The sidebar not show, but the block already was rendered (I debug this code and the build function of my block was called before of mymodule_preprocess_page function). Then how I programmatically avoid that this block not render.

Got to /admin/structure/block on your domain. Click the configure button beside your block. In the lower part of the configuration form you have a section called visibility. One of the tabs in this section is labelled pages. This is where you configure where the block is permitted or forbidden to be rendered. In your case one would write <front> and choose the radio button labelled "Hide for the listed pages".


Adding a Custom Solr Search Block that restricts search to one content type I have Apache Solr search 7.x-1.1 installed and working as my main site search.

I would like to add a search block to one page that allows the user to search, but restricts the results to a single content type. The new search block should be placed in a different location to the main site search, and the two should be able to co-exist on the same page.

What is the simplest way of achieving this please?

Once i stumbled upon Custom Search module I found this was easy to achieve. Install the Custom Search module and when configuring the module click on the 'search blocks' tab. Change the number of blocks to the number of additional search blocks you require. I needed two - each one searching by an different content type.

Now go to manage your blocks. Find the new search blocks within the list of block. Click 'configure' for search block to set the options and which content type to restrict to. Note that if you choose more than one content type you can choose whether to add radio buttons, or a drop down etc to allow the user to select what they will search for. This module also has some other interesting features which are outside the scope of this question - check it out.


How to display blogs related to particular taxonomy term name I am creating blogs in my site. I have categorized the blogs by using taxonomy terms. I want to display these category names in right side view as a block, and when user clicks on the name, views should display related blogs to the user.

I tried by using contextual filter but its showing content title not the taxonomy term names, as you can see in the above image right side block.
Below images shows the contextual filter settings i tried.

So please help me regarding this.

You don't need a contextual filter for this. The only thing you need is an exposed filter of the taxonomy you created. You can then use Better Exposed Filters to create links instead of a select list or checkboxes.


How to give confirmation for deletion through link? I have tabular format data and each row I have an edit and delete links , on clicking on the delete link it should ask for a confirmation to delete and if press delete only I need to delete. Now its asking for confirmation but not deleting any. Instead its giving me a blank page. Is it because it's submitted to the same function? It's not going to the products_delete_confirm_submit() on submission by the way. Or is there any workaround for this?

Here is the try :

Menu call back:

 function mailusers_menu() {
     $items['mailusers/usergroup/delete'] = array(
        'title' => 'Delete User group',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('products_delete_confirm', 3),
        'type' => MENU_CALLBACK,
        'access callback' => TRUE,
        'access arguments' => array('access admin tab'),
      );
 return $items;
}

callback function

function products_delete_confirm($form,$product_code) {
$form['_product'] = array(
        '#type' => 'value',
        '#value' => $product_code,);
//$form['#action'] = url("mailusers/products_delete_confirm_submit");
//      //drupal_set_message($product_code);

return confirm_form($form,t('Are you sure you want to delete '.$product_code.' Product?'),
        isset($_GET['destination']) ? $_GET['destination'] : "mailusers",t('This action cannot be undone.'),t('Delete'),t('Cancel'));

}

Delete submit handler:

function products_delete_confirm_submit($form, &$form_state) {
  $form_values = $form_state['values'];
  if ($form_state['values']['confirm']) {
  $param = $form_state['values']['_product'];
    drupal_set_message(t('Product ' .$param.' will get deleted.'));
    db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
    drupal_set_message(t('usergroup has been deleted.'));
    drupal_goto('mailusers');
 }
}

And in the table I am calling the delete link href="mailusers/usergroup/delete/10"

Don't bother testing the value of confirm, the user is only given a choice to submit or go back (with cancel link).

function products_delete_confirm_submit($form, &$form_state) {
  $param = $form_state['values']['_product'];
  drupal_set_message(t('Product ' .$param.' will get deleted.'));
  db_query('DELETE FROM {content_type_usergroup} WHERE vid = %d', $param);
  drupal_set_message(t('usergroup has been deleted.'));
  $form_state['redirect'] = 'mailusers';
}

Also, your access callback is set to TRUE, which bypass all permission checking.

Final answer

It should be products_delete_confirm(&$form_state, $product_code), see the example at https://www.drupal.org/node/751826#creating, you were messing with your form structure.


Omega Theme and Superfish Menu I am trying to use superfish menu with Omega 7.x-3.0-rc3 and so far from bits and pieces on the internet I did the following.

Create sub-theme from the '\omega\starterkits\omega-xhtml' folder.
Add 'regions[superfish_menu] = Superfish Menu' in sub-theme info file.
Add the following in the sub-theme info file: (the paths are correct - sf folder is in my sub-theme folder.

;Superfish Stuff
stylesheets[all][] = sf/css/superfish.css
stylesheets[all][] = sf/css/superfish-navbar.css
scripts[]          = sf/js/superfish.js

Add a Menu called 'Top Navigation' to the region with an expandable Menu Item/Sub-Items.

This is where it seems I got stuck...to add the following to page.tpl.php: (I have renamed the div in the code so that it matches the correct Omega region div - region-superfish-menu)

<script type="text/javascript">
  $(document).ready(function() {
   $("#region-superfish-menu ul.menu").superfish();
  });
</script>

I cannot seem to make it work as page.tpl.php does not exist in omega theme. Any clues? Thanks for helping!

Kevin

Why don't you just use the Superfish module that already integrates Superfish into Drupal. It automatically creates a block to add to any region you wish.


How to get a remote file and set it as a value for a file field using entity metadata wrappers? I am trying to get a remote pdf file from a web service and save it as a field's value using entity_metadata_wrapper, but somehow I couldn't get it working.
I can successfully retrieve the file using system_retrieve_file and save it locally. However, I couldn't set the file field's value to this newly retrieved file.
Here is my code (simplified):
// Retrieve the file from the web service.
// This works, I can see and open the retrieved file.
$file = system_retrieve_file($file_url, 'public://path/', TRUE);
$file = (array) $file;
var_dump($file);

$ewrapper = entity_metadata_wrapper('node', $nid)

// Set this file as a value for the node's file field.
// I've tried following lines individually and they both failed.
$ewrapper->field_pdffile->set($file);
$ewrapper->field_pdffile->set(array($file));

Both methods I've tried raised the following error:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of /drupal/sites/all/modules/entity/includes/entity.wrapper.inc).

I'm setting in the same code block other fields as well and they are set and saved without any error if I skip the file field.
For example, the following lines are working in the same code block for other fields:
// I'm getting the text from the web service
$ewrapper->field_text->set($some_text);
// I'm getting a term from web service
// Creating it if it doesn't already exist, and saving the 'term id' like:
$ewrapper->field_term->set($tid);
// A few more various fields are successfully set like that...
// Except that file field, which returns the above exception:
$ewrapper->field_pdffile->set($file);

What could it be, that I'm doing wrong?
UPDATE:
I've added a var_dump($file) and I'm getting the following output, which seems alright to me:
array(17) {
  'fid' => string(5) "13037"
  'uid' => string(1) "1"
  'filename' => string(31) "sample.pdf"
  'uri' => string(54) "public://path/sample.pdf"
  'filemime' => string(15) "application/pdf"
  'filesize' => string(6) "129804"
  'status' => string(1) "1"
  'timestamp' => string(10) "1409924961"
  'type' => string(8) "document"
  'uuid' => string(36) "a06f6bf7-61e1-48fd-bfc7-8bff6e72705f"
  'metadata' => array(0) {}
  'alt' => string(0) ""
  'title' => string(0) ""
}

Since @xurshid29 never post the correct answer here, I am posting it cause I find it "hard" to retrieve the comments:

(from @ЕлинЙ post)

// Retrieve file from web service (this works, I can see and open the retrieved file)
$file = system_retrieve_file($file_url, 'public://path/', TRUE);
$file = (array) $file;
$file['display'] = 1;
$file['description'] = '';

$ewrapper = entity_metadata_wrapper('node', $nid)

// Set this file as a value for the node's file field.
$ewrapper->field_pdffile->set($file);

More info on system_retrieve_file

And thanks to both of you for your work!


When to add an extra "helper" table rather than running complex query I'm trying to build a "notification" feature into my site similar to Facebook:

I would show a little graphic with a number indicating the number of new comments to nodes a user created or commented on.

The query will probably look like this, assuming uid=1 (haven't tested yet):

SELECT count(node.nid) as new_comments
FROM {node} node
INNER JOIN {node_comment_statistics} ncs ON node.nid = ncs.nid
INNER JOIN {history} h ON h.nid = node.nid
WHERE ( (h.uid = 1) AND (h.timestamp < ncs.last_comment_timestamp)
AND ((node.uid = 1) OR (0 < (SELECT COUNT(*) FROM comment c WHERE c.uid = 1 AND c.nid = node.nid)) )))

This query would run with every page request for all logged in users which could impact performance.
I could create a "helper" table where I keep a "new_comments" counter for each uid. For every comment added or updated I would then check which users need their "new_comments" counter incremented.

My question:

Is there a rule of thumb when to use such a "helper" table instead of running complex queries. Or do I need to create say a million records in Devel and test the performance of above query under full load?

As long as all your fields used in JOIN and WHERE are indexed properly, you don't really need a separate table to do this, I probably would rewrite it in a single query, sub queries tend to be slow.

If you want something intermediate (in case you have > 1.000.000 rows), you have 2 options:

Create a temporary table and keep it up to date using cron and/or
hooks
Use caching in Drupal to remember the result and combine it
with hooks

Both solution have pro's and con's:

Can be updated by cron, but has a record for every user, no matter if that user visits the site or not.
Needs to run the query when there's no cached data, but will be faster on a second page visit.


How to force the display of an empty field in panels for an editable field? I can't seem to force an empty field to display so that it can be edited with editable fields. I installed the Empty fields module which adds an option in the pane settings but still no luck.

Has anyone had success with this?

Edit: Form content with added submit buttons work, but Page Content is far more user friendly.

In your /sites/all/theme/YourTheme/template.php file, you could try using

function YourThemeName_preprocess_content_field(&$variables) {

    if (!isset($variables['field_name']) {
    $variables['field_name'] = ' ';
  }
}

but I don't know if the empty ' ' will show.


Multi-index searches without Solr? I'm struggling to set up a decent search using Search API. By "decent" I mean a small block that performs a multi-index search (nodes and taxonomy terms). I want to free visitor from defining what they want to search through, instead I want to provide a no-brainer which does the search and displays results in categorized, paged manner.

Even though I installed the multi-index submodule, when creating a search apge, I'm still limited to select one index. Then I found kind of confirmation in the README file that currently only Solr can take advantage of that. So the question is: is it possible to create a multi-index search without Solr?

Only Solr supports that functionality. What you need is:

Create a server in Search API, call it, for example, "solr_server".
Create two indexes, one for nodes another for taxonomies. Make sure both indexes belong to "solr_server"
In views (make sure that search_api_views module is enabled), select 'solr_server' from Show dropdown list.
Now you can add fields from every index, that belongs to "solr_server".

Hope this helps.


Admin login returns 'Sorry, unrecognized username or password.' When I attempt to login to my admin account, I'm getting a 'Sorry, unrecognized username or password.' message. The weird thing is that the password and username are correct. I've looked them up in the SQL database. I've even tried changing the password in the database, but have had no luck getting it to work. After every 5 attempts, I've had to use the DELETE FROM 'flood'; sql command in order to reset the attempts.

In my local environment, I'm having no trouble logging in. This is also the first time I've attempted to login to the production website.

Is there anything I can try to fix this?

If you changed the password in the database, it won't work - the password in the database is hashed, so entering an un-hashed password means it will never work.

Use the password recovery tool to get a new password, or use Drush:

drush uli

Either of these will help you get your password.


Private tempstore storage contains data for previous anonymous user I have an issue with private tempstore storage that I wasn't able to solve. I've implemented a webform handler, which populates data in this storage and then I'm creating tokens out of the saved values. This works fine, however, when anonymous user comes to page where token value is used, he/she sees last value saved in to the storage, before his/her session has been created.
This is strange, because setting a value for anonymous user should create a session for user, if it doesn't exist, yet: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TempStore%21PrivateTempStore.php/function/PrivateTempStore%3A%3Aset/8.6.x Do you have any idea why this happens, please? Should I use module https://www.drupal.org/project/session_based_temp_store? Should I consider using Sessions directly (https://drupal.stackexchange.com/a/246268/7580)?

Yes, this looks very much like a caching problem. You don't need to disable the anonymous page cache, though, this happens automatically for requests with a session cookie. What you need is a cache context session in render arrays containing session data, no matter whether you serve anonymous or authenticated users:
public function build() {
  $session = \Drupal::request()->getSession();
  $build = [
   '#markup' => $session->get('value'),
  ];
  $build['#cache']['contexts'][] = 'session';
  return $build;
}

The private tempstore is for large amounts of data. See What is the difference between \Drupal::request()->getSession() and \Drupal::service('user.private_tempstore')?


Node teasers break my layout Node teasers are breaking my layout by not closing div and span tags.

The nodes are being written using WYSIWYG and CKEditor 3.4.2.6041.

An example of this broken layout is:
http://www.energyjustice.net/node?page=2

Most probably Correct faulty and chopped off HTML is not checked in the input format used. Goto admin/config/content/formats and then look at the format used for this and make sure that it's last, eg:

If this doesn't work, check out How to get teaser break to work with WYSIWYG + CKEDITOR? for more things to look into.


How do I add a project? How do I add a Drupal 8 project (e.g. the Panels module) to my site?

The third solution would be:

1- Install drush : https://www.drupal.org/node/1791676

2- Move to the local home directory of your drupal website inside the Command Prompt / Terminal (according to your OS type)

3- Type this command in the Command Prompt / Terminal (according to your OS type):

drush en panels -y


How to remove a role after a user adds a payment method in Commerce? I am trying to set up a subscription-based site in Drupal 8/Commerce 2.
I'm using Commerce Stripe to process payments.  I want to remove a role from a user ("needs to add new card" role) when the user adds a new payment method (credit card via Stripe) on the payment method page (user/UID/payment-methods).
I assume I need to write an event subscriber, but I don't know which event to use for adding a payment method.
I tried to read through the code in commerce/modules/payment/src/EventSubscriber, but I couldn't find the event I need to hook into to remove the role.
Background
When a user's credit card has expired, they need to add a new card (add a new payment method).  In this case, I have flagged the users with a role, Add new card role.
Then I show a block to users with the Add new card role that says "Please update your card info." with a link to add a card.
However, when the user adds a new card, they still see the block asking them to add a new card, which is confusing.  So I want to immediately remove the Add new card role (to hide the block) as soon as the user adds a new card.

commerce doesn't offer the (content-)entity create event. You could use a hook ..

hook_ENTITY_TYPE_create -> after the entity was created 8will suit your need I guess)
hook_ENTITY_TYPE_presave -> before the entity will be created

Or setup events for entity creation, see Does Drupal 8 entities have any events I can listen to?


How can I make web scraping of a field more difficult? I have a text field that I get with <?php print render ($content['field'][0]['#markup']); ?> in node.tpl. I'd like to somehow make loading the markup require a click, and deselecting it to put the placeholder markup back. It's a select dropdown if it matters.

I thought javascript might work, to test if scripts worked in node.tpl I tried

var test ="<?php print render ($content['field'][0]['#markup']);?>";
document.write(test);

but it loaded the markup for every node on the page in one line. My php/js skills are weak so I'm hoping there's a module that might help me. I'm open to any suggestions though.

You can try to do something like this:

Your Placeholder


Is Drupal 8 with views in core stable enough to be used as a simple blog? I want to start using the new drupal 8 codebase, but I was wondering if I can use it in its state now as a simple blog using views.

The real question is: what's the Drupal core lifecycle look like?

First, we have feature thaw. During this time it's really a bad idea to even try to build anything on it. It's likely to be broken, buggy, and so on. (Although now we have extensive test coverage so it's less broken than you'd think.)

Then there's a feature freeze. People with some knowledge, patience and not too important sites -- say, a blog :) -- could start testing. It'd be great if this happened. You need to understand that there is still no guarantee that your data can stay intact from one git pull to the next. (This is where we are now.)

The next step is beta. From beta and on we support upgrades. So while it's not the quality you'd expect from a released product, it's time to begin serious testing. If you start testing when release happened, your problems will take a lot longer to be fixed.


Check Content Type in Paragraph Preprocess I've written a paragraph preprocess function that is working perfectly. The only issue is that I need it to only work when that paragraph is embedded in a certain content type.

function mytheme_preprocess_paragraph__paragraph_type(&$variables) {
   // Do things here if content type == 'specified_type'
}

I'm unsure of how to check the content type, though. How can I accomplish this?

The correct way of getting the entity data referencing to your paragraph is to use Paragraph's entity API.

/**
 * Implements template_preprocess_paragraph().
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */

function mytheme_preprocess_paragraph(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  // Get the parent bundle.
  $parentBundle = $paragraph->getParentEntity()->bundle();
}


Is there a module for tracking changes to a Drupal site's configuration? I want to create a simple system for tracking changes to my Drupal configurations and knowing which modules are used by some configuration settings is crucial, but will be happy to use an existing one if it is good enough. Is there a module that implements this?

I think you are looking for Configuration Management module.

  The module knows where configuration was changed and allows users to
  either "activate" a configuration that was changed in the datastore,
  or "write" to datastore if a configuration was changed in the
  activestore. If you enable the diff module, you can see the what is in
  the activestore vs. datastore.

and I'm not using this module before.


Where to find custom Content type related files in Drupal directories? I have a localhost Drupal 7.x installation on my system. I have just explored with UI and created a custom Content type which defines a form with radio boxes. (Home --> Structure --> Content types --> Add Content Type, and so on.)

I am assuming these custom content types will be stored in local directories of Drupal core. I am not able to figure out where exactly these stay. I am curious to make changes to that file and see if there is any reflection, though I am not sure if it works that way.

Actually, content is managed through the database, so you won't find a specific dir named Content Types in the drupal folder.


What are the best ways for creating galleries from images stored as entities? I have a gallery attached to node that allowed tagging of single picture.
I used Field Collection for that job.

Now I need to display those images in different structure:

User when creating a node may choose prefered display.

Also same types of displays may be used for display all images from all nodes.

Could someone give me any advice?

Hey you can use the Galleria module in D7. Here is a quote about it (from the module's project page):

... allows users to create image galleries using the Galleria jQuery plugin, found on http://galleria.aino.se.
There are several different approaches of using this module to create Galleria image galleries. The most typical and easiest way to do so is to use it as a field formatter for image or media fields. All images uploaded to such a configured field will then be displayed in a Galleria gallery.
You can also use it in conjunction with the References module to build a gallery of image nodes, referenced by a 'Node reference' field; or you can use the Views module to gather a list of images to display in a Galleria.