How to extend a specific node type form? I am searching a way to overwrite the NodeForm to get a class per bundle.

Actually EntityForm manages the form for all entities.
NodeForm extends it and manages the forms for all nodes.

I wrote a CustomNodeForm replacing NodeForm behaviour for all nodes.

/**
 * Implements hook_entity_type_build().
 */
function ftvisi_main_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('default', CustomNodeForm::class);
}

Now I'd like to get a class per bundle extending that CustomNodeForm but I feel like I am not able to do it.

CustomNodeForm might instantiate a form for each bundle - but I don't like that approach and we still just have one constructor which can leads to problems such as:

"OK my first bundle form needs this service, and my second bundle form needs another one, should I inject the full container itself and then use services on the fly ?" => Pretty bad idea, I know.

Anyway, if CustomNodeForm instantiates other classes itself, it will be hard to mock and test. So I definitively don't like that approach.

I then thought about using the form modes, but same problem: a form mode can be used on any node type, so we still don't have a class per bundle and we still have only one constructor for all forms using that form mode.

Any idea to help?

AFAIK forms are tied to operations at entity-type level, so you don't have any hook to only alter the form for a particular bundle. Since what you want is to inject certain services for a given bundle what you can do is to implement a chain of responsability pattern through service collectors. This allows you to inject only the service collector to your form and delegate to the collection to evaluate which service should apply for your given bundle. And finally the resolved service is the one that would concentrate the responsability. I could provide you with a deep example but could take some time, let me know if a code sample still needed.

UPDATE

This will be the solution in a near future, since sub-classing is the feature you are referring.


Import XML with nested elements into field with settings "Number of values" = "Unlimited" Noob to Drupal here.  I'm looking to import 100 xml files into an empty D7 database.  Each xml file contains links to other xml and image files.  I have Feeds, Xpath Parser, and Tamper modules installed.

Drupal Content type = Article
Fields (machine name):

unique_xml_id (Text)
body (Long text and summary) -> settings "Number of values" =
"Unlimited"
field_images (Image) settings "Number of values" = "Unlimited"

Here's the xml. Every xml file has a unique id by combining pid and gid.

<testContent pid="5" gid="000007">
  <textContent title="Title 1" ordinal="0">His car</textContent>
  <textContent title="Title 2" ordinal="1">Our car</textContent>
  <textContent title="Title 3" ordinal="2">
    This is my <textLink linkType="int" pid="5" gid="000014">car</textLink> -> link to xml
  </textContent>
  <visualHeader title="Images">
    <visualContent mid="1057" alt="Radiator" type ="thumb"> -> image url, ex: img/1057.jpg
      <visualLink pid="6" gid="001057"</visualLink> -> link to other xml file with parent img
    </visualContent>
    <visualContent mid="1092" alt="Wipers" type="thumb"> -> image url, ex: img/1092.jpg
      <visualLink pid="6" gid="001092"</visualLink> -> link to other xml file with parent img
    </visualContent>
  </visualHeader>
</testContent>

OBJECTIVES:

Map the concatenation of the xml attributes "pid" and "gid" to field "uniquexmlid" and make this check for uniqueness
Map textContent elements to body field values (array?), example:
body[0] = "His car"
body[1] = "Our car"
body[2] = "This is my car" (car is link to other node that does not exist yet in database)
Map "car" link to url of other node (not yet created from xml file) with path alias inside body[2] field

How do I accomplish these?  I'm open to suggestions of other ways of setting up the fields in Drupal.

Also when you import from html pages you have to set to html xpath parser.


Label for Child in Hierarchical Select While using Simple Hierarchical Select Module, I have 2 levels of Hierarchy for my Phone.

However I want to add the label for Child list like:

Is this possible? then how?

I know I'm late, because this answer has been answered long time ago, but I don't think this is the right way to do it, especially with the java script interval function – it might work but in many cases may cause a problem.

For those who need the same result I suggest to use this java script code which is based on action when the ajaxStop event is triggered.

First you nedd to create a java script file in your module directory, for exapmle: YOUR_MODULE_NAME/js/custom_shs_behaviors.js with the following code:

/**
 * @file
 * Custom behaviors for Simple hierarchical select:
 *   Change the first option text from "- None -" to whatever you want (default: "- Any -").
 *   Create labels for each level.
 */
 (function($) {
  Drupal.behaviors.customShsBehaviors = {
    attach: function (context, settings) {

      // Helper function for an option text replacement.
      // use: optionObj.replaceOptionText(); for default replacement from '- None -' to '- Any -'.
      // or optionObj.replaceOptionText('Foo'); to replace the '- None -' with 'Foo'.
      $.fn.replaceOptionText = function(replacement) {
        var replacement = replacement ? replacement : '- Any -';
        if ($(this).text() == Drupal.t('- None -')) {
          $(this).text(Drupal.t(replacement));
        }
      };

      // Function that helps to get the select element width including its padding and margin.
      $.fn.getSelectWidth = function() {
        var width = Math.round($(this).wrap('').outerWidth(true));
        $(this).unwrap();
        return width;
      }

      // Define labels.
      var labels = ['Label-1', 'Label-2', 'Label-3'];

      // act when the ajaxStop event is triggered (there are no more Ajax requests being processed.)
      // see: @link http://api.jquery.com/Ajax_Events/ @endlink
      $('.shs-wrapper-processed').ajaxStop(function(event, xhr, settings) {

        $("select.shs-select").each(function(level) {

          // fix the SHS bug - new level that is being created has the same ID as the previous one.
          // make sure that each select has an ID and the class corresponding to the level.
          // YOU CAN USE THESE TWO LINES ONLY IF YOU ARE USING SHS WITH THE ABILITY TO ADD NEW LEVELS.
          $(this).attr('id', $(this).attr('id').replace(/(.*)select-(\d+)/, "$1select-" + (level+1)));
          $(this).attr('class', $(this).attr('class').replace(/(.*)level-(\d+)/, "$1level-" + (level+1)));

          // Replace the first option text using the helper function for an option text replacement.
          $("option", this).first().replaceOptionText();

          // Get label width.
          var labelWidth = $(this).getSelectWidth();

          // Create label.
          if ($("label[for='" + $(this).attr('id') + "']").length == 0) {
            $(this).parent().before(
              "" + labels[level] + ""
            );
          }

          // Remove the label if the select element has just been removed by clicking any option on lower level.
          // There might be several Ajax requests bound with this action,
          // so we have to make sure that our "removing process" will be executed at most once.
          // See: @link http://api.jquery.com/one/ @endlink
          $("option:not(:selected)", this).one("click", function() {
            $(".shs-wrapper-processed").parent().find("label").each(function() {
              if ($(this).attr('for').slice(-1) > level+1) {
                $(this).remove();
              }
            });
          });
        });
      });
    }
  };
})(jQuery);

And attach the java script file to your form. You can do it by using the hook_form_alter() in your theme or module file:

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

  switch($form['#id']) {
    case 'YOUR-FORM-ID' :
      $form['#attached']['js'][] = drupal_get_path('module', 'YOUR_MODULE_NAME') . '/js/custom_shs_behaviors.js';
    break;
  }
}

You're done! With this code you can set the label for each level of your shs and even change the default option text, for example: from - none -  to - any -.


Creating custom node aliases inside a simpletest I am attempting to write simpletests to replicate the steps to reproduce on this d.o issue.

I need to create a test node with a custom alias, as if I had unchecked the "Generate automatic URL alias" checkbox and supplied my own value.

Currently, attempting to insert it with

$edit = array(
  'title' => $this->randomName(),
  'path' => array(
    'source' => 'node/1',
    'alias' => 'qwerty',
  ),
);

fails, and generates errors, as does

 $edit = array(
    'title' => 'asdf',
    'path[alias]' => 'qwerty',
  );

So, I tried:

$path = array('source' => 'node/1', 'alias' => 'qwerty');
path_save($path);

The above successfully creates an alias, but when I inspect $node->path[
alias'] it shows me something other than qwerty.

drupal_lookup_path('alias', "node/".$node->nid) also returns only the Pathauto-generated alias, and not any alias that was created manually, even in the node edit form.

Additionally, if I create a new alias from the same source, my original alias is not replaced, as it would be if I had manually entered a new alias into the field on the node edit form.

As I am attempting to exactly duplicate the steps to reproduce in the linked d.o issue, it matters how the alias gets created. Is there any way to more exactly replicate the manual creation of an alias on the node edit form, inside a test?

It turns out that

$edit = array(
  'title' => 'asdf',
  'path[alias]' => 'qwerty',
);

was correct, but that I needed to add the permission 'create url aliases' to the drupalCreateUser array.


Custom form, webform, or entityform Would it be best to create my own form or use contrib. drupal7 modules to complete my following need. If i use contrib. modules, which ones should i use.

I want to make a form that has 3 fields. 2 autofill and 1 auto complete. One of the autofill fields would just autofill the current users 'first and last name.' The auto complete field will auto complete existing users in the site - so if you begin to type in a users name it will auto complete for you. The other autofill field will autofill the autocompleted user's supervisor.

Spent a bunch of time trying to configure webforms or entityforms, then kinda wondered if this should just be done with an in house custom form. Whats the best Drupal7 practice for this?

At the end it will email 3 people and then be put into some review process. The 3 people will be the autocompleted user, the autofilled supervisor and a static HR email address. I suppose i would bake that all in a submit handler, if i did my own custom form.

The best and quick way to go with is using EntityForm. The module provides advantage of using field using which you can have Entity/User Reference fields with auto-complete, without writing a single line of code. To notify 3 users on Email, you can use Rules Module. And the other advantage is, it is maintained by Community so all security issues are tracked and fixed before the site can get affected.

Webform module doesn't support auto-complete by default you'll need to use Webform Autocomplete module for that. I've not used this module, so not sure if this provides the option for referencing existing entity.

If you're building it custom, you'll need to build everything by your own using Form API and Mail System. Which will be time consuming as compared to using EntityForm.


How to unpublish nodes 50 days after they are created by using the Rules module? I've tried the method described at https://groups.drupal.org/node/240678#comment-782543 , but it is not exactly what I need. So i changed it a little bit :

Create a ruleset

Name it "Unpublish Content"

In the Settings/Variables:

Data type = "Node"
Label = "node"
Machine name = "node"
Save

... next screen...Add rule

Name = "Unpublish Content Rule"
Save
Conditions (1):

Content is published
Data selector = node
Save

Conditions (2):

Content is of type = node
Value = your-content type
Save

Actions:

Unpublish content
Data selector = node
Save

Create a rule

using /admin/config/workflow/rules
Name = "Unpublish Rule"
React on event = After saving new content
Save
Conditions:

Content is of type
Data selector = node
Value = your-content-type
Save

Actions:

Schedule component evaluation
Component Value = Unpublish Content
Data selector = site:current-date <-- "This is what I changed, I want the node to be unpublished 50 days after it's creation."
Identifier value = unpublish [node:nid] <-- removed this.
node Data selector = node
Save

But I don't have date field.

I have tried many methods but nothing seems to work, I don't want to use other modules like Auto Expire.

Any suggestions to get this to work?

Have you looked into Rules Scheduler? The process is similar in that you create your rule, create a component that unpublished content, then use Rules Scheduler in the original rule as the action to run the component 50 days after "date published". Here is a video of scheduling nodes to be published after X time that you can follow: http://www.youtube.com/watch?v=OgRKLXRbPX8 .


How to get all the content types that don't have nodes? In Drupal 7 if you want a list with the content types that don't have nodes  you can do it with the following query:

SELECT type, name, COUNT(nid) as total
              FROM node_type LEFT JOIN node USING(type)
              GROUP BY type
              HAVING total = 0
              ORDER BY name

But in Drupal 8 we don't have the {node_type} table and you can't have access to all the available content types unless you use the 'entity.manager' service or you go to look inside the {config} table that have a column named name, but in the name column you will find this:

node.type.CONTENT_TYPE_MACHINE_NAME1
node.type.CONTENT_TYPE_MACHINE_NAME2

There is not an easy way to get the information from this table.

I found an example in the Entity Query support for aggregated queries page:

  Let's assume you want the amount of nodes per node type.

$query = Drupal::entityQueryAggregate('node');

$result = $query
  ->groupBy('type')
  ->aggregate('nid', 'COUNT')
  ->execute();

But only works for content types with more than 1 node, why? Again there is not way to find content types in the database that don't have nodes.

I really don't know the reason for this missing important part (and I can't find it) but I think that this is very important because the only way now to obtain the content type label is through the 'entity.manager' service.

In short, how to get all the content types that don't have nodes?

I know that you can use the 'entity.manager' service to get all the available content types and then through a loop look for all the nodes for each content types. But this way is very long and involve many database queries.

This is the short way that I found to obtain this information:

// Getting the database connection.
$connection = \Drupal::service('database');
$query_content_types = "SELECT DISTINCT SUBSTR(name, 11) as type FROM config WHERE name LIKE 'node.type.%'";
// Creating a temporary table.
$content_types_temporary_table_name = $connection->queryTemporary($query_content_types);

$query = "SELECT node_type.type, COUNT(nid) AS total
          FROM $content_types_temporary_table_name node_type LEFT JOIN {node} USING(type)
          GROUP BY type
          HAVING COUNT(nid) = 0
          ORDER BY type ASC";

$result = $connection->query($query);
dpm($result->fetchCol('type'));


How to change the view for a "Views: Filter by an entity reference view"-mode entity reference field on the node/add or edit form? I have 2 content types: registration (R) and class (C). R has an entity reference field which is referencing to C using the "Views: Filter by an entity reference view" mode. The entity reference field must use the select list widget. User account also has an entity reference field field_default_class which is referencing to C. Because of business logic, the field_default_class's value never exists in the entity reference view's filtered result which is used in the R node.

Now if an authenticated user adds or edits a node of R, I need to check if current user's field_default_class is set or not. If set, I need to pragmatically set the R's entity reference nodes' select list to the user's field_default_class's value, then disable the select list for disallowing user to change the value.

I guess it's difficult to set a select list's option value which is not in the view's filtered results. Or maybe my codes as below have errors. But I don't know where is wrong :-(

/**
 * Implements hook_form_alter().
 */
function sisucustom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_node_form') {
    global $user;
    $account = user_load($user->uid);
    if (isset($account->field_default_class['und'][0]['target_id'])) {
      $entity_node = node_load($account->field_default_class['und'][0]['target_id']);
      $options = array($entity_node->nid => $entity_node->title);
      $form['field_register_for_class'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
      $form['field_register_for_class'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;
      $form['field_register_for_class']['LANGUAGE_NONE']['#attributes']['#disabled'] = TRUE;
    }
  }
}

Or, is it possible to change the associated view to the entity reference field in node R? Because I can create another entity reference view which filters out only the one C which equals the current user's field_default_class's value. If it is, how to do it (in which hook)?

PS: I heavily use conditional fields module in node R. So maybe there are some pits against my goal. How to avoid those?

My code is wrong, now it works as below:

/**
 * Implements hook_form_alter().
 */
function sisucustom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_node_form') {
    global $user;
    $account = user_load($user->uid);
    if (isset($account->field_default_class['und'][0]['target_id'])) {
      $entity_node = node_load($account->field_default_class['und'][0]['target_id']);
      $options = array($entity_node->nid => $entity_node->title);
      $form['field_register_for_class'] = array(
        '#type' => 'select',
        '#options' => $options,
      );
    }
  }
}

Finally I searched out a thread answering my question about modifying the widget info here.


Reference to an Image of a different content type here is my question:

I have two content types, Events and City.
The goal here is to "connect" content of type "Events" with a city, so that, when i publish content of type "City", to include the logo (image field) of the referenced city.
What i have done till now:
I have used the field reference module,
creating a "field_reference" field on Content Type "Events". At its configuration, i chose the desired "logo_field" from the "City" content Type, but only the name of the city logo appears, and not the logo itself (on node page).
The same appears when i want to use this field in a view.

Any ideas?

Have you tried to use Entity Reference?

With this module, you can first add a connection between to entities, and then you may be able to create a contextual view of selected field of the connected entity where needed.


Shipping county value showing as a number Using Drupal 7 with Drupal commerce.

During the checkout in the shipping section I can choose a county from a drop-down list (a string value).
However, on the review order phase it is represented as a number (please see attached image). Moreover, it is printed as a number on the order pdf.

Any ideas on why is it so?

The issue here is common to countries whose administrative areas don't render with abbreviations, which is the case in other countries like the U.S. and Canada where States and Provinces are abbreviated when printed (e.g. SC, NC, TN, etc.). Many of those countries use simple numeric codes or nonsensical alphanumeric codes as an administrative designation but should have the full names of the areas printed for display.

In the Address Field module, we introduced a configuration option for such countries' address formats called render_administrative_area_value that must be set to TRUE to do so. I've opened an issue for Estonia that will also ensure we've done this for the other countries we know about:

https://www.drupal.org/project/addressfield/issues/2983142

I'll have a patch up there shortly. : )


Views exposed filter are cached after performing a search using Views exposed filter,the filter is cached and even I change that I get the same as previously results.How can I solve that?
thanks

make sure these settings are set:

remember last selection & caching


How do I get Views content items in "my language" but fall back to "default" if the content isn't translated? This is probably very easy but endless searching has proved fruitless - there's lots of UI changes between the D7 and D8 versions of these modules it seems.

What I want to do is create a blog in two languages. The default language is English. Mostly, the author will be translating the articles to Italian. However, I would like to create the blog view such that:

only one translation shows in the list, per node
if viewing the site in italian but there is no translation of a specific list item to italian, the english version shows (fall back to default language)
if he's only written an italian version, show that anyway instead of the non-existent english one

The options in views are similar looking to everywhere else, but in those other places this isn't really an issue. In standard nodes, the fallback kicks in automatically. Any ideas of how to configure this?

I think your requirements can be restructured into the following:

Show all content once.
Show the content in the current language, fall back to the other.

Then it becomes pretty easy:

Add the "Default Translation" filter to a view. That basically ensures that all your nodes are shown once because each node can only have one default translation.
Select "Interface text language selected for page" for "Rendering" language. That will attempt to display the site in the current language and fall back if that's not available. (Interface text sounds a bit misleading, but unless you explicitly enabled separate content language negotiation, that's the same as the content language).


how to edit the link user/%/edit? i have a test user called "buyer".
he has a profil with the tabs: view - edit - orders - files
i set pathauto for user to: user/[user:name]
when i look at the tab links the as followed:

view: domain/user/buyer
edit: domain/user/82/edit

question: why is that?
if i call the link domain/user/buyer/edit by hand, i get
"You are not authorized to access this page."

any ideas?

It is because path aliases are for a single path, so the path alias user/[user:name] is only for user/82.
If you want path aliases for all those other pages, they have to be added separately.

And because they are not pages that are covered by the pathauto module, you cannot use it for those pages.

You can manually add aliases at admin/config/search/path/add but because you can't use tokens there you would have to add aliases manually for each user (which is ridiculous).

The only module I know that can help you out is http://drupal.org/project/subpathauto

The equivalent module for drupal 6 is http://drupal.org/project/subpath_alias

Those modules aim to allow you to do what you desire.

It seems there is currently a bug in the subpathauto module though that is breaking user aliases. See http://drupal.org/node/1851102

I just tested 7.x-1.2 and it is working correctly.

You can get 1.2 from here - http://drupal.org/node/1416736


Using views to display content based on taxonomy terms? I have created a faculty profile system on our university departments site. Every faculty member is tagged with terms regarding an area of expertise (either in teaching or in research).
What I need is to create a view that takes the areas of expertise from a specific faculty members page, and displays the other faculty members that also work within those areas. (but only those areas)

What I have done  so far is a view that wants to show ALL the terms on EVERY faculty content type, but I need to have the view filtered somehow based on the specific page that is being viewed. Here is what I have:

http://sustainable.unt.edu/irene-klaver

Here is an example of what I need: http://sustainability.asu.edu/people/persbio.php?pid=188

The faculty nodes are a custom content type (CCK). The view uses Imagecache/Imagefield to use the thumbnails. The terms have their own vocabulary in Taxonomy, specifically for this purpose. I am using Drupal 6.

I have been told by a few that this might not be able to happen with Drupal, and that I have to create some custom php code in my node-faculty.tpl.php file. Since the ASU site aboves developer doesn't use Drupal, they couldn't really help me out much. I find it hard to believe that someone hasn't needed a function that is similar to this before... If anyone can at least point me in the right direction, I would greatly appreciate it!

Thanks!

Drupal Views can easily do this :)

Create your view and call it "example", and for this example, put Node Title in the Fields.
Add in an argument.  Here select Taxonomy: Term ID.
In "Action to take if argument is not present:" select "Provide Default Argument"
There, select "Taxonomy Term ID from URL" and then click "Load default argument from node page, thats good for related taxonomy blocks" and if you want, you can also limit it to specific vocabulary(ies) by clicking "Limit terms by vocabulary" and clicking on the one(s) you want.
Create a "Block Display" and save everything.
Goto your Site Building/Block Admin Page and look for "Views: example" and put it in a region of your theme.

Now, if all is well in the world, that block will appear and will display the titles of all nodes that also have the same taxonomy term as the node it is displayed on.  Of course, you will probably want this block displayed only on certain pages, but you can do that in your block UI as well.  And of course you'll also probably want to be fancier than just the node title, etc, but there you would include the fields in the specific nodes, etc.

ADDITION:

This is what I see here for a taxonomy term id argument with D6 and Views3:

UGLY SOLUTION:

I was sure there would be a solution to this using just Views, but I can't figure it out for the life of me.  Grrrr, I hope someone out there says Duh, this is how you do it. But, if you have the PHP Input Filter enabled, you can create a block that will do this instead of creating a custom module.  The PHP Input Filter is UGLY.  It should be killed with that dull ax I often use, but here goes:

Add a new block via the blocks UI with this as the block body:

<?php

$node=menu_get_object();

if (isset($node->type) && $node->type=='Faculty') {

  $vid = db_result(db_query('SELECT vid FROM {vocabulary} WHERE name = "Expertise"'));

  if (!empty($node->taxonomy)) {
    foreach($node->taxonomy as $term) {
      if ($term->vid == $vid) {
         print '
' . $term->name . '
';
         print '
' . views_embed_view('faculty_expertise_test2', 'default', $term->tid) . '
';
      }
    }
  }

}

?>

Make sure you select PHP Code as the Input Filter.  Select a Block description and title and save the block.  Place it in whatever region you want.  Cross fingers and see what happens :) Basically all this does is loop through all taxonomy terms of your Expertise vocabulary in the node shown and then calls the view with that argument. I think I have everything capitalized correctly from your examples, but the key things to customize about are Faculty, Expertise and faculty_expertise_test2, which are your node type, vocabulary and view.  If all works, then it's up to you to CSS things to your liking.  Hope this helps!

PS
I just realized that the view will most probably return the faculty member her/himself but that can be dealt with another day :)


I would like to be able to use some tokens like %post[key]used in webform, in my custum module how to call these up in my custum module I am creating a custom module webform3rdparty integration to icontact .Using my module create an extra field in weform field to add icontact field(mapping purpose).I want to use token replacement patterns in my field.How to call these replacepatterns in my custom module.

I think you need these hooks:

hook_token_info() - this hook will allow you to define empty placeholders. Define a few placeholders which you want to make available to the webform.
hook_tokens() - corresponding to the plkaceholders you have defined, pass in appropriate stuff and define a replacement pattern for each placeholders you have defined in your earlier hook_implementation.
Finally, while rendering user submitted value, apply token_replace() function to replace the placeholders entered by user with appropriate values.

UPDATE:

Got you. Have a look at this function _webform_filter_values(). This funciton is responsible for replacement of webform tokens. you can use this funciton in your code, pass in the stuffs you want to replace and the node and submiccions object and have the value replaced.

It will be impossible for me to give you exact direction, as i am not familiar with what you are doing. But i can give you a general idea. Token replacement often happens at the output stage. So it is more concerned with output. So mostly, you need to apply this to your code which displays/prints/uses the webform submission result of your field.

Say you create a webform field. I as an end user, enter a string to it which contains this: %post[key]. Now your submit handler code will need to use the said function. When you pass the input i entered through that function, my %post[key] is replaced by appropriate value.


How to assign content to user for manage turns? I need to create a system to assign turns to a people register in the site, for this need contemplate:

The administer assign turn to user in specified place.ex(turn 1, place 1, user 1)
There are two turns, morning and afternoon in one day.(turn 1 and turn 2)
The administer cannot assign a turn to user that have turn 1 in place 1 and later turn 1 in place 2, need show only the users that no have turn 1.
The system need show the turn to user in calendar, only need show the turns in the week, ex (Monday: turn 1 place 1, Tuesday: turn 2 place2, Wednesday: turn 3 place 3, etc).

I think make

content type of turns that have

- field date, end and start for statistics support and classify the week.
- turn select: turn 1 or turn 2.
- zones select: place 1, place 2, place3 etc.
- user to assign: user reference field that have all user that i can assign turns.

I want use drupal fields and contrib modules (if exist) to make this, or how to make better with drupal, any suggestions?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Webform component permission I have webform in my site, so I need to do that there are 2 user approval field components in my webform so they both should be unique value, in my case its working like if my name is joy then I submit that form then it will display joy on both field's value.

I want to just display only one field joy and another field value get from another user. please let me know if anyone has solution for this.

You can do by using Field Permission module.

Or first you have to create a user role. And apply condition to fields as per role.

Or you can use User Role Field module.


Unable to set a default value for a CCK field I am trying to set a default value for a CCK Multi Select field tried with PHP code

return array(
  0 => array('value' => "ONE"),
  1 => array('value' => "TWO"),
);

and without PHP Code by just selecting the values (after adding to Allowed Values) with required ON & OFF but still nothing gets selected in select drop down.

Simply try by creating a new (text)field & choosing widget as select list.
then put in allowed values
0|a
1|b
2|c
(putting 0|a in one line,1|b in other so on..)
& number of values to unlimited & save
by editing, select default values from drop down & save.
hope it helps..


Captcha on the user_login_form and user_pass form? just checked on my site and it seems that certain login forms do not have captcha. specifically the form named:

user-login-form
user-pass

I put in user_login_form in the captcha page to make it show up, but it doesnt seem like that is working. am i grabbing the correct form id from the NAME attribute in the form tag?

You should add captcha to
1. user_login
and
2. user_login_block(instead of user_login_form)

as shown below:


Adding markup inside first list item of main-menu I need to add some custom markup inside the first list-item of the main-menu as you can see here:

Item 1

                        …
                        …

Item 2

Item 2

With the following code, I can insert the markup:

function mytheme_preprocess_menu_link(&$variables) {
  $variables['element']['#below']['#markup'] = '
...
';
}

But this code adds the markup to every list-item, not just the first one. Do I use the appropriate function and how can I add the markup only at the first item of main menu?

I managed to apply the code only to the item in the main-menu by introducing a condition of menu-name and #href:

function mymodule_preprocess_menu_link(&$vars) {
  $element = &$vars['element'];
  $my_view = views_embed_view('view_name', 'display_id');
  if(strpos($element['#href'], 'home') !== false && $element['#original_link']['menu_name'] == 'main-menu')
  {
    $element['#below']['#markup'] = $my_view;
  }
}


How to update old CAPTCHA to use reCAPTCHA V2 I am very new to drupal I am trying to update a drupal site to reCAPTCHA V2 but I can't figure out how to. I know I need a new site key and secret key which I have gotten; but how do I actually make the CAPTCHA module update so I can put in my new keys. And so I can get the new reCAPTCHA check boxes instead of the images. I am using Drupal 7. Thank you for any help.

Just update module via update modules page:
Your_site/admin/reports/updates/update

Follow steps and update DB.

Go to modules page and check configuration for recaptcha, there you'll put your new keys (got from https://www.google.com/recaptcha)

Note: If you update module files using FTP, remember to run update.php script.


Get the custom fields created for User entity in Drupal8 I was trying to get the custom fields created for User entity in Drupal8:

Drupal::service('entity_field.manager')->getFieldStorageDefinitions('user') is returning all the fields

Drupal::service('entity_field.manager')->getFieldDefinitions('user', '') is returning only the default fields

Was doing a diff of the 2 arrays, but I was wondering if there is a proper way to achieve this?

You can filter the fields by checking which interface the field implements:

$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

The second parameter of getFieldDefinitions() is the bundle. The user entity doesn't have bundles, but you can configure bundle fields. In this case the bundle name defaults to the entity id.


Custom module menu path renaming/redirection Is it possible to create path like subdomain for custom module menu?

For example create url like xyz.example.com if path is example.com/xyz where xyz is custom module menu.

I've already tried to use .htaccess file

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

It correctly changing url from example.com/xyz to xyz.example.com but xyz.example.com redirected me to HOME page of the site.

I just want to change the url from example.com/xyz to xyz.example.com where module result will be displayed.

Thanks.

EDIT : My requirement is similar to this

You could modify $_GET['q'] during hook_boot(), something like the following.

function mymodule_boot() {
  $_GET['q'] = implode('.', array_slice(explode('.',$_SERVER['HTTP_HOST']), 0, -2));
}

There is probably a regex that could do the same as that explode/implode mess, but that does the trick to start with.


Additional field data stored outside of the field storage (in a separate table) doesn't load with the rest of the field I've implemented a custom field that needs to store data outside of the Field Storage mechanism and in a custom DB table. (The field structure is enough to require a second table, but not enough to justify creating a new entity type. It's an image field with tooltips that will be later styled with JS.) I've hooked the necessary functions and I can see that the data is getting saved to the table, but the load hook doesn't get called when the edit screen form is built, nor does it's additional content show up in the passed-in $items array.

Since hook_field_widget_form doesn't get the $entity being edited, I can't manually query the auxiliary table for the data. How do I get the data into $items and onto the form so the user can edit again?

(It also doesn't appear to be calling hook_field_load on the node load either, but I haven't started working on the field formatter yet.)

hook_field_load is being called, but only once after a cache clear. Either the loaded field or the whole node is cached somewhere. Remember to clear your caches!

I missed the initial load because I had yet to instrument the function with the typical bevy of dpm() and ddebug_backtrace() calls. Also the function itself isn't loading the data back properly, but that's outside the scope of the original question.


Can you resume sending mails to a list of which only part of the addresses are having had a newsletter? I set cron throttle to 500 and then cron to run every hour. Using a shared server on hostgator, apparently this appears to be too much. So what ended up happening is only 1000ish of my 2500 mail address were being sent a simplenews newsletter.

So is there any way of picking up where I left off so these 1000 people will not receive the same mail again (and unsubscribe).  And if not, would there be any way to export the simplenews log in a way where you can easily edit the adresses that were begint a newsletter and make a temporary list?

Update; my question comes down to whether a log of the actual successful (or failed) email adressess is accessible. I've looked into the watchdog table and queried SELECT messages FROM watchdog. This gave me a list where the column that's supposed to contain the 'To:' addresses, actually contains a wildcard. So instead of the value being an actual email adres, the value is %To.

Yet, on the site, I could go to admin/reports/dblog and would be able to filter simplenews. This way I can consult emailadresses that have been sent, but I would have to click each rown over 1.000 times and then copy/paste the email adres in excel or plain text to create a new list for the remaining addresses? I hope there is a way that I can link these wildcards with their actual address and then be able to export it into something that I can use to bulk operate?

To avoid automated spam testing, most hosting companies avoid reporting back on failed sending. If you somehow know who got and email and who didn't, you could suspend or remove subscription for those who did, send email again and after that re-enable users. That's pretty universal method, works for any mass sending mechanism.

If you don't know who got your email and who didn't, only raw number, you have a problem that's unsolvable.

For the future, Drupal integrates pretty well with some paid mail sending services. That's a solution for sending large amount of mail and keeping page on shared hosting. If you want to avoid mail sending services, virtual private server shouldn't have a limit on sent mail count. Sending mails is pretty expensive in terms of cpu and memory, and it's an outdated technology, so it's only to be expected shared hostings will limit and discourage it, except for small quantities like registration confirmation etc.


3-column fixed width Zen-based layout + SASS; giving exact width to columns I'm using Zen theme with SASS (+Compass), and I have a site with fixed width layout. This means I include fixed-width.scss in my custom Zen subtheme's .info file.

I would like 3 columns - 2 for the sidebars, 1 for the main content. By default, I got these (I don't know why, because $zen-column-count is set to 5...).

OK, the problem is that when generating the CSS-files, the width of the columns get automatically calculated based on different SASS mixins. I don't want to mess up the automatic calculation of margins etc., I just want to set the exact parameters.

The main outer grid width should be 920px wide ($zen-grid-width: 920px;).

Now I have these automatically calculated parameters:

sidebars: 184px, 184px
main content: 552px

BUT I want it like this:

sidebars: 220px, 220px
main content: 480px

Here is my fixed-width.scss: http://vpaste.net/n4ve0

How should the exact parameters be set for the sidebar columns when using SASS in Zen?

This is really more a math question than anything, but here goes.  Given that you're using a fixed width column layout, we have to start and find how many columns we need to achieve the proportions you posted. The least number of columns possible to achieve 220px | 480px | 220px is 46 with each column equating to 20px (920px / 46 = 20px). With 46 columns, the sidebars are 11 columns each and the main content is 24 columns.

The rest is just plugging in the numbers into the zen grids functions.  See http://vpaste.net/VDwL1 for my example.

After defining the number of columns with $zen-column-count, you need to plug in the numbers so that each sidebar spans the correct number of columns while starting at the correct column with zen-grid-item($column-span, $column-position). The Zen starter sub-theme comes with three layouts to account for 1 (left) sidebar + main content, main content + 1 (right) sidebar, and 2 sidebars + main content. Here is how it looks with our new, 46 column system:

/**
 * The layout when there is only one sidebar, the left one.
 */
.sidebar-first {
  /* Span 35 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(35, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }
}

/**
 * The layout when there is only one sidebar, the right one.
 */
.sidebar-second {
  /* Span 35 columns, starting in 1st column from left. */
  #content {
    @include zen-grid-item(35, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}

/**
 * The layout when there are two sidebars.
 */
.two-sidebars {
  /* Span 24 columns, starting in 12th column from left. */
  #content {
    @include zen-grid-item(24, 12);
  }

  /* Span 11 columns, starting in 1st column from left. */
  .region-sidebar-first {
    @include zen-grid-item(11, 1);
  }

  /* Span 11 columns, starting in 36th column from left. */
  .region-sidebar-second {
    @include zen-grid-item(11, 36);
  }
}


"skip_process_on_empty" plugin does not exist I'm trying to migrate entities from a D7 to a D8 site using this tut: http://www.metaltoad.com/blog/migrating-taxonomy-drupal-7-to-drupal-8

When I execute the migration I get the error:

  The "skip_process_on_empty" plugin does not exist.

And then it just hangs.

I have this in my migrate yml file:

parent:
    -
      plugin: skip_process_on_empty
      source: parent
    -
      plugin: migration
      migration: custom_taxonomy_term

I tried changing it to skip_row_on_empty but get the same error regarding "skip_process_on_empty".

Here's the contents of [mymodule]/config/install/migrate.migration.custom_taxonomy_term.yml

id: custom_taxonomy_term
label: Drupal 7 taxonomy terms
dependencies:
  enforced:
    module:
      - monster_migrate_7
migration_groups:
  - Drupal 7
source:
  plugin: custom_taxonomy_term
process:
  tid: tid
  vid:
    plugin: migration
    migration: custom_taxonomy_vocabulary
    source: vid
  name: name
  description: description
  weight: weight
  parent:
    -
      plugin: skip_on_empty  <--changed this per suggestion
      method: process
      source: parent
    -
      plugin: migration
      migration: custom_taxonomy_term
  changed: timestamp
destination:
  plugin: entity:taxonomy_term
migration_dependencies:
  required:
    - custom_taxonomy_vocabulary

And here's what I get when I try to execute it:

> drush migrate-manifest sites/all/modules/monster_migrate_7/manifest.yml --legacy-db-url=mysql://[user]:[pass]@localhost/monster
Running custom_taxonomy_vocabulary                                                                                [ok]
Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'custom_taxonomy_vocabulary'                                                                                [status]
Running custom_taxonomy_term                                                                                [ok]
The "skip_process_on_empty" plugin does not exist.                                                                                [error]
>

skip_process_on_empty and skip_row_on_empty were combined into a single plugin. Try this:

plugin: skip_on_empty
method: process

To skip a row:

plugin: skip_on_empty
method: row

Hope this helps!


Optional extra products on add to cart form We're trying to have it so that on a product display there are optional extras which can be added all at the same time as the main product by selecting checkboxes. These products are optional extras which are product specific.

We have tried the Commerce Product Add On module but it breaks with an ajax error when there is more than one main product variation and another option is selected on the product display front end.

We are trying to debug the error but we are also wondering if this can be created using something which already exists such as views bulk operations and rules. Any help would be much appreciated!

There is for example Commerce add to cart extras:

  This module provides alternative ways of adding products to cart.

  The initial version provides a views field handler ("Commerce Product:
  Quantity input field") that relies on the Views Form API (a part of
  Views 3 since RC1) to output a quantity textfield that turns the view
  into an add to cart form. The default quantity can be configured, and
  only products with a quantity larger than 0 are added to the cart.

Also, you can find 2 approaches (VBO + Rules, and custom VBO action) at Add multiple products to cart with VBO.


Textfields and values with a value of 0 get blanked out if stepped forward/backwards I have a multipage form programmed with the drupal FAPI having in total 3 pages of fields consisting of textfields, textareas and radios, the form can be stepped forwards and backwards.

On page 2 of the form i have a few textfields where the user needs to enter numeric values. If these fields are not applicable, the user is asked to enter a 0.

The problem I have now if the user fills out that page No. 2, fills in a few 0 in these textfields and steps forwards/backwards, and afterwards steps back to that very page, the fields formerly filled with 0 are blank.

I really have no clue how to solve that as I need to use numeric values.

I now could set the default value to 0 instead of an empty value, but that would force the initial form to have already a 0 set. I do not want to solve it like this.

I have the feeling that the 0 is probably treated as a NULL (but actually in PHP 0 and NULL are different), but I am not sure. Dumping out the form array shows that indeed that 0 values are blank.

A textfield looks like this:

$form['t_2_1_2'] = array(
    '#type' => 'textfield',
    '#title' => t('... label text ...'),
    '#description' => ' ... desc. text ...',
    '#required' => TRUE,
    '#default_value' => !empty($form_state['values']['t_2_1_2']) ?
        $form_state['values']['t_2_1_2'] : '',
);

The structure of the entire form handling is very much based on the drupal multipage form example in the drupal form examples package!

Is there any way how I can solve that issue, that a value of 0 persists in the form, even stepping forward/backward?

I already tried to investigate similar problems, and found one where where the suggestion was to prepend a space to the 0 value, but that is a hack and I do not / can not use that as such!

Any hints are greatly appreciated, as I am sitting on this problem too long now and my time is running out to solve that issue. Thanks in advance for your hints!

Update: As nobody could help me here and my time is running, I solved the problem by using an 'x' instead of the '0' value, changed the validation to check for either a numeric value or an 'x'. Now the values all persist in the form fields, when I jump backwards/forwards in that multipage form. If the user used 'x', the value will be converted into an '0' value in the submit handler because the data is stored into mysql, and these fields are of type integer. At least a way I can live with.

You could also simply allow users leave the field empty and convert any empty “numeric” fields to a '0' in your submit handler. That might be a better user experience since it would save users the trouble of having to enter any values in those fields.


How to hide webform block after submission for anonymous users? I can not hide webform block by Per user submission limit.

I choose Per user submission limit = 1- > ever, but block is shown.

How can I hide the block, if it was submitted?

When a visitor submit a form, cookie with a name "webform-123" (123 - webform ID) save in his browser. In the block visibility settings use the cookie existence check with PHP:

<?php
$match = FALSE;
if(!isset($_COOKIE['webform-123'])) {
$match = TRUE;
}
return $match;
?>

If the cookie does not exist, the condition will return the TRUE and the block will be displayed.


Looping Rules without Lists I have an online store using commerce and rules, with products that can be bought in different quantities.  Commerce stores the line-items in an order as a list, but it stores the quantity-per-line-item as a flat number.

I have a rule that needs to fire once for each tangible product- ie. number of line-items x quantity.

Rules can loop over lists, but I don't have a way of representing the quantity as a list.  Is there a way to loop using just a number?  Is there a way to turn a raw number into a list Rules can loop over?

I ended up doing this with the 'execute custom PHP code' action.  I created a 'Do Foo Once' component with the UI, and then added this to 'Do Foo N Times':

for ($i = $quantity; $i > 0; $i--) {
  rules_invoke_component('rules_do_foo_once', $i, $bar);
}


Installed Module crash my site. How do I bring my site back up by uninstalling a module I installed a module but it crashed my site and I can't get to the administrator backend anymore.  How do I disable this module to bring the site back up?

In Drupal 8, try to removing the module from your module folder and run http://YOURSITENAME/update.php

or

Removing module via Database - In Drupal 8 it is a bit hard to remove a module.

I think the best way is to use Drush.

drush pm-uninstall module-name (machine-name)


Drupal Feed importers: Update Node values without needing to include all values in Feed Currently when I try to import data through a feed, importer, if any field from the mappings is missing then the data for that field gets overwritten. This is despite of selecting

  Update existing nodes

or

  Replace existing nodes

Thus how can I ensure the data does not get overwritten with blank even though those mappings are provided but the column is not included in the csv.

Thanks.

You want to stick with the Update existing nodes to retain your existing content fields here.

The simplest way to prevent overwriting is to remove whatever mappings that aren't available in your CSV. If you have different CSVs with different available columns, cloning your current CSV feed importer and remove the columns from the new importer should accommodate different data update sources.


How to prevent all UPPERCASE body text? Some users enter body copy and comments with the caps lock on. All uppercase is considered shouting and I would like to convert it to lowercase or "natural" with uppercase characters at the beginning of a sentence.

Any easy solutions?

Converting the post to all lower case would be pretty simple; you can implement your own filter like so:

function MYMODULE_filter_info() {
  $filter['allcaps_filter'] = array(
    'title' => t('Disallow ALL CAPS posts'),
    'description' => t('Rudimentary filter which converts all text to lowercase'),
    'process callback' => 'MYMODULE_allcaps_filter_process'
  );

  return $filter;
}

function MYMODULE_allcaps_filter_process($text) {
  // Attempt to make the first letter of the first word uppercase. This is very
  // likely to fail as the inputted string will probably be HTML.
  return ucfirst(strtolower($text));
}

Once you clear the caches you'll be able to add that filter to any text format you want.

It's worth noting that the description rudimentary in the comments is very, very apt...for example this will also convert any HTML attributes/tags to lowercase which might break embedded image paths etc. It might provide a good place to start though.

Constructing more naturally cased alternatives is going to be very tricky, mainly because you haven't just got text in there...you've got HTML as well. I can't think of a decent way to do this at the moment to be honest, short of importing the string into a DOMDocument and looping through every element, converting the text in chunks as you go.

I'd provide an example for that but I think you've got one ;)


Show 4 input file fields on my node add image page I have a content type with an image field; the user can insert a maximum of 4 images. I need both the node add and edit form to show 4 input file elements, not only 1.

When you add a field there is an option to set number of items. You can set the number to 4 and you would have 4 input elements on the page.


How can I have the JS/CSS cache refresh on every page load? How to clear cache on every page load?

I am doing CSS & JS theming and currently having to manually clear cache (using devel module) every time and then reload the page again to see my changes?

How do I do it so that in every page load cache is cleared?

As long as you don't have JS or CSS aggregation turned on, you shouldn't have to clear cache to see your changes to existing files. You can see this settings by going to;

Admin->Config->Development->Performance(admin/config/development/performance).

If you are adding new CSS or JS files, you'll probably have to clear cache to register them with the theme system.

If you really want to clear cache on every page load, you should create a custom module that implements hook_init() and runs drupal_clear_css_cache() and drupal_clear_js_cache() (or any other cache clearing functions you may want), but this should be unnecessary.


Enabling view programmatically I want to know how to enable view programmatically in drupal 7? I need it to be exportable with features. I need a snippet code for that. Thanks!

Based on your question I honestly think you are doing something wrong, but if you really do have a legit use case I think you can just do this:

$view = views_get_view('machine-name-of-view');
views_export_status($view, TRUE);
views_save_view($view);


Location migration not working I'm trying to convert a d6 location field into a a d8 geolocation field, but when I run it the field does not get updated, and I don't get any messages either.

All of the other node data has been imported already so I am running the migration with the command: drush migrate-import ttf_location_migration --update

I am including title because without it I get an mySQL error message.

Here's my migration YML file:

id: ttf_location_migration

label: Migrate old location data to geolocation field

source:
  plugin: ttf_location
  key: ttf_migrate

process:
  nid: nid
  title: title
  type: type
  'field_location/bundle': type
  'field_location/deleted':
    plugin: default_value
    default_value: 0
  'field_location/entity_id': nid
  'field_location/revision_id': nid
  'field_location/langcode':
    plugin: default_value
    default_value: 'en'
  'field_location/delta':
    plugin: default_value
    default_value: 0
  'field_location/field_location_lat': latitude
  'field_location/field_location_lng': longitude

destination:
  plugin: entity:node
  overwrite_properties:
    - 'field_location/bundle'
    - 'field_location/deleted'
    - 'field_location/entity_id'
    - 'field_location/revision_id'
    - 'field_location/langcode'
    - 'field_location/delta'
    - 'field_location/field_location_lat'
    - 'field_location/field_location_lng'

migration_dependencies: {}

dependencies:
  enforced:
    module:
      - ttf_migrate

and my source plugin:

<?php

namespace Drupal\ttf_migrate\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Source plugin for location.
 *
 * @MigrateSource(
 *   id = "ttf_location"
 * )
 */
class TtfLocation extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {

    $query = $this->select('location', 'l')
      ->fields('l', ['lid', 'latitude', 'longitude']);
    $query->join('location_instance','li','l.lid = li.lid');
    $query->fields('li', ['nid']);
    $query->join('node', 'n', 'li.nid = n.nid');
    $query->fields('n', ['type', 'title']);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'lid' => $this->t('Location ID'),
      'latitude' => $this->t('Latitude'),
      'longitude' => $this->t('longitude'),
      'nid' => $this->t('Content ID'),
      'type' => $this->t('Type'),
      'title'=>$this->t('Title')
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'nid' => [
        'type' => 'integer',
        'alias' => 'nid',
      ],
    ];
  }

}

Any help much appreciated

Thank you

Do not repeat the field name for sub columns: Instead of e.g. field_location/field_location_lat use only field_location/lat, in the process:  section.

There also is no need to manually set interal keys like entity_id or revision_id: Only set the destination plugin and the field values, and Migrate module will fill all other internal columns for you.

destination:
  plugin: entity:node

process:
  title: title
  type:
    plugin: default_value
    value: NODE_BUNDLE_NAME
  langcode:
    plugin: default_value
    value: 'en'
  field_location/lat: latitude
  field_location/lng: longitude


Is there a way to run a shell script on a custom cron? I'm new to all this so maybe this isn't the best solution, but I've created a shell script cache warmer.

wget --quiet http://www.example.com/custom-sitemap.xml --output-document - |
egrep -o "http://www.example.com/[^<]+" | wget --delete-after -i -

I can also do this with drush commands too using the cache warmer module.

I need to figure out how to run these commands every couple of hours.

My understanding was that I could create a custom cron job with Elysia cron that ran the script on my server, but now I am confused if this is possible / how to implement.

When I go to the script section and write the following:

*/15 * * * * custom_cron

I am told it it is an invalid line.

Can you make custom timed cron jobs then use the elysia cron API to make a module call my shell script?

Thanks!

I believe you can edit the crontab or by talking to hosting provider you will be able to edit the crontab file.

In case, if you have to do it in custom module using Elysia Cron API, I assume you can do it following way :

function example_cronapi($op, $job = NULL) {
  $items['example_shell_cron'] = array(
    'description' => 'Send mail with news',
    'rule' => '0 */4 * * *', // Every 4 hours
  );
  return $items;
}

function example_shell_cron() {
  shell_exec ('wget --quiet http://www.example.com/custom-sitemap.xml --output-document - |
egrep -o "http://www.example.com/[^<]+" | wget --delete-after -i -');
}


How can I make it so that users can add content to my site? I have created a custom content type for my site that takes three fields. I then created a view that displays only that content type in a grid form. I need to know how to allow users to add content based in the form of my custom content type so that they can add things that will directly be added to the custom view I made. (Essentially the view makes a grid that displays rows of 3 images in each row. The images when clicked on will then take the user to a page that gives a description of what the image is along with a few other things.) Does anyone know what I can do with this, or if there is a much easier way to do this that I am totally missing?

Thanks for the help!

You only have to provide access to anonymous user to add content for the content type that you have created. For that go to permission page of Drupal:

admin/people/permissions

Check the following check boxes for anonymous user.

Basic (your content type) page: Create new content
Basic(your content type) page: Edit own content


How to create a block to show a digital clock? I need to create a block to show a LIVE digital clock?

I tried to use the http://drupal.org/project/clock and the http://drupal.org/project/jstimer  modules but it doesn't use javascript to refresh the time, it shows the time when the page is load, to refresh the time I need to reload the page.

How can I do this?

Something like this http://drupal.org/project/timeblock but for D7

100% agree with Jimajamma above on extracting the stuff you need from the timeblock module, all it is really doing is just adding two javascript blocks with a minimal amount of formatting. For example, to replicate the 24-hour clock, all you have to do is create a new block with an 'unformatted' input format and add this code (extracted from the time block module):

Quick fix to replace the body unload with a jquery $(document).ready() call, though probably not necessary inside a block.


Rate module and rule integration I don't fully understand how the rate module integrates with rules.

Here's my situation:

1) I created a widget of the type: Number up / down widget which allow users to vote in nodes of the Answer content type.

2) I created a rule which is fired in the event: User votes on a Node with the condition "Check the value of the vote" is "1"

3) A user "vote up" an Answer and the rule is fired.

So far so good...

The problem:

4) The same user "vote up" the same Answer and the vote is not added because the user only can give just one "vote up" per node, this is how the rate module works and it is all right. The problem is that the rule is fired even when the vote is not added, this is wrong, the rule should be fired only if the node get the vote.

Is this a bug? Do I have to add other condition to the rule?

It is not a bug. User voted up. His vote wasn't counted, but he voted all right. It might be used to update "last voted date" for example, or to give "forgetful" badge to an user who tries to vote many times on the same node. You either need to:

Look for an event that fires when vote is actually saved
Look for a condition that will let you filter out only new votes
Add if in the code that actually gets fired
If first two are not possible and third is to difficult, fill a feature request to add 1. or 2.

I'm deliberately not going to test these and find which one works, in hope future readers can benefit from algorithm for similar problems.


Adding ThirdPartySetting to webform entity results in wrong module dependency I added my ThirdPartySetting to webform element like this:
Added my config schema to file config/schema/mymodule.schema.yml like this:
webform.settings.third_party.mymodule:
  type: mapping
  label: 'Webform mymodule configuration'
  mapping:
    settings:
      type: mapping
      label: 'mymodule settings'
      mapping:
        email_element:
          type: string
          label: 'E-mail element'

and then in mymodule.module I've altered webform settings form like this:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'webform_settings_form') {
    $entity = $form_state->getFormObject()->getEntity();
    $elements = $entity->getElementsInitializedAndFlattened();
    $options = [];
    foreach ($elements as $element_name => $element) {
      $options[$element_name] = $element['#title'];
    }
    $form['third_party_settings']['email_element'] = [
      '#type' => 'details',
      '#title' => t('E-mail element'),
      '#open' => TRUE,
    ];
    $form['third_party_settings']['email_element']['email_element'] = [
      '#type' => 'select',
      '#options' => $options,
      '#title' => t('E-mail element'),
      '#default_value' => $entity->getThirdPartySetting('mymodule', 'email_element'),
    ];
    $form['actions']['submit']['#submit'][] = '_mymodule_form_submit';
  }
}

function _mymodule_form_submit(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\webform\WebformInterface $entity */
  if ($entity = $form_state->getFormObject()->getEntity()) {
    $entity->setThirdPartySetting('mymodule', 'email_element', $form_state->getValue(['third_party_settings','email_element','email_element']));
    $entity->save();
  }
}

This works fine, but when I export my configuration, I see that dummy module has been added to my module dependencies.
 dependencies:
   module:
+    - mymodule
+    - email_element

This also reflects in third_party_settings
+third_party_settings:
+  email_element:
+    email_element: e_mail
+  mymodule:
+    email_element: e_mail

What am I doing wrong?

Please use hook_webform_third_party_settings_form_alter() in mymodule.module and discard the submit handler which should solve that:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_webform_third_party_settings_form_alter().
 */
function mymodule_webform_third_party_settings_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\webform\WebformInterface $webform */
  $webform = $form_state->getFormObject()->getEntity();

  // Do stuff.

  $form['third_party_settings']['email_element'] = [
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('E-mail element'),
    '#default_value' => $webform->getThirdPartySetting('mymodule', 'email_element'),
  ];

  // Do not add submit handler.
}

Webform's WebformThirdPartySettingsManagerInterface wraps Core's ThirdPartySettingsInterface which is why I think you're seeing that behaviour.


Filling compound field programatically fails with EntityMetadataWrapperException I followed the instruction in the post from here to create a compound field and it work like a charm. Now I am trying to fill each of the 3 "columns" that make the compound field programmatically and I can figure it out how.

I am using the entity API to create the node see the code below:

$node = entity_create('node', array('type' => 'MY-CONTENT-TYPE'));
$entity = entity_metadata_wrapper('node',  $node);

$data = array('column_1'=>'value 1', 'column_2'=>'value 2', 'column_3'=>'value 3');

$entity->field_custom_compound_field = $data;

$entity->save();

But it does not work. What am I missing?

Note: I keep getting the error:

  EntityMetadataWrapperException: Unknown data property field_custom_compound_field.

I am posting this here in case someone is having the same issue:

I use the tutorial located here to create my compound custom field with multiple columns what I didn't noticed was in the hook_fields_field_info() implementation I should define the type of data the entity will take. To make things worse in the tutorial the author use the example where all the fields he created are text fields, but in my case I have date, decimal and text fields so I had to define each type. I found the solution in this post.

In a nutshell in my hook_fields_field_info() implementation I have to declare the entity property type, but since I am using multiple columns on the field I have to implement a call back function that will allow me to define the property type for each of my columns.

/**
* Implements hook_field_info().
*
* Provides the description of the field.
*/
function field_example_field_info() {
  return array(
  // We name our field as the associative name of the array.
    'field_example_rgb' => array(
      'label' => t('Example Color RGB'),
      'description' => t('Demonstrates a field composed of an RGB color.'),
      'default_widget' => 'field_example_3text',
      'default_formatter' => 'field_example_simple_text',
      'property_type' => 'field_example_rgb', // we add the propert type here
      'property_callbacks' => array('field_example_rgb_property_info_callback'), // we add the callback
    ),
  );
}

Call back function to define each columns type:

function field_example_rgb_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  unset($property['query callback']);

  $property['property info']['rgb'] = array(
    'type' => 'text',
    'label' => t('RGB'),
    'setter callback' => 'entity_property_verbatim_set',
  );
  $property['property info']['someothervalue'] = array(
    'type' => 'text',
    'label' => t('Some other value'),
    'setter callback' => 'entity_property_verbatim_set',
  );
}

After doing that the following code:

$node = entity_create('node', array('type' => 'MY-CONTENT-TYPE'));
$entity = entity_metadata_wrapper('node',  $node);

$data = array('column_1'=>'value 1', 'column_2'=>'value 2', 'column_3'=>'value 3');

$entity->field_custom_compound_field = $data;

$entity->save();

Worked like a charm.


How to change the Drupal Commerce Stock formatter? Drupal Commerce Stock displays the correct number of stock. For example:

Product Name, Price: $ 1.00, Stock: 20.

I would like to change the stock levels to 1, 2, 3, 4 and 4+. So if the stock level is 5 or more, the displayed stock will be 4+. What's the best way to do this?

If you want to display the stock of a product with 4+ when it's >5, assuming that you've got stock a field attached to the product and exposed to the node display (default behavior) you can use hook_entity_view_alter or hook_node_view_alter to alter the #markup of $build['product:field_stock']


Showing title keyword in autocomplete I have just installed search auto complete module,its working fine,but the problem is its showing title before every result like:

title: Drupal 7.9 Release

tile:Understanding Drupal

Here Drupal 7.9 release and Understanding Drupal are my article title may be due to that its showing,but anyhow i want to remove this.

Thanks

In search_autocomplete.view_autocomplete.inc file, line number 209 just replace it with the following line:

$object->label .= ' ';

that will remove the label (title) in search result.


How do I get clean output (without menus, header, footer, etc.) in Drupal? I need only processed content of particular theme file (mytheme.tpl.php) using the theme() function.
How do I get rid off header, footer and other stuff on the page?
And it will be good not to touch main theme page.tpl.php or anything else except module internals.

Probably there is something like:

return DRUPAL_CLEAN_OUTPUT(theme('my_theme',array('html' => $html))); ?

Just print it from your page callback rather than return it. Drupal will only invoke the theme wrappers for the html/page when you return something from your callback.

function MYMODULE_some_page_callback() {
  print theme('my_theme', array('html' => $html);
}

The other method is to set an explicit delivery callback for your menu item, to be used in place of the standard drupal_deliver_html_page() method. See the hook_menu() docs for more details.


User one time login and password reset I want to implement a functionality such that:
 The user registers on site and is sent an email (validation). Then he is taken to a page where hes is able to click on login form.

This was done using drupal's basic functionality. I had to change the message that was coming upon clicking onetime login page.(/user/reset/#hash)

I did it using hook_form_alter.

But it seems, that the text has been changed for the forgot my password link also.

Is there some way? May be I might have to create a separate page for the forgot password?

Thanks in advance

Try to do the form_alter, only if url has a #hash

if (preg_match('#^user/reset/(.+)#', $_GET['q'], $matches)) {
  //here for new user
}


Additional classes for price based on price components Is it possible somehow to add classes related to price components to the price container div? So you would be able for example to style a price based on how it is changed by its components. I thought it would be very nice.

Yes, you could theme the price components to add your own classes via a theme override.

The base implementation is in commerce_price.module

Here's a tweak that includes the price component $name in the class:

e.g, in template.php

/**
 * Themes a price components table.
 *
 * @param $variables
 *   Includes the 'components' array and original 'price' array.
 */
function MYTHEME_commerce_price_formatted_components($variables) {
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');

  // Build table rows out of the components.
  $rows = array();

  foreach ($variables['components'] as $name => $component) {
    $rows[] = array(
      'data' => array(
        array(
          'data' => $component['title'],
          'class' => array('component-title', $name),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total', $name),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}


How to override Drupal behaviors? I want to override the drupal core behavior Drupal.behaviors.filePreviewLinks which is located at core\modules\file\file.js from my custom module

I tried placing the following code in js file of my custom module

Drupal.behaviors.filePreviewLinks = {
    attach: function (context, settings) {
        console.log($(context).find('div.js-form-managed-file .file a'));
        //some custom code
    },
    detach: function (context, settings){
       //some custom code
    }
};

But it is not working. What I need to do? How to override Drupal core behavior in custom module?

EDIT

Let me explain my actual question. I am loading a form in page that is created using ECK entity type module. One of a field in form has 'file' as field type. So once I upload a file, it is showing filename with link in a table(I hope it is default drupal feature). I want to remove the file link and show only file name.

Use libraries-override in your theme's info.yml file

Step 1: Find the library name in core that the JS or CSS file to override belongs to.

For example, it is clear that core\modules\file\file.js  belongs to the file module. Review at core/modules/file/file.libraries.yml to find the library name .  In the yaml file, the library name is the top-level item in the yaml structure where file.js is defined.  In this case drupal.file.

#core/modules/file/file.libraries.yml
drupal.file:
  version: VERSION
  js:
    file.js: {}  #### Drupal 8+ defines the js/css to override in libraries.yml
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Step 2: Find the fully-qualified library name.

The fully-qualified library name is generally prefixed by the module name, in the format <modulename>/<libraryname>. However, some core system libraries don't follow this format, so if unsure of the fully qualified library name, search for instances of the <libraryname> in the core codebase, which may turn up a string with the fully-qualified library name like drupal/<libraryname>.

In this case the fully qualified name is file/drupal.file.

Step 3: Override the file in your theme

In your custom theme's info.yml file add the following lines:

libraries-override:
  file/drupal.file:
    js:
      file.js: js/file.js

If you want to override a core or contrib CSS file, the syntax is similar:

libraries-override:
  filter/caption:
    css:
      theme: # <-- this line must match the definition in libraries.yml
        css/filter.caption.css: css/components/captions.css
#        ^                       ^
#        |                       |
#      File path as defined     File path relative to your
#      in *.libraries.yml       theme's folder.

Step 4: Copy the file into your theme, and modify it to your needs

For the 2 examples given above, you'd place the files.js inside a folder js in your theme, and you'd rename filter.caption.css to captions.css and place it inside the css/components folder of your theme.

Step 5: Clear caches and reload the page.

Use your Web browser's resource inspector to verify the path to the overridden file is coming from your theme folder.


Views Load More for products listing page in ajax For my ecommerce website i am using View Infinite Scroll module which is for Products listing page lazy loading,

Lazy loading works fine for my products listing view, but my requirement is when i click View More button then only it gets to load more products.

Is there options to call View More button or anyother modules supports for my requirement, please tell me if anyone have any idea means.

You can use views load more module. It provides a button. Clicking that button lists more contents only. The pager should be defined in your views settings.


Seeking a Better way to Create a Collapsible Fieldset I'm creating a collapsible fieldset on my home page and have put the following code in a block (structure > blocks):

<form>

    <fieldset class="collapsible form-wrapper">
      <legend>
        Legend
      </legend>

Content

    </fieldset>

</form>

It actually works what I did using the 'Full HTML' text format. I did it this way though only because I don't know the preferred way.

I imagine this would normally be done (for security reasons or something...) by creating a module or via a preprocess function.

Am I wrong to second guess myself here? Maybe it's standard practice to do what I've done above.

Any guidance is appreciated. Thanks.

Form submit would not work unless you have an action for it.

You should rather do it in Drupal way, you will need following.

Create Custom Module in drupal.
Block API to create your custom block
Forms API. to create a custom form and call it in your custom block.

Here goes a demo module which will help you understanding the API
https://github.com/arpitr/demo_block_form

Installing the module will give you a block which will look like as


How to override a block generated by a module? The PCP module has a pcp-block.tpl.php file in it's module directory that generates a block output.
To change that output I read that I could just copy this file into the "templates" folder of my current theme and it would take precedence over the one in the module directory. But it's not working. I did clear the theme registry cache.
How do I get it to work?

Have you copied block.tpl.php to your template directory as well? In Drupal 6 you need to have the base form before a more specific template will be used. For example before region-sidebar.tpl.php takes, you need region.tpl.php; before node-story.tpl.php, you need node.tpl.php. In D6 the block.tpl.php is in modules/system/.

I don't use D7, and it could've changed as David G. says.


How can I implement 3-way relationship (reference) between entities? I have 3 entities: A,B — node types, C — user.
Node A has 2 reference fields, one to B and one to C.
What I need is to show in a view all B nodes for a certain C, which has a relation A-B=A-C

The Relation module should be ideal for that. It allows you to create a single relation entity that links 3 (or more) entities together. It's in beta and you may have to do some work to get the user interface you need (I say that based on the Relation session at DrupalCon London), but it's flexibility is superior to any other relation/reference module out there.


Set label of $entity programmatically in a custom form I need to change the label of a custom content type programmatically. I've looked around but I couldn't find a solution. This is my custom form:

class GroupContentForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

    $entity->set('label', 'kkkkk');
    $status = parent::save($form, $form_state);

    $form_state->setRedirect('entity.group_content.canonical', ['group_content' => $entity->id()]);
  }

}

What do I need to do to change the label? $entity->set('label', 'kkkkk'); causes an error as the field label doesn't exists, the same happens with title and _title

It's not clear what entity type you have. In the question you ask for the label of a content type, which would be the entity node, then the label field is title. In the question title it is a more general question about the label of an entity and in the code you redirect to a group_content entity route, which would suggest this is another entity type.

In this case, if you don't know the entity type, you could use this generic code to get the label field name and set the label with it:

$label_field = $entity->getEntityType()->getKey('label');
$entity->set($label_field, 'New label');


Is there advanced configuration for CKEditor in Drupal 8? In Drupal 7 I was able to add config rules to CKEditor in the admin (like config.allowedContent = true; for example). I can't find this option in Drupal 8. Is it possible to do something similar?

In regards to "allowedContent", this is set to true if you don't check "Limit allowed HTML tags and correct faulty HTML"( or another filter of type of FilterInterface::TYPE_HTML_RESTRICTOR) on your text format, otherwise it outputs the tags you have added there.

For more info on this, you can view:

ckeditor/src/Plugin/CKEditorPlugin/Internal:getConfig()

and

ckeditor/src/Plugin/CKEditorPlugin/Internal:generateACFSettings()

If wanted to override the Internal:getConfig method, you could create a new class that extends it and then replace the class using hook_ckeditor_plugin_info_alter().

function mymodule_ckeditor_plugin_info_alter(array &$plugins) {
  $plugins['internal']['class'] = 'Drupal\mymodule\Plugins\CKEditorPlugin\CustomInternal';
}

And then your custom override class:

<?php

namespace Drupal\mymodule\Plugins\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Allow custom config settings.
 *
 * @CKEditorPlugin(
 *   id = "custom_internal",
 *   label = @Translation("Custom CKEditor core")
 * )
 */
class CustomInternal extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {

    $config = parent::getConfig($editor);

    // Put your custom configs here.
    $config['allowedContent'] = TRUE;

    return $config;
  }

}


How do I migrate my site without doing a direct DB export and site upload? I'm in an odd situation. When I try moving my site from my dev server to my production server the whole thing blows up. I think it is something in my database, it even happens if I export the DB with all but the core modules turned off.

So what then is the best way to export my site (nodes, users, views, panels, contexts et al) to the production server then?

What you should have done is remove sites/all/default/settings.php;
Now copy and rename the: sites/all/default/default.settings.php => sites/all/default/settings.php

Phase 2
Migrate the database to the production server
Phase 3
Copy the drupal directory from your dev to production server
Phase 4
On the production server hit the following Your_Domain_Name.com/install.php
follow the install instructions and set the database settings and you will be redirected to your site with config.
Phase 5
run cron to make sure eveything is running ok and update if necessary


Does the $form['element']['#disabled'] = TRUE guarantee that the user cannot edit the field or is it just a UI setting I have a form element like this:

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => $node->title,
  '#size' => 60,
  '#maxlength' => 128,
  '#disabled' => TRUE,

);

Does this make the field 100% non-editable by the user or is it still possible to set a value for this field using manual form submission using jQuery / Postman to the action URL?

If you disable field in backend, the field value won't be actually changed even if you change it in HTML or by JS.
You can test it:
 - disable element in form alter
 - open element in Chrome inspector (or other) and remove disabled attribute
 - change value in field and save the form
 - changed value will not be saved


It's possible to create constants or similar and use them inside a node description or title in Drupal 7 Let's say we have a download page in a multilingual Drupal site, and we want to define the download version, for example '1.1.0' and a download URL 'http://myweb.com/setup_1_1_0.exe', to use it on the distinct languages nodes for the download page, inserting them as a tag or similar on the tittle and body of the node.

How could it be done in Drupal 7?

I'm not sure I fully understand your need. But I would try to set a token called current_software_version as 1.1.0. Node titles and descriptions support the use of Tokens.

Tokens may also be supported within links, when using contributed modules or the redirect module I think.

You typically make custom tokens within a custom module you create. If you want an easier way to make the token value and name, I would look at the Variable module to build a UI and Admin Edit page for your current_software_version value. The Variable module will provide a token of the value for use throughout the site for you.


Users are logged out when viewing nodes I'm having a really strange problem with my test website. When users (both admin and non-admin) visit node pages, they are logged out and are being logged in again as the user who commented last on the node.

I've no idea what causes this behaviour, as I've never experienced this before. I don't have any caching modules and clearing caches multiple times brings no solution. What can cause this problem?

I finally found the reason for this weird problem: my comments' template contained a misplaced global $user;. I don't know why this causes trouble, but at least it's fixed now. Hopefully, this can get people with a similar problem on the right track to find a solution.


limitation on "add more" button: Drupal 7 I am using add more for a field which provide only maximum limit But I want to add by default two fields with "add more" button up to a maximum number of 10 fields.

How can I achieve this ?

Sounds like you're after the Multivalue Settings module.

  So you can create fields where, for instance, users have to input at
  least 5 values but can input up to 10 values. Or you can create fields
  that allow 100 values, but only display 20 fields to start with.

HOWEVER (and this is a big however - if I could change the font size I would)

This module should probably only be used as a starting point, and should not be used in production. I'm sure you can get the code you need from it.

  Warning: this module is still very buggy. Actually, it only works in
  very few use cases. I suggest to only attempt using it with core
  fields (not fields from contrib modules). Even this may not work. I'm
  working on fixing things, but don't have much time. Help is welcome.


How to create a view that filters profiles based on current user's 'interested in' field value? I am working on a small matrimonial application. I've installed the Profile 2 module and added a few fields like 'interested_in', 'gender', 'partner preference', etc to the users of my site.

I need to create a view that will list all profiles with same gender as logged in user's 'interested in' field.

How can this be achieved?

Solution that worked for me:

I used MyModule_views_query_alter hook and added a join to the field table and the condition that matches the choice of logged in user and gender of users in db.

if ($view->name == 'profile_list') {
        $logged_in = $GLOBALS['user']->uid;
        $pr = profile2_load_by_user($logged_in,'main');

        $join = new views_join();
        $join->table = 'field_data_field_gender';
        $join->field = 'entity_id';
        $join->left_table = 'profile';
        $join->left_field = 'pid';
        $join->type = 'inner';

        $query->add_relationship('field_data_field_gender', $join, 'profile');

        $view->query->add_where(0, db_and()->condition('field_data_field_gender.field_gender_value', $pr->field_looking_for['und']['0']['value'], '='));
    }


Problem with submenus I am new at Drupal , and I am using version 7.43. I have already installed Bootstrap, and now I am defining the menus. But to realize Multilevel submenus I need the folder of bootstrap_subtheme

I searched but I couldn't find that folder, I found just the Bootstrap folder.

Any hints?

Create such sub-theme folder manually. The folder name you'd use for it will be the machine name of your subtheme.

For more details, refer to:

"Creating a sub-theme" (= Community documentation that applies to any sub-theme).
"Sub-theming" (= documentation about sub-theming specific to Drupal's Bootstrap theme).

If you prefer to look at a great (I think) example of a (contributed) Bootstrap sub-theme, then have a look at the Bootstrap Business theme.


Editing Drupal Search SQL I'm using the basic Drupal Search module (search.module) and I want to customize the SQL of the search. I don't know how to go about doing this.

There are two things I want to edit in the SQL:

1) Have the search return ONLY nodes with start dates (event_start_date) AFTER now.

And

2) Return results in ascending order.

Pretty basic stuff.

Perhaps I need to use another search module entirely. I don't know.

Any thoughts or suggestions?

The Views module provides a Search view out-of-the-box (it's disabled). I would:

Turn off the default Search module.
Install Views.
Clone the default Search view in the Views administration page and call it My SITENAME Custom Search.
Add whatever filters you want to this View like the date criteria you list and adjust the deafult sorting if needed.

tip: you can easily search all the text in say the title and body field(s) of your Nodes with 1 text search box by adding a Filter of type Global: Combine Filter which uses the title and body fields in your Views: Fields section.

note for really really really massive sites you'll want to actually use a robust search engine. But as a proof of concept or small site (less than says tens of thousands of nodes) this should work Ok.

EDIT

To use the existing site search mechanism you would use hook_query_alter to change the query array to add SQL conditions to the Where clause of the query statement with whatever conditions you want. Note, that perhaps you may not have the sql fields needed for the query logic (you might thought). And if thats the case you would then need to use sql Joins to be able to reference the fields in SQL you want to do business logic on. Then add/modify a sort by sql clause, the same caveats about fields applies here again.

My Views solution above is 5 minutes worth of simple configuration and then adjusting some CSS. This solution could be 5 minutes if all the fields are in the SQL query already -- or much longer to figure out the necessary joins and syntax. The Devel module can help you inspect the raw search query. Good luck.


Add event listener to modal close In Drupal we can open a modal is two ways, either with HTML:
Open Modal

Or with JS:
let ajaxSettings = {
  url: 'node/1',
  dialogType: 'modal',
  dialog: { width: 800 },
};
let ajaxObject = Drupal.ajax(ajaxSettings);
ajaxObject.execute();

Once the modal is open I would like to attach an event to the close button so I can drop a cookie on the close event to show the visitor has seen the modal and not show it to them again.
The close button has the class ui-dialog-titlebar-close but this is added after the initial page load so to attach an event we would need a dynamic click handler such as:
$('body').on('click', '.ui-dialog-titlebar-close', function() {
    alert('close button was clicked 2');
});

However this event never fires. This ctools issue mentions the same thing and has a solution involving binding to the CToolsCloseModalBehaviors event, however that was 6 years ago and I'm using D9 with no ctools so need to find a new solution.
When I inspect the attached events on the close button I can see jquery.ui/ui/widget-min.js r() and an anonymous function in jquery.min.js. Using non minified vs would help but not sure how to do that?

The clue was seeing the Drupal's modal just uses jquery widgets. So a simple Google for "jquery widget close event" lead me to this SO answer.
So the solution is:
$('#drupal-modal').on('dialogclose', function(event) {
    alert('closed');
});


How to change permission for dynamic routes? I am able to change permission callback perfectly for static urls: eg:
Works fine:

if ($route = $collection->get('entity.taxonomy_vocabulary.collection')) {
  foreach ($vocabularies as $vocabulary) {
    $perms['administer ' . $vocabulary->id() . ' vocabulary terms'] = array(
      'title' => t('Administer %name vocabulary terms', array('%name' => $vocabulary->label())),
    );
    $route->setRequirement('_permission', 'administer ' . $vocabulary->id() . ' vocabulary terms');
  }
}

But same logic does not work for dynamic routes i.e route having a variable say taxonomy machine name.

Does not work:

if ($route = $collection->get('entity.taxonomy_term.add_form')) {
        foreach ($vocabularies as $vocabulary) {
            if($taxonomy_vocabulary == $vocabulary->id) {
                $route->setRequirement('_permission', 'administer ' . $vocabulary->id() . ' vocabulary terms');
            }
        }
      }

Please suggest how to alter/change permission callback for taxonomy add/view etc routes.

The _permission route setting isn't a callback function like the access callback in Drupal 7; it defines one or more permissions that are checked before granting access to the route. There's nothing dynamic about the setting. Adding one (or more) 'administer taxonomy_id vocabulary terms' permissions will restrict access if the user doesn't have those one or more permissions.

If you need to define a dynamic access check, you'll need to utilize _custom_access and define your own callback function that takes into account a specific permission check based on the context (see Structure of routes for more information).


Append filter info to URL when using AJAX in 'View' module I am using the Views module and have created a view for a content type. I have added an exposed filter so that the user can filter the list of content based on a custom taxonomy.

I want to use AJAX for filtering the content.  Before I select 'yes' under 'use AJAX' in the 'advanced' tab, the filter appends the filter selection to the URL such as /content-type-view?category='selected-category'.  But once I select AJAX, I lose the update to the URL.

I want to combine the two, use AJAX but also have unique URL's so that I can direct users to pre-filtered instances of the view.

What am I doing wrong?

What you want to do is manipulate the browser's URL even though there are no page reloads, only AJAX requests taking place.

You are actually in need of the HTML5 History API.

And luckily there seems to be a module available, specific to your case:

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

Give this a try and good luck!