Why is access to some of my product displays denied for anonymous users?

I have the same problem. It`s because product entity was unpublished.
After publishing entity all warks correct.


How do I show the username field in the user edit form?

Go to admin/people/permissions and select the Change own username for the roles you need to be able to change their username.


Alternative:

Use the Panels module to get the ability to create "Mini-panels" which function as equivalents to the standard Drupal block.

I believe there is much better support for exporting mini-panels into Features, since exportability was a key design component for the Panels module.

Personally, I've been successful using Panels, mini-panels, and Features.


How do change address field titles to another language in Ubercart?

Installing the Ubercart translation solves the issue. Import the file using the Interface Translation module.


Flexslider views messing up my other images styles

You need to remove a flexslider css style:

.flexslider .slides img {
display: block;
width: 100%; }

The width setting is messing your brands up.


How do I get a new database connection with a new setting?

I like your gutsy move in this regard.
I wrote about changing innodb_flush_log_at_trx_commit in the DBA StackExchange

Feb 10, 2012 : Is it safe to use innodb_flush_log_at_trx_commit = 2
Mar 08, 2012 : What are some key configuration settings for using an InnoDb table for session storage?
Dec 07, 2012 : Dynamic change to innodb_flush_log_at_trx_commit

I also wrote about tuning InnoDB for better INSERT performance

Jul 04, 2012 : Capabilities of InnoDB INSERT Performance

EPILOGUE
You have the right idea. You should experiment with this on a Staging DB Server (load data, test drive the setting, kick the tires)
Note the difference between setting innodb_flush_log_at_trx_commit to 0 and 2

Setting to 0 : any mysqld process crash can erase the last second of transactions. The log buffer is written out to the log file once per second and the flush to disk operation is performed on the log file, but no writes are done at a transaction commit.
Setting to 2 : only an operating system crash or a power outage can erase the last second of transactions. The log buffer is written out to the file at each commit, but the flush to disk operation is not performed on it. Before MySQL 5.6.6, the flushing on the log file takes place once per second. Note that the once-per-second flushing is not 100% guaranteed to happen every second, due to process scheduling issues. As of MySQL 5.6.6, flushing frequency is is controlled by innodb_flush_log_at_timeout instead.

Based on this difference, you have to decide who do you trust flushing data, the Operating System or the mysqld process. Using 0 leans in favor of mysqld. Using 2 seems to be OS oriented.


How to create a dropdown list with node ids?

To get all the nodes ID's for a content-type, you can use EntityFieldQuery and node_load_multiple:

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mycontenttype')
  ->execute();
$nodes = node_load_multiple(array_keys($result['node']));

If you are using FAPI (form API), you can populate your dropdown list with these values easily.

Unfortunately, I can't help with the last part (displaying the node under the form).


I had similar, work to be done, in drupal 7.

So, what I did, is, I collected the breadcrumb title, like this,

$bread = drupal_get_breadcrumb();
$title = $bread[0];

$lastCharacter = substr($title, -1);

$lastCharacter gave whether the breadcrumb title ends in S or not. If it ended, then, I appended, (')at last otherwise, I apended, ('s).I did this by adding a function in template.php file. Also, you can do by making any module, or any other way you wish.


How to create user input dependent form elements?

Yes it is possible and quite easy. Read up on the #states value in the drupal form api documentation. I am assuming this is for Drupal 7...


From a permission point of view, (instead of groups) these are called "roles" in Drupal. (From a content-user-access point of view there is the Organic groups module, but that's another story.)

You can administer roles at admin/people/permissions/roles. You can mass assign users to roles at admin/people (Update options - Add a role to selected users).

All registered users automatically have a role called "authenticated user", so there is no need to duplicate that functionality.

For more info check out "Managing access control with permissions and user roles" at
https://drupal.org/node/22275


I currently am caching the result using cache_set()/cache_get() inside the hook_field_formatter_view function for my field

Honestly this is not a bad way to go about doing it. When you have custom logic which is resource intensive, taking responsibility for your own caching decisions is usually the right idea. Honestly, I really wish more developers would familiarize themselves with cache_get/set().

Entitycache appears to be an effort to do this generally, and over time I am sure that some best practices will emerge as more people work in this space. However as of today, for anyone looking at a similar problem-set: "Figure out how to cache it yourself" is a good answer.


I found a solution to my problem it can be done by passing information through url as said here


The error is in your php snippet. You request all rows, but $query->fetchObject(); only returns the first one, as you do not iterate over them.
Use something like $query->fetchAll() or $query->fetchAllAssoc('domain_id'); instead to access all rows.

But, I think there must be smarter ways to handle this. Can't you add a relationship from the node to the domain? (I never used domain before). Such relationship would give you the domain entity associated with the node, so you always have the right one.


translate drupal commerce product titles in views

Found a solution. I rewrote the results of the Commerce Product: Title Field and used the replacement pattern [title_field]. The translation then showed correctly.


Create version of site with no header/menu?

What I ended up doing was having a subdomain "simpleview.example.com". Since I was already using the built in multisite, it opens up the same structure as "www.example.com" by default and all the links still work as they are relative. I then added a CSS file that would only show up if it was the simpleview subdomain (using the $_SERVER variable to get the URL) and made the elements I didn't want hidden with {display:none}.

Not sure if this is the best way to do it, but it got the job done without too much trouble.


Which drupal hook to implement to react on module installation?

You should do it the other way around.

When your module is enabled, it should check for other modules that has implemented it's hook and call them to build up the cache you need.

Then you could create an API function for other modules to call when their module is activated.

It makes more sense to build it like that. You never know when the cache is reset anyways, so you can never rely on having a complete cache data all the time anyways.

Another solution would be to build the cache when it's needed. It doesn't make sense to build the cache data before it's actually needed. The normal thing to do with cache in drupal is to check if the cache data is there, if it's not create it and save it in the cache for next time. That would spare you the headache of trying to know all.

To answer your question, there is to my knowledge not a way to hook into the process of modules being installed / enabled.

Update:
For Drupal 7 there have actually been created a hook to react on modules being enabled: hook_modules_enabled()


How do I add just one extra node to a view? Display OG contents plus OG group node

Took me a while but eventually solved this....

Needed to add

$query->group_operator = 'OR';

into my hook_views_query_alter.


When term is not selected, output specific text

You can use DDF module to implement this.
Module url is https://www.drupal.org/project/ddf


Optional multiselect field, hide the - None- option

To get rid of "- None -" from selected field of a selected form, use:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

Of course for many fields it's inconvenient, but if they all share common parent (fieldset), you can iterate using foreach like:

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    foreach( element_children($form['fieldset_name']) as $key => $child) {
       unset($form['fieldset_name'][$key][LANGUAGE_NONE]['#options']['_none']);
    }
}

This is not a ready code, just a sketch. Hints to make it work:

Unset elements of original $form, not $child generated by foreach.
Test if what you want to unset is there at all.
dpr() or var_dump() to see what's the exact structure you are working with.

You will need to wrap these into a Drupal custom module. Read Module developer's guide, especially Creating Drupal 7 modules, and hook_form_alter() API reference if you need more backgroung.

Inspired by this answer.


The homebox module makes that reasonably easy to do, worth a look: https://drupal.org/project/homebox
Details from its project page:

Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.
Homebox is currently used on Drupal.org for the 'Your Dashboard' feature.


Multilingual menus: logic and architecture

It seems to be impossibe to have one multilingual custom menu in Drupal 8.0.

What you have to do is to create one menu per language. You specify the one language of the menu as you show in your image.

Then in blocks you place all your menus in the same place. Here you can choose which menu is chosen for which language.

This is far from elegant, since you have to edit each language separately without a translate button. But apart from being a cluttered process to create, it works nicely.


For some "object" there is.

on admin/reports/fields you find a list of every field, with type and machine name
on admin/structure/types you find a list of every content type, wth machine name

and so on for views, rules and any other "object".

If you need a "report" you could use Views, o make a directly a query.


How do I programmatically log in a user with a POST request?

Staring from 8.2, Drupal supports json endpoints for Cookie authentication. You don't need to post the form anymore

curl --header "Content-type: application/json" --request POST \
  --data '{"name":"admin", "pass":"admin"}' \
http://drupal.d8/user/login?_format=json

Output will look like

  {"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}

Change record: https://www.drupal.org/node/2720655

Other authentication methods: https://www.drupal.org/docs/8/core/modules/rest/using-other-authentication-protocols


Both of the below formats should work,

function my_header_block_info() {
  return array(
    "headers" = array( //I have Replaced => with = on your code
      "info" => "Header Block",
      "cache" => DRUPAL_NO_CACHE,
    ),
  );
}

-----OR-----

function my_header_block_info() {
    $blocks = array();
    $blocks['headers'] = array(
        'info' => 'Header Block',
        'cache' => DRUPAL_NO_CACHE
    );
    return $blocks;
}

Make sure to clear the cache after updated your code.


How can I ensure automatically that a module is disabled on my live site?

You can hide modules from the admin UI by using the hidden property in the module's .info file:

hidden = TRUE

This method might be useful if you want to make sure the module is never enabled via the UI.

In case you're interested in how to do the opposite (stop a module from being disabled), it's also done in the .info file by setting the required parameter:

required = TRUE

Once you've done that Drupal will see the module as a 'core' module and stop it from being disabled through the admin UI.


Remove node_access check from content revisions view

In the hook_views_query_alter is possible to alter the query tags. Unfortunately, the method tag_remove is not present, but the $tags variable is public, which allows us to do:

function yourmodule_views_query_alter(&$view, &$query) {

    // Disable Node Access check for myview
    if ($view->name == 'myview') {
        $view->query->tags = [];
    }
}

I hope this will help somebody who needs unrestricted Views (e.g. for Services).


Using Drush on a Drupal 8 site installed via Composer

Acquia Dev Desktop comes with Drush included, and I assume that you could just continue to use that for Drupal 7. However, since you installed Drush Launcher and are using it as drush (drush.bat), you are shadowing it. Break the shadowing by renaming one of the two.


Drupal's implementation of menus is a bit special, It doesn't always work the way it seems it should.

You can take a look at the core implementation of template_preprocess_page() to how the Main Menu links are added as a variable to the page template. You have to drill down a bit in the API docs, but the function you want to call in your implementation of theme_preprocess_page() is menu_navigation_links(), which will return an array of links in the menu.

Looking at line 106 of Drupal core's page.tpl.php file, you can see how the main menu links are themed in the template by calling the theme() function with a hook of 'links__system_main_menu'.

Theoretically, this implementation should be able to be duplicated with a custom menu by following the standard naming conventions. So, in template.php, you could have:

function THEMENAME_preprocess_page(&$variables){
  $variables['custom_menu'] = menu_navigation_links('menu-custom-menu');
}

function THEMENAME_links__menu_custom_menu(&$variables){
 //custom theme function here
}

and in page.tpl.php, you would add something like this:

<?php print theme('links__menu_custom_menu', array('links' => $custom_menu, 'attributes' => array('id' => 'custom-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Custom menu'))); ?>

However, adding the custom menu as a variable on your page template is not necessary. You could easily place the custom menu's block into a desired region via the Drupal admin interface.  Also, you could change the site's settings for the Main Menu source, effectively replacing the default $main_menu variable in page.tpl.php with your custom menu.

EDIT: I am just seeing your addition about your end goal being to just add some custom html to the menu items for icons. Depending on how you are adding these icons, there are a couple different Drupal module options.

Menu Icons - allows you to upload an image via the Menu item's settings and automatically generates CSS (customizable via a template) that adds the image as a background on the menu item.

Menu Attributes - allows you to add a custom class to each menu item via its settings in the admin. Once a unique class is added to each menu item, you could use CSS to add an icon to the menu item or use javascript to inject the additional HTML into the menu item.


change fields in content type after creation

Have you tried to peek inside a database via PhpMyAdmin ? For every field you have field_data_field and field_revision_field table, containing several columns depending on the field type. And also some config tables like field_config and field_config_instance, so many things to be aware of.

This is more an advice than a clear answer, meddling with database may be risky task.

But I do understand if you have large data collections, you might try to risk to hack database to convert to other field type.

Beware that field tables may be referenced by other tables / modules, so backup your db first and test on clone.


Accidentally deleted sites/all/modules in Drupal 7

Assuming the backup files you have are the same as the ones that were deleted, that should be fine.

You'll probably want to flush the cache but other than that there shouldn't be any problems in theory.


How to use mysql queries in Action in a Triggered Rule?

First off, you should be using the drupal SQL coding conventions:

db_query instead of mysql_query
db_fetch_array instead of mysql_fetch_array

I would structure the query like so:

$query = "SELECT field_codigo_value
          FROM content_type_inmuebles_en_venta
          SORT BY field_codigo_value
          LIMIT 1";

$result = db_query($query);

return $result;

You should know that triggered rules allows you to pull a value out of the database without writing a custom query. We need a bit more context as to how this node is related to your triggered rule, but I would guess that you can load the node that you just created or load a referenced node to the node that you just created and then use the available tokens to fill in the CCK field that you need filled in.


How to display registration form fields based on the taxonomy term?

On Drupal 7 you've a new API named State API. You can use it to hide or show your fields.


How to pass query parameter in form submit?

Stick with your original route definition:

mymodule.word:
  path: '/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

Then set your submit handler to this:

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

  $data = $form_state->getValue('edit');
  $url = Url::fromRoute('mymodule.word', [], ['query' => ['word' => $data]]);
  $form_state->setRedirectUrl($url);
}


Please note this path('node/custom') actually doesn't exist in Drupal System.

Whenever we create using admin a menu it asks for a valid path otherwise it shows error of Url doesn't exist. So probably it enters the data in database directly but will not be listed in the admin unless it has a valid path assigned.

Please try by adding a page, e.g node/1 to the path and then try.

$item = array(
'link_path' => 'node/1',
'link_title' => 'Custom Title 001',
'menu_name' => 'menu-custom-menu', // Menu machine name, for example: main-menu
'weight' => 0,
'plid' => 0, // Parent menu item, 0 if menu item is on top level
'module' => 'menu',
);
menu_link_save($item);

and make sure node/1 exists in the system.

Hope it will help you.


How I can change the value of a commerce product field after Completion process?

Preface: I'm assuming this question is about D7.

Create a custom rule (using the Rules module) like so:

Rules Event: checkout completion event.
Rules Condition: entity has field, for the field with machine name "field_prodstat" (which will make that field available as a token you can select in subsequent Rules Events and/or Rules Actions).
Rules Action: set a data value, for the field with machine name "field_prodstat".

Update

Below is an attempt to also address your comment below this answer, the relevant part of that comment is like so:

  I have a content type called "Appointment". When that appointment status = "Accepted Pending Payment" I created a rule to build a new product for that "appointment". So now I have a product related to that appointment. I just want to update "Appointment" status to "Paid" when his product appear in an order with status = invoiced. I don't know if you have any other proposal to do that.

That comment starts revealing your real question, which is pretty different from your original question. To answer your real question is not something that can be explained in just a few phrases. I suggest you have a look at the video tutorial about Removing Items From the Cart Using Rules which demonstrates a scenario which is pretty similar to what you're asking for (in your extra comment). Here is part of what is shown in that video (quote is from that link):

  Create a rule that loops through all the line items when the order is about to be saved. Have it call a component (rules subroutine) for each line item to see if that line item should be removed.
  Create the component that does the work. It needs to take two arguments (line item and the order-about-to-be-saved).

To make this also work for your case, I think you'd be close if you only replace the last Rules Action in the used Rules Component by a Rules Action that applies the update you're asking for in your comment.


view exposed filter ajax error coming for non administrator user

Go to Views Ui Setting Tab on Advance and uncheck Javascript ...
it's Work for me


Drupal Views rewrite link dependent on boolean value

I finally got it to work as follows:

PHP field, Value Code:

return $data->field_field_booleanval[0]['raw']['value'];

Output Code:

<?php
  print_r($value);
?>

This returns the correct VALUE for the boolean field. So you can skip the Value Code unless you plan on using the variable elsewhere, and output could look something like:

<?php
  $booleanval = $data->field_field_booleanval[0]['raw']['value'];
  $fileval = isset($data->field_field_file[0]); // shouldn't be set if no value

  if($booleanval) {
    echo 'Link';
  }
  else if(!$booleanval && !$fileval) {
    echo ' ';
  }
  else {
     echo $row->field_file;
  }
?>


How to make Posts/Blogs mentioning a user appear in the user's profile?

Step 1

Use the Message module to create "Messages" each of those mentions, similar to what is detailed in the answer to "How to get notifications in a new window when using the Mentions module?".

Step 2

Perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user'.
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module).

Notes:

Consider Step 5 as a bonus: whenever a new message gets created, the user gets a shiny notification in the format of an iOS-like (red) badge with the number of unread mesages.
No custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).


Translation "Global: Text area" in views footer

Use PHP instead of text area, make the strings translatable by using t('MyString').

Update: usign PHP is not a recommended practice... Probably you could have a template for that view.
and inside a string inside t('My String')... Then you can use the translation interface.


Anonymous users unable to download purchase

You have disabled the rules for creating an account for the anonymous user.
Therefore, the license never gets assigned to an actual user, stays assigned to user 0.

Commerce License and Commerce File were designed to license the file to an actual customer. I suggest either re-enabling the rules and creating the user accounts or developing a custom solution for the file downloads (you don't need most of commerce file if there's no actual user... just a temporary file link).


Differences between 'Add existing field' and 'Add new field'

Add new field is used to create a new field; Add existing field is used to connect the existing field with another content type.

I don't think it's a big difference but it's a good option for developer to attach their fields to other content types. For existing field, after you have created the new field, you can attach that field to multiple content types.

See also When should I use an existing field?


Easiest way to add a custom class to a block would be to override the default block.twig.html twig template within your theme.

You'll need to copy the above file from /core/themes/stable/templates/block into your custom theme using the same directory structure.

**  NB don't edit the file found in core directly!! This is bad practice and you'll lose any changes when you upgrade Drupal core. **

Clear the cache and you should now be able to edit the block template file and customize it.

Then, to load CSS, you must define an asset library. You can then load that asset library using {{ attach_library('mytheme/special-block') }} in your Twig template (assuming the theme is called mytheme and the asset library special-block).

Helpful links:

Working with Twig templates
Template naming conventions
Debugging Twig templates
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


View listing page/block relationship configuration

Ok, so Content using field_course_reference (Relate each Content with a field_course_reference set to the content.) was used and required and then Content using field_course_offerings (Relate each Content with a field_course_offerings set to the paragraph.) was used and required using the first relationship.

This ended up allowing me to filter out and only display courses that had an available offering using Content: Course Reference (field_course_reference) with an operator set to Is NOT empty. I was also able to get the other two filters required to work.

However, I still have an issue where instead of just showing the course once, it displays it as many times as course offerings it has. So say that I have 5 different times the course is offered (The Part-Time Offering [Paragraph] allows for unlimited offering choices), it ends up listing the same course 5 times on my page.

Is there any way for the view to only display each course once, disregarding how many offerings are available for each course?

EDIT: Found the answer to the above. Once I turned on aggregation in the advanced settings, it only displayed each Course once.


Counting the number of rows returned from db_query() with the "SELECT" statement

If you look at the db_result() documentation for Drupal 6:

function db_result($result) {
   if ($result && mysql_num_rows($result) > 0) {
    // The mysql_fetch_row function has an optional second parameter $row
    // but that can't be used for compatibility with Oracle, DB2, etc.
    $array = mysql_fetch_row($result);
    return $array[0];
   }
   return FALSE;
}

I also saw that you could do this in Drupal 6:

$num_rows = db_result(
  db_query("SELECT COUNT(*) FROM {node} WHERE type = '%s'", $type->type)
);

It looks like you could simply do:

// Execute your query.
$result = db_query($your_query);
// Use mysql_num_rows() on the result set.
$num_rows = mysql_num_rows($result);


In your title field deselect "Link this field to the original piece of content"
select "Rewrite the output of this field"
add two fields "Content:path" *"Global:Custom text"* and hide them from display by selecting "Exclude from display "
In the Global:Custom text field select Rewrite the output of this field and enter lightframe[|width:800px; height:600px; scrolling: auto;]
Go inside your title field again. Look under "Replacement patterns" for [view_node] and build up your link. Make sure the two fields Content:path and Global:Custom text are arranged before your title field or else you wont be able to use them.

Your link should look something like:

[title]


How do I instantiate a custom class with dependency injection?

A class implementing ContainerInjectionInterface is instantiated by calling the factory method create().

See Drupal\Core\DependencyInjection\ClassResolver

/**
 * Implements the class resolver interface supporting class names and services.
 */
class ClassResolver implements ClassResolverInterface, ContainerAwareInterface {
  use DependencySerializationTrait;
  use ContainerAwareTrait;

  /**
   * {@inheritdoc}
   */
  public function getInstanceFromDefinition($definition) {
    if ($this->container->has($definition)) {
      $instance = $this->container->get($definition);
    }
    else {
      if (!class_exists($definition)) {
        throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $definition));
      }

      if (is_subclass_of($definition, 'Drupal\Core\DependencyInjection\ContainerInjectionInterface')) {
        $instance = $definition::create($this->container);
      }
      else {
        $instance = new $definition();
      }
    }

    if ($instance instanceof ContainerAwareInterface) {
      $instance->setContainer($this->container);
    }

    return $instance;
  }

}


Getting node view mode in field preprocess

In a field template the view mode is stored here:

$variables['element']['#view_mode']

So you could check in preprocess, if the node is not displayed as teaser:

function MY_THEME_preprocess_field(&$variables) {
  if ($variables['element']['#view_mode'] != 'teaser')  {
    // node is not displayed on the front page
  }
}

The same condition in a field twig:

field.html.twig

{% if element['#view_mode'] != 'teaser' %}
  node is not displayed on the front page
{% endif %}


DS uses it's own templates. Go to admin/config/people/accounts/display, then scroll to the bottom and DS will show you which templates you can use to overwrite the output.

In the example below there are 2 suggestions. Hope this helps you out.


How to load content on different domain with jquery .load()

You can use a local PHP script to pull the external data. Then use AJAX to show it in a block.

      // ajax call to a php script
      $.post("/sites/scripts/my_script.php",
        { "post_parameter" : "post_value" },
        function(data){
          // put the result into a div
          $('#result').html(data);
        }
      );

Then again if you only want to display an external website, you can use an <iframe>.


Regarding menus for authenticated users only

What I usually do is:

Install and enable Taxonomy Access
Create a vocabulary called Access
Create 2 terms in the new Access vocabulary: Public and Private
Attach the term reference fields for Access vocabulary to each node type you wish to protect. You may want to set the default value to "Public".
Go to Taxonomy Access configuration page and set D (deny) View access to Anonymous users on Private term. Leave the rest of the options (update delete view tag etc) I (ignore).
Configure the access control for Authenticated users and set A (allow) View access to Authenticated users on Private term, and set I (ignore) for all else.
Now all you need to do is set Private on nodes you wish to protect, and set Public for all else.


If I understood you right. I had some similar task in the past. I had form of all product variations in the table with textbox inputs for quantity. And they must be added multiple to cart.

The main function is commerce_cart_product_add_by_id($product_id, $quantity);

What I did:
I created custom field formatter for "Product reference" field and rendered it as table of variations with text inputs for quantity.
And on form submit I loop all products in foreach and add them to cart.

But if you don't want to create additional formatters there is another solution.

You can use your hook hook_form_commerce_cart_add_to_cart_form_alter()
Render form elements for all your product variations there by custom code.
Replace form submit with your custom submit
Add products to cart in custom submit (call commerce_cart_product_add_by_id() in foreach).

Also you can write your text VariationID:LineItemOption:Quantity[_repeat] into some hidden textfield element. After submit you'll read this text in $form_state


A combination of following modules would do what you want

Media

  The Media module provides an extensible framework for managing files
  and multimedia assets, regardless of whether they are hosted on your
  own site or a 3rd party site - it is commonly referred to as a 'file
  browser to the internet'.

  Media is a drop-in replacement for the Drupal core upload field with a
  unified User Interface where editors and administrators can upload,
  manage, and reuse files and multimedia assets. Any files uploaded
  before Media was enabled will automatically take advantage of the many
  of the features it comes with.

Media: YouTube

  Media: Youtube integrates with the Media module to make Youtube videos
  available as file entities.

  Users can add Youtube videos to their site in a file field or insert
  them into a WYSIWYG area by pasting the video's URL into the media
  browser web tab. Formatter options are available to customize the
  Youtube player's appearance, show the video preview image, and enable
  the Javascript API. The 2x branch is under active development and uses
  the Youtube iframe embed that can serve HTML5 videos to mobile
  devices.

Media Mover

This is the module that would do what you have asked. I have highlighted the point you have asked

  Media Mover is a set of modules which allows website administrators to
  easily create complex file conversion processes. The core of Media
  Mover is the media_mover_api module which creates a set of rules
  allowing multiple modules to interact with a file. Media Mover can
  take a file emailed to an email account, turn a file attachment into
  an FLV file, create a new node with the file data, and then save the
  file on an external file storage system like Amazon's S3 all at once.
  And that's just the start.

  What you can do The core set of Media Mover modules offers lots of
  options for someone manipulating rich media.

  get attachments from an email account
  get attached files from nodes of a specified type
  get files from previously harvested files
  get files from CCK filefield and imagefield fields
  get files from a FTP server, provide file tokens for user authentication as well
  create a thumbnail from a video file with ffmpeg
  transcode video files into web friendly (and other) formats
  compress a file with zip
  move a file to Amazon's S3 service
  attach file back to node
  save file and related data as a node
  add a file to a CCK filefield or imagefield
  save a file to YouTube


How do I render the view of an entity reference?

Views are config entities, and as such not rendered like content entities. When you reference a config entity, all you get out of the box are two formatters that can render data which all config entities will definitely have: An ID, and a label.

You need a formatter that knows how to render a View display rather than the View entity itself. Core doesn't come with one unfortunately.

You could write your own easily enough, but as already mentioned in the comments there's the Views Reference Field module which will provide the functionality.


You probably have not defined your theme hook in hook_theme().

The Using the theme layer section of the Development handbook has an in-depth discussion about this.


Content:author Relationship Not Showing Fields for Comments View

You need to filter for a User fields if I understand correctly (i.e. you want to display only comments on the current node when the node author has a certain role).

Select User: Roles as the filter and make sure the Relationship select box is set to the identifier for Content: Author. That will let you filter the comments by the node author's role.


Override default language via URL parameter

It's been more than a few years since I've done this in Drupal 6, so things may be a bit vague and hazy. I do remember there being an order menu for this, where you could say that language gets selected first by cookie, then browser language, then user preference, then path prefix, or change the order entirely.


Output your $vars in the theme so you can see your candidate templates.

EDIT: I thought you were looking for a content type solution when I first read this :)

Here's a gotcha:
you have to have master templates before you can have ones within it. For example content-field-field_my_content.tpl.php will not work until content-field.tpl.php is in place in the theme.

You may need to place some PHP in your template.php within preprocess_page()

if(!arg(2)) $variables['template_files'][] = 'page-node_'.$variables['node']->type;

(The arg2 check helps make sure this doesn't happen on edit pages.)

Lastly, you can also accomplish this with Context Layout.


D7: Newsletter type project.The articles are grouped in a set (newsletter) published on a regular basis

IMHO if your newsletter isn't meant to be emailed, the easier solution is using views with a filter on the date of nodes + a module that gives you the pdf display, like Views_PDF.

Then if you want to send your issues by mail, you may extend with Views pdf mime mail to attach the exact pdf to your mails, but it's still under development and I'm not sure if it works.
Please consider than whenever you talk about email newsletters, probably the most complete solution is still Simplenews and its submodules. If I were you, I would use Simplenews Scheduler + Insert view, like I did in a similar situation [D6].

Hope it helps


It uses the Responsive Bartik theme. I can see from the CSS that it uses CSS media queries and from the project description that it uses JavaScript (Html5shiv, Respond.js and Selectivizr.js).


Why is my theme's block preprocess function not reordering elements?

I figured this out. Drupal can be so infuriating when you are new to it.

The rendering of the search_form_block was happening in a template function file:

bootstrap-search-form-wrapper.func.php.

containing:

function bootstrap_bootstrap_search_form_wrapper($variables)

The function customizes the rendering of the search form by calling out elements specifically - thus ignoring '#weight'; the wrapper function is part of the bootstrap theme.

The solution is to overwrite the bootstrap theme function with a similar function in our child theme: function mytheme_bootstrap_search_form_wrapper($variables)

o.O

Hopefully this helps someone.


How to decide between module_exists and function_exists?

You should always program to the API and not the implementation.  If Drupal provides a mechanism to do something, use it.

module_exists() should almost always be used for soft dependencies on something provided by a Drupal module.  You can always get version info, and decide what to do, using system_get_info().  There have been cases where functions are available when modules have been disabled (some of the class autoloader modules have has this problem).

function_exists() should be reserved for checking whether a PHP feature or library is available.  Core has some examples of this in some of the drupal_ wrappers for string manipulation and character set conversion.


Move XML once they're processed in Feeds

You can use hook_feeds_after_import to move xml after successful import.

/**
 * Invoked after a feed source has been imported.
 *
 * @param FeedsSource $source
 *  FeedsSource object that describes the source that has been imported.
 */
function hook_feeds_after_import(FeedsSource $source) {
  // See geotaxonomy module's implementation for an example.

  // We can also check for an exception in this hook. The exception should not
  // be thrown here, Feeds will handle it.
  if (isset($source->exception)) {
    watchdog('mymodule', 'An exception occurred during importing!', array(), WATCHDOG_ERROR);
    mymodule_panic_reaction($source);
  }else {

        // You can write here you own code to move xml.

   }
 }


give permission of create new revision to specific roles

permissions (minimum):

  node:

  View published content

  View own unpublished content

  View content revisions (optional)

  [content type]: create new content

  revisioning:

  [content type]: view revisions of own content

For content types, in its edit UI:

  Publishing options: Create new revision, New revision in draft,
  pending moderation (requires "Create new revision")

if you want to do it with Drupal core only, then this will suffice:

  node:

  View published content

  View content revisions (otional)

  [content type]: create new content

For content types, in its edit UI:

  Publishing options: Create new revision


You should be able to make the distinction by checking $form_state['triggering_element']:

switch ($form_state['triggering_element']['#name']) {
  case 'select1':
    // Do something
    break;
  case 'select2':
    // Do something
    break;
  // ...
}


Views 3: Getting related content from node ref field

Your question is not quite clear whether you want to show band information when viewing a band-story node or to show band stories when viewing a band node. I'm assuming it's the second one.

Create a View with "Content" under "Show", and choose "Band Story" as the node type.

Clear the check box to create a page or make a block if you want. That's up to you:
Save and continue to Views UI.
In the Views UI, make sure you have 2 filters added - Node is published, and the node's type is Band Story.
Default sort criteria would be "Newest first". Change it if you want.
Add a new contextual filter.
In the add contextual filter, choose the field that refers to Band node. This field should be in the Band Story node type.
Add the argument. You will get the argument's settings page.
Under "When the filter value is NOT available", choose "Provide default value". Under "Type" select list, choose "Content ID from URL".

You can optionally add a validation criteria if you allow the node reference field to refer other node types than "band" as follows.

11.  That's it! Save the View and put the block (you have to give a name to it) in the sidebar (or anywhere else). it will inherit the current node's ID and will show Band Story nodes that have this node ID in its node reference field.


When you click on a field or a setting. At the very top, you need to use the For "override" option. (select This [view type] override) so it only affects your current view.


Filter nodes matching user account field [list (text)] using different field names but same key

I don't think there is module to do a filter that compare 2 arbitrary value but you can add a php filter using Views PHP module

Then, you can create a PHP filter in your view.
Someone write an example that is quite similar to what you need : https://drupal.stackexchange.com/a/44100/36824


upgrading from D6 to D7: Is lower version updated required?

It is strongly recommended that you upgrade to the latest version of Drupal 6 before trying to upgrade to Drupal 7.  Make sure you read the text under "MAJOR VERSION UPGRADE" in the file UPGRADE.txtthat comes with Drupal 7 - it is also online.  You should be able to go from where you are directly to the latest Drupal 6 version (currently 6.27) - there is no need to go through intermediary minor versions.  And you can go directly from the latest Drupal 6 to the latest Drupal 7 (currently 7.18).

Before you start, disable and uninstall all contributed modules you don't need. Also disable and uninstall all modules (such as CCK) that say upfront that no upgrade path exists. If a module offer an export/import feature (e.g. Biblio), then use it.  Export all content from Drupal 6, then disable and uninstall the module.  Reinstall the module and import the data when your Drupal 7 configuration is stable.

For all contributed modules that remain installed at this point, make sure you upgrade them to their latest stable Drupal 6 version before you start.

Also make sure you make a backup of everything before starting.  You may have to go through the upgrade several times. In your first attempts you will discover contributed modules that break your site when you upgrade. You must disable and uninstall those, and then try again.  Repeat as many times as necessary.

Depending on the complexity of your site, you may want to fasten your seatbelts.  It's going to be a bumpy night.

Upgrading a stripped core configuration is fairly painless.  But not all contributed modules has a (working) upgrade path.  In particular, if you've used CCK, expect that some data does not make it into Drupal 7 automatically.  (I ended up writing my own DB conversion scripts using flat text files as intermediaries - and in some cases: scraping content and pasting it back into the upgraded site).


How to make a Views Filter criteria based on another language version existing?

Answer: https://www.drupal.org/project/select_translation. It does exactly what I need and much more.


How to allow the translation of menu links provided by my_module.links.menu.yml

Ensure you visited a page with these menu items at least once in the target language before trying to translate them at user interface translation. They need to be picked up first before appearing there and can only then be translated like any other UI string.


I didn't think there was a module, but I found one. Take a look at this module. From the project page:

  Face Detection module uses the jQuery Facedetection library to provide
  an image viewer jQuery plugin.

  It only has been tested on Chrome, Firefox 3-8, IE 9


How to apply a function to the title of a teaser made with display suite?

If you added the title as a field in Display Suite, I'd recommend you look at the field functions of Display Suite.

You may use a Code field, but I'd discourage that.

Rather remove the title from the display, then add the truncated title as a new field in the preprocess function, ie:

$variables['new_title'] = truncate_utf8($variables['title'], 48, TRUE, TRUE);

Then add a new preprocess field to display suite, using the exact same name as the new field, ie:

new_title

You can then place this new field in Display Suite.


The only special thing I see there is getting the effective URL, which is actually something that was specifically added back to Guzzle 6 for Drupal: https://github.com/guzzle/guzzle/issues/1166

See \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher::fetch:

  /** @var \Psr\Http\Message\UriInterface $actual_uri */
  $actual_uri = NULL;
  $response = $this->httpClientFactory->fromOptions([
    'allow_redirects' => [
      'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
        $actual_uri = (string) $uri;
      }
    ],
  ])->send($request);


You could use hook_menu_alter(). Something like this should work:

function yourmodule_menu_alter(&$items){
  $items['user/%user_category/edit']['access callback'] = 'yourmodule_user_custom_access_function';
}

function yourmodule_user_custom_access_function($u){
  return user_access('administer users');
}

This way, only users with "administer users" permissions will be able to edit user informations.


I found and article explaining how to theme the node form here (http://batayneh.me/post/theming-node-forms-drupal-7). To solve the other part of your question - Only people who pay can use the "create content" you can create a new role and specify that only users with the new role can create content.


Output the total number of rows in a view

You can add a custom section to either the header or footer to do this.

Edit the view / display.
In the center section, click Add next to Header or Footer.
Choose Global: Result Summary.  Add it where you need it.
Then, edit the textarea to be the format that you need.  There are a bunch of tokens available for building up the numbers.
Preview the view, and then Save if everything is OK.


Display a view inside a field collection with eva

After thinking outside the box a bit, the answer lies in setting the contextual filter to accept the "field collection item" id using the appropriate relationship (not the field collection item entity).


Required Fields with unlimited field collection items

I faced This bug in field collection module ( really I didn't find out why they do this :(  ). There is no way to achieve this ( have unlimited and required fields in field collection ).
You just achieve it trickly . (set it unlimited and none-required) . use jquery for validate( checking filled )  fields.

This problem almost accures when you don't want set default value for field .(if you set default by any edit add a waist item  ).


View not displaying correctly for all visitors

Okay, this may or may not work...but...lately D7 has a similar issue.

If you select the view, and click the link "settings" under "Query Settings", you can make the view appear by selecting "Disable SQL Rewriting". There is a security risk, and this issue needs to be solved, ex-post-haste, but it works.

This has been an issue with every View I have seen of late, provided all your permissions are legit.


Changing Drush make default subdir for install profiles

I just tested this and the following works:

projects[my_install_profile][subdir] = ""


There is some discussion in several places about this, including an issue in the Composed Field issues queue.

The module author writes;

  I haven't investigated the mechanics behind it but theoretically all that needs to be done is to somehow implements the process that those modules do on retrieving the field value from the database and then unserialize and concatenate the retrieved value.

The problem of course with storing serialised data is the inability to effectively query it using any type of relational db (No indexes.)

You can always build a query using a LIKE on the serialised data ...

WHERE field_one-composed LIKE '%query%';

But that's horrible. :(

My comment on the initial question stands; do you want to achieve this using the GUI or through code? I'll update this answer based on your response.

While I appreciate this is not the question, I'm curious about why you chose this module for your use case?


How to restrict ckeditor to display full html alone?

You can install the Better Formats module to achieve this.

Better formats is a module to add more flexibility to Drupal's core input format system.

  Features

  8.x & 7.x (needs more testing for a stable release)

  Set allowed text formats per field.
  Set default order of text formats per field.
  Hide format tips per role.
  Hide more format tips link per role.
  Hide format selection per role per entity.
  Currently only works on Field API fields on fieldable entities implementing core - style text processing. The good thing is that is
  most things in core and contrib.

This will let you limit what format is available per field implementing formatted text, like a body field.

Despite what the warning says, I have used this extensively on many sites to do exactly what you asked about.


Set parent for programmatically created menu links

Turns out when setting the parent you don't use the id of the menu_link_content you use the 'menu_link_content:' followed by the uuid of the link. Here's an example of a properly formatted parent field.

  'menu_link_content:0025c274-4db3-4745-b51e-714c998b5a50'

I fixed the code like so

    foreach ($items as $id => $title) {
        if ($id == '2') {
            $parent = 'menu_link_content:' . $previous_menu_link->uuid();
        } else {
            $parent == NULL;
        }

        $menu_link = MenuLinkContent::create([
            'title' => $title,
            'link' => ['uri' => 'internal:/node/' . $nid],
            'menu_name' => $menu_id,
            'expanded' => true,
            'langcode' => $langcode,
            'status' => TRUE,
            'parent' => $parent,
        ]);

        $menu_link->save();
        $previous_menu_link = $menu_link;
    }


How To Redirect to a Named Node upon Registration

You can use the Rules Module to redirect a user after an account is created.

Simply add a new rule for the event "User account has been created"
Add an action of "Page redirect"
Fill in the information for the page you want to redirect the user to.

Make sure that "Immediately issue the page redirect" is not checked or else the same thing will happen and the email will not get sent.


Drupal 7 views grouping and aggregation with recipe ingredients

I use the group by option in the Format settings.  If you group by the Title, then Exclude that field from display...you should end up with a list as you describe above.


Empty cart functionality with a link, (no form) in Ubercart

Check Cart Links API page:
http://www.ubercart.org/node/1427

So, you have to enable Cart links module (included in Ubercart) and your link will be:

http://example.com/cart/add/e

Ubercart wil ask for confirmation for this action. If you don't want this confirmation I think you will have to write your own empty cart routine:

Define in your own module hook_menu an entry for your desired path. Then, assign as callback a function of your own. Inside that function, call uc_cart_empty(uc_cart_get_id());

For example:

  function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    return 'Your cart has been emptied.';
  }

Note that have to provide a message to show the user.

If you want to use the link with AJAX (so no page reload is done) you will need to something like this:

 function mymodule_menu() {
    $items['your/path'] = array(
      'page callback' => 'mymodule_empty_cart',
      'type'          => MENU_CALLBACK
    );
    return $items;
  }

  function mymodule_empty_cart() {
    uc_cart_empty(uc_cart_get_id());
    print 'done';
  }

You will have to add the jQuery code to do the AJAX call. The print statement is sent back to user's browser but it will not be shown (at least if you do not show it to the user in your jQuery code).

For both examples you may adjust the other menu options (access restrictions, for example). Check hook_module documentation:
http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/8


For the first image if its content type you can create a view of that content type with fields
as shown in the table.


As far as Google is concerned if your website is well structured it will be easy for crawlers to crawl your website.Morever Google Rich snippets uses RDF and it needs every site to be RDF structured if you want to enable rich snippets for your website.

Drupal 7 rich snippets and RDF

  So Unless you have any problem with RDF module enabled why you need to
  disable it?


Adding Rules to Canada Post and UPS (Ship-by-weight)

I doubt you'll be able to "create a rule" using either Commerce Canada Post or Commerce UPS (as in your question). Because creating rules is mostly commonly done with the module ... euh ... Rules.

Even though I'm a fan of Rules, I'd rather first try a NOT commonly known/used solution to answer this question, i.e. the Math Field module. It is a fairly new D7 module, released only this year. Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

The reason why I think the Math Field module might be a solution (or at least worth giving it a try), is because of the various fields that appear to be used (as a prereq) for using either Commerce Canada Post or Commerce UPS.


Give permission to translate a specific language

There is an awesome module for it... Translation Management

  You can specify that a user can only translate from English to Spanish
  and another user can translate from English to French and you can also
  have a translation administrator to maintain translation jobs.. And it
  provides a beautiful interface for it.. There is a Guide for it
  too..


Database in settings.php doesn't exist yet site is live. Where is the data?

The hints from Tony Mao & Alexei pointed me in the right direction. It turned out there were a bunch of backups in non-intuitively named folders, so I was looking in the wrong place.

I ended up finding the right settings.php file with sudo find . -name settings.php.


From experience the Migrate module can do all of this for you if you're willing to sit down and write some PHP code to define Mappings and the necessary individual migrations from/to whatever content you need.

See the project page for alot of introductory information and the /examples directory for sample beer data migrations.

EDIT

the Migrate module is a developer module which you must write PHP classes to define field mappings and source to destination content types. Example migration classes are discussed in the official documentation. There is also a Drupal 2 Drupal migration module that provides some UI to require less custom coding.

At this time I cannot provide additional tutorials/examples -- there are many available on google, eg:

not free:
https://drupalize.me/videos/introduction-migrate-module-series?p=1271

free 45min talk from a DrupalCamp:
http://vimeo.com/54448150


Why the cron is launched when I visit the website and why is it taking so much to complete?

The cron can make different tasks such as check for updates to Drupal core and modules, removing temporary files, index content and cleaning up log files.

When you enter to your site the cron is executed and performs his tasks every X hours. You need enter to your site to activate the cron execution, if you want a different behavior you need read this: https://www.drupal.org/cron

There is no way for Drupal to run a cron job without bootstrapping. And the bootstrapping occurs when a visitor hits the site (Nothing happens on a server without someone or something running it). If you want really scheduled cron jobs, you have to set it up server side and this is certainly the best option, for this read: https://www.drupal.org/node/23714

Edit: I found now this article Why Drupal cron is not running as often as you think and how to fix it


How to maintain a local mirror on my Mac?

First, download MAMP.

Then, use MAMP to run Drupal locally (great info here, on drupal.org). Another option is the Acquia Stack Installer, but that's only better if you plan on running Acquia Drupal (at least, in my experience). MAMP is pretty powerful (I even have it, or XAMPP on Windows) running a few Intranets here and there).

You can either grab the files using FTP, and put them in MAMP's htdocs folder (or configure MAMP better, so you can put the files into your ~/Sites/ folder, for instance, using virtual hosts), or you could use source control, like Git or SVN, to manage your drupal site codebase—then just do a git clone to your computer and you'll have the entire codebase.

Use PHPMyAdmin or some other tool to download the database for your website, and then, using MAMP's installation of PHPMyAdmin, import that database into a database on your local computer. You'll need to make sure the settings.php file for your site can authenticate to MySQL on your local computer.

You can either set up a user for your local MySQL installation with the same password and username as your live server, or you can customize settings.php so it uses a different database name and credentials on your local computer. See, for instance, Suggestions for settings.php - Local dev, Development server, Live server


How to extend a test class of dependent module

You can use function module_load_include to include file in your module. Class not found because main class not include in your case.


The node object is made available through the $form array in $form['node']['#value']. You can find list & sell price through the $form['node']['#value']->list_price & $form['node']['#value']->sell_price properties.


How do I properly render a private file URI with l()?

The function file_create_url() is what I was after. I'm able to find what I was after with that.

dpm(file_create_url($file_obj['uri']));


Are service autowiring and class autoresolving not anymore supported?

I found out, that in Drupal 9 some autowiring "magic" from Drupal 8 was removed. Drupal also overrides the Symfony dependency injection by its own logic. Therefor you must write your own service provider class in your module to autowire your service containers (basically all PHP classes, except e.g. Drupal Plugins or Drupal Entities, which Drupal 9 resolves by its own).
Like this (path: modules/custom/my_nice_module/MyNiceModuleServiceProvider.php):
<?php
declare(strict_types=1);

namespace Drupal\my_nice_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Finder\Finder;

class MyNiceModuleServiceProvider extends ServiceProviderBase {

  public function register(ContainerBuilder $container) {
    $containerModules = $container->getParameter('container.modules');
    $finder = new Finder();

    $foldersWithServiceContainers = [];

    $foldersWithServiceContainers['Drupal\my_nice_module\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\RegionalCouncilMeeting\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/RegionalCouncilMeeting/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\DomCrawler\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DomCrawler/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\MongoDBFetcher\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/MongoDBFetcher/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\MongoDB\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/MongoDB/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\RegionalCouncilMeetingsArchive\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/RegionalCouncilMeetingsArchive/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Entity\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Entity/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Extractor\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Extractor/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Service\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Service/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\DrushCommandFacade\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DrushCommandFacade/')->files()->name('*.php');

    foreach ($foldersWithServiceContainers as $namespace => $files) {
      foreach ($finder as $fileInfo) {
        $class = $namespace
          . substr($fileInfo->getFilename(), 0, -4);
        // don't override any existing service
        if ($container->hasDefinition($class)) {
          continue;
        }
        $definition = new Definition($class);
        $definition->setAutowired(TRUE);
        $container->setDefinition($class, $definition);
      }
    }
  }

}

Here is a good presentation about this: https://events.drupal.org/sites/default/files/slides/drupalcon.2019.autowiring.pdf
The Autoservices Drupal module can also be a good example for your own solution: https://gitlab.com/upstreamable/drupal-autoservices


How to postpone access check to theme hooks?

Take a look at the Field Permissions Module:

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes. Role-based
  field permissions allowing different viewing patterned based on what
  access the user has. Author-level permissions allow viewing and
  editing of fields based on who the entity owner is. Permissions for
  each field are not enabled by default. Instead, administrators can
  enable these permissions explicitly for the fields where this feature
  is needed.

EDIT

Based on comments, either create a module using this or add this to a template.php file and adjust as necessary:

function THEME_OR_MODULE_NAME_node_view_alter(&$build)
{
    global $user;
    if($user->uid == 0)
    {
        if($build['#node']->nid == 1) // add node id's you want hidden here
        {
            if(isset($build['field_image']))
            {
                unset($build['field_image']);
            }
        }
    }
}

This example will hide the field_image field on the node id = 1 only for anonymous users. Use the machine names for the fields found on the manage fields tab of the content type.

If you prefer a UI ready option, you can look at the Content Access Module

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


How to find all inputs that make use of the php input filter to fully disable the php filter module?

Rather than re-inventing the wheel, just install the Security Review module, which has the following check:

  PHP or Javascript in content (nodes and comments and fields in Drupal 7)

For blocks you can check the format column in the block_custom table.

The difficult one is Views - I've yet to find a reliable way to locate rogue PHP in Views programmatically.


How to access fields value in views-view--[viewid]--[view-display-id].html.twig template

The template name needs double dashes between each section views-view--homepage-carousel--block-1.html.twig.

At the views-view level all of your data is in rows. You would need to loop through your rows and then get the fields. But it's much easier to just override the main structure you need to in views-view, and then use views-view-fields--homepage-carousel--block-1.html.twig to change the structure of the actual fields, in which case they are available under fields like your example code.


You need to add a new submit handler to the form:

function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'custom_user_submit_handler';
}

Inside the new submit handler set the redirect:

function custom_user_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form_state->setRedirect('user.page');
}


Block expands more than the height of content when using collapsiblock module?

This is a wild guess (no time to test this) but you could try some of the following and see if this will make a difference:

Try using a different version of jQuery (download and install jQuery Update and then go to Configuration>Development>jQuery update and test different versions. Don't forget to clear the cache every time before the test).
Try tinkering with your CSS classes for the block and its contents to include a max-height: 100% property. For example, try this for the ID of the block (e.g. #block-block-2) and/or for the .content class inside that block (#block-block-2 .content)


How to translate Groups in a multilingual site?

Your question appears to be somehow related to this issue, which is closed and fixed. That issue contains an image which looks like so:

So check if the version of the Group module that you're using, includes the patch included in that issue.

If you don't have it included, it's probably why you don't have a "group content type" translation option in /admin/config/regional/config-translation. And if you do have it included, go checkout that translation option to see what happens.


Change entity reference field widget type based on role?

I ended up getting this to work after finding hook_field_widget_properties_alter. This allows you to, as the hook implies, target the various properties of the widget directly. Global $user seems to provide the $user variable, which allows you to select the role that you want to apply the module to. You can change it from 'administrator' to 'authenticated user', 'anonymous user', or any other needed role to fit your needs.

<?php
function entityreference_widget_field_widget_properties_alter(&$widget, $context) {
  //Assign role that will be affected by the module
  global $user;

  if (in_array('administrator', $user->roles)) {
    // Change entityreference widget
    $field = $context['field'];
    if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_review_band') {
      $widget['type'] = 'entityreference_autocomplete';
      $widget['module'] = 'entityreference';
      $widget['settings']['match_operator'] = 'CONTAINS';
      $widget['settings']['size'] = '60';
    }
  }
}

To find out exactly which pieces of the widget needed to be altered, and what to, I created another test field of the type that I wanted to alter my current field to. I then inserted dsm($widget) within the hooks curly brackets of the hook, and then inspected the page with the field on it.

Explanation of dsm() and dpm() for anybody who needs it:

There's so little help anywhere on how to use dsm() or dpm(), and working through this module finally made me understand it. Basically, modules target different elements, and in order to figure out what to target, or what you will be altering, you need to inspect the elements. What dsm() lets you do is view the properties of any given variable (e.g. $form_id most commonly it seems, or in this case $widget or $context) in each of the elements on the page that include it. If anybody stumbles on this and still needs clarification, feel free to ask. It took me forever to figure out how the heck to use dsm().


Login and registration form in a single page

This has been answered many times here.
See this Print registration and login forms on same page

For this You need to create a page for Registration like this

page-user-register.tpl.php

And print the page contents as usual.
in that page you could try render user_login_block

Additional resources

http://www.trevorsimonton.com/blog/page-usertplphp-profile-php-template-drupal
http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_login_block/7


What API function do I use for redirecting to external URLs?

You should use drupal_goto() for internal and external redirections.

Use 'external' option for external redirections:

drupal_goto($url, array('external' => TRUE));

  drupal_goto($path = '', array $options = array(), $http_response_code
  = 302)

$options: (optional) An associative array of additional options, with the following elements:

'query': An array of query key/value-pairs (without any URL-encoding) to
append to the URL.
'fragment': A fragment identifier (named anchor) to append to the URL.
Do not include the leading '#' character.
'absolute': Defaults to FALSE. Whether to force the output to be an
absolute link (beginning with http:). Useful for links that will be
displayed outside the site, such as in an RSS feed.
'alias': Defaults to FALSE. Whether the given path is a URL alias
already.
'external': Whether the given path is an external URL.
'language': An optional language object. If the path being linked to is
internal to the site, $options['language'] is used to look up the alias
for the URL. If $options['language'] is omitted, the global $language_url
will be used.
'https': Whether this URL should point to a secure location. If not
defined, the current scheme is used, so the user stays on HTTP or HTTPS
respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
only be enforced when the variable 'https' is set to TRUE.
'base_url': Only used internally, to modify the base URL when a language
dependent URL requires so.
'prefix': Only used internally, to modify the path when a language
dependent URL requires so.
'script': The script filename in Drupal's root directory to use when
clean URLs are disabled, such as 'index.php'. Defaults to an empty
string, as most modern web servers automatically find 'index.php'. If
clean URLs are disabled, the value of $path is appended as query
parameter 'q' to $options['script'] in the returned URL. When deploying
Drupal on a web server that cannot be configured to automatically find
index.php, then hook_url_outbound_alter() can be implemented to force
this value to 'index.php'.
'entity_type': The entity type of the object that called url(). Only
set if url() is invoked by entity_uri().
'entity': The entity object (such as a node) for which the URL is being
generated. Only set if url() is invoked by entity_uri().

$http_response_code: (optional) The HTTP status code to use for the redirection, defaults to 302. The valid values for 3xx redirection status codes are defined in RFC 2616 and the draft for the new HTTP status codes:

301: Moved Permanently (the recommended value for most redirects).

302: Found (default in Drupal and PHP, sometimes used for spamming search engines).

303: See Other.

304: Not Modified.

305: Use Proxy.

307: Temporary Redirect.

Drupal 8

Drupal 8 has removed drupal_goto function, for redirect to external URL see this answer for the question: How do I redirect to an external URL?.


How can I add a field in Entityform / hook_form_alter

That is the way it should be done.

For example using

MODULE_form_ENTITYFORM_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {}


How to check if a url exists on my own website

This is what fixed it:

if (!drupal_valid_path($path)) {
  // Not a system URL.
  if (!drupal_lookup_path('source', $path))  {
    // Not a path alias.
    // $path does not exist.
  }
}

Where $path is a relative url.

Source


Export content in features using UUID features

The uuid module has been reworked, and, as of 2012.05.25, uuid_features has not been updated to address those changes (though there is a patch RTBC).

In the meantime, to export nodes using uuid_features in Drupal 7:

Install features version 7.x-1.0-rc2.
Install uuid version 7.x-1.0-alpha1. (Not the latest version.)
Install uuid_features version 7.x-1.0-alpha1.
Enable the features module, the uuid module, the uuid_node module, and the uuid_features module
Go to Configuration > System > Universally unique identifiers, and click the "Create missing UUIDs" button
Go to Structure > Features > Create feature, and from the "Edit components" dropdown, select "Content: uuid_node", then pick the nodes you'd like to export into your Feature


How to enable endpoint without RESTUI module?

Ok, I finally found out how to enable an endpoint to be accessible without RESTUI module. This gives more flexibility to keep everything in code and one custom module.

This instructions applies to Drupal > 8.2 only.

First you need to know how to create a custom rest resource, which can be found here or here.

So, let's say we have a custom module named 'custom_rest' that contains REST plugin resource. Module returns only a single node json data. The structure of the module looks like this:

|custom_rest
|--|config
|  --|optional
|      --rest.resource.custom_rest_resource.yml
|--|src
|  |--Plugin
|     |--rest
|        |--resource
|           --CustomRestResource.php
|--custom_rest.info.yml
|--custom_rest.module

The most important files for us are:

 -  CustomRestResource.php
 -  rest.resource.custom_rest_resource.yml

CustomRestResource.php is a plugin with the custom rest resource. My get method looks like this:

  public function get($nid) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $data = node_load($nid);
    return new ResourceResponse($data);
  }

This method returns a json node structure for an existing node. That's it, it's just for testing purposes only. It can do anything you want.

As for the enabling an endpoint it needs an extra yml file that should be located in:

/custom_rest/config/optional/rest.resource.custom_rest_resource.yml

The contents of the rest.resource.custom_rest_resource.yml file for this particular endpoint looks like this:

langcode: en
status: true
dependencies:
  module:
    - custom_rest
    - hal
    - serialization
    - user
id: custom_rest_resource
plugin_id: custom_rest_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - hal_json
      - json
      - xml
    supported_auth:
      - cookie

Of course, the name of the file, dependencies, id, plugin_id, configuration should be adjusted to your needs.

If you have all of this and you will enable the module this endpoint should be accessible in browser or any app that handles http requests (postman, etc.).

Notice that this yml file won't be triggered if you already enabled the module. If you've added this file after module enable, you should uninstall the module and enable it again.


specific htaccess in some sites on multisite

Apache does not support this.  You can use REWRITECOND to conditionally match rewrite rules, but there is no way to conditionally hide AuthType directives, except to separate the Drupal sites into different Drupal root folders.  Putting an .htaccess file in the sites/mysite folder won't work, because settings.php is read via php, not served up by the webserver.

Use Drupal features to protect your content.  If you turn off the "Access Content" permission for anonymous users, then a Drupal login will be required to view any page; all others will get "Access Denied".


Is there a Rules Action to set an entity reference field to null / empty?

Ahh, got it. If anyone else runs into a problem doing this. The issue I had was that I was leaving the data selector blank and it was giving me an error message. BUT If you switch to the direct input mode and leave it blank it will work. Have a great one.


how to pass arguments in forms submit array in drupal

I assume you want to pass some data not entered by user. You can use hidden fields for that and when user submits his data you will get that field data as well and if you are bothered about tampering of data you can use #access to make sure its not tampered with.


EDIT: If you use Features and the field under that references the taxonomy term under question is in one of your features, there's is much easier way to do this. Add this to your my_module.field_base.inc:

// Exported field_base: 'field_user_blogs_ref'
$field_bases['field_user_blogs_ref'] = array(
    ...
    'settings' => array(
      ...
      'options_list_callback' => 'my_callback',
    ),

Neat. This has the additional benefit that it applies only to this field base as there might be more fields referencing this vocabulary. The same could probably be done with the code below as well but extra effort.

ORIGINAL ANSWER: still leaving this as this method might be useful for some cases.

I finally did this by altering the code that provides the options to the select widget. You can see how this is done in the content_taxonomy module

1) Provide a hook_field_info_alter to set the callback function

function content_taxonomy_field_info_alter(&$info) {
    $info['taxonomy_term_reference']['settings']['options_list_callback'] = 'content_taxonomy_allowed_values';
}

2) Provide the callback that returns the options

function content_taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($tree['vocabulary'] == 'user_blogs') {
        return my_callback($vocabulary);
      }
      $max_depth = (isset($tree['depth']) && !empty($tree['depth'])) ? $tree['depth'] : NULL;
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'], $max_depth)) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('- ', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

Notice that the function provides the options for all taxonomy vocabularies, but if the vocabulary is of a certain type then it calls another function that returns the options the way required. If you don't use the content_taxonomy module you can copy and use the taxonomy_allowed_values function from the taxonomy module.


Why print $block->content sometimes converts line break to  but sometimes does not?

This could be due to the input format you are using for the block's content region.

Assuming you are using the default input format (id 1), the filter option Line break converter is probably enabled. See admin page: /admin/settings/filters/1

You can uncheck this setting in the default input format or you can use a different input format by clicking on the Input format fieldset under the Block body content region.

If you do not have any other input formats, you can add a new one that does not use this Line break converter setting here: /admin/settings/filters/add

Note: Being able to configure or add any input format requires the administer filters permission from the filter module.


Recaptcha dissappears after form submission

check the "Persistence" option in the CAPTCHA settings? You must choose "Always add a challenge".


Show parent child relationship of taxonomy term in view

You can also try Views tree module.

Project page says

  This module provides a tree-based style plugin for Views. It is
  equivalent to the tree-based style template from Views 1.

  It is based off of the list style. Although it generates a nested
  view, there is still only a single query run for the view making it
  quite performant.

  Compatibility

  This module has been tested and used with the following
  relationship-oriented modules:

  Taxonomy (in core) - parent/child relationships


How to add a "viewed" icon to pages that are visited

In my opinion using a cookie could be a nice way to accomplish that need. (Maybe even the only way).   A quick search came up with the user_cookie_save function >> https://api.drupal.org/api/drupal/modules!user!user.module/function/user_cookie_save/7

Use it to save the cookie with the video URL or another identifier and read that cookie when loading the page and set the viewed flag.


Webform submissions are content entities without Field API  enabled.  Comments can only be attached to fieldable entities.  Webform submission data is not stored Field API, but your use case is a very reasonable example of why Field API could/should be enabled.  The challenge is the UX for supporting fields, and webform elements at the same time could be overwhelming.  I am not prepared to support this the core Webform module.  A dedicated webform_comment.module could be created to enable Field API and might even only support for adding comments to submissions.

You are going to have use hook_entity_type_alter() to add 'field_ui_base_route' to the WebformSubmission entity.

  If your content entity is fieldable, provide 'field_ui_base_route'
  annotation, giving the name of the route that the Manage Fields,
  Manage Display, and Manage Form Display pages from the Field UI
  module will be attached to. This is usually the bundle settings edit
  page, or an entity type settings page if there are no bundles.

-- https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/8.2.x


Get currently active 'simpletest' user during test

Inside the test method?

No idea what in $GLOBALS['user'] is, but you certainly can't rely on it. You are never "logged in" in that context, you are only logged in when doing requests with drupalGet()/drupalPost().

If you used drupalLogin(), you can look for $this->loggedInUser. If not, then it's not possible, other than maybe doing a GET to /user and then trying to get the username from title.

Inside a page callback, $GLOBALS['user'] is the current user, just like you'd expect.


Use Grouping by a Field

Grouping by Fields is a standard feature in Views.

Create your Content Views with Page Display
Add the Country Field (Probably a Taxonomy term reference, there are ways to import country lists BTW)
Set Format to Grid and set Number of columns
In Format Settings set Grouping field Nr.1 to your Country field

Check in Preview that things look the way you want.
Edit the Country field and set it to Exclude from display because you have it output above each result group, your probably don't want it in each grid cell too
Edit the Country field Style settings if you want more control over how the "group headings" are output, but this works only in certain cases: D7 How to change the HTML wrapped around a grouping output (HTML h3 tag), D8 Allow to configure the h3 element for view style plugins, although you can use Custom text field for more control too.


I got duplicated modules after updating an installation. How to remove them?

Here are the steps I would perform to address this question, in the specified order:

Download and unpack a fresh copy of the new Commerce Kickstart release.
Create a list of all your modules in your sites/all/modules folder, and identify all modules in there with the same name (module namespace) as in the new Kickstart release. The result should be a list of the duplicate modules that need to be resolved.
Use the Hacked! module to identify any hacks, patches, customizations, etc that might have been applied to any of these duplicate modules in the sites/all/modules folder.
Disable and uninstall the duplicate modules.
Backup and then delete the entire folder of each of the duplicate modules in the sites/all/modules (or move them to a folder outside your Drupal root directory).
Enable the fresh copy of the new Kickstart release. That inherently will also re-enable the vanilla version of the duplicate modules, as contained in the new Kickstart release.
Reply any hacks, patches, customizations, etc that are appropriate to be  re-applied (e.g. because upgrading to the new Kickstart release does not make them obsolete).
Should you run into weird problems because of some of the duplicate modules being moved to another directory, then download and enable the Registry Rebuild module (and/or related Drush RR command). That will probably resolve those problems.


How to move installed modules from /sites/all/modules/* to /sites/all/contrib/modules/*

You only need to move your modules to the your new location and rebuild the regisry. When the registry rebuilds the path to the modules will be updated. Check registry_rebuild().

  Rescans all code in modules or includes directories, storing the location of each interface or class in the database.

Although, I would recommend you to backup you database before testing this.

If you are using drush you could also rebuild the registry using the following command:

drush cc registry

You can also install the registry_rebuild command for drush:

// install registry_rebuild
drush dl registry_rebuild
// rebuild the registry
drush rr


Thanks to @leymannx
composer update drupal/core drupal/core-dev --with-dependencies

did it


You are not supposed to create view block for each term, your view can take dynamic argument for taxonomy and will return results accordingly, All you need is to have contextual filter setup for your views.


In Views, you can set the number of values returned in the pager config by selecting 'Display a specified number of items'. Have you tried that set to 5?

If you said something like 'the top 5 in the draggable views list will be displayed' in the help/description that would do it for your users, plus they could then bring back stuff if they wanted without having to go out and reflag it. to automatically unflag content, you could hook into hook_flag() and unflag the oldest or something with some custom php code.

Check out The Flag PHP API, which talks all about that kinda stuff.


Add an contextual filter of type Content: Author uid
Under WHEN THE FILTER VALUE IS NOT IN THE URL select Provide default value.
Select User ID from logged in user.


There is a way but it may not be ideal depending on how far you are along in your site development. The way you would link content to content is through the node_reference field that comes with the CCK module. The problem is that this doesn't work with Drupal profiles in 6.x, only nodes. One solution is to install the content profile module

http://drupal.org/project/content_profile

which allows you to create a new content type for your profiles. From there, you would just add a field of type 'node_reference' to your new profile content type and connect it to 'locations', and allow the user to make multiple selections, etc.

Of course this is less than ideal if you already have a significant number of profiles on the system but there is a migration path from the core drupal profile data to the new type in another module:

http://drupal.org/project/profile_migrate


How to flag a product variation on a commerce website?

I wrote a way to use Flag for product variations here: http://drupal.org/node/1911568

Here is my solution:

Add a flag "add to wishlist" for commerce_product entity type.
Install computed field module.
Add a computed field to the product (not the display content type)
In Display Code (PHP) area of the field:

$entity_id = array_shift(entity_extract_ids($entity_type,$entity));
$display_output = flag_create_link('add_to_wishlist', $entity_id);

(Computed Code (PHP) part can be left empty, we dont want to store anything in database)
5. Go to Manage Display of the product and set the newly created computed field's format: "unsanitized" and make sure it is visible.
6. Go to Manage Display of the product display content type (not the product) and use your product's wishlist computed field there.

Now you can create a view to display a user's products in his wishlist. It is straitforward. You just add any field, add a relation: your flag and tweak the view as you like. You can also use view's menu system to create tabs on the user profile: http://drupal.org/node/326580


It is much easier to create an xml view of your content in each language and import it with feeds module and xpath. Or if it is easier for you, you can export to csv with views data export and import to your new drupal with feeds csv parser. It is much easier and more reliable as you have total control of your content. Though be careful with the delimiters if using csv. XML is safer.


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

This code will work fine:

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

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


Using module_invoke() and render() causes PHP warnings

Blocks aren't render arrays, they're made up of a subject and content key.

You'll probably have better luck referring to those explicitly:

$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);


What's best practice when working with the language[und]?

I find that using the Entity API module is a great help and also makes code more readable. The above code will not always work, since the language of the node and the language of the field can be different.

With the entity API module, and its wrapper, you can use the following code:

 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

This should be bullet proof. One thing about using the entity module is that if you try to access a field that doesn't exist, you will get a nasty error and an exception thrown instead of a notice and wrong behavior.

To avoid this, you could do try/catch like this

try {
  $field_val = $node_wrapper->field_doesnt_exist->value();
} catch (EntityMetadataWrapperException $e) {
  $field_val = 'default/fallback value';
}

Or you can use isset() which EntityMetadataWrapper handles internally:

$field_val = 'default/fallback value';
if (isset($node_wrapper->field_doesnt_exist)) {
  $field_val = $node_wrapper->field_doesnt_exist->value();
}


Drupal CKEditor module remove line breaks

The solution is simply in two points:

Adding the following config to in the advanced option tab of the desired profile:
admin/config/content/ckeditor/edit/Full

config.protectedSource = [/\r|\n/g];

This will keep the source of the content with new lines as it is and forget about its shape in the wysiwyg.

In for the container that holds your content, use the following css rule:

white-space: pre-line;
This will keep lines separated as paragraphs.

checkout those screen shots:

Add the protected source config:

Don't worry about it in wysiwyg:

Just look at the source:

It will look like the following on the frontend:

  Don't forget to flush cache specially if you optimized and aggregate
  js and css, also remove your browser cache or enabling remove cache
  during using dev tools (chrome)


Hide Certain Values from an Apache Solr Facet

I kept looking for a solution on the internet after posting this question and i have discovered this module:  https://www.drupal.org/project/facetapi_bonus which does exactly what i need


A nice way to build a related content algorithm

This was what I ended up writing to select nodes:

$query = db_select('node', 'n');
$query->addField('n', 'nid');
$query->addExpression('COUNT(n.nid)', 'ncount');
$query->innerJoin('taxonomy_index', 'ti', 'n.nid = ti.nid');
$query->condition('ti.tid', $tids, 'IN');
$query->condition('n.type', $types, 'IN');
$query->condition('n.nid', $node->nid, '<>'); // Exclude current node
$query->condition('n.status', 1); // Published
$query->condition(
  db_or()->condition('n.language', 'und')
         ->condition('n.language', $node->language)
);
$query->groupBy('n.nid');
$query->groupBy('n.title');
$query->groupBy('n.created');
$query->orderBy('ncount', 'DESC');
$query->range(0, 10);

$results = $query->execute();

Kudos to Similar by Terms module, as I copied most of it from there. The magic happens when you order by ncount field.


Datepicker not appearing when an url alias is added

I have date_popup module under date enabled and any form field with date_popup type displays date picker for me:

$form['my_date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'Y-m-d',
      '#title' => t( 'My Date' ),
  );

It seems to work for me regardless of which url it is used on.


I had similar situation and resorted to using viewfield. Works like a charm. Recommended.


Check if you have a module that uses any of the Google's API (translate, maps, youtube, calendar,...).

Seems that one of the modules implements hook_cron() where is trying to access to one of the Google services through its API.

If that is the case at Google Cloud Platform you can configure a key to solve the issue.

If that is not the problem, try to check the logs to see if you can get more info about this error.


Drupal 6 Webforms sends duplicate emails

Your can deactive the submit button after it was clicked with custom javascript.

I write a sample below:

Drupal.behaviors.FormSubmitDisable = function (context) {
  $('YOUR BUTTON ID').click(function () {
    $(this).attr("disabled", "true");
  });
};


Views Contextual filter using two terms, one assigned to node and one not

You can use relationship settings to add in the taxonomy, and then add field to also add items tagged with that Term into the slideshow.

Something like this:

Edit your view and add a relationship (3rd column on right) for
Content: Taxonomy terms on node

Then under your filters add:

"Taxonomy term: Term" and Select the term that is 58

I just did a test with a sample view and results were as expected, it showed me all the items for that node plus the specific term.


How to expand NodeForm so new argument can passed to it

After you have integrated the form class in the entity type as form mode
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('service', 'Drupal\mymodule\Form\ServiceBuilderForm');
}

and invoked the node form in a controller
$form = $this->entityFormBuilder()->getForm($node, 'service');

or without controller directly in a route:
_entity_form: 'node.service'

the entity including the field data is passed to your form
class ServiceBuilderForm extends NodeForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $node = $this->entity;
    if ($node->getType() == 'service_request') {
      $field_value = $node->field_service_type->value;

and you avoid the error from your question that the entity is null.


Is it possible to show Poll results as a table in Views?

Try to use below modules :

Responsive Tables
Data
FooTable


Creating a ticketing system in Drupal 8. How to change a node's field value without going to the edit page?

You could build an ajax form that would update the node's "Ticket Status" field, embed that in a custom block and place that block on the page for that node or embed it in the node.  Instead of in a block, you could also create a field formatter plugin that embeds the ajax form into the display for that field.


hook_theme_suggestions_hook_alter() not working for Views

Found the solution. As it turns out, for some reason Drupal doesn't play nicely with custom theme suggestions starting with a word + single dash.

I updated my HOOK_theme_suggestions_HOOK_alter() function to include $suggestions[] = 'test__template'; (with 2 underscores between the words) and updated my template name to test--template.html.twig (with 2 dashes to match the 2 underscores), and everything works as expected.


How do I pass the nid of the current node to the first step multistep modal form?

I think the simplest way would be to change your path to incorporate the nid, e.g.

function MYMODULE_menu() {
  $items['mymodule/%ctools_js/modals/%node'] = array(
    'title' => 'Title',
    'page callback' => 'MYMODULE_callback',
    'page arguments' => array(1, 3),
    ...
  );

  return $items;
}

Change the path in the link

$build['links']['popup']['#links']['mylink'] = array(
  'title' => 'show popup',
  'href' => 'mymodule/nojs/modals/' . $nid,
  'html' => TRUE,
  'attributes' => array(
    'class' => array(
      'ctools-use-modal',
      'ctools-modal-mymodule-style',
    ),
  ),
);

And in your callback:

function MYMODULE_callback($js, $node) {
  // $node is fully loaded, continue as normal...
}