Is it possible to get user uid in login form submit in DrupalGap?

Try using this hook in your app: http://api.drupalgap.org/7/global.html#hook_services_postprocess

/**
 * Implements hook_services_postprocess().
 */
function my_module_services_postprocess(options, result) {
  if (options.service == 'user' && options.resource == 'login') {
    drupalgap_goto('user-dashboard/'+ Drupal.user.uid);
  }
}

You may also need to set the action on the form object to null so that DrupalGap core doesn't try to redirect the page to the path indicated by the form's action variable:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(form, form_state, form_id) {
  if (form_id == 'user_login_form') {
    form.action = null;
  }
}


Define node array id as parameter in routing

A custom parameter converter would probably be the best solution.

It's quite easy to implement; + symbols tend to be quirky in URLs so this example uses commas instead:

MODULE/src/ParamConverter/NodesConverter.php

namespace Drupal\MODULE\ParamConverter;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\Routing\Route;
use Drupal\Core\ParamConverter\ParamConverterInterface;

class NodesConverter implements ParamConverterInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public function convert($value, $definition, $name, array $defaults) {
    // Add whatever extra validation you feel is necessary here
    $nids = explode(',', $value);

    if (!empty($nids)) {
      return $this->entityTypeManager->getStorage('node')
        ->loadMultiple($nids);
    }
  }

  public function applies($definition, $name, Route $route) {
    return !empty($definition['type']) && $definition['type'] == 'nodes';
  }

}

MODULE/MODULE.services.yml:

services:
  module_nodes:
    class: Drupal\MODULE\ParamConverter\NodesConverter
    arguments: ['@entity_type.manager']
    tags:
      - { name: paramconverter }

MODULE/MODULE.routing.yml:

custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: '[\d\,]+'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      nodes:
        type: 'nodes'

The regex for the route could probably be improved, the param could be made optional, etc; other than that it should work. The controller for the route at /custom/1,2,3 will receive an array of loaded nodes for the same IDs in the $nodes argument (or an empty/smaller array if none/only some were found).


Rules Scheduler Component parameter is empty

Some tips to help you find out what's happening / going wrong (based on revision 2 of your question):

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).
It could be a permission issue, i.e. think about which "user" (authority) the scheduled component executes with.

Some more tips to help you find out what's happening / going wrong (based on revision 3 of your question), and your extra comment which includes "... shows this error: "Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2227 of database.inc)." The log has a "page not found" warning from /admin/config/workflow/rules/components/manage/autocomplete/node_to_archive/form-xxx.../ ...":

Try to temporary remove that very last rules action (to execute that PHP code), and see what happens.
If the error still doesn't go away, it seems the time is right to start Rules debugging, as explained in my answer to "Where is the Rules Evaluation Log?".

Last but not least ...

About this part of your question:

  The problem is that the scheduled component gets an empty parameter and so can execute the actions. Drupal log shows an "The variable or parameter node is empty." warning.

Please have a look at what's described in my answer to "Why can my view not access the data of a new node when using Rules event After saving new content?". It explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...). I wouldn't be surprised that this is also what explains your problem. Here is why I think so:

Your (main) rule uses the event "after saving something".
Assume that the rules action (to schedule your component) actually happens (also) "before saving something"; In that scenario the part of your message that says "The variable or parameter node is empty." makes sense ... (get it?).

So it would be interesting to see what would happen if (even only to test), you'd replace the (single) Rules Action (to schedule your Rules Component) by the execution of an additional Rules Component (let's call it "Test_tip_from_Pierre") which is scheduled to execute after X secs or mins, and with a single Rules Action (equal to your Rules Action you now have in your main rule). Using that approach, for sure the node will have been saved before you actually schedule your original Rules Component. And that is what might resolve (eliminate / prevent) your warning like "The variable or parameter node is empty."


Image field - 'Number of values' is not showing up in admin form

Answering my own question:
I tracked down the bug by disabling module by module and finally found out that disabling the Gigya - Social Infrastructure module was bringing back the form fields.

Fortunately the issue was already listed and solved five days ago!


Set the path to:

cars/%taxonomy_term/%taxonomy_term

Then add two relations in the advanced section:

Taxonomy term referenced from field_brand
Taxonomy term referenced from field_color

Then add two times the following context filter:

Name (Taxonomy Term)

Select in the first context filter the relationship field_brand and in the second context filter the field_color:

now it should work as expected.


How to find the entity specific named id?

This should do it (definitely works for all core entities, I don't have any custom entities to play with on my sandbox site I'm afraid):

$type = 'taxonomy_term';

// Get the entity type info
$info = entity_get_info($type);

// Grab the id key
$key = $info['entity keys']['id'];

// $key contains 'tid'

I'm pretty positive this will work across any entity type though, according to hook_entity_info() the id property of entity keys is required:

  Every entity object passed to the Field API must have this property and its value must be numeric.


Views : how to combine fields in exposed filter using is between operator

This is a "smoke and mirrors" situation, in which you want the end user to experience one thing when the code is doing something completely different.

I would do a little bit of jQuery trickery.  First, I would expose all 4 fields (the high and low for each of the 2 fields) as text boxes.  Then, I would use the jQuery UI slider (which ships with Drupal Core) to update the high and low values as the user changes them.  Of course, the jQuery should hide the actual text boxes as well.  This will give you the effect that you are looking for.

Finally, if you wanted this to be ultra simple in the event that Javascript fails, you can use a form alter to hide one of the pairs of text boxes and then, when the form is submitted or the view loaded, populate the values for the other filter programmatically.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE-FORM-YOU-WANT-TO-TARGET') {
    // you'll have to look through the $form array for the field you want
    // I suggest installing Devel and running dsm($form);

    $form['YOUR-FORM-ELEMENT']['#default_value'] = isset($_SESSION['max']) ? $_SESSION['max'] : 1000;
    // Do this for all the applicable form elements...

    // Finally, tell Drupal that you want to see the form when it is submitted.
    array_unshift($form['#submit'], 'MYMODULE_filter_submit');
  }
}

function MYMODULE_filter_submit($form, &$form_state) {
  $_SESSION['max'] = $form_state['values']['YOUR-FORM-ELEMENT'];
}

You'll have to double-check to see what the variables actually look like.  I suggest installing the Devel module and putting dsm($form); and dsm($form_state); at the beginning of the functions.

Lastly, any time that you add a hook, don't forget to clear your cache or Drupal won't find it.


How to use a contextual filter value in a menu displayed on the same page

Something about the answer by @No Sssweat got me thinking, so I searched differently and discovered that arguments.field_topic_target_id contains the value from the contextual filter. So, the answer is to my question is to use:

/books-by-popularity/{{ arguments.field_topic_target_id }}

as the Popularity link in the menu. Credit to @No Sssweat for providing the spark!


Date module has the ability to add time field with the same field , I think you need to enable that in the field settings. see screenshot:


Get Node ID in hook_field_formatter_view()

As the Field Collection docs says:

  A field collection is internally represented as an entity, which is embedded in the host entity

So what you need to do in your field, is:

Test if it's container is a node. This case works already.
Test if it's a Field Collection entity.
Fallback to situation when you can't obtain parent container or it's an unexpected entity.

Now we'll take care about 2. point. If you can safely assume your field is always in a node, you can use code from answer by Chris Muench:

$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;

Note that you are writing formatter, and it means you have no guarantee that host entity will always be a node. If it's not, go to point 3 on my list.


In order to allow non-admin users to search for other users on your site, you'll need to give the appropriate user role (typically "authenticated users") permissions to "view user profiles" and "use advanced search". To access User search, you can utilize the "Advanced search" link in the Search block, or use the URL /search/user

Note, these permissions will also allow users to see other users' profile pages, so make sure this is acceptable for your use case.

If you need to search both nodes and users from the same text box, you'll need more than Drupal's Core search functionality to do so. See How to search both Users and Nodes simultaneously in drupal 7 for some suggestions.


Modify Override the Views Filter Criteria Programaticly

You can use hook_form_views_exposed_form_alter() :

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'flag_lists_user_lists_public') {
    $form['usershare']['#value'] = 'admin';
  }
}


Page redirect in rule after VBO new custom operation is is not redirecting

There could be a possibility that some other redirect rule is overriding you page redirect to cart Rule. So please check if in case any other rule is getting triggered or not. If yes, then set priority of page redirect to cart rule's high.

For checking if any other rule is overriding the "Page redirect to Cart"  rule we can actually use
watchdog('Backtrack message','<pre>'.print_r(debug_backtrack(),true).'</pre>');
It will give show everything what all code running at the time the rule triggers.
You are absolutely correct sir, just need to set the weight of Page Redirect to Cart rule lower than other rule. It will set the priority higher.


Block with entities referenced in a field from current node (of different type)

You need to add relationship Entity Reference: Referenced Entity for field which is referencing to Place content type and you will see the Place field in fields.

Hope this will help.


Documentation can be done in many different ways using different modules. If you decided to go with Books, then it is really up to you to create new books or taxonomies for new releases. Look at how Drupal's documentations is organized on https://www.drupal.org/documentation.


field_get_items() is the one you're looking for.

$items = field_get_items('node', $node, 'field_FIELD_NAME');
$first_value = $items[0]['value'];

It also takes care of language selection for you, so no need to worry about that one any more.


Change text in Commerce Kickstart "order total" dynamically

You can use the hook_commerce_price_formatted_components_alter()
The following example checks if VAT has been applied to the order total and changes the string accordingly:

/**
 * Implements hook_commerce_price_formatted_components_alter().
 *
 * Alters somes text at the checkout form
 *
 * @param $components
 * @param $price
 * @param $entity
 */
function mymodule_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  $pieces = explode('/',current_path());
  if(!isset($components['tax|ch_vat']) && $pieces[0] == 'checkout'){
    $components['commerce_price_formatted_amount']['title'] = t('Order total (excluding VAT)');
  }
}


prepare() function doesn't work well in migrate module

Unfortunately you can't set the value directly like that, you need to reference the language and delta in the classic, hated method:

public function prepare($entity, stdClass $row) {
  $row->title = "This is title 1";
  $row->field_CT_body[LANGUAGE_NONE][0]['value'] = t("This is body");
}

Note: This function takes 2 params, the entity object being built and the source row. So, since we're altering the entity object, we gotta manipulate it as such.  (I'm not sure, but you might be able to wrap that object in a metadata wrapper in order to use the cleaner API)

Also, please note that the "value" key will depend on the field type in use.

Note: untested code but it should be fine! :)


My Drupal was hacked: Remote Code Execution – base64_decode() with ‘PCT4BA6ODSE_’

Your site has indeed been hacked.  Many possibilities of a backdoor exist now.
You can start by upgrading to 7.32 or better and downloading the Hacked! module and scanning your system files for changes.
You can also use one of the following commands to find the exploited files.

grep -Rl PCT4BA6ODSE . | xargs sed -i 's/<[?]php.*PCT4BA6ODSE_.*[?]>/<\?php \/\/ RECOVERED FILE - more info at AllAboutTodd.com \?>/g'
find . -type f -newermt 2014-10-01 ! -newermt 2014-10-31 -name "*.php"

The latter command will find all files that end in .php which were last modified in October. To search instead the files for which the permissions were changed in October, replace -newermt with -newerct.


Drupal 8 Menu Tree issue in my contrib theme possibly because of "Convert menu tree building to a service."

Does https://drupal.org/node/2226481 help you?

This should be something like

\Drupal::service('menu_link.tree')->renderMenu($main_link_source);


You can use template suggestion to override page.tpl.php for specific taxonomy term page. For this to work template suggestion file should be named page--taxonomy--term--[ID].tpl.php., where [ID] - ID number of taxonomy term for which you want to edit the page.

More on template suggestions: http://drupal.org/node/1089656


Filtering date fields in Views - How can I test for NULL

For User "Last access" or "Last login" dates the "Is empty (NULL)" option is not available.

For those particular dates, an alternative is to test for "Greater than 1970-01-02".


How do I get the number of rows affected from an update query?

$update_query->execute()->rowCount() would cause a Call to a member function rowCount() on a non-object (or Call to a member function rowCount() on int, on PHP 7.4) since $update_query->execute() returns the number of rows  matched by the update query, including the ones that actually didn't have to be updated.
rowCount() can be called only when execute() returns an object implementing StatementInterface, which is the case for Select::execute(), Truncate::execute(), Upsert::execute(), and Query::execute().
Unfortunately, the only way to get the number of rows changed from an update query is to fetch the rows matching the update condition (in your case, the rows for which uid is equal to $uid), and count which rows have, for the desired fields (in your case, name_of_user, url, website, industry, company_size, company_type, headquarters, founded, page_picture, tagline, and updated_at), a value different from the value set by the update query.


Boost crawler - maximum time to use for crawling on every cron run?


How to combine two node/add/* forms into one form but create two different types of content in drupal 7 on submitting it?

My initial thought on a solution was also entity reference and entity inline form but a few caveats regarding the latter. The enitity inline form adds a submit for the additional content type, this seems against your proposed UX so you will need a hook_form_alter to change this behaviour (and indeed the label)  have a look at http://drupal.org/node/1880850 for a solution I worked on that will give you a lead in (but not a solution to) this.

The other issue is that I got a lot of annoying but non-fatal and non-damaging errors when I loaded entity inline form so stability may not be 100% there. This could be an issue.


How to set the first option as the selected in the SELECT form via hook_form_alter

You need to add the following code to your implementation of hook_form_alter():

if (empty($form_state['input']['title_1'])) {
  // set the first element as default value
  $form_state['input']['title_1'] = reset($options);
}


How to override Bootstrap theme files in sub-theme

You should put those files in yourtheme/templates/ (no sub-folder) and a quick cache clear after that.

See bootstrap_subtheme/templates/README.txt:

  This folder is where you should place all your overriding template files. By
  default, the Bootstrap base theme provides all the necessary template files in
  various folders inside of sites//themes/bootstrap/theme. For example, the
  page.tpl.php template file is located at
  sites//themes/bootstrap/theme/system/page.tpl.php. To override any of these
  files, copy them from the Bootstrap base theme and place them in here.


Private website with Rules - Inherit custom fields

This is very straight forward in Rules without the need for extra modules:

Event: Content is viewed of type [content-type]

You can add one event for each content type, or as the description in the Rule itself states: If you need to filter for multiple values, either add multiple events or use the "Entity is of bundle" condition instead.

set a boolean field in the content type to determine if it should be public or not
Condition: Data Comparison: Parameter: Data to compare: [node:field-to-determine-if-viewable], Data value
Action: Page Redirect: Parameter: URL: user/login

This will check every page load of a content type (or all if you so desire) and redirect if the boolean is set (or not set) depending on how you want it set up


You will need to add contextual filters in the view.

Just go to advanced -> contextual filter -> add new 'content:nid'
field.
Check 'profile default value' option from list entitled 'WHEN THE FILTER VALUE IS NOT AVAILABLE' -> Choose 'Fixed value' option and add multiple nids seperating them via '+' e.g. 1+2+3
Then from 'more' fieldset check on 'allow multiple values' option.

This should do it. You can check also in sql query generated by view below it which should show something like this in where clause e.g. WHERE (( (node.nid IN('1', '2', '3') ) )


No, you can't do that with the current version of simplenews.

Some alternatives:

Use Mailchimp integration and create segments, groups, then use conditional merge tags (http://kb.mailchimp.com/article/all-the-merge-tags-cheatsheet#Conditional)
You could hack the simplenews module, but that is more shaky... Using the simplenews scheduler and the simplenews content selection module you could patch up a solution.
The newsletter module might be the best platform to do this as they are active and you might find people who want to collaborate. Also the architecture is more generic.

For the moment I will use #1, but in the future I will probably have to implement a neater solution with #3.


How can I use Display Suite with a Drupal Commerce view?

In the FORMAT section of the views edit page, there is a "Show:" option.

If you choose "Fields" (oftentimes the default for any Entity view, including nodes) then you cannot control the output of those fields with Display Suite.

There is an option "Rendered Entity".

You can alter the settings for this option, and select any view mode that you have created/configured with Display Suite. For example you can create a view mode "Foo", and select that view mode in the settings for the "Rendered Entity" option. This will work for any entity.

So you want to create a new view mode for your Commerce entity, select the layout of your choice, put the fields you want in the regions of your choice (maybe the two column 50/50 layout), and in your view Select "Rendered Entity" and select the proper view mode.


Export and import configuration settings and content

See this question and answers on why what you want to do is not possible at the moment.

How to add the configuration changes from a website to another website?


how to make URL aliases of nodes created via form include node title of original page?

try the Pathauto module:

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

Once set up, you can have it assign the path based on the title of the current node (X) and the field value you assign to the title of node (Y).  If you are using nodetitle or something to automatically assign the title for node (Y), you will have to run some custom code when content type (Y) is created in order to assign its alias.


How can an address database be converted to an account profile?

If you want to keep current content type, add Reference field to your user and reference your type via reference field.

If you don't want to keep current content type, it is better to import the data directly into user fields.


DraggableViews was designed for just this purpose.


How do I remove the appended string from image and Javascript URLs?

The strings are to ensure that the files are not cached by proxies or intermediary caches when Drupal rebuilds its own caches. Whenever Drupal's cache is cleared and regenerated these strings will change. These are 'cache buster' strings.

Check this for an explanation of what is cache busting - https://www.adopsinsider.com/ad-ops-basics/what-is-a-cache-buster-and-how-does-it-work/


Using a template_preprocess_node in an adaptive subtheme

Since you are using a node preprocess function, the variable you created will be available to the node.tpl.php file, not the page.tpl.php file. You need to either move your print statement to node.tpl.php or implement template_preprocess_page() in template.php.


I have never used that module before but by reading its home page I found this

When a user submits a webform with protected files he will be sent an
email with a link to the downloads page. The link contains an
individual hash code that will be checked upon page load to verify the
access. If verification fails access will be denied. If it succeeds
the user will see the default private upload file listing with all
protected files that are attached to the webform.

Now based on your question you want to add a link direct to the protected files by the module, bypassing (if that is possible) the access verification, to violate the module's functionality. Why you want to do that ? I think that this is not a good idea even if possible. Probably you are looking for another module or I am missing something.


You have to change the settings in view as follows

Go to view and find Exposed Form (under Advanced).
Click on Settings

3.Uncheck 'Autosubmit' option to prevent 'Automatically submit the form once an element is changed'.

4.Click on Apply and save the view.

That's it.


Statistic count not working with API call

Node views are only counted when node_view() is invoked (i.e. when the node is actually viewed).

When retrieving a node via services you're not, conceptually, "viewing" it, so you shouldn't expect the view count to increase.

In order to get your desired workflow, you'll probably need to implement a custom services resource which updates the statistics manually when a node object is requested. See How to create a custom resource with Services-3.x for more info.


Defining Devel generation rules for custom nodes

I usually create a simple custom module for migratig data from an external data source and no need to use devel for this kind of tasks.

you have a very good example here :

http://timonweb.com/how-programmatically-create-nodes-comments-and-taxonomies-drupal-7

you can simply adapt the code and make a foreach loop on your array.


Second Contextual Filter on Calendar Module

Entity reference field can not provide content id to your view through contextual filter by default. You'll need to define a relationship to your entity reference field so that view is able to pick up Client node id ( content:nid) as contextual filter.

Remove contextual filter that you have now and add relationship to the entity reference field 'Client'. Then add contextual filter to Content:nid. In relationship setting select the alias of relationship that you added previously. In the section " When filter value is not available" check 'Provide default value -> raw value from url -> path component = 2'. Also check "use path alias".


Where are the pages for the Statistics module shown?

After enabling the statistics module, be sure to configure the module (admin/config/system/statistics).

The documentation for the statistics module indicates that:

  To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked. This access log is used
  to store data about every page accessed, such as the remote host's IP
  address, where they came from (referrer), what node they've viewed,
  and their user name. Enabling the log adds one database call per page
  displayed by Drupal.

  The Discard access logs older than setting on the settings page
  specifies the length of time entries are kept in the log before they
  are deleted. This setting requires a correctly configured cron
  maintenance task to run.

  Enable Count content views to turn on and off the node-counting
  functionality of this module. If it is turned on, an extra database
  query is added for each node displayed, which increments a counter.

After configuration, data will begin to be collected for the four reports that statistics provides:

Recent hits (admin/reports/hits)
Top Pages (admin/reports/pages)
Top Visitors (admin/reports/visitors)
Top Referrers (admin/reports/referrers)

NOTE: This applies to all Drupal 7 installations.  Statistics is a core module and is not specific to Commerce Kickstart 2.


Unable to specify different grid columns settings for page and attachment

You can apply different Format to different Views Displays.
In your Attachment Display you have to click on the Format option, not on the Settings link. This will open the modal dialouge where you change the Format for the Attachment, but before you save make sure you change the For option to This attachment (override).

The default option for the For is "All displays" so if you change it under Attachment, it will automatically change on your Page Display as well, unless you override it like I described above.
Just remember that the overriding option appears on the modal dialogue where you're choosing the option, not on the "Settings" modal that depends on which option is set.


Is there a module for scalable input / output for unlimited value fields?

You could of course write both a formatter and a widget to implement some sort of paging, but that doesn't change the fact that Drupal will always load all 100+ field items when loading the node and saving (by doing a DELETE first and then an INSERT) of all 100+ field items when saving that node.

There isn't really a nice way to do this properly using fields. In case of references (node, user, ..), a possible workaround is to reference those entities to the current one, so that each one only has one (or a few) references, instead of 100%. Then you can display them on the referenced entity using a view.

Using a non-relational field storage implementation like MongoDB can help with the storage performance problems because it's a single load/save operation, no matter how many fields and field items you have. But it's still one global operation for all field items at once.


How can I filter related content types in Drupal?

You could populate the second list manually by using the PHP code option to generate the values, the values could be something such as ProjectNid|TaskNid|Task Title.

You could then have a javascript hook so when a project was selected from the dropdown, it reads the nid value and then filters out the tasks where the first element (Project nid) doesn't match.

The other way would be reload the page after the project has been selected, and have the PHP code which populates the task field look at the current active value for Project and pull in the related tasks, or use a view with an argument set to achieve the same result.


Function preprocess_views_view if not logged in

Sure, add either:

global $user;

to your function and check its uid status or wrap the drupal_add_js in an IF block using the Core API function user_is_logged_in()

For exmaple:

$user_is_not_logged_in = (user_is_logged_in() === FALSE);
if ($user_is_not_logged_in) {
  if ($view->name == 'foo') {
    /* drupal_add_js(...); */
  }
}

EDIT:

So the full thing (doing your homework for you) would look like this:

/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
    if (!user_is_logged_in()) {
      // add needed javascript
       drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
       drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
    }
  }
}


What are the legal considerations to build a service like Drupal Gardens and earn profit from it?

The primary complication is the use of the Trademark "Drupal" in the product or service's name or domain. You'll need to contact the Drupal Association at http://association.drupal.org, or Dries Buytaert, the trademark holder.

If you're not interested in using the Drupal trademark as part of your product or service's name there shouldn't be any problem.


How to make Drupal upload pasted links to .doc files from the internet

Can be achieved with Filefield Sources module.

  FileField Sources is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser


You could try to use Views aggregation.

Define the relationships of the fields.
Under Advanced > Other enable aggregation
Add fields of the animal nodes and define the grouping as "count" in the field's aggregation settings.
Define no results bahaviour as "No" and rewrite the result as "Yes". Define 0 as "no result". All in the field settings.

Hope that helps!

cheers,
j


I lost custom fees when apply pricing rules

Are you using Rules 7.x-2.8? There's a known issue with that release that breaks the application of pricing rules: https://www.drupal.org/node/2403851

The latest development build of Rules may fix the issue: https://www.drupal.org/node/2324587


You price resolver should have something like
if (isset($result['price'])) {
    return new Price((string) $result['price'], $context->getStore()->getDefaultCurrencyCode());
}

Before your price resolver's return line put:
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
$order_items = $cart->order_items->referencedEntities();
foreach ($order_items as $order_item) {
  if (!empty($order_item->field_custom)) {
    $order_item->field_custom->value = 'Hello World'; // set new value
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_manager->updateOrderItem($cart, $order_item);
  }
}


How to pass a parameter into a form upon creating?

Just add it to your form's buildForm method signature:

public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) {
  // Use $arg
}

Then literally pass it to the form builder's getForm method:

$data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm', $service_type);


$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  $chunk,
];

In the above, $chunk is the list of parameters that will be passed to the batch process method. So if $chunk is an array of 5 videos, your method signature would need to look like this to match.

static function processBatch($video1, $video2, $video3, $video4, $video5, &$context) {

That's probably not what you're hoping for. To fix, just wrap $chunk in array:

$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  [$chunk],
];

Now your process method signature looks like this:

static function processBatch($videos, &$context) {

And you just need to loop through the videos in each operation.


Entity references from a view with list of nodes that can be references to nodes that keeps references

Edit: this approach is only for listing the assignments, not changing them.

--

First make sure that the product content types have a common view mode. Pick "teaser" for example.

Create two views:

Products list: the "outer view" to list all the t-shirts, pants shoes.
Packages per product: based on a contextual filter, list all package assignments of a given product. As you have different fields link the product content types with the packages you might want to start with one type. Once it works, replicate the view/view display for the other product types.

The second view now needs to be embedded into the teaser view of products. My preferred way of doing so is using panelizer to override the teaser view mode but you can also do this using the "Eva" module.

Hope this helps :)


I don't think you can sort that way with an entity query.  But with a select query, you have more flexibility.

I would try something like this:

$database = \Drupal::service('database');

$query = $database->select('node_field_data', 'nfd')
  ->fields('nfd', ['id']);

$query->condition('nfd.status', 1);
$query->condition('nfd.type', 'news');
$query->range(0, 5);

$query->leftJoin('field_product_category', 'pc', 'pc.entity_id = nfd.nid');
$query->addExpression('pc.field_product_category_target_id <> :target_tid', 'is_featured', [':target_tid', $target_tid]);

$query->orderBy('is_featured');
$query->orderBy('nfd.changed');

$matches = $query->execute()->fetchAll();


After looking for several forums and apache solr help, I made it like this...

Notes:

1 $form_state['values']['keys'] - The search text

2 $form_state['values']['localidade'] - The taxonomy term search value

function MYMODULE_search_block_form_submit($form, &$form_state) {

// Check if localidade is empty
    if (empty($form_state['values']['localidade'])) {
    // localidade empty
        drupal_goto('pesquisa/' . $form_state['values']['keys']);
    } else {
    // with localidade
    // check what is the tid of my term localidade
        $t1 = $form_state['values']['localidade'];
        $t2 = taxonomy_get_term_by_name($t1, "localidade");
        $t3 = array_shift($t2);
    // term no found
        if (empty($t3->tid)) {
            drupal_set_message('Não reconheçemos a localidade ' . $form_state['values']['localidade'] . ', por favor coloque uma localidade sugerida.');
            drupal_goto('pesquisa/');
        } else {
    // build search parameter with the term tid
            $t11 = 'pesquisa/' . $form_state['values']['keys'];
            $options['query']['search_param'] = 'f[0]=bundle:empresa&f[1]=im_field_localidade:' . $t3->tid;
            drupal_goto($t11, $options);
        }

 }

}


Send old Simplenews to newly registered users?

I also found a brute way.

Set newsletter sending status to 0 which will allow a resend to the entire userbase.

Install https://www.drupal.org/project/simplenews_filter

Select only the users that were missed the last time via Views, and send.

(One could also select to send all and delete the subscriber ids from the spool table where you dont want to send)


I haven't used this in a while (2 years), but it did what you described back then!

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


Passing multivaluearray from php to javascript after ajax call

I searched on the wrong position, after i found:
http://www.thecarneyeffect.co.uk/drupal-8-ajax
I got the solution here
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21SettingsCommand.php/class/SettingsCommand/8.2.x

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\SettingsCommand;

function ajaxCallback(array &$form, FormStateInterface $form_state) {

    $form_state->setRebuild();

    $myValue = $form_state->getValue('myValue');

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new SettingsCommand([
       'variable' => $myValue,
    ], TRUE));

  return $ajax_response;
}


How to add a filter in view with list of values

To add a list of ranges you can use the Grouped filters option with Widget Type: Select, instead of Single filter.

Then you can add your groups below. Each group becomes an option in your select list.


How to format CCK fields printed in custom template

You'll need to preprocess these elements into the template and format them to the way you want.

Let's take this practical example.  Let's say we have a content type of 'blog' and we wanted to preprocess the same variables as above to be used in the template file...

/**
 * Preprocess variables for node.tpl.php
 *
 * @see node.tpl.php
 */
function theme_preprocess_node(&$vars) {
  if ($vars['type'] == 'blog') {
    if (isset($vars['field_invoice_due_date'][0]['value'])) {
      // Makes June 1, 2012 format from the time provided
      $vars['date_format'] = date("F j, Y", strtotime($vars['field_invoice_due_date'][0]['value']));
    } else {
      $vars['date_format'] = '';
    }
    if (isset($vars['field_invoice_amount_to_bill'][0]['value'])) {
      // you can use whatever function to format the money value, this is just an example.
      $vars['amount_to_bill'] = "$". number_format('%i', $vars['field_invoice_amount_to_bill'][0]['value']);
    } else {
      $vars['amount_to_bill'] = '';
    }
  }
}

if your moving these fields into a custom template, than you can preprocess with this hook as well:

 /**
 *
 * Implements hook_preprocess
 *
 * @param $variables
 * @param $hook
 */
function hook_preprocess(&$variables, $hook) {
  if ($hook == 'custom_template') {
    // do your preprocess magic here, you can find the variables by either dsm() or print_r()
  }
}

then, in the template do this:

<?php print $date_format; ?>
<?php print $amount_to_bill; ?>


How to keep/access copy of original Feed file when using HTTP Fetcher?

I have a simple solution for you but in this time I have not enough time to test it by myself.

First find your importer form_id, then in your custom module add custom submit handler then get URL of uploaded file then save it in where you want with system_retrieve_file(), e.g.:

function yourmodule_form_alter(&form, &$form_state, $form_id){
  if ($form_id == "importer_form_id") {
    $form['actions']['submit']['#submit'][] = 'yourcustom_form_submit_handler';
  }
}

function yourcustom_form_submit_handler($form, $form_state){
  // dpm($form_state['values']);
  // find file url and put it in $url
  // then try to fetch it with system_retrieve_file
  system_retrieve_file($url);
}


Cannot install Search API pages module, due to database errors?

I have had a similar issue.  I resolved it by installing search api on a fresh drupal install and exporting the databases then importing to the original database.  I would not recommend doing this first however.

First you should uncheck search api module in your modules list, then click the uninstall tab and uninstall it.  Grab a new copy of the search api module to make sure you didn't have corrupt files and install it again.  If this doesn't work, then you may want to try what I had to do.


ServiceProviderBase override "winner" - can this be done with module weight?

Yes, the serviceProviderClasses are discovered in DrupalKernel::discoverServiceProviders(), I've stopped the code there and the list was sorted by module weight and modules with the same weight alphabetically.


WSOD with error when login as administration

To troubleshoot, add these lines to your settings.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Once you add these, you should see some error output.


How to export Group module entities with the Features module?

Have a look at the UUID Features Integration module, which provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. It depends on the UUID and Features module. Some more info aboout this module(from its Community documentation):

  Drupal's core entities are supported by default within the UUID module, but if you want to export content contained within custom entities, you will have to implement UUID support using their API.

The challenge with the UUID Features Integration module is that its documentation is not complete (yet). So for adding UUID Features support for custom content entities (such as Groups), refer to the module's includes/ folder and use one of the existing implementations as an example.

2 more documentation issues that may be of some help also:

Issue # 2310115.
Issue # 2236497.


Huh? It's been a year and no one has found the error referred to by the message ("Call-time pass-by-reference").

Leave

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

unchanged.

And change this:

parent::options_form(&$form, &$form_state);

to:

parent::options_form($form, $form_state);

and your error should go away.

Briefly (for those who are new to user defined functions, as it relates to this issue)...

Function declaration

A function's arguments are defined in the function's declaration (the line that begins with the function keyword). They are a list of PHP variables the function expects to receive from the caller (see  Function arguments  in the PHP manual for more information). The function declaration determines how many arguments are expected, their datatypes, whether they are required or optional, and whether they are passed by reference or not, among other things.

You have surely noticed the $form and $form_state variables used in lots of form-api function declarations, sometimes with and sometimes without a preceding &. Each & tells the function that that argument will be passed to it by reference. This means the function does not receive a copy of the variable from the caller (as usual), but a pointer to it.

A function may change the contents of references directly from within the function, while a copy is private to the function and must be returned, if the function want its changes to be available to the function that called it (of course, the caller must know what to do with the returned data). Any changes made to reference variables remain after the function ends.

Function execution

When a function is called/executed, the & MUST be omitted, otherwise you get the aforementioned "Call-time pass-by-reference" error. The function declaration determines if it's a reference, not the caller.


How repeating field values in "EntityReference select list widget" as I would with "autocomplete widget"

I found everything I was looking for in the Multiple Selects module. Here is a quote about it (from the module's project page):

... provides a widget called Multiple Selects list for the the following fields types:

entity_reference
node_reference
user_reference
taxonomy_term_reference
list_integer
list_float
list_text
list_boolean
commerce_product_reference

Rather than having a multi-select field, this modules allows you to have multiple select fields with the traditional FieldAPI 'Add another item' button.


How to add a hierarchical taxonomy to a content type

You can take a look on Simple hierarchical select and Client-side hierarchical select module.

Simple hierarchical select

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

Client-side hierarchical select

  A simple client-side hierarchical select widget for taxonomy terms.

  The widget provides three settings:

    Force selection of deepest level (If checked the user will be forced
    to select terms from the deepest level.)

    Parent (Allows to select a parent term to use only a subtree of a
    vocabulary for this field.)

    Labels per hierarchy-level


To add a field to the user entity, you need to visit the menu entry Administration > Configuration > People > Account Settings > Manage Fields. You can then define the field properties (including specifying whether it appears on the registration form or not) and customize how it is displayed on user pages.


Omega and Panels: Is there a way to change "Omega XX column grid" layouts?

What you need to do is update your region area in omega to adjust the # of columns each one takes up.


Need to create a report in Drupal 7 that counts Articles by Author for date range

Create a view by selecting users and add filter by date.


Remove webform field while edit webform submission

Try to download & Install Webform Fields Permission module.

Note : Please read comments if you have any query.

If your issue not solved then try once Webform Component Roles module.


Have Database Update ignore prefix for multisite with shared database

Looking at the comments in settings.php, you may well be able to do something like this:

$databases['default']['default'] = [
  'database' => 'db_name',
  'username' => 'root',
  'password' => 'root',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => [
    'default' => 'shared_',
    'custom_table' => '',
  ],
];

I haven't tried it, but in theory that should set the prefix for all tables to shared_, except for the custom one, which would have no prefix.


Dynamic Page Cache not working for my controller?

You need cache keys

'#cache' => ['keys' => ['key1', 'key2', ...], ...]

and this is not the dynamic page cache, it is the standard render cache which will take care of this.


How do I extend the schema of an existing config_object?

Use hook_config_schema_info_alter().
function module_b_config_schema_info_alter(&$definitions) {
  $definitions['module_a.settings.api']['mapping']['additionl_one'] = [...];
}


How to fix the Invoice module's total amount?

It is not a mistake. That moduo do rounding. See the photo:

Subtotal: 134.50
VAT: 25.55
Total: 160.06

So, the real value of VAT is 134.50*0.19=25.555 and real total is 160.055 but for invoices you need to do rounding at two decimal places. And you get total 160.06.


Bootstrap subtheme does not recognize stylesheets

I forgot to turn the subtheme on in the theme settings.


Can't see User fields as options for a context filter

The tutorial you're watching is out of date (I watched it too); it was created when Views was in beta/RC and things have changed a bit since then.

You just need to add the user as a Relationship under the "Advanced" options...then you'll get the user filters as you'd expect.


Ajax request: 500 (Internal Server Error)

At a glance, there's some issues with the code, however, the main error may be:

$product = entity_load_single('product', $pid);

where you don't have a $pid value, you're setting $fid instead.

$fid = $_POST['pid'];


Admin login returns 'Sorry, unrecognized username or password.'

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

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

drush uli

Either of these will help you get your password.


You can read user roles using below code...

global $user;
$user_roles = $user->roles;
$progress_value = x * 5; // where x is value extracted from $user_roles
if( is_numeric($progress_value) && $progress_value > 0 && $progress_value <= 100 ) {
  $style = "width: ".round($progress_value)."%; display: block";
}
print '

  <div id="progress-value" style="<?php print $style; ?>">

';

Now the solution needs some CSS to make it look like a progress bar. Start with a basic style - just a black border with a gray filling:


How to copy field value into another field by its node ID?

I could not find a solution to my problem, but I found a workaround.  Instead of 3 phases with each their own content types, I instead was able to make one content type and use the vertical tabs to create 3 "sections".  It is not ideal but it should work.  I would still like to know if what I am asking is possible.


Try node_view

<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

Read: Rendering Drupal 7 fields (the right way)


Entity reference get all related items in a view

One way of doing this in a non-programmatic way is to use views_field_view. With this method you will only get a set number of nesting levels - for example 4 levels: create a view of your specific node Content Type with 4 Pages, A, B, C, and D. In Page A, insert a Views Field that references Page B, in B a field to Page C, and in C a reference to page D. Pages B, C and D should have a contextual filter for a Node ID (nid). In each page, the Views Field View field should pass the Node Reference as an argument to the next Page. I hope this is clear. Let me know if it's not, and I can expand this.

EDIT: If you are looking for "infinite depth" I suggest that you look at the programmatic alternative for Views, EntityFieldQuery(). Perhaps a recursive call to a function that does the query, while you build a global multi-depth array with the data you need, then theme it as a table.


what is the difference between using drupal_add_js and ['#attached']

If you are using drupal_add_js() in your form building function, you are attaching JavaScript to a page, and that's it.

If you are using $form['#attached']['js'], other modules may interact, test and change it as they need, using hook_form_alter(). That's the way you should choose every time your JavaScript is functionally related to particular form.

Other than that, they are functionally the same.

Note that it is usually better to use JavaScript libraries than plain JavaScript files, as they allows you to declare versions, keep relations between JS and CSS, manage dependencies, well, they are generally way more powerful.

Of course then you should use $form['#attached']['library'] when your JavaScript Library is functionally related to particular form, and only use drupal_add_library() when no form is in any way related to library's function.


How to programmatically create a custom panel pane

Ok my question maybe was not the best but at least I hope the following will help new themers get on track.

I created a custom content type called: seminar
I created this node--seminar.tpl.php and placed it inside /sites/all/themes/awesome (the name of my theme)
Inside this file I copy pasted the code found in /modules/system/node/node.tpl.php and I tweaked the code as follows.

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> post clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
  <?php if (!$page): ?>

         <?php print $date_day; ?>
         <?php print $date_month;?>

      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

      <?php print render($content['links']); ?>

Keep in mind that in order to achieve this

 <?php print $date_day; ?>
 <?php print $date_month;?>

so that $date_day and $date_month correspond to sth meaningful, I had to go through this. Othewise by default drupal outputs sth like  Apr 30  and we can't target Apr and 30 seperately for CSS styling.


Reset button is not working after previewing the webform

Your code works as designed - resets form to a state it was at page load. After preview state JavaScript resets to is set to what user entered. That's not a Drupal issue, that's just how JavaScript and browsers works. Browser simply does not have that data any more - HTTP is a stateless protocol even if we work around it every day and don't even consciously notice that we do.

If you want that button to do something else, you need to use Drupal's AJAX and obtain values you want to reset to from the server directly. Alternatively, you can attach custom submit handler to that button, one that would not really submit anything, but clear data from $form_state['input'] and trigger form reappearing.


You cannot add elements to the form outside of the form definition. You are adding your form elements in your block class, which is why it's not working as you expect. If you want to alter the entity form, you'll need to use hook_form_alter() and add your ajax there.


Granting per-node-type permissions in hook_node_type_insert()

So, my bet is that the new node type isn't getting added to the cached list of types that node_type_get_types() returns. At the very end of node_type_save(), it calls node_type_cache_reset(), but that's probably running too late for your code.

So try putting a call to node_type_cache_reset() at the top of your function, and hopefully that will do the trick.


You could use hook_form_alter in a module to attach a the CSS (library) to the form with the needed changes.


Smart Paging Clean url redirects to Queried strings automatically

Issue was with Global Redirect Module. Patch here https://www.drupal.org/node/1843500#comment-7535655 works, testing it on development site for now.


How to update the uid of a node in node revision table?

Along with what Japo said, the latest revision will mirror the update, it does not get applied retroactively, not sure why you would want that specifically. Unless this is a case where anonymous users create content or are assigned content and you want them to have edit access to all past revisions?

Either way, nothing will solve this for you short of a custom module that does a db query to force the UID value on the table.


Rotate views results based on number of times viewed

IMHO I don't think that you will be able to find a module that does this. You will need to write custom code for that. Depending on how comfortable you are hacking with Drupal and PHP you might find it trivial or very difficult.

So here are the requirements:

The counter must persist between page renders, so you need to store it in the database. A CCK field (D6) or "just" field (D7) will do the trick. You would assign this new field to your image content type.
This is a View. So how could you write to CCK field when rendering a View? The answer to that is preprocessors. How to write preprocessors is beyond the scope of your question. So is how to write to a CCK field. You can look for that answer in other Stack Exchange questions and the main Drupal site.
On your View, you would then sort the images by this "counter field".

That should do it.


View my local site on smartphone and tablet

Go to the terminal and type

  ifconfig

Check for you IP address.

Suppose your drupal url is

  www.localhost/drupal

then go to your iPad and iPhone browser and type

  IP Address/drupal

Using this you could see your local drupal site on iPad and iPhone.


Embed a view into a Webform for submission

To embed a View in a Webform, you can use the View element.

Below is the YAML for how you would embed the Frontpage view into a Webform.

frontpage:
  '#type': view
  '#name': frontpage

@see \Drupal\views\Element\View


Image style is not working for larger size image

If you allow users to upload large images, you might run into this problem even after upping the PHP memory limit. If this happens, I strongly recommend installing this module: Max Image Size.

Suppose you allow users to upload 10mb image files straight from their digital camera, without forcing them to use image editing software.

Without Max Image Size module, the uncompressed image data for that massive file is held in memory and manipulated multiple times for each image style. That consumes a huge amount of memory. For many-megabyte "straight from camera" images that'll often exceed any memory limit you could or would want to place on a web server for one user's process.
With Max Image Size, there's a step before that honking great image reaches GD, cleanly scaling it down once to a large-but-reasonable size (2560x1600 by default, this setting can be changed). All the image style manipulations are then done to that image using much less memory.

This also has the effect of capping the largest possible size another user would get if they click an "original image" link. Very occasionally this might be a problem  (e.g. if you're selling professional stock images and need the original monster-sized file - though even then it might be better to upload a raw or tiff file as an untouched plain download alongside the JPG), but usually it's a good thing too. If a user is on mobile data and clicks a full-size image link, they'll normally expect something like a high-quality 2560x1600 wallpaper, not some beast that takes minutes to load and wipes out a substantial chunk of their data allowance.


Unattended automatic security updates / upgrades

Please also keep in mind there are '0-day' vulnerabilities out there, which can be used to compromise your website even before Drupal publishes a security advisory and corresponding patch. And that even if you use an automated update for Drupal core, there still will be a time window in which your site was vulnerable.

The best way to deal with these kind of issues is therefore to have all your Drupal code in a version control system - Subversion or Git for example. This way you can easily:
- identify when there has been an intrusion with a status command (this will show you all modified files in your source files)
- reverting these changes, and therefore repair all harm done, by resetting the source tree to your latest commit

The only downside is that you have a little more work to do with each update, as you need to commit all changes back to your repository after each code change. But this is a very small price to pay for the added benefits and piece of mind this provides.


Remote attribute in mymodule.libraries.yml

According to the code/comments in LibraryDiscoveryParser::buildByExtension, it's to help ensure licensing info is included for 3rd party libraries:

// If this is a 3rd party library, the license info is required.
if (isset($library['remote']) && !isset($library['license'])) {
  throw new LibraryDefinitionMissingLicenseException(sprintf("Missing license information in library definition for definition '%s' extension '%s': it has a remote, but no license.", $id, $extension));
}

It's also mentioned in the library docs, but it just says that it's a good idea to include the remote info, not why. It doesn't appear to be used in the code other than the licensing, so I think it's safe to assume it's a reference/info value for now. There is no incorrect value to-to-speak, but it would make sense to set it to the URL of the project you're referencing.


How to automatically skip intermediate redirects?

Use the Rules module with a custom  rule which looks like so (in Rules export format):

{ "rules_redirect_multiple_paths" : {
    "LABEL" : "Disallow multiple paths",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "about-us\\d+",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirect to path about-us ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "about-us" } }
    ]
  }
}

Some details about how to use read this rule:

Rules Event: use the "Drupal is initializing" event, to ensure that the rule gets triggered BEFORE the actual content (of a path to be redirected) is shown. If you'd use an event like "content is viewed", you'd be too late, the content "would" already be shown.
Rules Condition: verify if the path to be redirected matches any of the paths you want to be redirected, such as about-us01 or about-us02 ( * ).
Rules Actions:

Show a message about the redirect, which is just for QA testing (feel free to remove that Rules Action after you saw it working).
Perform the actual redirect to the desired page.

( * ) Note that the actual Regular Expression I used goes a bit further: it would also perform a similar redirect for paths such as  about-us03 or  about-us456, though it would not trigger such redirect for (eg)  about-us/789. Here is an attempt to translate the various parts used in the regular expression about-us\\d+:

about-us: it must start with about-us.
\: escape character.
\d: it must be followed by a digit (anything from 0 to 9).
+: it may be followed by 1 or more of the preceding token (so one or more extra digits).

PS: If you're struggling with regular expressions, then have a look at RegExr.


How can I export a group of settings in Drupal 8

There are two different things you can do.

You can, as you found, export and import single objects.

Or, you can do a config sync. Which means everything and is usually used to import configuration changes from staging to production or similar.

So you can do a full config export, then all the files will be in your staging folder (not the same as a staging environment) and import them in a different site. Note that there are some limitations, for example, you always need to do a full import (so export the existing config of a site, update it with some changes, then import it again) and the sync only works if the UUID in system.site matches, as it is not supported to import from a separate installation. (But you can import a group of files that don't exist yet.. careful with the UUID's, as the same object with a different UUID is treated as a delete + create, not update).

So you need to pick the files you want to re-use and put them either into an existing export from the target site or put them in a config/install folder of a module, then it will be imported when that module is installed (and only then, there are no automated updates).

You can also look at the 8.x version of the Features project, which basically offers a UI to pick a number of configuration files, similar to what you might know from D7.


The problem of my above question is a core bug. I added it to the Drupal Core issues, hope it will be solved soon. https://www.drupal.org/project/drupal/issues/2935113

In the mean time I found a work around. I use two different filters in the two added groups. Both filter on the same thing.

So in group 2, I filter on my Wat? field.

In group 3, I filter with the 'Has taxonomy filter'.

Both filter on the same taxonomy term but because they are different filters it does work now.


You just need to put all that logic into a single function:

function ukf2_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
  }

  if (!empty($variables['page']['sidebar_first'])) {
    $variables['content_column_class'] = ' class="col-sm-10"';
  }

  else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

  if (!empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class2'] = ' class="col-sm-8"';
  }

  else {
    $variables['content_column_class2'] = ' class="col-sm-12"';
  }

}


Is there any way to use a jQuery overlay to confirm/reject node deletion?

You might be able to do that with:

https://drupal.org/project/ctools_automodal_admin

  Provides automatic modal support for any hook_menu() paths that have
  'modal' => TRUE defined. This makes it easy to add optional modal
  support in any contrib module and helps reduce the burden on module
  developers to support modals.

If you added the node delete path, perhaps node/%node/delete to the modal paths, it may just work.


As the site the content differs for each users, it can't be cached.

Well, that is not entirely true. At least for Drupal 8 the options for caching have improved drastically. Previously we could cache a query and its output, but Drupal 8 comes with tag-based caching.

Every entity in the system can (and core entities by default) expose a cache tag. This allows individual entities to be cached. Views tag-based caching in turn uses these tags to determine if the cached view output can be served or should be rebuilt.

This means that the view query will still be executed, but all the individual nodes can be served from their individual caches. If none of the nodes has been updated, the rendered output of the view will be served from cache too.

As for scalability (SQL vs NoSQL is not really a Drupal question), there is a tradeoff (but I really do not know enough of this to provide a good explanation). A views relationship is nothing more than an SQL join, this means that all data exists once and is merged into a data set on request. If you do not want to use relationships but a search_api based approach, the same data set should be composed elsewhere. Since you do not want to use relations you should fetch all nodes of all followed users in one run.

Depending on how your view and search database are configured, this could result in every node getting stored once in the dataset of every follower. With a lot of users and a lot of content this can grow in size very fast. It will likely be faster though because you'll only have to lookup one id instead of all the id's of the entities on the joined tables.

TL;DR
It depends on what you show and how you build the index.


How to check Drupal distribution version from CLI?

Just run the following command from the root directory of your Open Atrium installation:

drush status-report

This should give you the output similar to the status report screen in the standard Drupal backend. In my Open Atrium installation, one of the lines reads:

Install profile            Info      OpenAtrium (openatrium-7.x-2.18)

So in this case I'm running Open Atrium version 2.18.


Typically there is a theme function associated with the different sort of output you can give data fields or indeed any fields If you want to change this you do so on the theme level by overriding the default theme function in your themes template.php file.

Date popup

function YOURTHEME_date_popup($vars) {
  $element = $vars['element'];
  $attributes = !empty($element['#wrapper_attributes']) ? $element['#wrapper_attributes'] : array('class' => array());
  $attributes['class'][] = 'container-inline-date';
  // If there is no description, the floating date elements need some extra padding below them.
  $wrapper_attributes = array('class' => array('date-padding'));
  if (empty($element['date']['#description'])) {
    $wrapper_attributes['class'][] = 'clearfix';
  }
  // Add an wrapper to mimic the way a single value field works, for ease in using #states.
  if (isset($element['#children'])) {
    $element['#children'] = '
' . $element['#children'] . '
';
  }
  return '
' . theme('form_element', $element) . '
';
}

Although it must be said this is being themed as a form_element so there is no fieldset.

Date combo is themed as a fieldset and again can be overriden...

function YOURTHEME_date_combo($variables) {
    $element = $variables['element'];
    $field = field_info_field($element['#field_name']);
    $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);

    // Group start/end items together in fieldset.
    $fieldset = array(
            '#title' => t($element['#title']) . ' ' . ($element['#delta'] > 0 ? intval($element['#delta'] + 1) : ''),
            '#value' => '',
            '#description' => !empty($element['#fieldset_description']) ? $element['#fieldset_description'] : '',
            '#attributes' => array(),
            '#children' => $element['#children'],
    );

    // Fix required marker.
    if ($element['#required']) {
        $fieldset['#title'] .= " " . theme('form_required_marker');
    }
    return theme('fieldset', array('element' => $fieldset));
}

If you replaced 'fieldset' with 'form_element' this would work.


To debug, add a user update hook and check if they role is being unchecked, then log the $edit to your watchdog log then you should be able to see who/what is causing this change. This is a very rough example and you'd have to customize it to fit your roles etc.

function YOURMODULE_user_update(&$edit, $account, $category) {
   if (user_has_role($YOUR_ROLE_RID, $account) {
     debug($account, 'account', true);
     debug($edit, 'edit request', true);
     // maybe add an email notification letting you know the event fired
   }
}

You can then test it by manually disabling that role and see if the debug messages appear in your log. Then if it works, just wait and see what happens when the mysterious permissions troll strikes again.


Views block in custom region rendered outside of page.tpl

Searh your php.ini and change the value of max_execution_time to:

max_execution_time = 300

By default php.ini have 30 seconds and PHP needs more time to process it, in this case you have 300 seconds.

EDIT: As you say in your comment that your problem persist, you can use the following solution, but you need know that your site can take a lot of time to process your request.

Edit the file YOUR_SITE/sites/default/settings.php and add this in the second line and save the file:

set_time_limit(0);

Read more about this function at php.net


Does $form_state['redirect'] require a rebuild?

Form generation reports the following text:

  $form_state['redirect'] is used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with drupal_goto(). See drupal_redirect_form() for complete information.

The function drupal_redirect_form() is called by drupal_process_form(), which calls it after executing the form submission handlers with form_execute_handlers().

if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  // Execute form submit handlers.
  form_execute_handlers('submit', $form, $form_state);

  // ...

  // If batches were set in the submit handlers, we process them now,
  // possibly ending execution. We make sure we do not react to the batch
  // that is already being processed (if a batch operation performs a
  // drupal_form_submit).
  if ($batch = & batch_get() && !isset($batch['current_set'])) {
    // ...
  }

  // Set a flag to indicate the the form has been processed and executed.
  $form_state['executed'] = TRUE;

  // Redirect the form based on values in $form_state.
  drupal_redirect_form($form_state);

  // ...
}

In short, the form is not rebuild, before redirecting the user to a new page. The $form_state array that is passed to drupal_redirect_form() is the same array passed to form_execute_handler() (the difference is that the form handlers can add or alter values contained in $form_state).


How to prevent drupal 7 from saving a node

So basically, you don't want a form for content entry, but you want a form to streamline the user navigation - right?

You can probably alter the node form (implementing hook_node_submit for instance) to stop it from saving data, but I recommend against it. The essence of a node is that it is site content, so it doesn't make sense to have a node form that doesn't save a node to the database.

You can build a custom form that does exactly what you want it to do by implementing hook_menu (to choose the url for your form) and a custom form generating function. See form_example.module for examples of custom forms.


{{ content.field_test }} doesn't work in node.html.twig

Uninstalling Field Layout module will solve this. (tested with Drupal 8.6.10, using subtheme built on Barrio Bootstrap 4).


After node creation how do i add simple buttons to edit the field values

The $node_id is blank as there is no value passed for it. In order to get node_id in the submit handler function, you should pass the node_id in the form. So pass the node id value as a hidden field in the form and get the value of hidden form element through $form_state of redirect_button_form_submit. In that way you can do it.
Example :
$form['node_id'] = array('#type' => 'hidden', '#value' => $nid);
Yes it is possible for you to edit $node->content['apikey'] if and only if it is saved in database. Create a new field as apikey in the content type and store it.
Hope it helps. Thanks.


How do I send an email notification to a user who flagged another user using rules?

Solution: I created FLAG users, so that users can flag each other.

RULES is set up as follows: New event, node new content.

Elements (3 items)
1st  : Fetch users who have flagged a user
Parameter: Flag: Flagname..., user: [node:author]
Provides variables: Users who flagged (usersflagged) Add another

2nd : Add Loop
Parameter: Lijst: [usersflagged]
List item: Current list item (list_item)

3rd : Send E-mail
Parameter: To: [list-item:mail], Subject: Sitename | [node:author]..., Message: Dear [list-item:name], ..., From: no-reply@sitename.com

Next step to discover is how to digest the mail. And I am wondering how much impact this rule will have on a busy site.


Which configuration settings should be used to prevent "No statistics available" in the Admin Reports?

This has nothing to do with Google Analytics or your Provider. Check /admin/config/system/statistics. This will populate your /admin/reports/hits.


Generally you shouldn't remove fields that are used by other mechanisms, like Views. Now when it's done, the best way I know is to export view, manually remove fields that was deleted from it, and re-import. And don't forget your backups.


/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */

function MYTHEME_preprocess_block(&$variables) {

  if ($variables['block_id'] == 'target_block_id') {

    //load node object
    $node = menu_get_object();

    // do something with node object

    // add variable to your block template file
    $variables['block_variable'] = 'something';
  }
}

Available block variables - Block variables


Path-based context and URL aliases - wrong block shown

In the end, we changed the whole approach here, and made the jump menu load the new block with AJAX.  (I wasn't the person who developed the new way of doing this, so I can't provide much more detail, I'm afraid.)  This was a lot less buggy than my original approach!


Drupal already has a UI layer in the theme. There are modules which will allow you to switch the theme depending on the device (have a look at mobile_theme), so you can have different themes for different devices. This way your modules should only send data to the theme layer which then acts appropriately for the device viewing.

However with the increasing sophistication of mobile devices it is possible to create a site which has the same markup but adapts to the device using clever css and jquery.


Populating select list from a taxonomy term field

You'll have to reformat the options array to be in the form 'return value' => 'display value'. See https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#options


Using Rules to Update the Data of a Relations Endpoints (Referenced Entities)

Just in case someone happens upon this, I did find a patch that provided the solution for this error. Turns out the Redhen module had some revision conflict with the entity API, so this patch here fixed the error, and it should be included in further Redhen updates


How to remove a prefix with hook_form_alter?

In your hook_form_alter the following should do the job and has the benefit of leaving the element there if required.

$form['buttons']['back']['#access'] = false;


Views: Relationship with webform submission

You have to use hook_views_data_alter for node and webform submissions relation in view.

function mymodule_views_data_alter(&$data) {
  if (isset($data['webform_submitted_data']['data_numeric'])) {
    if (!isset($data['webform_submitted_data']['data_numeric']['relationship'])) {
      $data['webform_submitted_data']['data_numeric']['relationship'] = array (
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'nid',
        'label' => t('Referred node'),
      );
    }
  }
}


disable date field (only update with datepicker)

Add 'readonly' => 'readonly' attribute to your field,

ie:

$form['myform']['from_date'] = array(
'#type' => 'textfield',
'#title' => t('From date'),
'#size' => 8,
'#default_value' => (arg(5) == null)? '0':arg(5),
'#attributes' => array('onclick' => 'GetdatePicker(this);', 'readonly' => 'readonly'),
);


It turns out I needed to recreate this "system" page as an "existing page" using the - Page Manager Existing Pages - module (drupal.org/project/pm_existing_pages). I am not entirely sure why, but this solved my problem.


I have been unable to find any existing module to do this and would be quite surprised if one existed. You will very likely have to develop your own module.

Here is a brief rundown of how such a module might work:

Implement a new field type providing either a form for the user to create the subtitles or upload a subtitle file in one of the many subtitle formats. https://support.google.com/youtube/answer/2734698?hl=en
Parse the input from the form and store it. You'd likely want to store it as JSON or something else that will be easy to work with in JavaScript
Write code to pass the data to the browser
Use Javascript to update the Language 1 and Language 2 content to match the data in your stored subtitle file. You can use the YouTube API to get the current time of the video https://developers.google.com/youtube/iframe_api_reference#Playback_status

I think it would be a lot easier to just use YouTube to do this but I'm sure you've already thought of that.


Recommend a theme function to modify the 'Submitted by' line for a node?

You can alter the node info using template_preprocess_node
function template_preprocess_node(&$variables) {
 // your code
}

The $variables array contains the following arguments:
$node
$view_mode
$page

This is the default value
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' =>
  $variables['name'], '!datetime' => $variables['date']));

You can override is as you wish. Give a try.


Get view via php based on page number and 1 argument (uid)

You can specify a page inside a view with views_embed_view().

Fisrt argument will be the view's name

Second will be the page you want to display (Defaults to default)

And then as many contextual filters you want/have

So it will look something like this views_embed_view('view_mahcine_name', 'page_3', uid);


Migrate with Cloud Files fopen:Too many open files

I believe there is a bug in the rackspace cloudfiles api which causes connections to not be closed properly. In normal, web-based, circumstances this isn't a problem because at the end of the processing all of the connections are closed and you never usually open enough connections to have a problem.

However, I'm running the migration via drush from the command line which means the process isn't ending for a VERY long time after A LOT of connections and eventually I hit the limit for the max number of open "files."

This isn't a perfect solution, but it works even if it's hackish.

class MyArticleMigration extends BasicExampleMigration {
    public function __construct($rangeStart = 0) {
        parent::__construct();

        // code to set up the query where I pull my source data from the database.
        $query->range($rangeStart, 35);

        // rest of the code...
    }
}

class MyArticle0Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(0);
    }
}

class MyArticle1Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(200);
    }
}

class MyArticle2Migration extends MyArticleMigration {
    public function __construct() {
        parent::__construct(400);
    }
}

// etc...

Then on the command line I just run:

drush migrate-import MyArticle0Migration
drush migrate-import MyArticle1Migration
drush migrate-import MyArticle2Migration
drush migrate-import MyArticle3Migration

etc...


Views exposed filter to search multiple fields

Yes, you can have multiple fields search in a single exported filter using Global: Populate filters and Views filter populate module.

Check this answer.


I just found the solution looking a bit in the Multi level (multirow) header for table FAPI element and doing some test.

This is the way that I found:

// The table header.
$header = [
  $this->t('Name'),
  $this->t('Description'),
  [
    'data' => $this->t('Weight'),
    'colspan' => 2,
  ],
  $this->t('Package'),
];

// The table.
$form['modules'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => [[1, 2, 3, 4, 5]],
  '#sticky' => TRUE,
];


How to avoid Drush command not found after switching to aegir or other user?

Try to create a symlink to let all user access drush.

sudo ln -s /usr/local/bin/drush /usr/bin/

if not worked try

sudo ln -s /usr/local/bin/drush /usr/share/bin/


Homebrew

Install Drush by Homebrew:

brew install drush

via Phar binary

sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush


Maybe another simpler way exists, but after a little digging in the core I found that the modules list (admin/modules) with all the information is retrieve from the _system_rebuild_module_data() function that use the
info_parser service to retrieve all the module information.

If you want to know the module package you can use this code:

$module_machine_name = 'views';
$module = \Drupal::service('module_handler')->getModule($module_machine_name);
$module_info = \Drupal::service('info_parser')->parse($module->getPathname());
// To use dpm() you need the devel module.
dpm($module_info['package']);

Output:

  Core


This looks like a security problem to me.  I examined the headers being sent by IE and the session variable in the cookie doesn't appear to be getting set/transmitted.  This is because IE has strict rules about cookies in iFrames, whereas Firefox does not.  Without the session variable, your cart is not being saved.  I would take a look at this related question: https://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer and apply the solution presented there.  It should solve your problem.


If you want to use a custom date format, you should write this as a record in the database. In your profile-install function, you can use following code to accomplish this:

system_date_format_save(array(
    'format' => 'd.m.Y',
    'type' => 'custom',
    'locked' => 0,
    'is_new' => true,
));


How do I add a text field that links to the taxonomy_index table

Use the field collection module.

Create a new field collection field attached to your content type, and then in your field collection put 2 fields: 1 taxonomy term reference field, and 1 text field.


How to build a specific administrable page layout?

Sounds like a job for Panels

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


How do I calculate the resource requirements for using Solr?

This is not the most complete answer but no one else has stepped up so hopefully this can be somewhat helpful.

I would say that the biggest potential issues on a box that size would be running out of memory and disk space. You can allocate memory to your java vm to mitigate potential memory issues. Solr is under load when indexing and retrieving search results (obviously). You can mitigate the indexing load by indexing in small batches. Though in terms of memory footprint if you are substituting solr with normal Drupal search your load on apache/mysql will be greatly reduced.

I would say that I've run multiple solr instances with a higher load than you are describing on a 1GB VPS.

You may get a more detailed answer if you go to ServerFault or the Solr mailing list and share the solrconfig.xml and schema.xml files from the ApacheSolr module.


You have to check your field handler, node tpl.php or field tpl.php and use drupal_render($yourform), it's the cleanest solution I see.


Date field with selection back more than 20 years

The default is actually -10 years

Since yours is longer, scroll own and select "Other" and type -25

Save settings
Now when you edit again, you should see


Letting a view know in which pane it's being displayed

Build your views as "view content pane" displays.  That way any context you require for use in contextual filters can be provided in the panel UI when you set up the pane.


How to implement an E-commerce solution for a jobboard?

This can be easily done with the Recruiter Distribution and Ubercart or Commerce.

If you are not using the recruiter distribution you can used the Profile2 to created to ask

  - Checkboxes (for terms and conditions) - Document upload (CV,
  picture etc) - Other basic details (name etc)

For the Terms and conditions you can used the Site Disclaimer module.

You need to created a role that allows them to register to the website and created a profile. After that you can add a button to Upgrade their to another role which would give the user the ability to see or do more stuff in your website.

You can follow this tutorial to learn how to upgrade a role with Ubercart. How to Configure Drupal 7 and Ubercart to Sell User Roles


How to get the correct reference to this item?

The correct reference is:

  if ($rowinfo['target_id']['#value'] == 94)


Updating Drupal core in a Acquia Dev Desktop?

The Acquia documentation for Dev Desktop lists very clearly the steps that need to be taken to upgrade your Drupal install: https://docs.acquia.com/dev-desktop/upgrade.

Also, if you are a subscriber, you can open a ticket with them and they will assist you.


Can we write php conditions in view field templates?

No. Do not make a view that pulls a nid, then do node_load in the template. This will be a performance killer.

You should create a view mode using Entity View Mode module, add the fields to the display, and theme it with node--node-type--view-mode.tpl.php. Then the configured View only has to show 'Rendered Content' - and pick the view mode. Then you're done.

See: https://www.youtube.com/watch?v=wcskTtvR6Mo


Countdown timer on discount products pages

You can use the Field Timer module

  This module provides field which can be displayed as a
  timer/countdown. A start/target date can be any date or an entity
  property which represent a date (for example, created date of a node).
  Module provides 4 field formatters: simple text and 3 formatters based
  on jQuery plugins County and jQuery Countdown. If you are looking for
  a configurable countdown/timer, this module is for you. It allows to
  configure backgrounds, effects, formats, language of timer.

OR

Countdown Timer Field

  Countdown timer field module allows you to create countdown timer
  field to count the days, hours, minutes, and seconds until a specified
  event. The module uses jQuery Countdown Timer to display the countdown
  timer in a nice graphical way.


Is it better to start a Drupal theme from scratch or extend an existing one?

I've done both many, many times and my experience has led me to say: I would start a theme from scratch every time.

Most of the starter/base themes for Drupal contain massive amounts of superflous HTML code (because they have to allow for every possible eventuality) which introduces more DOM complexity than there ever needs to be in a page. This is bad for your page load time, which in turn is bad for SEO. It's also bad for code readability and Javascript performance on the client side.

The other thing is that (rightly or wrongly) you won't always agree with the decisions the developer(s) of the theme have made with their HTML/CSS/JS and it can be very time consuming to fix an existing theme to conform to your own standards.

Why not create your own base theme? It would be a good exercise to learn how to do it and you'll be 100% sure that the code is as streamlined as you want it to be. From then on you can just use your own base theme each time you want to create a new one.

The link to the theming guide in alastair's answer would be the perfect place to start.


Copy same content date fields values to separate content types by rules

field: date_2 is not listed because of a field configuration mismatch between both fields.
Everything MUST match between them.


How to programmatically set the user timezone

You can use Set method on user Entity like the following:

$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);
//- Set Time Zone to London
$user->set('timezone','Europe/London');
$user->save();

NOTE : You can set other fields with set method, for example if you can activate the user with $user->set('status',1); or give him administrator role with $user->set('roles',['administrator']); .


Does Drupal cache db_query results for multiple users?

You need to put in an else {...} after using lock_acquire(); or have it return right after calling  lock_wait().

Also, db_query is not cached in any way


Display only banners for a specific month

Create a contextual filter against the field that holds the month number. Provide a default value of PHP code:

return date('n');

Now only those nodes will display in September that have 9 as the month number.


How can I build the results of a view in code then send them to the view?

Use hook_views_query_alter().

Alter the query before executing the query.
This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified


Storing ajax callback variables in PrivateTempStore

PrivateTempStore is not the right fit for this. You want to store the value in the $form_state, but you do not store it in the AJAX callback, you store it in the submit handler, then set the form to rebuild (which will persist the values in the storage. You can set a custom #submit handler on your ajax submit button that is only called when that button is clicked:

$form['wrapper_amount']['value'] = [
  '#type' => 'number',
  '#prefix' => '
',
  '#suffix' => 'pcs
',
  // note - #name is commented out, as you should never
  // need to change it in Drupal, and doing so will have
  // unexpected consequences.
  // '#name' => "amount--product-1",
  '#ajax' => [
    'callback' => '::calculatePricePerUnit',
    'event' => 'change',
    'disable-refocus' => TRUE,
    'progress' => [
      'type' => 'fade',
      'message' => NULL,
    ],
  ],
  '#submit' => ['::customSubmit'],
];

Then your custom submit will look like this:

public function customSubmit(array &$form, FormStateInterface $form_state) {
  $total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
  $form_state->set('total_price', total_price);
  $form_state->setRebuild(TRUE);
}

After playing around with this a little, I can see that a submit button is required to be able to call a submit handler where rebuildForm() can be recalled. If you set the #ajax on a non-submit button, ajax is called, but rebuildForm() is not able to be called.

As such, I'd say the hack for this is to create an #ajax submit button as I've shown above, but hide it. Then add some custom JS on the number field, that on blur triggers a click of the hidden submit button.


How can I delete a row from the database?

You can do it by using this code

$query = \Drupal::database()->delete('table');
$query->condition('some column', 'some condition');
$query->execute();


How can I translate the Profile 2 field labels?

EDIT: the following description describes the steps for Drupal 8, but they are similar for Drupal 7:

You need the potx module to extract a translation template which you can translate. Unfortunately there isn't an official Drupal 8 release available, but you can use this github fork, which works fine for my needs.

Here is a short procedure to handle translations of my modules:

1. extent your module with the Interface Translation Properties (only Drupal 8)

Example my_module.info.yml:

name: My Module
description: ''
type: module
core: 8.x

'interface translation project': my_module
'interface translation server pattern': modules/my_module/translations/%language.po

Now your module is available for the locale module and translation can be handled with drush locale-check resp. drush locale-update.

2. create a subfolder for your translations

In the subfolder ./modules/my_module/translations I put the generated template and the *.po files. Fore more information have a look at the documentation on drupal.org.

3. create your template

I'm using drush to create the template. The best way for me is the creation with

drush potx single --folder=modules/my_module/ --api=8

It generates a general.pot file at the root directory of your Drupal installation. I move it into the translation folder but it's not necessary.

4. create your translation

To create a translation I'm using Poedit as editor. You can create different language files from the general.pot template. The free version of Poedit is quiet useful for editing *.po files. Save your language files in the translation folder.

5. import the translations

Run the following commands to import the translations:

drush locale-check && drush locale-update

And clear the cache:

drush cr

That's it ;)


How to unset fieldset in hook_form_alter?

The mentioned solution ['#access'] = false will be a possible solution, but if it's not working you may try:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state) {

  $form['#after_build'][] = 'YOUR_MODULE_form_FORM_ID_after_build';

}

/**Replace MACHINE_NAME with your fieldset group machine name.**/

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

  // Hide the B2B group.
  field_group_hide_field_groups($form, array('group_MACHINE_NAME'));

  return $form;
}


How to query the database to create a report based on user input variables in a form?

I think you pass some arguments when you redirect the page to another page.
You can pass arguments like this way..

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

Or You also can use drupal_goto() like this

drupal_goto('your_url', array('query'=>array(
'variable_name1'=>'variable_value1',
'variable_name2'=>'variable_value2',
'variable_name3'=>'variable_value3',
...... ...
)));

You can check below links for more information.
https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_redirect_form/7
https://www.drupal.org/node/291680
https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_goto/7

Note : Ignore to use this options.
And last options is $_SESSION variable. you can store your data in session and after  getting data from session in your destination page you unset that particular  session data.


Your code is using the string concatenation operator with an array; you need the assignment operator.

$rows[] = array($record->nid, $record->title);

$headers = array(t('node'), t('Title'));
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

return theme('table', $headers, $rows) . theme('pager');

Depending from which function contains that code, it could also be re-written as follows:

$page = array();
$rows = array();

$nodes = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->extend('PagerDefault')
  ->limit(5)
  ->execute();

foreach ($nodes as $node) {
  $rows[] = array($node->nid, $node->title);
}

$page['table'] = array(
  '#rows' => $rows,
  '#header' => array(t('Node'), t('Title')),
  '#theme' => 'table',
  '#empty' => t('No content available.'),
);

$page['pager'] = array(
  '#theme' => 'pager',
);

return $page;


Is is it possible to set an expiry time on the cached version of each node individually in a Drupal 6 website?

Check out Scheduler.

From the project page:

  This module allows nodes to be published and unpublished on specified dates.

What are some examples of factors for expiry date?