Drupal 6 Search Redirect I would like to modify the search box to point to a custom search function.
So far, I have modified template.php to detect when the search box is being
called from a specific module and I reset some variables.

function my_theme_preprocess_search_block_form(&$vars, $hook) {
    $uri = request_uri();
    if (preg_match("/\/my_module/", $uri)) {
        unset($vars["form"]["search_block_form"]["#title"]);
        $vars["form"]["search_block_form"]["#title"] = t("SOME SEARCH MESSAGE");
        $vars["form"]["search_block_form"]["#value"] = t("SOME SEARCH TERM");
    }
}

That works fine. But now what I want to do is have that form submit to some module of my own creation. Oddly, this isn't as obvious. Do I need to modify something in modules/search/ ? If so, what?

The way to alter the action handler for the search form is to add a submit handler, as outlined here: https://stackoverflow.com/questions/6444769/altering-search-form-action-not-working-for-custom-search-module-drupal-6. You can call your function in the submit handler or redirect to it from the submit handler.

/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }


How to setup views exposed filter with result between 2 fields values I have content type called the materials with 2 temperature fields as Max. and Min.

in the views, there is between operator from filter and normally it use for user could input 2 values to the form for filter.

from my case, I want user could input 1 temperature value in the filter and the views result will be the termperaure between Max. and Min.  fields.

is that any way could approach this function?

The Range module allows you to add a numeric range field to a content type and provides Views filters allowing you to select values within or without the range.


Alter granularity in date exposed filter from Y-m to Y if only year is selected I am trying desperately to get the following working:
Goal:
I have a views that displays a list of events. To this views is a date exposed filter attached, with granularity Y-m(year month). I want this filter to filter with Y granularity if only the year is selected, and by Y-m if both are selected.
In addition to that, the view is set so that: when no date filter is selected, then filter by upcoming events, else, use the exposed filter value
Issue:
The month is required, even if I alter the form
I am suprised by the fact that exposed_form_alter as well as the validation fct are called multiple times, before the view is pre-build and before it is pre-executed, but this might be normal behavior.
See here: http://cl.ly/image/1C0t3Z3O0D3W (hook_views_*** dpms the function's name)
Draft:
The solution was inspired by this thread
function lezoo_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'views-exposed-form-teaser-list-panel-pane-1')
  {
   $form['#validate'][] = 'lezoo_views_exposed_form_validate';

  }
}

function lezoo_views_exposed_form_validate(&$form, &$form_state) {

  $handlers = &$form_state['input'];
  foreach ($handlers as $key => $handler) {
    if (
      isset($form[$key]['value']['#type'])
      && $form[$key]['value']['#type'] == 'date_select'
      && $form[$key]['value']['#date_format'] == 'Y-m'
      && $form_state['input'][$key]['value']['month'] == '') {
      $form[$key]['value']['#date_format'] == 'Y';
    unset($form[$key]['value']['#granularity'][2]);
    unset($form_state['input'][$key]['value']['month']);
  }
}
dpm('form validation');
   // dpm($form);
   // dpm('form_state');
   // dpm($form_state);
}

function lezoo_views_query_alter(&$view, &$query) {
  //If a date was selected in the exposed filter, ignore the default date filter '> today'
  $conditions = $view->query->where['1']['conditions'];
  $date_index = 3;
  if(isset($view->query->where['1']['conditions'][$date_index]) &&
    //if a date exposed filter was set
   $view->query->where['1']['conditions'][$date_index]['field'] != 'node.nid')
  {
    unset($view->query->where['1']['conditions'][2]);
  }
}

I am really stuck here, IRC is not helping unfortunately, and i would really appreciate more insights on this!
Thanks in advance!

So, I ended up going the very ugly way.

First, my module is now reduced to:

    function lezoo_views_query_alter(&$view, &$query) {
  //If a date was selected in the exposed filter, ignore the default date filter '> today'
  $conditions = $view->query->where['1']['conditions'];
  $date_index = 3;
  dpm($conditions);
  if(isset($view->query->where['1']['conditions'][$date_index]) &&
    //if a date exposed filter was set
   $view->query->where['1']['conditions'][$date_index]['field'] != 'node.nid')
  {
    unset($view->query->where['1']['conditions'][2]);
  }
}

which is needed because the default filter on dates(not exposed) is after today, but if you select a date, then ignore that filter.

And I added a second date_exposed_filter, so that I now have date1->granularity:Y, and date2->granularity:Y-m. I then use css to hide the Y of Y-m, and js to mirror both Year fields. if anyone is interested, here is the code I use:

            var year = $('.views-widget-filter-field_date_value_2 select.date-year');
            var ymonth = $('.views-widget-filter-field_date_value_1 select.date-month');
            var yearm = $('.views-widget-filter-field_date_value_1 select.date-year');

            ymonth.change(function(e){
                var value = $(this).val();
                //var value = e.target.value;
                var empty = value == "";
                if(!empty)
                {
                    yearm.val(year.val()).trigger("chosen:updated");
                }
                else
                {
                    yearm.val("");
                }
            });

            year.change(function(e){
                if(ymonth.val() != '')
                {
                    yearm.val(year.val()).trigger('chosen:updated');
                }
                else
                {
                    month.val('');
                }
            })


How do I implement bootstrap's panel component for a specific block / block region in my bootstrap (sub) theme? I have a bootstrap sub-theme, and would like to render some of my blocks using Bootstrap's Panels components, so that the block would need to be wrapped something like this:

    {{ header }}

    {{ content }}

So far I've tried to implement this via the following series of dirty hacks:

Setting the css-class setting on the advanced settings of the view to panel panel-default
wrapping the header of the view in a
 block
setting the row-class parameter in the settings of the view's unformatted list format to panel-body

This almost works, but isn't quite right:

The issue is that the resulting classes aren't nested correctly:

If I manually modify the classes in my browser and set view-header to panel-heading and view-content to panel-body I get the desired effect:

So I know what I want, but how do I achieve this? I'm new to twig and I feel like there must be an easy solution to this out there, I just don't know what it is. Note that I don't want to make every block behave like this, just this one.

Quick-and-dirty way: Uncheck all the boxes to display default classes in Views, and then use a twig template specifically for that views block to write the CSS exactly as you want.
You can find the Views twig templates in /core/modules/views/templates.
It depends on how you configured the view, but if it's an unformatted block, you want the unformatted template, views-view-unformatted.html.twig.  Copy that file from the Views template directory into your subtheme's directory.
Next, you have to rename the file so that it only applies to the block. In Drupal 7, Views was nice and gave you the suggested theme hooks, but in Drupal 8, you have to figure them out yourself.
The rule is TEMPLATE_NAME--VIEW_MACHINE_NAME--DISPLAY_MACHINE_NAME.
If you go to edit the view in the admin UI, you can get this info from the URL.
/admin/structure/views/view/VIEW_MACHINE_NAME/edit/DISPLAY_MACHINE_NAME.
Once you rename the file, you will need to rebuild the cache to get Drupal to use it.
Sometimes you may need to customize other views templates as well (a single view can use multiple templates); you can do that in the same way as described above..


Drupal 7: Theme hook for form not found Drupal doesn't call the theme function for my form in my module (error log: Theme hook wc_challenge_actions not found.). I found similar posts on stack exchange, but none of the solutions works for me.

Form declaration

    function wc_challenge_actions($form, &$form_state, weACT_Challenge $challenge) {
      $form['action_groups']['#tree'] = TRUE;
      $form['action_groups']['#type'] = 'fieldset';
      $form['action_groups']['#title'] = t('Action groups');
      $form['action_groups']['#theme'] = 'wc_challenge_actions';

      // rest of form definition, works correctly

      return $form;
    }

Theme function

    function theme_wc_challenge_actions($variables) {
      drupal_set_message('The theme worked!');

      // rest
    }

Drupal never calls this function... Any ideas?

You have not defined your theme function in hook_theme

 function yourmodule_theme() {
   return array(
     'wc_challenge_actions' => array (
       'render element' => 'element',
     ),
   );
 }


How do you show/hide delete(remove) product button in the Cart? I have an issue with the delete/remove product button from the Shopping Cart. Some of my products show and some don't (see screenshot below). I checked the rules and can't find this anywhere.

What I am trying to achieve is to have the Remove on another collection I created. It only works for Postpaid Collection which is the BLU Studio X product. However, the Remove link doesn't appear on the top product (above the red arrow where I want the Remove to show on that product as well).

There is a rule set somewhere and I can't find it. I even created a new product variation and content, and it doesn't show the link in the shopping cart. It only shows it for the Phone product that was created by the previous user.

Shopping cart in Drupal commerce is a view. To remove the "remove" link, all you need to do is edit it and remove the "remove" field.

The view can be found at /admin/structure/views/view/commerce_cart_form/edit
and remove the field (Line items referenced by commerce_line_items) Commerce Line Item: Delete button (Remove)


How do you programmatically modify a programmatically created content type? I'm creating a Drupal 7 site that has many content types which are defined programmatically. It is quite likely that, after launch, I will be required to slightly modify some of the content types. During development, whenever I need to make a change, I just uninstall the module, make the changes in code, and reinstall it. In a production environment where the data needs to be kept stable, this is clearly not acceptable.

How can I modify one of my existing content types programmatically? Also, how would I apply this update?

http://api.drupal.org/api/drupal/modules--field--field.crud.inc/function/field_update_field/7
http://api.drupal.org/api/drupal/modules--field--field.crud.inc/function/field_update_instance/7

Open WWWROOT/profiles/standard/standard.install (starting from line 199)
Profile install creates basic content types (like Article and Basic page)


Webform, let data expire after a period of time How might I expire data collected in Webform? That is, I'd like to purge data after a period of 6 to 18 months.

Alternatively, I'd be happy to find a module that cleans up old data in a Drupal 7 database.

Try the Webform auto-delete  sandbox project.

  Automatically delete webform submissions after a set period of time.


Intermittent hook_menu error - call_user_func_array() expects parameter 1 to be a valid callback As the title suggests I'm getting intermittent errors when hook_menu is called. Based on the error message it's as if the callback can not be found. Clearing the cache resolves the issue and the page works as expected. However, if the server is idle the error reappears. Any ideas as to what might be happening? Here are some details:

Error as reported in log:

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_protected_download' not found or invalid function name in menu_execute_active_handler() (line 517 of /var/www/drupal/includes/menu.inc).

All code is in the my_module.module and the module is enabled:

function my_module_menu()
{
    $items = array();
    $items['lesson-register-for-download'] = array(
        'path' => 'download/register',
        'title' => t('Register to Download a Lesson Plan'),
        'title callback' => FALSE,
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
        'page callback' => '_protected_download',
    );
    return $items;
}

function _protected_download()
{
    // check cookies and redirect here
}

You say your code is in my_module.inc, which means you have to tell the menu system that it is in there.

By default drupal will load my_module.module, but because the function is not in there it can't find the function.

As a side note, generally you should put hooks like hook_menu() in the .module file.

To tell the menu system that it has to load my_module.inc for your menu callback, do this:

$items['download/register'] = array(
  'title' => 'Register to Download a Lesson Plan',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
  'page callback' => '_protected_download',
  'file' => 'my_module.inc',
);

Note the 'file' param.

Also, I made a couple of other changes:

Removed t() from the title and removed the 'title callback', because by default title callback is t().
Removed the 'path' param and changes the array key for the menu item. The path param was used in drupal 6 but not in drupal 7.


get the vid of last saved vocabulary How can I get the last saved vid. taxonomy_vocabulary_save($vocabulary); is not returning the vid.
I have used the following way.

$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);
// get the vid of currency
$vocabulary = taxonomy_vocabulary_machine_name_load('currencies');
//save a variable for vid
variable_set('currencies_vid', $vocabulary->vid);

Is there any better method?

The vocabulary object that you pass to taxonomy_vocabulary_save() will automatically be populated with the new vid, so you don't need to reload the vocabulary after you've saved it.

This code will work fine:

$vocabulary = new stdClass();
$vocabulary->name = 'Currencies';
$vocabulary->machine_name = 'currencies';
taxonomy_vocabulary_save($vocabulary);

variable_set('currencies_vid', $vocabulary->vid);


How to filter types of Webforms with Views I am trying to create a simple View of webforms to display a list of currently available jobs.

This is what I am trying to accomplish:

Webform1
description description description description...
[Read more]

Webform2
description description description description...
[Read more]

Webform3
description description description description...
[Read more]

I thought webforms would be a decent solution considering I can add/remove them once the job listing is expired. It is also very easy to go through submissions.

Only issue I am having is that the contact form I have is also a webform.

So I am getting some unwanted items in my view query. I am having a difficult time figuring out a simple yet robust solution to filter the different types of webforms.

The only filter criteria available for a view of webforms are Webform: Node & Webform: Status and I believe neither will help me accomplish what I need.

Anybody got any ideas of what I could do to differentiate between webforms for views filtering?

You can enable Webform functionality on all the different content types. You don't have to use the Webform content type which comes pre-packaged with the module.

Make a new content type, and go to: /admin/config/content/webform and enable webform functionality on the new content type you created. Then add the webform to it.

Then you just need to filter by content type on Views.


How do we theme node view component? I've tried to theme a portion of a node by adding some values in to it using

hook_theme and a twig template

I've used hook_node_view to add a few variables and then I have included the theme specified in hook_theme and printed it in twig template.

Here is the code; nothing is working like nothing.

function content_statistics_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
    $node_count = some function called;
    foreach ($node_count as $key => $value) {
      $node_statistics = array(
        '#theme' => 'content_statistics_list',
        '#letter' => $value->letter,
        '#word' => $value->word,
        '#sentence' => $value->sentence,
      );
    }
  }
  $node->content['content_statistics_list'] = array(
    '#markup' => drupal_render($node_statistics)
  );
}

/**
 * Implements hook_theme().
 */
function content_statistics_theme($existing, $type, $theme, $path) {
   return array(
    'content_statistics_list' => array(
      'variables' => array('letter' => NULL, 'word' => NULL, 'sentence' => NULL),
      'template' =>  drupal_get_path('module', 'content_statistics') . '/templates/' . 'content-statistics-list',
    ),
  );
}

In content-statistics.html.twig, I have printed {{ letter }} but it is not showing anything on the node page. It is also causing an error.

  Warning: Attempt to modify property of non-object in content_statistics_node_view()

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

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

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


indexing nodes and links in views I have a content type that contains text, picture and term reference (cat, dog).
I've used views and create a page with cats and a page with dogs.

The problems:

I want only 2 pages indexed by Google. The dogs page and the cats page. I don't want Google to index my nodes separately. Now I have one page with all my cats, one with all my dogs ( << the pages that should be indexed by Google and published for the users) and one page for each cat and one for each dog ( << pages that i don't want).
On my front page I need a 2 column area : column1, column2. Both columns should contain text and image. ( If I create new content type and then use a view I have the same problem as above.)
When I click column1 I want to go to cats page.
When I click column2 I want to go to dogs page.
How can I assign links different links for the view results? I know I have "Output this field as a link" in "REWRITE RESULTS" but it uses the same link for all views elements. I also know about "Link this field to the original piece of content". But this mean that my info from column1 should be in cats page and from column2 in dogs page. And I only wish to display the info from column1 and column2 on my front page.

How could I solve this ? Which is the best solution in order to create something like this ?

Use http://drupal.org/project/node_noindex for noindexing concrete nodes. Or modify robots.txt for excluding count of nodes, Disallow: /node/, for example, next help for you: Robots.txt Tutorial.
Do you mean that clicking on whole column should lead to cats/dogs? If so, create custom template (in Views editing you should see in "Theme:Information" -> "Display output" -> take latest filename and copy source from link. Create this with filename and paste source. Wrap whole code into ....


How to change the node breadcrum name & there url inside in drupal 7? There is a node where breadcrum shows like this :

Home › Shop Products › Product Name

Now I want to change the breadcrum. I can easily change the "Product Name" but unable to change the "Shop Products" name. How can I change. I have try to add custom code in template.php file but unable to got result.

Please help me to solve this.

You can change the appearance of the breadcrumb using theme_breadcrumb function in your template.php
Here is a page with several snippets of example code you can use to get some inspiration on how you should write your code.


How do I add CSS files only to the front page? I am trying to add a CSS file to the front page. I have seen Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme; I just need to know the HOOK machine name for the front page.

function THEMENAME_preprocess_HOOK(&$variables) {
  $variables['#attached']['library'][] = 'CSSPATH';
}

What name should I use for the preprocess function, in order to make Drupal calls it only for the front page?

You can find exactly what you want under the topic Adding Libraries to Specific Pages at this tutorial Drupal 8 Theming Fundamentals, Part 1

To give you a real example, I am going to explain with the Bartik theme, so you can change easily.

I have created a css file cssfile.css under the path css/cssfile.css. Now this CSS file I want to use on only front page.

Step 1: Add the library to the theme: Add the following code in the bartik.libraries.yml

css-filling:
  css:
    theme:
      css/cssfile.css: {}

Note: Here I have given the name css-filling to this library but you can give any other name. We will use this name in path
Step 2: Setting the code in bartik.theme so above perticular library(ultimately css) will only be added to front-page,

function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}

Note: Now in the above code the important thing is path, bartik part comes form the themename and css-filling comes from the step-1.

This code I have tested in my test site and it is working on front-page only.


List migrations separately but use single migration class I have successfully created a custom migration class which works perfectly but my issue is with the drush migrate-status output.

When I execute drush migrate-status all the XML files I am attempting to migrate from ( I have over a hundred of them each with the same XML structure ) are all compacted into a single migration of 10,000. What I need is for each of my xml files to be listed individually.

I know I can achieve the individual listing by giving each of my XML file a unique migration class but that is inefficient because the code will be exactly the same in all the classes except for the class names.

Can anyone suggest a solution to help achieve my objective?

It sounds like you're trying to force a tool to do something it's not supposed to do. The migration tools drush migrate-status command only provides a high-level overview of the migration batch work associated with a migration (current state, migration source entities found, number of entities, migrated, etc.)

There is drush migrate-messages if you're wanting to inspect individual migrations that may have failed. But if you're wanting a super-granular, per-entity, view of each migration item then you're probably looking at building your own tool or debugging a migration as it's being processed.


How can I delete taxonomy terms for a specific node type? I had a taxonomy vocabulary (Tags) shared across all of my content types including those like forum and blog that could be user created. I'd like to remove the terms / Tags from all node types except story. Story can only be created by site authors. Is there an acceptable way to do this?

I tried deleting the tag field from the content type. However, it does just that.  The field isn't part of the type, but the terms remain assigned to the existing nodes.

If I were going to do this programmatically with a MySQL script, are there tables other than taxonomy_index, field_data_taxonomy_vocabulary_, and field_revision_taxonomy_vocabulary_ that I'd need to delete rows from? It seems like I could generate a list of nids I want to remove terms from, and then delete the corresponding rows from those 3 tables.

Thanks in advance for any help. I'd be happy to provide additional information.

The field isn't part of the type, but the terms remain assigned to the existing nodes.

That doesn't sound right; to the best of my knowledge removing the field from a content type will (normally) remove all data attached to nodes of that type. They get moved to a field_deleted_* table and then purged on a cron job.

It might indicate there's a problem somewhere in your installation, or it might just be 'one of those things'.

The 3 tables you mentioned are the only places you'll need to delete data from, but you'll also need to flush the caches after the purge (or at least truncate cache_field)


Why do PAreview/codesniffer gripe about missing "scope modifier"? I am writing a simpletest file for my Drupal module. It works OK, but when I use PAreview (automatic tool based upon PHP codesniffer to check correctness of Drupal code), I get the following error flagged: `No scope modifier specified for function "setUp".

My function setUp looks like this:

function setUp() {
  parent::setUp('realnamereg');
  variable_set('user_email_verification', FALSE);
}

Changing into into a public function fixes it:

public function setUp() {
  parent::setUp('realnamereg');
  variable_set('user_email_verification', FALSE);
}

Do anyone know why PAreview/code sniffer complains about this, and whether making the function public makes any difference?

As this example blog shows, a testcase is a php class. The definition of setUp in the base class is a public function. Your implementation function of setUp must/should match the defined definition. So Parview bitches.

class MymoduleTestSuite extends DrupalUnitTestCase
{ ... }


How to export Views data in separate sheets/tables to Excel file? I've two content types say Reports-1 and Reports-2. Using views I've displayed them as shown in the image. Reports-2 is attachment for Reports-1.

I used Views Calc to display sum at bottom of the table. (Total SUM)

By using Views data export module I could able to export data to Excel format.

Right now the exported excel looks like follows.

But my question is is there any possibility to show the data in separate tables with headers as Reports-1 and Reports-2? (like following image) to recognize the Reports. I need to display sum as well for Individual reports.

I'm also thinking to export views in different sheet of the same Excel. Is it possible?.

Can I do modifications on views-data-export tpl files. Is there any chance to render views output there? Any hints/suggestions!! ?

You can do it by using Phpexcel

check out the above link.may it will help you.
i have customised my excel and csv files using phpexcel and it works great their.


Omega Tools Transform Theme Name error I am getting the following error when trying to create an omega-sub-theme on my local machine (OSX) using drush on Acquia Dev Desktop.

PHP Fatal error:  Call to undefined function _omega_tools_transform_theme_name()

Install process I followed goes:

Set Name
unique machine name
Omega (HTML5 base)
Default Starterkit
Destination: sites/all/themes
keep starterkit read me files
enable theme/ set as default
download libraries defined in libraries.make

Fatal error occurs here.

As per Clive's comment the error was Omega-Tools. I had disabled it but it required uninstalling and then I even had to delete the module from the modules directory to stop it from showing up in the modules page. After this I encountered this issue ( https://www.drupal.org/node/2200473 ) and then everything worked. Thanks Clive.


Drupal multisites share modules and libraries? I want to duplicate a drupal site to make subsites where each site will utilise the same basic modules and core but just have slight variations in theme and need own database on a dedicated server. To save memory I want to avoid having subsites all containing same modules, I have only briefly read the documentation for drupal multisites where they share the one core but is it possible to share sites/all/modules and libraries as well?

Yes.

In a multisite setup anything in sites/all is shared.
This means sites/all/modules, sites/all/themes, sites/all/libraries are all shared.

In addition to that, if you have things that are specific to a subsite, for example, a sub-theme, or a module or library, you can add them in sites/subsite_name/modules, sites/subsite_name/themes, sites/subsite_name/libraries.


Is there a better way than twig files overwrite? In my project, I have a " field--node--title.html.twig " file, I used this file to overwrite the title label to be able to give it a certain class.

I know you can be more specific using " field--node--title-x.html.twig ", Where x can be a block or a page!

I was wondering if there exists a better way of doing this. Maybe I could do IF conditions inside " field--node--title.html.twig " file to check for a certain block or a certain page.

This would be much easier and it would also decrease the number of files in the field folder in templates.

Yes, usually there is a better way: preprocess functions allow you to alter the render array that is passed to the twig template. Adding a class is, in most cases, possible, but you might need to check how the twig file is turning the render array into markup.

This article has more info: https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file


Update user via REST (and under AngularsJS) I need to update a user fields via REST SERVICE. I'm under AngularJS, so this is my function into my .service()

setMyUtx: function (params) {
            return $http({
                method : 'PUT',
                url : 'http://XXXXXXXX/rest/user/'+params.uid,
                data : {'data' : params.value},
                headers : { 'X-CSRF-Token' : $cookies['csrftoken'],'Content-Type': 'application/json;charset=utf-8'},
                cache : false
            })
        },

where params.value is :

var data = {};
      data.field_primary_aircraft = {};
      data.field_primary_aircraft.und = [{value:1}];
      ProfileService.setMyUtx({'uid' : $scope.datiUtente.uid, 'value' : data});

If I exec this function, my drupal site return no error with this output:

{"field_primary_aircraft":{"und":[{"value":0}]},"uid":"7","roles":{"2":"authenticated user"}}

But no update is done (I know it because the original value of field_primary_aircraft is 1).

Why this ? Where is my error ?

I suggest you first try to test it with a browser REST application extension.
I would recommend this for Firefox: https://addons.mozilla.org/he/firefox/addon/rest-easy/

If you still doesn't get any error, check your watchdog... there is no reason this shouldn't work.


Preventing spam registration /url redirect im getting more and more spam account registrations. what is the simplest way to handle this if one does not need browser based registration? people register the REST/services way via an app.

can this be achieved without additional modules? e.g. server redirect?

If you don't need user self-registration then just disable that functionality.

To do this go to :
/admin/config/people/accounts (Admin > Configuration > People > Account Settings)

And for the Who can register accounts? setting choose Administrators only.

If later on you decide that you need that functionality, you can enable it back and then just add a captcha to your user registration form, or integrate something like honeypot or logintoboggan.


Confused about hook_update_n I am updating a module that I built for my site. When I originally built the module, I didn't know much about Drupal and I gave it a version of 0.0.1. Now I'm working on a completely different version that will be using 7.x-2.x as the version. I need to run an update for the module to work. I have this function

function contacts_blocks_update_7200() {
  // Update code.
}

When I go to update.php on my site, I get an error that there are no pending updates. I've also tried contacts_blocks_update_7201. Neither is working. I do not understand how to make an update run this function. I've had a similar issue with another module and was never able to get the update function to run and ended up doing it manually.

I checked the schema_version of the module in the system table and it says 0. I'd really like to learn how to do this. How do I determine the N for hook_update_N?

Provided your project's machine name is contacts_blocks, make sure that your implemenation of hook_update_N is located in a file named contacts_blocks.install that is inside your project directory.  (Make sure you spell it exactly right contacts_blocks.insall will not work.)

The four digits should be [major version][minor version][2 digits for sequence], so the correct name in your case (branch 7.x-2.x) should be 72XX, where XX is some sequence number.

To figure out what number to use for the last two digits, run the following query:

SELECT schema_version FROM `system` WHERE name = 'contacts_blocks';

If it returns no result, then use 7200.
If it returns something below 7200, then use 7200.
If it returns a number above 7200, but below 7298, then increment with 1 and use that (e.g. if it returns 7202, use 7203).

If there is a weird value for schema_version in the systems table, and you're just experimenting (i.e. nobody else have your module, so you're not going to distribute the contacts_blocks.install file with your update to anyone), you can get a fresh start by disabling and uninstalling the module (just disabling is not enough), the reinstalling it again.

API link: function hook_update_N


How to create multi-page node views in D7 I have a content type with user related fields that users can fill out, similar to a profile. I would like to split this node into a series of sub-pages/multipages and group fields together on each sub-page, rather than having all fields show as one huge node.

It's very similar to having tabs or a pager system but I don't want the actual tabs or pagers to be visible since I need to have my own links to each "tab"/multipage. I have tried to do this with Field Group module but it doesn't allow multipage groups in the node view (only in the node edit form). If I create Field Group tabs, that does split the node but then I have no way to hide the actual tab labels and (as far as I know) it is awkward trying to link to each of the individual tabs since they don't have a proper url. If it were possible to create additional local task tabs (after View, Edit) each tab would have its own url (node/#/edit, node/#/info, etc), and I could then hide, sort and rename the tabs very easily using Tab Tamer. But it's my understanding that there's no module with this sort of "add a local tab" functionality.

Is there currently a way to create multipages with D7, in the node view?

Have you tried the Book module which comes with core? It will do some bits of what you need but you can build a module to further modify it.


File URI - Change domain name Is it possible to change the domain name when creating urls to the image:

file_create_url($file->uri)

I need the images to say they're coming from another domain, but I can't change the base_url, since we need to keep drupal accessible on origin.

Example

Origin: http://domain1.com/files...

When creating image urls, they will be http://domain2.com/files...

Looking at file_create_url() I think it should be possible to pass in an absolute path, starting with /files... and then prefix the return value with your domain, protocol, whatever you need.

To handle that at a single location in code you can also use hook_file_url_alter().

Is it possible that you're looking for the CDN module?


How do I debug "unexpected % in php_eval()"? While testing with PHP 7 a site, which works fine with PHP 5.5, I get this error on some pages:

  ParseError : syntax error, unexpected '%' in php_eval() (line 7 of ..\modules\php\php.module(80) : eval()'d code).

I have no idea where to search that %. It could be in code, or a token in panels or anything. I already read comments in this similar question, but maybe someone got same bug while testing PHP 7.

This error is from php code in a text field.

  Speaking of debugging, errors in eval()’d codes throw up error
  messages that don’t provide much help in identifying or locating the
  error. There’s a good chance you might have to go through your
  database manually to find and fix the error. Such errors might even be
  fatal in certain instances, for example, if the error is in a block
  that is displayed on all pages.

Source: http://valuebound.com/resources/blog/enabling-php-filter-in-drupal-7-core-what-can-go-wrong


How do I theme my module output (specifically the nodes coming out of EntityFieldQuery)? I'm using EntityFieldQuery to get node IDs that match certain criteria in my module. At the end, I am doing: return node_view_multiple($nodes, 'full'); in the page callback function (which itself is called from hook_menu).

If I use node--content-type.tpl.php, I override the display everywhere. Ideally, I would like an array containing Node information that is sent to the tpl file, (like a controller returning display array to a view in CodeIgniter), which I can loop through and create a custom display.

How do I go about this?

Instead of doing a full node view you can make a custom node view like

return node_view_multiple($nodes, 'module_name');

That will enable you to create custom logic for this view type and setup field display as well if needed.

To define your own view mode you need to add it using hook_entity_info_alter

/**
 * Implements hook_entity_info_alter().
 */
function hook_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['module'] = array(
    'label' => t('Name'),
    'custom settings' => TRUE,
  );
}


Scheduling a module to run at a specific time Is there any way to schedule a particular sub-module to run at a specific time? I found hook_cron but it seems to rely on a scheduled cron job in crontab to run cron.php and then cron.php calls hook_cron. I have multiple sub-modules that I would like to schedule to run, all at different times. The scheduled times are user-inputted from the front and processed in the main module. Because of this, for hook_cron to work, I would need to pass in parameters from the main module (based on what the user inputted)

Any help is appreciated.

I am using Drupal 6

Depending on how detailled your specific time is, you could still use hook_cron. For example, let's say the normal cron runs every hour, you could check date('H') in your module and only if it equals a predefined value, the cron function in your submodule will be executed.

function MYMODULE_cron() {
  if (date('H') == 3) {
    // this code will only be executed between 3:00am and 3:59am
    // do your stuff
  }
}


Modules appear as themes in themes page Not serious but interesting. I entered into the themes page and besides themes I also found there modules.

Any suggestion what can cause this behavior?

All modules listed there are dependencies of the Dawn theme, and when we look at the Changelog there are entries like: - Added jQuery Update, Honeypot modules.

There is no way for a theme to define module dependencies (you'd need an installation profile for that), so my best guess would be the theme creators packaged the modules within the theme.
Normally I would have checked that for you, but it is a little harder with commercial themes. You should browse through your Dawn theme folders and see if the modules are nested in a sub-folder somehow. (Perhaps there is even a README explaining you should move them?)

The reason they are listed as themes is because modules and themes both provide a *.info file containing the details, and only the folder they are in is used to distinguish between module or theme. Since the module / theme detection in Drupal can scan multiple folders deep (eg. Views UI module is a subfolder of the Views module), it probably detects these modules's .info files and assumes they are themes since they are in the sites/all/themes folder.


How do I include a twig file in a custom block type module? I've created a custom module that creates a jumbotron custom block type. The module has an empty .module file and a dir config/install with many .yml files. This works great when I install and create blocks. I can even place my block--bundle--jumbotron.html.twig in the templates folder of the theme and styling works great! I would like this twig file included in the module and many tutorials explain how to do this if you have a build function in your module, I do not. The module is just creating a block type for me.

Create a theme hook with the template name by replacing dashes with underscores:

mymodule.module:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__bundle__jumbotron' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}


How can I get a user_reference type field working that allows me to enter names that don't exist on the site as well as ones that do? So essentially I want a text field to operate in a similar fashion to the facebook tagging text field. By default I would be looking up other users on the site. So user reference field is obvious. However if the user isn't found I'd still like to keep the text they entered as they are just entering someone's name.  Obviously I could just go and code this I'm just wondering whether anyone has done or seen this done before?

Autocomplete username looks like it does the auto complete bit for user registration. It's fairly simple. And could probably be adapted for your UI needs. image annotate looks like it does something similar, but without the ajax.

If you end up making it and publishing it, you can always post it here as an answer.


Forms in a table won't show I am trying to display a form in a table, but it is showing an empty result, while the header is displayed. I can't understand what I am doing wrong.

/*
 * cart form and page display
 */
function cart_page_form() {
  $form=array();
  $form['#tree'] = TRUE;

  $checkboxes=array();

  foreach($_SESSION['cart'] as $key => $qty) {
    $checkboxes[$key] = '';

    $form['checkboxes'][$key] = array(
      '#type' => 'checkbox',
      '#default_value' =>check_plain($key),
    );

    $form['quantinty'][$key] = array(
      '#type' => 'textfield',
      '#size' => 4,
      '#maxlength' => 4,
      '#id' => 'prod_qty',
      '#default_value' => check_plain($qty),
    );

    $form['price'][$key]['#value'] = t('244p');
  }

  $form['remove'] = array(
      '#type'           => 'button',
      '#name'           => 'remove_selected',
      '#value'          => t('Remove selected'),
  );

  $form['submit'] = array(
    '#type'           => 'button',
    '#name'           => 'update_quantity',
    '#value'          => t('Update'),
  );

  $form['checkout'] = array(
    '#type'           => 'submit',
    '#name'           => 'checkout',
    '#value'          => t('Зделать заказы'),
  );

   return $form;
}

/**
 *Implementation of hook_theme().
 *
 */
function yalublurudn_theme() {
  return array(
    'cart_page_form' => array('variables' => array('form' => NULL)),
  );
}

/**
 * display cart page
 */
function theme_cart_page_form($form) {
  $rows = array();

  foreach(element_children($form) as $key) {
    if (isset($form['checkboxes'][$key])) { //// make sure this is one of our table rows
      $row = array();
      $row[] = array('data' => drupal_render($form['checkboxes'][$key]));
      $row[] = array('data' =>drupal_render($form['quantinty'][$key]));
      $row[] = array('data' =>drupal_render($form['price'][$key]));
      $rows[] = $row;
    }
  }

  $header = array(
    'Checkboxes',
    'Title',
    'Quantity',
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render($form); // Render rest of form components.

  return $output;
}

In Drupal 7, a theme function like yours receives an array containing the variables declared in hook_theme(). If you execute element_children($form) with the form you defined, you get an array containing the following values:

checkboxes
quantinty
price
remove
submit
checkout

The control statement if (isset($form['checkboxes'][$key])) { will not be executed, if not in the case you have $form['checkboxes']['checkboxes'], etc.

Your theme function should use the following code.

function theme_cart_page_form($variables) {
  $form = $variables['form'];
  $rows = array();

  foreach(element_children($form['checkboxes']) as $key) {
    $row = array();
    $row[] = array('data' => drupal_render($form['checkboxes'][$key]));
    $row[] = array('data' =>drupal_render($form['quantinty'][$key]));
    $row[] = array('data' =>drupal_render($form['price'][$key]));
    $rows[] = $row;
  }

  $header = array(
    'Checkboxes',
    'Title',
    'Quantity',
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render_children($form); // Render rest of form components.

  return $output;
}

Actually, you should declare the theme function using the following code.

function yalublurudn_theme() {
  return array(
    'cart_page_form' => array('render element' => 'form'),
  );
}


Pre-filled subject Form I wanted to attach a form to my node, in wich the subject would be already filled with the nodes title.
I was trying something with webforms and views but didnt get any results. Any Ideas?

If subject is a simple textfield on webform and token module is enabled then you can set this textfield's default value using token.


Tab on user page doesnt show up I dont know what i doing wrong but for reasons the tab on user page doesnt appear!
i have like three tabs which i place my self in custom module and they ok.. But now trying to use the principle i used nothing works.
below is my code! Any suggestions?

$items=array();

$items['user/%user/mysite-news'] = array(
'title' =>t('Мой Новости'),
'description' => t('yo news.'),
'page callback' => 'mysite_news',
'page arguments' => array(1),
'access callback' =>array('view kupon'),
'type' =>MENU_LOCAL_TASK,
);
$items['user/%user/mysite-news/my-news'] = array(
'title' =>t('Мой Новости'),
'description' => t('see your news.'),
'page callback' => 'mysite_news',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight'=>-15,
);

//and my call back function
function mysite_news($account){
  $my_name=t('my name is $c',array('$c'=>$account->name));
return $my_name;
}
?>

if i visit the link
user/1/mysite-news/my-news

the result is displayed, "my name is admin".
But the tab doesnt show on user page.. please help.

You don't define the 'page callback' for the MENU_DEFAULT_LOCAL_TASK since it is taken care of by the 'root' page, plus without any additional tabs it won't show up anyway.  If you add another MENU_LOCAL_TASK it should show up.  You can think of the default local task as the page itself, there would be no reason for a VIEW tab there without anything else like EDIT UNPUBLISH etc.


Multiple products on add to cart? E.g. node contains a product Poster for $5 and e.g. a checkbox saying "+ Cup" which is another $5. So it's two different products, how do I let user select if they want just a poster of if they want the poster + the cup, so check the box for the cup and on add to cart it adds both items?

If you create a product reference field with Unlimited, it won't let to choose multiple items, it renders as a dropbox/select list for one item to choose and add to cart.

https://www.drupal.org/project/commerce_product_kit is locked to total products set for the page in the product reference field, so it always adds both products on Add to cart, no select option.

So basically how to add 1 to 2 products on same page clicking Add to cart only once.

Have you already tried the Commerce Product Add-On module? That sounds like exactly what you're describing.


How to reset specific form elements I have a form which I have included a reset button. Here is the code:

function submission_list($form, &$form_state) {

  ...code here...

  $form['filter']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('submission_list_reset'),
  );

  ... more code ...
}

function submission_list_reset($form, &$form_state) {

  if (isset($form_state['etd_filter'])) {
    unset($form_state['etd_filter']);
    $form_state['values']['filter_user'] = '';
    $form_state['input']['filter_user'] = '';
  }
  $form_state['rebuild'] = TRUE;
}

I thought what I have in the submission_list_reset function is correct but it still displays whatever the user typed in the filter_user text field. I have tried clearing the values and input array with no success so I must be missing something really basic here. I have searched Drupal Answers and Google but have not found an answer. The answers I have found on Drupal Answers is about adding a reset button but not about clearing specific fields.

Thanks.

You can attach the reset function in this way:

function submission_list($form, &$form_state){
  $form = array();
  $form['name'] = array(
    '#title' => 'Name',
    '#type' => 'textfield',
  );
  $form['surname'] = array(
    '#title' => 'Surname',
    '#type' => 'textfield',
  );
  $form['actions'] = array(
    '#type' => 'actions',
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#attributes' => array(
        'class' => array('my-submit-button-class')
      ),
      '#submit' => array('your_submit_function')
    ),
    'reset' => array(
      '#type' => 'submit',
      '#attributes' => array('class' => array('my-reset-button-class')),
      '#value' => t('Reset form'),
      '#submit' => array('submission_list_reset')
    )
  );
  return $form;
}

function submission_list_reset($form, &$form_state) {
  $form_state['values']['name'] = '';
  $form_state['values']['surname'] = '';
}

function your_submit_function($form, &$form_state) {
  drupal_set_message('The form has been submitted');
}

But please consider to use ajax callback for this reset function, it would be better do not reloading the page only because of resetting. More info - Ajax forms in Drupal 7


how to use Views Datasource to export view in JSON I am new in Drupal. I am using Drupal 7 and i have created a view based on the terms and displaying it as Block to display it in the website. But, I want to export the view data in the JSON format.

I have installed Views Datasource module and enabled it in the Module administration.

But, i can't see the way to export my current view data to JSON through this module.

Can any one please help? is there any settings i am missing?

or is there any easy way like modules or plugins i can use?

You can achieve this by combination of two modules. Views data export and Views data export - JSON support. Once you install these two modules create a view as data export and select format as JSON.


what is the difference between render() and drupal_render()? what is the difference between render() and drupal_render() anyway ?
Is there a reason to use only drupal_render()?

The docs for render() explain it pretty well:

  This function renders an element using drupal_render(). The top level element is shown with show() before rendering, so it will always be rendered even if hide() had been previously used on it.

render() is basically just a wrapper for drupal_render(), except that it makes sure the element passed in is set to be shown when passed through to drupal_render().

It also makes sure the element passed in is an array (which is all drupal_render() can accept). If it isn't, the element is return back as-is. So it provides a bit of a safety net if you like.

If for any reason you have a variable you need to render, and you don't know if it's a string or a render array, you can pass it straight through render() without having to test the variable type yourself.

For some real-world examples of that sort of situation there's a list of calls to render() you can look through.


For product type 'donation' allow customer to choose "price" and add allocation field Using Drupal commerce I want to change checkout functionality to allow the user to choose the amount for product type 'donation' on the user details page. See here:

The user should be able set "the price". How would I go about this?

You may also see that I  want to add a custom input for choosing allocation of the donation. Would I do this using a hook to alter the form? How? And would it capture the data within commerce store admin?

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

Check the Screenshot below.


How to create additional drupal sites with a drush script I'm using drush site-install for my initial site, and everything works great, but when I go to try create another site (using table prefixes so I can use the same database), drush attempts to drop and recreate the database, so I loose all the table from my first site. I know how to target drush to a particular subsite, but I'm not sure how to tell the drush site-install command not to drop the database tables.

Is there a better way to do this if I want to setup a initial site with 2 additional sites?

Drush has very limited support for table prefixes; site-install is just one of the ways that Drush can fail.  sql-sync has similar problems.  It would take a lot of work to fully support table prefixes everywhere; it is best and safest to just use multiple databases when using Drush.


Theming two instances of an input field in one form I have two instances of the Search form in one page. The search field needs to have different CSS classes in each instance.

Instance 1:

<input type="text" class="form-control input-foo" placeholder="Search">

Instance 2:

<input type="text" class="form-control input-bar" placeholder="Search">

All the relevant theme templates and preprocess functions that I can find to edit the classes output on the field, apply to both instances. E.g. input--search.html.twig.

For the time being I have instead applied a class on the block that each of these forms is contained in, but I'd like to know if there's another solution.

Is there a reason having the class on the input would be better than having it on the block? e.g. does it make some CSS/JS awkward by not being able to target the input directly?

If not, having the class on the block seems like the ideal solution both in terms of ease-of-development and semantics...you want the search input to be styled based on where it is. That feels like a natural separation for a hierarchy of selectors: .block .input

If the blocks are in different regions, you could use the region class instead, which is there by default in most themes; that would avoid even having to alter the blocks themselves.


How to unpublish postings according to the value of a field? I was able to set rule to unpublished after +30 days. But I would like to tweak my rule to give to my users the possibility to choose between posting for 2 weeks, one month or 3 months.

So, I guess that there would be an "if choice X, than unpublish after Y period of time". Can the field (to choose duration) be a text dropdown?

Can this be done without PHP? If so how?

So, I figured out that I can add a condition like this :

Parameter: Data to compare: [node:field-time-limit], Data value: 2 weeks

But since I have 3 choices for my ads (2 weeks, 1 month, 3 months), does this means that I have to make 3 different rules, one for each time limit?
(it seems to make sense, but I'm not shure).

Note: I'm aware of the thread about "Tutorial 2: Publish content exactly 24 hours after it was created".

Your question seems to exist of actually 2 questions, so here are 2 parts of an answer to address each of them (I'm assuming this question is about D7).

Part 1

Refer to my answer to "How to specify a Rules condition related to select list values?" for an example Rule (in Rules export format) that allows for specifying a Rules condition related to a specific value selected via a selection list.

With this (and some minor tuning of that sample to fit your field and values), you have an answer to your "if choice X, than unpublish after Y period of time".

Part 2

Refer to my answer to "Redirect users with specified roles to specified term pages", which shows how you can redirect to various URLs (depending on some role). It also explains 2 possible approaches for either creating multiple rules (1 for each role) versus just 1 rule (by using the Conditional Rules module).

With this (and some minor tuning of that sample to fit your case here), you have an answer to your "does this mean that I have to make 3 different rules, one for each time limit". The actual answer is: either way can work (personally I'd go for just 1 rule, using the Conditional Rules module).

PS: So yes this can be done without PHP, it only requires some site building using the Admin UI for Rules.


Discount select list I've checked for a similar question but nothing helped me.
So, i want to add a list in shopping cart with 3 options:
a) No discount
b) 70% discount
c) 65% discount
When the user selects, lets say 70% discount, the discount will be added in total amount and after that is going to select the payment method.

I'm doing this because there is no available module for deposit. The 30% of deposit that i want is like 70% of discount.

Thanks and i hope there is an easy solution that i couldn't find

Try doing this with the Commerce Discount module.  With it, you can create discounts that are either hard-coded dollar amounts or are percentage based.  You'll use the second option.

This module uses Rules to calculate the discount amount based on a product price or the entire order amount.  Read more on the module documentation page: http://drupal.org/node/1706132


Enable Password and Confirm Password fields in Registration form i want to have registration form in my drupal site, but that is limited to the fields email and username.

I also want to have fields "Password" and "Confirm Password" in the registration form, so that the user does not need to check his email for his password and can login to the site directly after registration.

How can i achieve this?

I think the LoginToboggan module can do everything you need.

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

  Allow users to login using either their username OR their e-mail
  address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
  Customize the registration form with two e-mail fields to ensure accuracy.
  Optionally redirect the user to a specific page when using the 'immediate login' feature.
  Optionally redirect the user to a specific page upon validation of their e-mail address.
  Optionally display a user message indicating a successful login.
  Optionally combine both the login and registration form on one page.
  Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
  Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)


Custom entity custom cache tags I've created a custom entity and having trouble providing proper caching.

When you create custom entity, by default it has only one cache tag entity_type:id.

Problem is, I need to display same entity to different users (by role) in a different way.

So I think I need cache tags, such as entity_type:id:user_role? How do I go with this?

To add a cache dependency on user roles you don't need a cache tag, but a cache context user.roles.

However, you rarely need this context, because there is already a default render context for the hashed user permissions user.permissions, set in the container variable required_cache_contexts, which is applied on all render arrays:

default.services.yml:

parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']


Entity Translation and Taxonomy I'm having hard time integrating Entity Translation module with tags (Taxonomy and TagClouds modules). I want the following:

Cloud of tags to be showed on the site
Tags must be translatable, i.e. each tag must be showed in English or Russian, depending on the current language.

There are at least two problems. The first is that ET module breaks TagClouds. More specifically, whenever I enable these two modules (in any order), showed cloud of tags disappears. What is more suprisingly, it even doesn't matter was translation of tags enabled in ET module or not ( admin/config/regional/entity_translation -> translatable entity types -> taxonomy term) -- cloud of tags always ends up disappeared. Dblog doesn't show any errors. Is there any other place I can check for them?

The second problem is that if I make taxonomy term translatable in ET, I get strange errors when I'm trying to translate terms. For example:

If I get to the page of some tag created before enabling ET, for exampleen/taxonomy/term/8, than click Translate tab, I will see that current name is not English nor Russian. If click add button in either language, I will get not found error -- see screenshots.

If I click to edit button in list of tags (admin/structure/taxonomy/tags), I will get even more interesting error -- Access denied, You are not authorized to access this page.
Finally, If I click add items on some vocabulary and save it, I will get the following exception: Exception: Invalid translation language in EntityTranslationDefaultHandler->setTranslation() (line 635 of /var/www/drupal/sites/all/modules/entity_translation/includes/translation.handler.inc).

Name and Description fields of tags are marked as translatable (admin/structure/taxonomy/tags/fields/name_field -> Field translation
Users may translate all occurrences of this field: Name in Теги)

What I am doing wrong?

Drupal version is 7, all modules are up to date. I also use i18n modules for translating the interface, by the way.

The exception can be fixed by visiting the following page: 'admin/config/regional/entity_translation'.

Then make sure that under the vertical tab 'taxonomy term' and the fieldset of your vocabulary the following is unchecked: 'Hide language selector'.

You may need to check 'Exclude Language neutral from the available languages' if that doesn't work.


How to translate entity in the views footer I am creating a multilingual site. I have views and when it was created, I added to the footer entity (node/22). Next, I created a translation of this content and now changed id (node/45). How to specify the settings views to display different node corresponding to the user's language?

With views php module you could add php in footer instead of entity. Sample untested code:

global $language;
if ( $language-> language='en'){
$n=node_load(22);
echo $n->title; //or any other field
} else ...

A more elegant way is to use a view attachment and put another view in the footer


What is the syntax for l.d.o translations in a drush make file I have read the Drush Make documentation, and understand you can download translations at the time you use the drush make command, since there is an option. What I don't understand clearly is how to add a translation from localize.drupal.org to your .make file. Any help and/or an example would be amazing. Thanks.

Drush Make documentation: http://drupalcode.org/project/drush_make.git/blob_plain/refs/heads/6.x-2.x:/README.txt

The post beta9 dev version of drush_make also supports downloading drupal core translations with, for example:

projects[] = nl

Source: http://drupal.org/node/644916. (There's also a documentation patch there.)


How to load multiple values from a field with views_php module? I'm trying to build a responsive gallery. Since views won't let me rewrite the field's output with html5 data attributes I need to print the output using a PHP field in views.

Using the module views_php, I'm accessing the values of the image field this way:

$source = $data->_field_data['nid']['entity']->my_field['und'][0]['filename'];

This way I load the value from the ['und'][0] array, this would work properly if a field  has a single value.
But what if in the node creation, in my field I want to upload multiple images. How could I change the [und] numerical value to load as many values as my field has.

Thanks in advance.

As Syd said, it seems like you need a foreach loop. It's not readily apparent what you're wanting to do with the $source variable, but I'm guessing it's something like the following:

foreach ($data->_field_data['nid']['entity']->my_field['und'] as $a_file) {
    echo '<img src="' . $a_file['filename'] . '">';
}


Drupal Commerce: How to get payment module settings? How to programmatically retrieve configuration of the specific payment module?

I tried

$settings = rules_config_load('commerce_payment_MODULE_NAME');

It returns very basic info (name, ID etc) and empty "settings" array.

Cant also get it directly from DB .

It is stored in serialized array that can not be fully processed with the unserialize() function.

I'm using this:

$payment = commerce_payment_method_instance_load('foo|commerce_payment_foo');

where foo is the payment method string identifier.

The resulting array contains the 'settings' index, with the data saved in the settings form.

In other words foo|commerce_payment_foo is instance id which consist method_id|rule_name.

The method_id can be found by executing commerce_payment_methods() and rule_name can be found in URL when editing Payment action (at /admin/commerce/config/payment-methods).


Multilevel Categories & Menu - How To? I would like to be able to create content of a particular type but be able to set multi-level categorisation. But I would like a menu where I can select a category and see all content including child categories as well.

e.g.

Fruit

Local

Apples
Pears

Tropical

Pineapple
Bananas

'Fruit' menu would show all fruit

'Local' Menu would show all local, apples and pears

'Apple' Menu would only show Apples

I am trying to achieve some thing like this side menu:
http://learningexchange.ptc.com/tutorials/by_product/ptc-creo/product_id:1

There won't be a definite answer to this question as this can be achieved in a lot of possible ways. Depending on your knowledge in drupal you could start with the built-in drupal taxonomy system that enables you to classify your content as needed (e.g. with a tree-like-hierarchy or even related terms). To build the menu you can try the taxonomy menu module or use Views to create this manually.

For a start i recommend reading through this overview: https://www.drupal.org/documentation/modules/taxonomy


Editing Image of Media Type Image in Drupal I'm having an issue with an Image field that I've set up under a Media Type. I'm able to create nodes, upload images or select images from the media browser just fine, but if I need to edit the node and change the photo, when I save it I get the following warning and my image disappears:

User warning: Missing file with ID image/jpeg. in Drupal\image\Plugin\Field\FieldType\ImageItem->preSave() (line 327 of core/modules/image/src/Plugin/Field/FieldType/ImageItem.php).

The only way I seem to get it working again is to completely delete the node and recreate a new one.

I have other fields set up the same way with normal content types and it works fine. Is there something I'm missing?

I'm using Drupal 8.5.3

Check your Field Mapping for the Media type you created.
Set them all to - Skip field - and you should be able to edit the media content without errors.


How do I add a css class to body from a page callback function? I have a module that produces a lot of pages. A set of these are handled by a particular part of my application, and I would like all these to have a class added to either html or body. I'd settle for #block-system-main.

The existing answers point to a template preprocess hooks e.g. hook_preprocess_html() but this feels wrong.

I'd have to create that hook and then tell it to go somewhere else to determine which page call back was used and which class to apply - it's all backwards. Drupal's already selected the right callback, so a 2nd lookup is another thing to maintain and an inefficiency.

I could of course do something like set a global $extra_page_classes variable and then implement the hook to add these classes to the page, which is more efficient but it's still messy. Or I could add (yet another) wrapping <div> to my callback output, but that's not going to give a themer chance to adapt the rest of the page elements outside of the main content.

Seems odd that a page callback, responsible for the substantial content of the page, can't set page-level attributes. A page callback can, for example, choose to call drupal_add_css(), but it (apparently) can't do something as simple as add a class to the page.

As it seems odd and Drupal usually has some (often hidden) elegance, I thought I'd ask specifically if there was a better way.

Well, I think your confusion comes from the D7/D6 fact that a "page" has little clue whats going on around it. As you've said the page callback function tells drupal "what goes in the $content" but not what adornments happen on the page HTML DOM around $content.

To my knowledge unless your using Panels, Context or something else to share "page state" through components of your site -- this is simply how D7 simply works.

Without using context, panels, etc. I usually end up looking for url paths or NIDs or custom content array attributes #project-add-body-classes in hook functions to fire off my logic.

For what you describe I would use hook_html_alter() and look for a page path to alter the body_classes array as needed.


Transpose Article to Media (Image) I am rebuilding a Drupal 7 site, making some changes to the data structure along the way. On the old site, I have a content type with an image, a description, and a couple other text fields. On the new site, I need this content to appear as images within a gallery (Media Gallery module). I also need to preserve the description field.

I'm not sure where to start. I used the Feeds module to migrate some other content types to their new versions, but that module cannot create this "Media" object, only nodes.

Thanks.

Media Feeds should allow you to create media objects that you can use in your gallery.

  This module is the Drupal 7 solution for Media Feeds Integration. It
  provides mappers for the Feeds module. The target can be a Media
  asset, image or file field on an entity (such as a node).


Password reset causing 404 I'm getting a strange issue using the 'Reset your password' functionality in Drupal 8.

Basically, the process works fine up to the point of clicking the Login button on the screen that shows the following message:

This is a one-time login for foobar and will expire on Tue, 20/09/2016 - 15:25.

Click on this button to log in to the site and change your password.

This login can be used only once.

When the 'Log In' button is clicked, the user is taken to a 404 page, with a url similar to:

user/reset/123/1474293937/ukVdmEMWoYablzZHPYJzMa30-p_skkDv06d564V1KHQ/admin

At that point, the user is logged in, and they can go to their 'Edit profile' page and change their password, but it's not very friendly to be presented with a 404 page after being logged in.

Any ideas why this is happening?

Something is intercepting the submission to the user password reset form.

The form should post to the user.reset.login route (/user/reset/{uid}/{timestamp}/{hash}/login), handled by UserController::resetPass(), then redirect to /user/{uid}/edit?pass-reset-token={TOKEN}.

This could be a number of different things which you'll have to troubleshoot (e.g. Rules performing some redirect logic on login, an altered form submit handler, Apache redirect, a module performing some redirect logic on a subscribed event, etc.).

Given that the destination URL is essentially appending "/admin" to password reset form URL that should probably clue you in on what is causing the problem.


Customise main-menu link - adding a '/' between  items I am using the Omega HTML5 base theme and am attempting to add a '/' delimiter between main_menu items on my site.

I have searched high and low and the closest I've come is the following:

function MYTHEME_menu_link(array $variables) {
$delimiter = '';
  // Only add delimiter to the main menu
  if (strpos($variables['element']['#theme'], 'main_menu') !== FALSE ) {
    // Only add delimiter if item is not the last one
    if (!in_array('last', $variables['element']['#attributes']['class'])) {
      $delimiter = '/';
    }
  }
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  // Add delimiter just before the closing
 tag
  return '
' . $output . $sub_menu . $delimiter. "
\n";
}

This actually works on any another template (just not OMEGA). Irrespective does anyone have an approach to adding this forward slash on main-menu items?

Thanks!

I would suggest a purely CSS approach to this. There is really no need to go through the trouble of adding a function to your theme for this change.

The following CSS code would get you (at least close to) the results you desire:

  ul.main-menu li:after {
    content: "/";
  }
  ul.main-menu li.last:after {
    content:"";
  }

The :after pseudo-class's support includes all browsers except IE 7 & below and Firefox 3.0 and lower.


How can I display custom data from the database in a View? I'm working to create a new website in Drupal 8 and cannot figure out how to reference custom table data within a View.

Specifically, I have a script that is taking data from an external DB and populating it into my Drupal DB into custom tables. How can I allow Views to see this data?

In Drupal 7 I have experience using the Forena module and the Data and Schema modules to accomplish same DB and external DB references, but what I'm finding is that support for these three modules in Drupal 8 appears to be lacking, making me think that there is a better way to do this in D8 that everyone knows about but me. :)

I'm not sure if I'm just not researching correctly, but I'm unable to find a clear answer about how to go about obtaining this functionality in Drupal 8. Drupal 8 is so different and I'm not sure if I should be looking for a contributed module or if this is something I would code directly.

Hopefully someone can point me in the correct direction?

Ok, yeah, I feel a bit silly now and was making this too difficult. There is a module for this for Drupal 8!

I was able to accomplish what I needed with Views Custom Table.

Thank you prkos for the comment.


how to display the list of unread nodes and read nodes I want to show the list of unread nodes and read nodes.
Actually, My scenario is to show the article listing page. The page contains the drop-down contains all, read and unread. The all list all the articles, In read, need to list the contents already read by the user and In unread, need to list the contents not-read by the user. For read, I did with recently-read module but that is not tracking the unread nodes. Hope somebody have already worked with this.

Thanks advance.

Using the Flag module seems like a no brainer to me to get this to work: introduce a flag that is used to flag relevant nodes as "read". To actually do so, just use the Rules module (using a Rules event like "When viewing content", a kind of getting started with Rules).

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the node(s) for which their flagging status corresponds to "read", or "NOT read", or "all of them". If you want, you can created 3 tabs in your view to show these all / read / not read nodes.

Ps: I'm assuming this is about D7.


field_attach_update stopped working - how to debug this? I am using this simple code:

$order = commerce_order_load($order_id);
$order->status='completed';
field_attach_update('commerce_order', $order);

To update the status of order to completed.

This code use to work but does not work anymore (the order status is not updated).

How to debug this ?

UPDATE:

Using :

entity_get_controller('commerce_order')->resetCache(array($order->order_id));

Does not work neither.

You can't debug what ain't a bug :)

status is a property, not a field, of the commerce_order entity type - so it isn't affected by running field_attach_update(), which just saves field data, and avoids saving the entity itself.

You'll need to use commerce_order_save(), entity_save(), or manipulate the commerce_order table directly, and then clear the cache using the entity controller.


what does Drupal API mean? What does it mean when someone says Drupal API? Does that phrase include drupal hooks, theme functions and every other drupal term or is it used as a synonym for api.drupal.org

I am really confused please define it for me to understand it easily.

Many thanks

It's a generic term to encapsulate all the programming interfaces Drupal provides. Any further meaning would have to be inferred from the context of how it was used (FWIW, I've never heard "Drupal API" to refer to the documentation site api.drupal.org).

When specifying a particular component of the Drupal API, you'll often see it labeled with its functionality (e.g. Drupal Routing API, Drupal Batch API, etc.) to clarify what part of Drupal's API is being discussed.


How can I update a field on a user profile with Drush I'm creating users with user-create but I have added extra fields to the user like membership number.

Is there a way to update that field with a number when I create the user?

Take a look at Drush Entity. Here is a quote from its project page:

  ... you can query the entity system available for Drupal 8, 7 and (some of) 6.


Why do some webforms have their elements value in translation UI (/admin/config/regional/translate)? I have enabled webform module on a Drupal 8 installation.

For some reason, there are default webform templates such as "Donation" and "Contact Us" which have their elements values translated in the translation UI at /admin/config/regional/translate. The problem is that some webforms templates have HTML markup in their elements value like the following:

    '#prefix': '
'
    '#suffix': '
'

This will prevent saving any value, drupal telling the user that there are translations with invalid HTML tags:

  The submitted string contains disallowed HTML: information: '#title': 'Your Information' '#type': fieldset first_name: '#title': 'First Name' '#type': textfield '#required': true last_name

  etc...

Regarding this issue, I have a few questions:

what actions trigger the elements value availability in this interface? On install, on config save...?
do the webform module really uses this interface to translate the content of the forms?
and if yes, am I missing a module or something to make it work?
and if not, should this be considered as a bug? The closest issue I have found is this one: https://www.drupal.org/project/webform/issues/2913548

It looks like this is this template: https://cgit.drupalcode.org/webform/tree/modules/webform_templates/config/install/webform.webform.template_job_application.yml?id=a988217057ed5ba842a3722de01f2d07df59e5e1

Apparently, this was a side effect of the "translatability" of the elements value. A patch has been created by jrockowitz on the drupal issue tracker which will prevent having those values editable in the translation UI: https://www.drupal.org/project/webform/issues/2965060#comment-12587556


Database administration site on Drupal: entities vs. manual programming I've been asked to build a small database administration site based on Drupal. The site should have basic editing possibilities of the existing database with several tables. (The structure is not complicated).

To get it more clear, one table contains books being sold in the publishing center. The book has a set of identification numbers, title, e.g. The structure of book is very similar to basic node with fields.

The question is: Is it a good idea creating a custom entity with described architecture and process data in terms of 'book'  entity (and therefore the database will be automatically modified according to current architecture) OR it's better to implement simply some interface and update database manually using db_query etc. ?

While I can't see any significant benefits to doing this with Drupal, I think this should generally work. I've converted old systems that were using db_query and custom code to Drupal 7 Entities with the Entity API module with success, and I've been pretty pleased with the results. As long as the schema is solid, without issues, or you can modify it as needed, this will work fine.

Depending on the data structures and the normalization of related entities/properties you may need to create your own EntityController to override the loading (and saving if using Entity API module) to ensure that the data is queried and updated properly.


Why is my custom webform submit handler not submitting? I've looked at a number of posts, but none of them have quite the same issue as I am. I've added two custom submit buttons to a webform (in addition to the default one created by the admin page.) My custom validate function and submit function are being called, but the default submit function is not - i.e. the error logging I've put in my custom function gets printed, but the form is NOT actually submitted. Any ideas?

function create_vector_user_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'webform_client_form_24': // free trial webform
    $form['submit']['64_bit_btn'] = array(
      '#name' => 'op',
      //'#button_type' => 'submit',
      '#type'   => 'submit',
      '#value' => t('DOWNLOAD 64-BIT TRIAL'),
      '#executes_submit_callback' => TRUE,
    );

    $form['#validate'][] = 'create_vector_user_free_trial_form_validate';
    $form['#submit'][] = 'create_vector_user_free_trial_form_submit';
    $form['actions']['submit']['#submit'][] = 'create_vector_user_free_trial_form_submit';
    break;
  }
}

function create_vector_user_free_trial_form_validate($form, &$form_state) {
// this function runs correctly

}

    function create_vector_user_free_trial_form_submit($form_id, &$form_state) {
    error_log("submit!");
    if (strtoupper($form_state['clicked_button']['#value']) == 'DOWNLOAD 64-BIT TRIAL') {
        error_log("submitted 64");
    }
    else if(strtoupper($form_state['clicked_button']['#value']) == 'EMAIL ME A LINK') {
        error_log("submitted email");
      $to = $form_state['values']['submitted']['email'];
      $params = array();
      $params['version'] = $form_state['values']['submitted']['download_type'];
      $key = 'homepage';

      drupal_mail('create_vector_user', $key, $to, language_default(), $params);
    }

    else {
        error_log("submitted default 32");
    }

  error_log("test end");

}

ETA: I've also tried this in my form_alter function based on this article about custom validation:

$form['#validate'][] = 'create_vector_user_free_trial_form_validate';
// $form['#submit'][] = 'create_vector_user_free_trial_form_submit';
$first = array_shift($form['#submit']);
array_unshift($form['#submit'], $first,'create_vector_user_free_trial_form_submit');

//$form['actions']['submit']['#submit'][] = 'create_vector_user_free_trial_form_submit';

I found the problem.

One of the features of webform is the ability of have multi-page forms, and the way how webform determine if it is in the "final" page is checking if the submit button has the value "Submit" and if that is not the case then it thinks to there is another page to evaluate before to submit the last function.

You can see this in the file webform.module in the line 3174:

 // Check for a multi-page form that is not yet complete.
 $submit_op = !empty($form['actions']['submit']['#value']) ?
 $form['actions']['submit']['#value'] : t('Submit');
 $draft_op = !empty($form['actions']['draft']['#value']) ?
 $form['actions']['draft']['#value'] : t('Save Draft');
if (!in_array($form_state['values']['op'], array($submit_op,
$draft_op, '__AUTOSAVE__'))) {

In the case of your example $form_state['values']['op'] doesn't exists and even if it exists it wouldn't has the value 'Submit'  so it  will try to handle your form as a multipage form and It will not execute the last part of the function.

What I did to make your example work was only add the this in your submit function $form_state['values']['op'] = 'Submit'; and that's it.

It feels like a hack but that is the way how webform work :(

Below the example if you want to compare it with your code:

<?php

/**
 * Implements hook_form_alter().
 */
function test1_form_alter(&$form, &$form_state, $form_id)
{
    switch ($form_id) {
        case 'webform_client_form_5':
            $form['64_bit_btn'] = array(
                '#name' => 'op',
                '#type' => 'submit',
                '#value' => t('DOWNLOAD 64-BIT TRIAL'),
            );
            $form['#validate'][] = 'create_vector_user_free_trial_form_validate';
            array_unshift($form['#submit'], 'create_vector_user_free_trial_form_submit');
            break;
    }
}

function create_vector_user_free_trial_form_validate($form, &$form_state) {
    // this function runs correctly
}

function create_vector_user_free_trial_form_submit($form_id, &$form_state) {
     // add your code here
    $form_state['values']['op'] = 'Submit';
}

(please note to my module is called test1 you need change this with the name of your module)


How do I set a path alias for each forum? I created a forum on a site using the core Forum module. When we create a new forum, Drupal creates it as a taxonomy term. When we create the new forum, if we associate a path alias, that URL alias is only associated to the taxonomy term and not to the forum.
If we click on a specific forum from the index page (example.com/forum) we are sent to example.com/forum/nn.

How can I associate a path alias? I'm not being able to do it via the Pathauto module. Can someone tell me how to do it with that module or using any other solution?

It is possible to add a path alias to a forum, without installing any third-party modules.
You could install the Pathauto module, but that is more for automatically assigning the path aliases when creating/editing an entity, or for bulk-assigning path aliases to existing entities. If you install the Pathauto module to create path aliases for the forums, notice that under Enabled entity types on /admin/config/search/path/settings, you don't see an entry like Forum. Use the default values for that form field (which include Content and Taxonomy term that you cannot deselect), and you will be able to set path aliases for the forums.

It is a quite confusing, since in /admin/config/search/path/patterns/add you need to select Forum for Pattern type.

Maybe it would be less confusing if Forum would be an option for Enabled entity types too.

In this case, anyway, the path aliases that the Pathauto module says to assign to forums are really assigned to the taxonomy terms associated with the forums. The effect of this is that the /forum page would not use any path alias for the forum links.

I created a sandbox site on simplytest.me, and I just enabled the Forum module. I created two forums (Module development and Theme development), and created a forum topic (Porting the "User activity" module to Drupal 8). I went to /admin/config/search/path, and created the following path aliases.

/forums/1/general-discussion pointing to /forum/1
/forums/2/module-development pointing to /forum/2
/forums/3/theme-development pointing to /forum/3

Doing so, the /forum page used the path aliases I set, in the links to the forums, but the forum topic pages used links like https://dsze.ply.st/taxonomy/term/2 under Forums.

So, or you set a path alias that is used from the /forum page (but not from the forum topic pages), or you set a path alias that is used from the forum topics page (but not from the /forum page), or you set two different sets of path aliases (a set used from the /forum page, and a set used in the forum topic pages).


On content update email referenced users - Drupal 7 Rules module I feel like I am almost there but I am running into a problem.

I have a contenttype called projects with some users assigned to each project node. When a project node is updated I want to send a notification email to the referenced users.

What I have now is that all users get the email as the content gets updated.

Your help is greatly appreciated!

I just figured it out, i used a loop that went trough all the referenced users and then I added a action that send an email to every user in the loop.


Benefits of using a base theme? In building a new theme (for a bespoke build, rather than distribution) is it essential to start with a base theme? If I look at the Zen theme, for example, I would scrap most of the HTML and CSS in order to start with a blank-er canvass than that theme provides. Are there still many benefits to using a theme like Zen in that case?

Update
In an attempt to clarify, this is for a professional project, and in terms of HTML/CSS we'd usually start from as little as possible; normalize.css, modernizr and not much more. Most themes seem too 'opinionated', there's too much we'd have to re-style or remove to the point where it would slow development down.

If you're not doing a traditional 3 column with header and footer site layout, then no - you probably won't get much out of something like Zen.

That said, you can still leverage the awesome Zen Grids gem with SASS and get the benefits Zen's grid system without any of the cruft from the base theme.

Anyone who has themed enough Drupal sites understands that you're going to be dealing with machine-generated HTML at some point (either from Views, or some other contrib module). You could spend a ton of time overriding all the theme functions to get the exact HTML you need so you can apply the col-xx classes your grid system of choice needs, or you can use the classes that already exist on the pre-existing markup and make them compatible with your grid with Zen Grid's mixins.

I like to say that Zen Grids acknowledges the reality of Drupal theming and comes up with a system that works with Drupal as opposed to against it.


Load Bootstrap CDN only if not is loaded before from another project I want to load Bootstrap CDN but only if is not loaded before. How can I do this?
Today I'm loading on Libraries.yml like this:

And it works. But the problem is: in some cases the Drupal site already have another project that loads Bootstrap CDN and it is a conflict.
Is there a way to load Bootstrap CDN only if not exists?

One approach:
Attach the modal-page-bootstrap library as you are doing, and don't also load bootstrap.js in another way.
Don't worry about adding libraries multiple times to the same page. Drupal is smart enough to only load that library once, and at the right time and order.
The conflict will only arise if you are loading bootstrap.js some other way besides attaching a library. If this is the case, then as @leymannx says above you need to find where the extra bootstrap is coming from.
If the Bootstrap CDN is loaded by a script tag in a Twig template, just remove that script tag and only load the CDN via the library, allowing Drupal to keep track of it.
Another approach:
If another_project is a theme or contrib module, then it has probably already defined the Bootstrap CDN as a library. If this is the case, you could just attach that library wherever you need it to prevent conflicts. Take a look at the another_project.libraries.yml file to see the name of the library, and then load that library wherever you need it in your custom theme or module. Again, as above, this will allow Drupal to manage the library so that it will only be loaded once, and only where it is needed.
Note, however, that by doing so you will create a dependency on another_project. If you do this in a custom theme or module, then you should make that dependency explicit by declaring the dependency in your info.yml. Otherwise, if another_project is not present for any reason, you won't be able to load the library.


D6 to D7: How can I get all the migrated content to have the "Text format" of "Full HTML" for the body I am migrating content using both the migrate, migrate_d2d and my own custom module which references the 2 migrate modules.
The below code successfully migrates content from Drupal 6 to Drupal 7 when registering and running the migration of "PressMigration" within the .module file but I always want the Drupal 7 migrated content body area to have the "Text format" of "Full HTML".
How can I get all the migrated content to have the "Text format" of "Full HTML" for the body.

Thanks,

John

class PressMigration extends DrupalNode6Migration {

  protected function query() {
    $query = parent::query();
    //Only include specific nodes in migrationj
    $query->addJoin('LEFT OUTER', 'term_node', 'tn', 'n.vid=tn.vid');
    $query->addField('tn', 'tid', 'tn.tid');
    $query->addField('tn', 'vid', 'tn.vid');
    $query->condition('tn.tid', '115', '=');
    return $query;
  }

  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->addFieldMapping('field_release_date', 'field_release_date');
    $this->addFieldMapping('field_contact', 'field_contact_information');

    $this->addFieldMapping('field_subtitle', 'field_sub_title');
    $this->addFieldMapping('field_teaser', 'field_media_excerpt');
    $this->addFieldMapping('field_custom_title', 'field_custom_title');

    $this->addFieldMapping('field_alt_lang', 'field_alternate_lang');
    $this->addFieldMapping('field_related_item', 'field_media_related');
    $this->addFieldMapping('field_archiving_date', 'field_archive_date');
  }

}

You should try to set the input format on the body field in this way:

$this->addFieldMapping('body', 'body')
 ->arguments(array('format' => 'full_html'));


populating a webform select list from a view? I have a webform in D7 where I want the user to select a value from a dropdown list. These values I want to be dynamically updated from a view. How can I do this?

I found the webform viewreference module, but it's D6. There is a d7 port that someone made using coder, but, like author notes, I get an error when I try to view the form with the view reference webform component.

Are there any solutions out there?

Take a look at the sandbox project Webform Views Select.

  This module will let you populate a webform select component with data from a view.


Features/Themes and Drush Make Files: How to manage updates? I am trying to automate my development by using Drush Make Files and Features.

I am using Drush Make.me to create the make file.

I have created a Features module on my local machine. What's the best way of telling DrushMake.me about this module.

I guess I could upload it to my webspace and then put the URL into Drush Make. However, I am not sure if this is the best way of doing it. For example, what happens if I update the feature in the future. How will existing website that contain the old feature know that it has been updated.

Also I have my own custom Theme which I want to include in the makefile. If I just Zip and upload it, I would have to do this everytime I update the theme which doesn't seem very efficient (plus how will existing sites know that the theme has been updated).

At this stage, I would like to keep my theme and features private as I want to work out all the kinks.

Any advice on how to managed everything would be most appreciated.

You should build an installation profile to go with your make file.  Then, you could store your theme inside the installation profile.  There's a Drush command to make an installation profile; see this issue on drupal.org.  If you use this technique, you can just run drush pm-update to update modules, and then re-build your makefile and installation profile using the Drush generate-profile command.

Another option would be to just store your custom theme in a git repository.  You can load a module or theme from a Git repository.  See this answer for details on how to do that.