Unable to install Pathauto, pathauto.settings already exists in active configuration

Before trying to do whatever I suggest below first of all have a full backup of the site.
It seems pathauto module is not uninstalled properly.
To solve your problem you can just delete the pathauto.settings from config using drush.
Use the below command to delete the conflicting config.
drush cdel pathauto.settings
It will delete the existing pathauto configuration.Then you can install the pathauto module.
You should consider using composer for the module management.


use imce for images in articles but not within the editor

You need the Filefield sources module. It allows you to select an existing file on the server.


How to check if search_index's solr is running?

The SolrConnector plugin provides a pingServer() function that will determine it the endpoint can be accessed, so to really test it you likely need to be able to call that.

I'd first check to see if there is an abled server by calling $solrIndex->isServerEnabled().

Then I'd get the server, its backend, the connector, and run the ping:

$server = $solrIndex->getServerInstance();
$backend = $server->getBackend();
$connector = $backend->getSolrConnector();
$response = $connector->pingServer();

or just

if( $solrIndex->getServerInstance()->getBackend()->getSolrConnector()->pingServer() ){
  // Yup
}
else {
 // nope
}

The return value from pingServer() is:

  The latency in milliseconds if the core can be accessed, otherwise
  FALSE.


Pathologic settings are on the text format.  So you'd go here: admin/config/content/formats and click "configure" next to the format you want to tweak.  If it's a format that has Pathologic selected for it, then you will see a "Correct URLs with Pathologic" vertical tab down near the bottom of the page.  The settings are in there.

It sounds like you have anotherdomainwehost.com in the list of "all base paths for this site".


You will need to create a custom module to do this. Not having experience with Drupal development it will be hard.

Since you are doing this in Drupal 7 you should not use nodes for this, but instead create your own entity. It takes a bit of extra effort, but it will help you, as you can design your entity to fit your needs. The entity API will help you do create an entity without having to think about much of the boring CRUD stuff.

You will also need to define a database table, where you entities can be stored, you will need a unique identifier, store the participants and the referee, the outcome and other useful data like when the entity was create, when the game was held etc.

Using the entity API module you can also create views integration for you entity which will allow you to display lists of games, like the 5 most recent and those sort of things, For displaying a tree of games you might need to do some custom coding. I'm guessing you want to display a tournament style list, which won't be easy. If that is the case you'll need to create some relationship between the games and use advanced CSS to create the display you want.


I do not see that you are saving the project node, after changing field value.

function mymodule_flag_flag($flag, $entity_id, $account, $flagging) {
  $node =  node_load($entity_id);
  $freelancer = $node-> uid;
  $project_node = node_load($node->field_projet['und'][0]['target_id']);
  $wrapper = entity_metadate_wrapper('node', $project_node);
  $wrapper->field_freelancer->set($freelancer);
  // You missed
  $wrapper->save();
}


Conditional fields module - Required fields that are hidden are still required to be filled

All fields are set to be required in their field settings.

This is your mistake.  If you set the field to be required in the field settings, it will be required whether it is invisible or not.  So you need to uncheck this setting unless the relevant field will always have a value.

Instead, you should trigger the "make required" action provided by the Conditional Fields module whenever showing the relevant field for input.  Unfortunately, the last time I tried this in Conditional Fields, it did not work due to a bug.

Alternatives

Field Conditional State is a stable module that works similarly to Conditional Fields.  You can use this to properly set required fields.

Or, if you prefer a code-based solution, look into the #states API.


Saving a default value when using entityMetaDataWrapper->save()

The default value is used for the widget form only, it won't be automatically set if you use node_save or a metadata wrapper. You see it in the form when you edit the newly created entity because there's no value for that field, and Drupal dutifully fills in the default value. It doesn't update the value of that field on the entity, just populates the form input.

You'll need to populate it manually, but you can get the right value with the field API:

$instance = field_info_instance('node', 'field_foo', 'article');
$default_value = $instance['default_value'];


You can use the
View Slideshow module and create many blocks of slider from the content you create.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


In order to have it appear in the admin menu.
You need to give access to:

"Use the administration pages and help"

Because the My Workbench link is child of admin:
/admin/workbench


How to access $variables in a module function where $variables is not passed to it. (D7)

Call your function from inside your module's preprocess_page() hook.  Eg, in your custom module, let's say your function that calls your view is mymodule_call_view().  Let's further assume it returns the value you want to set your page variable to.  You could do it this way:

mymodule_preprocess_page(&$variables) {

  // any other preprocessing you are doing goes here

  $variables['variable_you_want_to_set']=mymodule_call_view();

}

Then, when drupal is building the page, it would call your preprocess function, which would call your function that iterates through the view, etc...


How can I filter a view by "has translation"?

This is not tested but you could probably add the filter "Node translation: Child translation" to your view. Together with the current user language fiter this could work. Description is: "Content that is a translation of a source translation."


How to relate a field to another field in content type like a foregn key?

Instead of using relationships use field collection module. In this module you may create a collection of fields that they all point to an entity.

As an example you can create author collection and in this collection insert first name field,last name field,gender field or any other information you need.

You can add this collection as a field to the book content type.


Can't add instance of custom field type to entity

You’re confusing the required length property of a varchar field with the size property of a text field.

Replace size with length (or varchar with text if that makes more sense) and your code should start working.


How to create a custom field programmatically on content type creation?

It is the NodeType::load() in seo_form_submit() that is failing because the bundle doesn't exist at the time the form is submitted for the first time.

My recommendation would be to redesign this code so that the logic to create/destroy the field is in both a hook_node_type_insert() and a hook_node_type_update().

You will need some way to pass the value of the checkbox on the form to these respective hooks. Most likely through a custom configuration or schema.

Edit: It looks like there is more than one design pattern that would work as well as the one I recommended in this answer. Please reference Entity CRUD, editing, and view hooks.


You can utilise watchdog at the end of your hook_cron implementation, then implement db_update to update your desired table.


How to modify the link titles shown in /node/add page?

You should copy template_preprocess_node_add_list() into your module or theme and customize.  I would advise against trying to change the value in the node type because it's the name of the bundle type across the site.  It will show many places you don't want to update.

For example, to update the article link:

function mytheme_preprocess_node_add_list(&$variables) {
  foreach ($variables['content'] as $type) {
    if ($type->id() == 'article') {
      $variables['types'][$type->id()] = array(
        'label' => $type->label() . ' (Only one article can be created and edited)',
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label() . ' (Only one article can be created and edited)', new Url('node.add', array('node_type' => $type->id()))),
        'description' => array(
          '#markup' => $type->getDescription(),
        ),
      );
    }
  }
}

Another alternative to the preprocess function is just to copy /core/modules/node/templates/node-add-list.html.twig into your theme and add your custom rules there.

UPDATE:

Due to the question's particular requirements, I'm adding another solution that works without altering the seven theme (that conflicts with my solution above).  In the solution below, we alter the output of $node_type->label() conditionally:

function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['node_type']->set('label_callback', 'mymodule_node_type_label');
}

function mymodule_node_type_label(NodeType $type) {

  if (\Drupal::routeMatch()->getRouteName() == 'node.add_page' && $type->id() == 'article') {
    return $type->get("name") . ' (You can only add one of these)';
  }
  return $type->get("name");
}

UPDATE:

Here's another solution that works with the seven theme.  You can alter the particular node types you like in the preprocess function in your custom module.  This will only alter their labels within this context.

function mymodule_preprocess_node_add_list(&$variables) {
  $article_type = $variables['content']['article'];
  $variables['content']['article']->set('name', $article_type->get('name') . ' (Only one article can be created and edited)');
}


You can separate template file for overriding the user-login page.

Just create a template file called page--user--login.tpl.php file for theming the login page.


Display menu items deeper as second level. (show as expanded doesn't actually expand menu items)

This is "by design" of drupal / the themes.

With the help of a module like Menu Block you can create blocks that have the functionality you are searching for and then place the Blocks where the menu was.


These instructions integrate the eComma 7.x-1.x installation instructions, but with your requested modifications to make them work with Panelizer.

Create a basic installation of Drupal for your local development. You need to use MySQL / MariaDB as your database, eComma won't work with PostgreSQL at the moment [reason].
Install eComma (assuming you use drush, which is a great tool for Drupal developers …):

drush dl ecomma
drush en ecomma

If you want to install the module in a way that allows you to contribute back with Github pull request, replace the content of the eComma module with the Github repository's 7.x-1.x branch:

cd <your_docroot>/sites/all/modules/;
rm -R ecomma/*;
git clone "https://github.com/coerll/eComma.git" -b 7.x-1.x --single-branch ./ecomma

Install the patch mentioned in the eComma README. It fixes Community Tags' Drupal issue #2193175, which otherwise leads to Server Error 500 on node view pages (/node/<some-node-id>).

cd sites/all/modules/community_tags
wget "https://www.drupal.org/files/issues/community_tag_tagadelic_d7_fix-2193175-4.patch"
patch -p1 <"community_tag_tagadelic_d7_fix-2193175-4.patch"
rm "community_tag_tagadelic_d7_fix-2193175-4.patch"

Go to "Administration → Configuration → Search and metadata → Clean URLs" (/admin/config/search/clean-urls) and select "Enable clean URLs".
Go to "Structure → Taxonomy → Add Vocabulary" (/admin/structure/taxonomy/add) and add a vocabulary.
Add or edit the custom content type that you want to use eComma on.
In the edit form of that content type, go to the horizontal tab "Comment settings" and set "Preview comment: Optional".
Go to "Manage fields" for your content type (/admin/structure/types/manage/content-type-name/fields) and add a new field.

Use field type "Long text" (it will only work with that, not with "Long text and summary").
Go to the field settings. If you problems doing so (like "Notice: Undefined index: instance in ecomma_form_alter() (line 351 of …/ecomma.module).", you can manually enable eComma for the field in the database instead of doing the next two steps. You would use a query like:

INSERT INTO ecom_ecomma_field_enabled (field_name, content_type_name, ecomma_enabled)
VALUES (''your_field_name", "your_content_type", TRUE);

In the field settings, use "Number of value: unlimited" (though that's probably not obligatory).
In the field settings, select "Enable ecomma commentary features", right above the "Save settings" button.

Again, go to "Manage fields" for your content type (/admin/structure/types/manage/content-type-name/fields) and add a new field of field type "Term reference", using the "Autocomplete term widget" and selecting your Vocabulary from the field settings.
Go to "Configuration → Content Authoring → Community tags" and select "Enable community tagging" for the new vocabulary that you created.
Go to "Configuration → jQuery update → jQuery and jQuery UI CDN" and select "None".
Edit your eComma content type again, there go to the horizontal tab "Community tags settings" and select "Community tagging form: Block".
Go to "People → Permissions" and

Check "Community Tags: tag content" for authenticated and anonymous users. This will also enable unauthenticated users to see the tags, but not to tag.
Check "Community Tags: edit own tags" for authenticated users.
Check "Comment: view comments" for anonymous and authenticated users. This will enable unauthenticated users to see the comments, but not to comment.

Configure Drupal to show the "Long text" text field of your new content type, plus various eComma blocks, when somebody views a node of that content type. Depending on what layout mechanism you use (vanilla Drupal, Panels / Panelizer, Display Suite, context etc.) this will be different. Here's how to do it for Panelizer:

Go to "Administration → Structure → Pages", enable "Node template" and edit it.
In the node template, create a new variant of type "Panel", with the optional feature "Selection rules".
Add a new selection rule for your new variant, and doing so choosing "Node: type" from the dropdown list and later the content type(s) which you want to use with eComma.
Go to the "Content" section of your new variant, click a gear icon where you want to add content, choose "Add content" from the dropdown.
In the content selection dialog, go to the "Node" tab and select the Long Text type field you want to use eComma on (it starts with "Field: …" in this list). The eComma annotation dialog will not appear if you add this field as part of an aggregate, like by putting in the full rendered node with this dialog!
Click the gear icon again, click "Add content", and now from the Miscellaneous tab of the dialog, one by one, add the "Community tagging form" block and all blocks starting with "eComma". Normally these blocks are nicely integrated into overlapping tabs in eComma, but I could not yet find out how to achieve this with Panelizer. The "Community tagging form" block is needed because if not adding it, it will not appear as part of the JavaScript tagging form either!
Save this all.

Test your setup.

Create a node of your new content type.
Enter some text in the "Long text" text field – not in the "Body" text field. And save.
View the node and select text with mouse cursor to start annotating it.


Colorbox inline style="display:none" doesn't disappear

O.k... I changed the code to this and it works...

Link to click

        <input name="name" type="name" />
        <input name="phone" type="phone" />
        <input name="email" type="email" />


I use jQuery to alter the exposed form select options. Got error: "An illegal choice has been detected." How to bypass validation?

The function that shows those errors is _form_validate(), which contains the following code.

  // Validate the current input.
  if (!isset($elements['#validated']) || !$elements['#validated']) {
    // The following errors are always shown.
    if (isset($elements['#needs_validation'])) {

      // ...

      if (isset($elements['#options']) && isset($elements['#value'])) {
        if ($elements['#type'] == 'select') {
          $options = form_options_flatten($elements['#options']);
        }
        else {
          $options = $elements['#options'];
        }
        if (is_array($elements['#value'])) {
          $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
          foreach ($value as $v) {
            if (!isset($options[$v])) {
              form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
            }
          }
        }

        // ...
      }

The function is always executed, whenever the form has a validation handler, or not.

You could set $form['#needs_validation'] to FALSE, but _form_builder_handle_input_element() sets it to TRUE. The function is called from form_builder(), which is then called from drupal_process_form(), or drupal_rebuild_form().

  // Mark all posted values for validation.
  if (isset($element['#value']) || (!empty($element['#required']))) {
    $element['#needs_validation'] = TRUE;
  }

After _form_builder_handle_input_element() is called, form_builder() calls any #process function set for the form element.

  // Handle input elements.
  if (!empty($element['#input'])) {
    _form_builder_handle_input_element($form_id, $element, $form_state);
  }
  // Allow for elements to expand to multiple elements, e.g., radios,
  // checkboxes and files.
  if (isset($element['#process']) && !$element['#processed']) {
    foreach ($element['#process'] as $process) {
      $element = $process($element, $form_state, $form_state['complete form']);
    }
    $element['#processed'] = TRUE;
  }

It also calls any #after_build functions set for the form element.

  // The #after_build flag allows any piece of a form to be altered
  // after normal input parsing has been completed.
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
    foreach ($element['#after_build'] as $function) {
      $element = $function($element, $form_state);
    }
    $element['#after_build_done'] = TRUE;
  }

You could set a #after_build function that executes code similar to the following one.

function mymodule_remove_validation($form_element) {
  unset($form_element['#needs_validation']);

  return $form_element;
}

I am using unset($form_element['#needs_validation']) because the if-statement in _form_validate() checks isset($elements['#needs_validation']), instead of !empty($elements['#needs_validation']).

In this way, the form element would not have #needs_validation set to TRUE, and Drupal would not check the returned value for the form element is one of the possible values it can get, nor is the length of a textfield string longer than required.
It doesn't avoid the form validation handlers are run, thought.


how to create hook for send email to profile2 type user

In condition add data comparison instead of user role if want to send mail only basis of profile type as below.

Edit:

In Action Section
Select Send Main or Send Html Mail under System and follow as below png file.

This may help it..


Deleting a Drupal 8 Content Type Field also Deletes all the Views linked to it... Undo?

Yes, that's what currently happens. Drupal informs you on the delete confirmation page what all will be deleted.

You can try one thing that to restore your backed up database.

Also, there is an issue that tries to improve it so that the view updates itself instead.


Date and links formatting in node template

Answer for the date formating: {{ date.value|date('U')|format_date('custom', 'j/m/Y') }}

For the URI investigate the data structure with twig vardumper.


You can handle this from CSS.

Like :

.button-logged-in.input{
    background-image: url(/images/buttons/submit.png);
}

Example : https://stackoverflow.com/questions/2920076/html-css-how-to-add-image-icon-to-input-type-button


Can't edit Main menu block in sidebar by clicking on "gear"

It is caused by legacy functionality in old versions of jQuery no longer being supported in more modern versions. In this particular case I think it has to do with browser version detection, which has fallen out of favour for feature detection.

Add the jquery-migrate script to your theme's javascript folder and load it via your theme's info file.

If you continue to have issues you might need to make sure this file loads directly after the jQuery main file.


This is the perfect place to use em instead of px for your font sizes. Change the font size in your body to font-size: 13px; or something, whatever size you want to be your standard size font.

Then, for all of the other elements, you can use em to adjust the size of the font based on percent. For example, font-size: 1.5 em; would be 1.5x larger than the standard size of 13px, and font-size: 0.5 em; would be 0.5x the size of the standard of 13px;


How do I send notifications for followers of a group when group content is updated?

Its depend on how regular you want to notify the user. If you want actual real time notification then go for nodejs module. See the documentation and you will get better idea about it.


How to remove author name from blog post url?

For Drupal 6; you can go to admin/build/path/pathauto page and change URL alias pattern for Blog content type (under Node paths settings).

You can make it blogs/[title-raw] or anything else you want.

Note: The picture above shows how to do change URL pattern. But, the URL pattern isn't what you want. The URL here something like that: term/blog-post-13.html.


Do I have to set a default value to a variable in Twig

It's controlled by a Twig environment setting, strict_variables:

  If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false).

Drupal doesn't change the default value, so if you also leave that setting at false you won't need to make sure variables exist before referencing them. In fact, if you set it to true I imagine quite a few core and contrib would start throwing exceptions.


view results not show for unadministrator users

What is your view path or URL? Is this URL protected for any specific user role?

1) Is there any field permission is given?

2) Can you please select role instead of permission from access? And set specific role you want to give permission.

3) Is there any contextual filter is applied?

4) Check your views filter criteria. Remove some of the filters which you have doubt on that filter and try it.


You can try https://www.drupal.org/docs/8/modules/permissions-by-term, hope this can solve your problem.


Get 404 for url specified in module.routing.yml

I believe you did not install the module

if you tried to install you would get

drush en final

  ParseError: syntax error, unexpected 'final' (T_FINAL), expecting identifier (T_STRING) in /home/giorgos/share/gwebsites/dru8.dev/web/modules/custom/final/src/Controller/ExampleController.php on line 2 #0 /home/giorgos/share/gwebsites/dru8.dev/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/home/giorgos/s...')
   #1 [internal function]: Composer\Autoload\ClassLoader->loadClass('Drupal\final\Co...')
  ...

final is reserved keyword thus it confuses the php parser when it sees

namespace Drupal\final\Controller;

Can also be caught with my vscode setup and linter

You have to change final to something else but then you have to rename it elsewhere in your module (folder name, file names, reference to the class etc)

Otherwise the module is working fine.


Cannot uninstall modules due to missing table br_schedule

Found the issue. My database updates are not happening. Ran updatedb:status with drush and I get:

file_entity                           8004        hook_update_n   Fix entity field mismatches on the file type field.
business_rules_schedule entity type               entity-update   The Schedule entity type needs to be installed.
file entity type                                  entity-update   The File type field needs to be updated.
node entity type                                  entity-update   The node.field_zipcode field needs to be updated.

"Fix entity field mismatches on the file type field." is failing so the "business_rules_schedule" update isn't happening.


Get all users with edit/view permission for a node

Every content type has fix pattern of permission

For node edit permission, Just use user_access() with string parameter
"edit own [content-type] content"
OR
"edit any [content-type] content"
If current user has this permission it return TRUE else FALSE

AND

If you want this permission for other user, Just pass user object as second argument in user_access()


Only Admin allowed to alter order in 'Review' state

The best way to achieve this might be with a custom module. You could use hook_form_alter() to alter the order edit form and add a validation function that checks the order status and the logged in user ID - and throw a form validation error before saving if you want to prevent them.

You might be able to accomplish this point-and-click-style with the Rules Forms module (https://www.drupal.org/project/rules_forms) which adds the ability to trigger Rules events during form validation. I haven't tried that module myself, so I can't say for sure.


How to get project's data from packages.drupal.org

Yes, the Composer documentation on repositories describes this mechanism, specifically, the provider-includes and providers-url properties.

These properties describe the package indexes & the URL pattern used for look up, for example:

https://packages.drupal.org/8/packages.json (root index)
https://packages.drupal.org/8/drupal/provider-2018-2%24082d3c8e1745428fcd819891137e88683576066b00ed52bd80811943e98e8d08.json (first index)
https://packages.drupal.org/8/drupal/commerce%24f8b852956418601bb4d985203d4138a18e2bfc0ae1b67b249a667228190fd26f.json (a specific package with all its releases)


Loading a views block inside another block

You can achieve it by following snippet in your block,

  Some random text here...
  echo views_embed_view('view-name', $display_id = 'display-name');
  Some random text here...

eg:

 <?php echo views_embed_view('test', $display_id = 'block'); ?> //dont forgot to enable text format as PHP.


Injecting metadata into all nodes within one folder

You won't be able to use PHP like that in Twig, but your logic isn't far off. One of the reasons Drupal 8 switched to using Twig was to avoid having potentially unsafe PHP in template files – this sort of thing generally belongs in a module rather than in a template, especially as it's not related to the presentation of content.

Drupal doesn't have a concept of folders, but we can look at the path of the content (e.g. /courses/drupal-development or /contact-us or /news/2018/cool-thing-that-happened) and work out if it's 'under' courses or not that way.

Something like this should work, but is untested:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $current_path = \Drupal::service('path.current')->getPath();
  $exploded_path = explode('/', $current_path);

  // Add Swiftype metatag, see https://swiftype.com/documentation/site-search/crawler-configuration/meta-tags.
  if ($exploded_path[1] === 'courses') {
    $metatag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'tags',
        'data-type' => 'course',
        'class' => 'swiftype',
        'content' => 'course',
      ],
    ];

    $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
  }
}

Or to do it by content type:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'instance') {
      $metatag = [
        '#tag' => 'meta',
        '#attributes' => [
          'name' => 'tags',
          'data-type' => 'course',
          'class' => 'swiftype',
          'content' => 'course',
        ],
      ];

      $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
    }
  }
}

If you need help setting up a module then take a look at https://befused.com/drupal/first-drupal8-module - but you can stop once you've created a your_module_name.module file – this is the file that the code above will go into.


Getting access denied when altering user view route

Can't be sure as you haven't posted your controller, but my guess would be that you are not type hinting the argument there as UserInterface $user, so it doesn't get upcasted. That is required for _entity_access to work


NID as a contextual filter doesn't work on some nodes

Finally I configured what was the problem. There were two referenced fields related with Relationship in view, and for those two relations I have checked the box "Require this relationship". So whenever I created content without any of those fields, content view was empty. When I unchecked  "Require this relationship" boxes, everything works good.
How ever thanks for your effords to help me.


What can cause duplicated XML sitemap links?

Please visit the feature request about "Remove duplicate links when using both menu and node sitemap". It has a patch which works fine.


Move field from one profile type to another?

There's no easy way. That means if you don't have a lot of records your better off doing it manually.

If you must:
   1. Add the field to profile type B.
   2. Change the nid in the field data and revision DB table for every user from the nid of profile A to the nid of profile B.
   3. Remove the field from profile type A.


how to assign different default images to different roles

If you want to display an image for a particular user role , say "Role1" , then in page.tpl

 <?php global $user;
  if($user->roles[2] == 'Role1')
 {
 print $logo;
 }?>

Just print the $user to get in what values your role is in the role array.

If you print $user, your role may be in this,

 [roles](
 [1] = role1
 [2] = role2
 [3] = role3
       )

So choose your role and check the condition and accordingly print the $logo however before that get the image in $logo using the image source tag.


Your question is indeed very confused. You might first clarify some Drupal basic concepts.

What is a block ? "Blocks are the boxes of content (such as "User Login" or "Who's online") that can be displayed in regions (such as footer or sidebar) on your page." Read Working with blocks (content in regions) for full understanding.

What is a content type ? We don't speak about structures but content types : a Content Type is a pre-defined collection of data types (Fields), this is how site editors can input original content on a Drupal site. Read Working with content types and fields.

What is a view ? "Using the Views module, you can fetch content from the database and present it to the user as lists, posts, galleries, tables, maps, graphs, menu items, blocks, reports, forum posts etc." Read Working with Views.

How to change the way blocks, fields, and so on display  ? this is a very wide question.

Without editing any code, you can make some basic choices in admin/structure/types/, and for the content type you'd like to edit,  manage display of each of the fields
you can install an infinity of contributed themes
you can create your theme, and then customize your regions, edit your stylesheets... A good place to begin might be the Theming Guide

Drupal is a very powerful CMS / CMF , but you'll have to deal with these concepts to feel a bit more confortable


Page template suggestion based on content types but not for node/edit or node/delete

A slightly different approach: Add a custom theme suggestion for the canonical route of your node type(s).

This way, you neither have to meddle with path arguments whose position might change, e.g. when using subpath aliases in a later stage of your site's development cycle, nor have to extend your checks for additional routes added by third party modules, as e.g. node/{nid}/translate, node/{nid}/revisions, node/{nid}/devel, and so on.

I didn't test it though, but you could do something like this:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for page.html.twig.
 */
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (
    $route_name = \Drupal::routeMatch()->getRouteName()
    && $route_name == 'entity.node.canonical'
    && $node = \Drupal::request()->attributes->get('node')
  ) {
    $suggestions[] = 'page__node__' . $node->getType() . '__canonical';
  }
}

Then you could rename your page template to page--node--my-type--canonical.html.twig and it should be picked up only for your node type my_type at its canonical (view) route.


I suggest using Privatemsg module it had a nice attachment field and now it is fieldable that means you can add highly customizable file fields.

Thou Privatemsg module will work not as content type but more like internal messaging tool I also suggest checking out Notifications which depends on Messaging module. It will send emails upon creation or edit of chose content for all users you chose. You may also look into Team Notifications module which will allow your users to create subscriptions for others. Which is integrated with Organic groups module (OG). OG is best way for grouping and allowing users to group themselves yet if you are looking for a simple solution this may not fit due to it`s extensive functionality which results in fairly complex results.


How can I use Drush to sanitize a database on a remote server?

You can use sql-cli command for that:

  drush @alias.dev sql-cli < custom_sanitize.sql


Twitter feed on Drupal from multiple accounts

The twitter module allows you to get the tweets from various accounts and display them  via views.

So you can have a view for your first 3 users and then another one for the other two and so on...

Now, you will have to provide an authenticated account  via the twitter apps api. But then you'll be able to pull tweets from other non authenticated accounts.


Is it possible to run drush 8 smoothly on Win10 WSL (Windows Subystem for Linux)?

We haven't tried this yet. Please give it a spin, and report your results in the issue queue.

Note also that if you want the dev branch of Drush 8, you should use the 8.x branch.  The master branch is now Drush 9.


Multiple separate forms for searching up different apache solr indexes

The the Search API is perfect for the job. This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine (including Solr). You can create multiple indexes with their own individual search pages/blocks and have granular control over what fields are searched and the relevancy.


How to award User Points after checkout using Rules?

In order for your Rules Condition to be satisfied, ALL these criteria must be true:

Order contains the product whereas the SKU of that product must be "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI".
The quantity of the specified product on the order must be "= 1".

Since the user does not seem to receive the userpoints, it must be because of either of these reasons:

Reason 1: your Rules Condition is not satisfied. Assuming that there is no typo in the SKU value, it could be because the quantity is NOT "= 1".

As a quick check to find out if this is what is causing your issue, simply do a test in which you (temporary) change this rules condition to the opposite, by using the "negate" checkbox for that Rules Condition. If in that scenario the userpoints are granted, you can be sure that the quantity is indeed NOT "= 1" (even though you may think/expect that to be the case ...).
Reason 2: your Rules Condition is OK, but your Rules Action for some unknown reason does not actually grant the points to the user.

As a quick check to find out if this is what is causing your issue, just add another Rules Action (before the one you have already) to simply "Display a message" (which you find within "System"). All the message should be is something like "Rules Action triggered". If in that scenario such message is actually shown, you can be sure that the cause of your problem is something related to your Rules Action (to grant points) that is not working as you think/expect it to work.

If none of the above helps, then it's time for Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".


How to create a multilingual node programmatically?

Fortunately I found a post named Create and translate a multilingual nodes programmatically.

And here is the code with some comments:

use Drupal\node\Entity\Node;

$node = Node::create([
  // The node entity bundle in this case article.
  'type' => 'article',
  //The base language
  'langcode' => 'en',
  'created' => \Drupal::time()->getRequestTime(),
  'changed' => \Drupal::time()->getRequestTime(),
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  //If you have another field lets says field_day you can do this:
  //'field_day' => 'value',
  'body' => [
    'summary' => '',
    'value' => '
The body of my node.
',
    'format' => 'full_html',
  ],
]);
//Saving the node
$node->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/my/path", "en");

//Creating the translation Spanish in this case
$node_es = $node->addTranslation('es');
$node_es->title = 'Mi prueba!';
$node_es->body->value = '
El cuerpo de mi nodo.
';
$node_es->body->format = 'full_html';
//Saving the node
$node_es->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/mi/ruta", "es");


Check if anything in this list of typical things might help:

Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly (in your settings.php).

Another option is to check the logs. If you find errors there (like PHP Fatal errors), then try to narrow down that error to the module that causes the error and disable that module (and report it in its issue queue on Drupal.org). If you don't know which module is causing it, then first disable all modules, and enable them one by one again. If at some point the error then comes back, then that must be the problem module causing your problem. Then disable that module again and re-enable all others.


Embed a collection of form inside a form

Drupal forms are very different from Symfony forms.

There is no concept of sub-forms, but there is no limit to the complexity a single form can have as a form is an almost arbitrary render array structure.

A commonly used concept there is #tree. By default, the form input element names are flat.

If want to edit multiple elements in the same form, you can build a structure like this:

<?php
$form['#tree'] => TRUE;
foreach ($things as $id => $thing) {
 $form['things'][$id]['name'] = ['#type' => 'textfield', ...]
}

Without #tree, you would have multiple textfields named 'name', when set to TRUE, you get something like name="things[5][name]".

In Drupal 7 and earlier, it was complicated to render those nested forms in a table, you needed custom theme functions that then built the actual table. In Drupal 8, it just works, in the above example, you would just need to add something like $form['things']['#type'] = 'table' and then each $id will be a table row.

Then you can get all those values in the submit method with $form_state->getValue('things') and process them again in a loop.


Unless you're running a multi-site or another non-standard configuration (and the way the question is phrased, I do not think you do), you can't delete the sites/default folder or the files within it.

The reason you can't delete it is because: This directory (unless you've set up a multi-site or similar) contains (among other things) the settings.php for your site. If you delete it, all you settings including the database credentials will be lost, and your site will stop working.

Please also note that the sites/default folder has nothing whatsoever to to with the theming of your site.

If you have installed a new theme, and have the problem that the new theme is not used, this problem is not related to the presence of the sites/default folder on your site.


Editing a node deletes body content reproducibly if Locale module enabled

Implement hook_form_submit() and either set a breakpoint there, output to the messages or log the form_state values to see what's actually being submitted. Implement hook_node_presave() and do the same to see what's actually going to be saved to the database.
There is a chance the client-side JS or some validation hook changes the value for the field, so you will have to either dig or debug through all your modules. It's hard to tell something specifically, because any module, either contrib or custom one, can put its own hook and empty the content for some reason.


Add ajax on hook_field_widget_paragraphs_form_alter

You should be able to get this information from the submitted data in $form_state, specifically the triggering element.
For example:
use Drupal\Component\Utility\NestedArray;

function _type_paragraph_callback(array $form, FormStateInterface $form_state) {
  $button = $form_state->getTriggeringElement();
  // Go one level up in the form, to the widgets container.
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -2));

  return $element;
}

I've copied this from the Paragraphs module:
modules/contrib/paragraphs/src/Plugin/Field/FieldWidget/InlineParagraphsWidget.php


Print Preprocessed username Field Value in User Template

You're probably looking for the username theme:

$variables['userName'] = [
  '#theme' => 'username',
  '#account' => $account,
];


How do I programmatically "place" an order?

A little digging and I figured it out on my own:

Event handler for for this event: commerce_order.order.paid

and with this handler code:

  public function paymentCompletedHandler($event) {
    $order = $event->getOrder();
    $order->getState()->applyTransitionById('place');
    return;
  }


How do I reset the number of failed login attempts?

Drupal 7 prevents brute force attacks on accounts. It does so by refusing login attempts when more than 5 attempts failed. The amount of failed logins is recorded in the table 'flood'.

You can either wait before trying to login again, or clean the flood table following one of the procedures below:

Manually delete all of (or the last applicable) rows in 'flood' table.
Execute the following query on the Drupal database. To execute this query it will be necessary to login to the database. This is typically done through the command line or through a GUI interface such as phpMyAdmin.

DELETE FROM `flood`;

From the command line, with drush installed, execute the following command:

drush php-eval 'db_query("DELETE FROM `flood`");'


How to set up drush aliases for a local server for rsync?

To set up to do a drush rsync or drush sql-sync to a remote machine, set up aliases for both sites on the local machine.  The alias for the local site should be as you have shown in your question.  For the remote machine:

$aliases['stage'] = array(
    'uri'  => 'staging.mysite.com',
    'root' => '/home/user/www/mysite',
    'remote-host' => 'stagingfqdn.myisp.com',
    'remote-user' => 'wwwadmin',
  );

'remote-machine' should be the fully qualified domain name of the machine that hosts the remote site.  This may or may not be the same as the 'uri' parameter.  You might need to edit /etc/hosts, but only if the remote machine is not resolvable in DNS (unusual).  The 'remote-user' should be the name of the user that owns the files at the Drupal root; usually this is not the user that the web server runs as.

It sometimes makes sense to sql-sync from local to remote -- for example, when bringing a site live for the first time.  Usually, though, you are going to want to rsync your code from local to remote (or check it out from a vcs), and sql-sync your database from remote to local (and never the reverse).  This will insure that you do not overwrite user-generated content. See the features module for one common solution for pushing configuration to the remote machine via copying files.

Edit: Made a typo: said 'remote-machine', but it should have been 'remote-host'.  Corrected above.

Edit 2: Originally I said "rsync your files from local to remote (and never the reverse), but I meant code.  Corrected above.  It is, of course, reasonable and customary to rsync %files from remote to local, as shown in your updated question.


Fatal Error when trying to log in DRUPAL

Can you confirm which version of php you are using? I just realized that the magic php constant "DIR" (which I first used here in beta4) may only work in php versions 5.3 or greater, so I'm guessing you have a version that's below v5.3.

According to the Drupal requirements, the PHP requirement for Drupal 7 is "PHP 5.2.5 or higher (5.3 recommended)", So I may have made a mistake by introducing a construct that's not compatible with some php versions that Drupal 7 still supports. I'll need to fix this, but either way if you can confirm your php version that would be very helpfu


Create your first view block for Apartment with the exposed filter. Create attachments for each of the other two that inherit the exposed filter. As the comments stated, as long as they used the same field this will work perfectly.


It turned out to be a problem with nginx/php5-fpm settings that timeout prematurely. When I use apache (using another port) the problem does not exist.


Use a try...catch block and recover in whatever way makes most sense to your application.
The file is already on the disk by the time you get access to it (in the /tmp folder), so no. If you don't explicitly choose to keep it, it will be deleted either by a system job or the system module's cron run.


Node image instead of pointer icon in openlayers map

output the image's URL in your view which supplies data to your map.
create a new openlayer style, and for the marker graphic, give it your field name enclosed in ${}.

eg. add field_image to your view, set it to output 'url to file'
then add a new style and tell it the marker graphic url is ${field_image} and select an image style (eg. thumbnail)

use this new marker style on your overlay and you'll see the image show up as a marker icon.


Getting the selected option value of a radio button in form_state storage

Try using a string for the step id, something like this:

function multiform_second_form(&$form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  $options = array(
  'simple' => t('Simple'),
  'multiple' => t('Multiple'),
  'custom' => t('Custom'),
  );

  $form['qtype'] = array(
  '#type' => 'radios',
  '#title' => t('question'),
  '#options' => $options,
  '#description' => t('Chose a question type.'),
  '#default_value' => 'simple',
  );

  $option_value = isset($form_state['values']['qtype']) ? $form_state['values']['qtype'] : 'simple';
  $form_state['storage'] = array(
    'qtype' => $option_value,
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Next step'),
  );

  $form['#submit'][] = 'multiform_second_form_submit';

  return $form;
}

function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['next']) && $values['op'] == $values['next']) {

  switch ($form_state['storage']['qtype']) {
    case 'simple':
    $form_state['storage']['step'] = 'multiform_qsimple_form';
    break;
    case 'multiple':
    $form_state['storage']['step'] = 'multiform_qmultiple_form';
    break;
    case 'custom':
    $form_state['storage']['step'] = 'multiform_qcustom_form';
    break;
  }

  }
}


Views Filter Content Type Drop down option sorting

One solution here is to use the Grouped filters option the Filter type to expose setting. In each grouped filter you can use the Is one of... operator and select the type. Grouped filters have weights that you can drag around to any arbitrary ordering.

As an example, here's a reverse ordering of content types:


It sounds like you are almost there but without writing custom templates for each content type I would look at display suite. That way, when you click manage display for each different content type you can choose "custom display settings" and then "search result". This will let you build a different layout for each different content type as a search result (and if you like eventually build your own template files easily based on display suites templates).

Then you go back to your view and choose "Show: Display Suite -> Search Result" and each result will be shown as you have set up in the manage display screen for that type. You can still use all the filters and sorts as you like.


remove fivestar rating from $print['content'] in print module

go to your content type manage display page and enable the custom display for the print view mode: http://prntscr.com/e0k5d6
go to newly enabled print custom display and hide your fivestar field: http://prntscr.com/e0k633


Include a part template on specific node page

If you want override page.html.twig for special node 2. You can try this code

{% if node.id == '2' %}
   {% include directory ~ '/templates/parts/custom_html.html.twig' %}
{% endif %}

if other template you need process in your function theme first:

YOUR_THEME_process_FUNCTION_THEME(&$vars) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $vars['node'] = $node;
  }
}


If I clearly understand your question You want to create something like this:

Different layout based on Node Type

Go to Structure --> Pages and enable Node Template (/node/%node)
There should be only one variant - go to Selection Rule. From drop down menu choose Node Type: and then choose Variant for Node Type being viewed.
Create as many varants as you need for any Node Type


How do I make an ajax callback in Field Plugin formElement() reload form?

Here is what I did in TVI which does something similar to what you are doing (changing out options):

    // form code ...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

// form code ...

  /**
   * Ajax callback - null the value and return the form.
   * The value gets nulled because we cannot overwrite #default_value in an ajax callback.
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @return mixed
   * @see https://www.drupal.org/node/1446510
   * @see https://www.drupal.org/node/752056
   */
  public function loadDisplayOptions(array &$form, FormStateInterface $form_state) {
    $form['tvi']['view_display']['#value'] = '';
    $form_state->setRebuild();
    return $form;
  }

In my form code, I am reading the values from $form_state and checking them - which is passed to a function that populates the option list. Therefore, when the AJAX callback rebuilds the form, the new option list will be populated.

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->config('tvi.global_settings');
    $views = Views::getEnabledViews();

$view_options = ['' => ' - Select a View -'];
$display_options = ['' => ' - Select a View Display -'];
$default_display = '';

foreach ($views as $view) {
  $view_options[$view->id()] = $view->label();
}

if (isset($values['view'])) {
  $display_options += $this->getViewDisplayOptions($values['view']);
}
elseif ($config !== NULL) {
  $view = $config->get('view');
  $view_display = $config->get('view_display');

  if (isset($view)) {
    $display_options += $this->getViewDisplayOptions($view);
  }

  if (isset($view_display)) {
    $default_display = $view_display;
  }
}

$form['#prefix'] = '
';
$form['#suffix'] = '
';

// irrelevant fields redacted...

$form['tvi']['view'] = [
  '#type' => 'select',
  '#title' => 'Using the view',
  '#description' => $this->t('The default view that you want to use for all vocabularies and terms.'),
  '#default_value' => $config->get('view'),
  '#options' => $view_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#ajax' => [
    'callback' => '::loadDisplayOptions',
    'event' => 'change',
    'wrapper' => 'tvi-settings-wrapper',
    'progress' => array(
      'type' => 'throbber',
    ),
  ],
];

$form['tvi']['view_display'] = [
  '#type' => 'select',
  '#title' => 'With this view display',
  '#description' => $this->t('The view display that you want to use from the selected view.'),
  '#default_value' => $default_display,
  '#options' => $display_options,
  '#states' => [
    'visible' => [
      ':input[name="enable_override"]' => array('checked' => true),
    ]
  ],
  '#prefix' => '
',
  '#suffix' => '
',
];

return parent::buildForm($form, $form_state);
}

(Sorry for the broken paste) So when the form rebuilds, the options are populated from another method, while the AJAX callback just triggers a rebuild.

As a side note, the reason I am setting #value to '' is to force the field to default to the placeholder 'Select a Value' on change. Otherwise, it will stick to the last selected position by the user.


Keep custom theme when using AJAX submit

The form AJAX callback uses /system/ajax as the default. The menu router item for /system/ajax implements a theme callback to try and render the ajax contents in the same theme. For example, perhaps this is a node edit form and you have set node forms to use the same theme as the admin theme. The callback will find that. In your case, it is likely rendering in what it thinks is the default theme. Fortunately, you can specify your own ajax path like so:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('class' => array('submit')),
  '#ajax' => array(
    'callback' => '_display_form',
    'wrapper' => 'ajax_wrapper',
    'effect' => 'fade',
    'event' => 'click',
    'path' => 'vista/system/ajax'
  ),
);

You'll then have to create a menu item for 'vista/system/ajax', which I guess would be a duplicate of 'system/ajax' without theme callback. Perhaps something like this:

/**
 * implements hook_menu
 */
function mymodule_menu() {
  $items['vista/system/ajax'] = array(
    'title' => 'AHAH callback',
    'page callback' => 'ajax_form_callback',
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    // 'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
    'file path' => 'includes',
    'file' => 'form.inc',
  );
  return $items;
}

Don't forget to clear cache so the new menu item takes affect.

Also, I wanted to bring your attention to the ThemeKey module which is great way to change themes based on path.


You can find validation in Contextual Filter. I am attaching screen shot for the same.

However you can also use the glossary view which is provided by Drupal.


Bulk editing of Fields on multiple entities

The Multiple forms module might point you in the right direction.

Here is a quote from its project page:

  This is an API module which lets you put several forms into one <form>.


Replace URL query string with slash for a cleaner URL

You can use something like this on your custom module for the redirects with the query strings.

/*
 * custom redirect with query string
 * module implements hook_init()
 */

function MyModule_init() {
  if ($_GET['q'] == 'userguides/contacts/my-first-user-guide/article/referral-partners') {
    drupal_goto('userguides/contacts/my-first-user-guide', array('query' => array('article' => 'referral-partners')));
  }
}


You can achieve that using the Feeds module

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  PubSubHubbub support
  Create nodes, users, taxonomy terms or simple database records from    import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

This article might help you to achieve this.


How to redirect everything to 404 not found?

If you are just trying to keep it from being indexed, you can just add

User-agent: *
Disallow: /

To the top of your robots.txt


Access a field from page.html.twig template

The page title has its own preprocess hook. You may want to use hook_preprocess_HOOK() to add your image to the variables. As it is using the page-title.html.twig template, the theme registry HOOK is called 'page_title'.

Following is an excerpt from a theme's page title preprocess function of a D8 theme that is adding the URI of an image with an image style applied along with the page title. Maybe you find it useful as inspiration for your use case:

use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_HOOK() for page title images.
 */
function mytheme_preprocess_page_title(array &$variables) {
  $image = '';

  // Load the image entity from current route.
  if (
    !empty($node = \Drupal::routeMatch()->getParameter('node')) &&
    $node->getType() == 'page' &&
    $node->hasField('field_image') &&
    $image_entity = $node->field_image->entity
  ) {
    $style = ImageStyle::load('title_image');
    $image = ($style->buildUri($image_entity->getFileUri());
  }

  $variables['image'] = $image;
}


How to add custom checkout pane to drupal-commerce in drupal 8

Here is an excerpt from our step-by-step guide "Creating a custom checkout pane for Drupal Commerce in Drupal 8". The rest can be found here: https://ws.agency/blog/creating-custom-checkout-pane-drupal-commerce-drupal-8

"In this article, I'll show how you can create a custom checkout pane for Drupal Commerce in Drupal 8. For this purpose, we'll create a checkout pane with a configuration form and the ability for users to add coupons to their order.

Checkout pane needs to be created with the correct annotation and in the correct namespace. We'll create CommerceCoupons class in module_name/src/Plugin/Commerce/CheckoutPane directory with annotation like in code below.

namespace Drupal\module_name\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the coupons pane.
 *
 * @CommerceCheckoutPane(
 *   id = "coupons",
 *   label = @Translation("Redeem Coupon"),
 *   default_step = "order_information",
 * )
 */
class CommerceCoupons extends CheckoutPaneBase implements CheckoutPaneInterface {

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition,     CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
}

This means that our custom checkout pane will have an id 'coupons' and will be labelled as Redeem Coupon and will be set on order information step by default.

First, we'll create the settings (configuration) form for our pane. For this purpose, we'll have settings if we, for example, want to set up that user has the ability to redeem only one coupon on order. For this, we'll have to implement four functions.

First, we'll setup our default configuration.

/**
 * {@inheritdoc}
 */
public function defaultConfiguration() {
  return [
      'single_coupon' => FALSE,
    ] + parent::defaultConfiguration();
}

Then we'll implement summary for our configuration form.

/**
 * {@inheritdoc}
 */
public function buildConfigurationSummary() {
  $summary = !empty($this->configuration['single_coupon']) ? $this->t('Single Coupon Usage on Order: Yes') : $this->t('Single Coupon Usage on  Order: No');
  return $summary;
}

Next, we'll build our configuration form..." Continue reading...


How can I create two blocks at once from the same custom module?

You can a create as many block plugins as you want within a single module. Each of these plugins must have a unique ID in annotation. In order to reduce code duplication you can create an abstract class that would hold all common functionality. Other classes can extend it and override methods that need a different implementation.


I think the answer from @ipwa is close but is not quite there.

What you want is an output like this:

<img src="/fallback.jpg" srcset="/1x.jpg 1x, /2x.jpg 2x, /3x.jpg 3x" />

Here's what you need to do:

Enable both the Breakpoint and Repsonsive Image Style modules.
Add an image field for uploading 1 image to a content type. Editors should upload the highest quality image needed.
Configure three normal image styles that produce the desired resolutions for each of the 1x, 2x, and 3x pixel densities.
In your theme, or a custom module, create a breakpoint yaml file with the following contents:

my_module_or_theme.image_pixel_density_only:
  label: Pixel Density Only
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
    - 2x
    - 3x

Rebuild caches.
Add a new responsive image style.
Configure the responsive image style so that it uses the breakpoint group that you just created. This should expose a 1x, 2x, and 3x fieldset. For each of these fieldsets, select type "Select a single image style." and choose the appropriate image style.
Configure the image field formatter for image field you created in step 1 to use the responsive image style you just created.

Drupal will output the srcset just like I described above and will not output a "sizes" attribute (which you don't need). Browsers will know what the pixel density is of the device and automatically select the most appropriate image based on that.


See this tutorial. Looks like it does exactly what you ask.

The tutorial includes a video but here is the written explanation:

1) Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)

2) Create a Taxonomy View here: admin/structure/views/add

You want to make sure that you choose "taxonomy" entities.

3) Add a contextual filter for "Taxonomy term: Parent term"

Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

4) Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.

5) Save that view and create a new view here: admin/structure/views/add

Make sure this view is for a "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

6) Add a contextual filter for your taxonomy term, mine was called "Product Categories"

Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

7) Add a "No results" item called a "View Area" and select "Page_1" from your first view (this is the second page we created)

8) Save this view and go back to the first view.

9) Add a "No results" item called a "View Area" and select the second view that we just made.

10) Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/[name]" that way your catalog names are clickable


PDF with print module and wkhtmltopdf - how to install?

I have downloaded the latest version for Windows.
  As described in the instructions I put the executable in the directory sites / all / libraries.
  After I renamed the cryptic file names wkhtmltox-0.12.1.2_msvc2013-win32.exe in wkhtmltopdf, it was recognized in the print module settings.

The executable you've downloaded is the installer, not the wkhtmltopdf executable. You need to install it to the sites/all/libraries.


go through the discussion on https://groups.drupal.org/node/177179. You will get to know the answer of your question


How to clear Text in search box once the user selects other option

I think you can do it in 2 ways:

You can use javascript to clear the value of textfield after
page load or on click.
You need to rewrite field or rebuild form when option changes.

It`s all that i can say without some code.


One option would be to create a custom route. You might need to use a different name than /node/add/

So in a custom module add in your_module.routing.yml

article_add:
  path: /add/article/{{ keyword }}
  defaults:
    _form: '\Drupal\your_module\Form\AddArticle::AddArticleWithYourKeyword'
  requirements:
   _permission: 'administer site configuration'

And then create a Form in your_module/src/Form/AddArticle.php

<?php

namespace Drupal\your_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class AddArticle extends ControllerBase {
    public static function AddArticleWithYourKeyword($keyword) {
         //Here you can generate your form with your added keyword and return it as a render array
    }
}

This will allow you to grab a form and make edits to it, or generate an entirely custom one. In my example I made it so you pass the keyboard in the path itself not as a GET variable, but if you need you can just make the route /add/article/ and then check for GET variables inside your function.

UPDATE
Another method would be to implement the hook_form_alter function

function yourmodule_or_theme_form_node_form_alter(&$form, FormStateInterface $form_state) {
$request = \Drupal::request();
$keyword       = $request->get('keyword');
  if (in_array($form['#form_id'], ['node_article_edit_form'])) {
    $form['keyword'] = [
      '#type' => 'textfield',
      '#title' => 'keyword',
      '#default_value' => $keyword,
    ];
  }
}

Not 100% sure of the syntax but that's the general idea.


Webfrom Validation on textfiled when using default value

Sorry that this isnt a direct answer to your question, but it seems to me to be bad practice to use a default value in an input field and then disregard it as a submission. Would a placeholder not  be more appropriate for your requirements?
You could even style the placeholder to look like form input via CSS


There is no easy way. You have to have deep knowledge of the site's content to know how to edit what appears on the page. This is only obtained through poking around the site or asking a knowledgeable colleague.


How to get webform field value in hook_webform_results_access

$submission->data[$sid][0]

for exemple:

if (webform_results_access($node) && ($node->nid == '23')) {
      $actions['resend_ical'] = array(
      'title' => t('Resend ical'),
      'href' => 'ical?' . $submission->data[5][0] . '&' . $submission->data[6][0] . '&' . $submission->data[35][0] . '&' . $submission->data[36][0] . '&' . $submission->data[24][0] . '&' . $submission->data[34][0] . '&' . 'node/' . $node->nid . '/submission/' . $submission->sid ,
      'query' => drupal_get_destination(),
    );
  }

this is that simple!


Is it possible to abort sending of the e-mail somewhere in the middle of sending procedure?

As reported in the documentation for hook_mail_alter(), you can avoid a message is sent by setting $message['send'] to FALSE.

  Parameters

  $message: An array containing the message data. Keys in this array include:

  'id': The drupal_mail() id of the message. Look at module source code or drupal_mail() for possible id values.
  'to': The address or addresses the message will be sent to. The formatting of this string will be validated with the PHP e-mail validation filter.
  'from': The address the message will be marked as being from, which is either a custom address or the site-wide default email address.
  'subject': Subject of the email to be sent. This must not contain any newline characters, or the email may not be sent properly.
  'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.
  'headers': Associative array containing mail headers, such as From, Sender, MIME-Version, Content-Type, etc.
  'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before hook_mail_alter() is invoked.
  'language': The language object used to build the message before hook_mail_alter() is invoked.
  'send': Set to FALSE to abort sending this email message.

At least, your code should check the value of $message['id'] which is a concatenation of the short name of the module and the key assigned to the message from the module.

function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {

    // Verify other conditions are true.

    $message['send'] = FALSE;
  }
}


Restrict acces to file field only to certain role

like Colin McClure says, to control per node you can use with http://drupal.org/project/content_access .In the respective Access Control tab of each Content Type (when you edit a content type), you will find, in the bottom, the option to enable per content node access control settings.

About control per fields, seems that exist several modules to achive this:

http://drupal.org/project/field_permissions
http://drupal.org/project/cck_private_fields
http://drupal.org/project/privacy

and, from this resource you can find hooks to get permissions per field:

http://drupalcode.org/project/cck.git/blob/refs/heads/6.x-3.x:/modules/content_permissions/content_permissions.module

<?php

/**
 *  Implementation of hook_perm().
 */
function content_permissions_perm() {
  $perms = array();
  foreach (content_fields() as $field) {
    $perms[] = 'edit '. $field['field_name'];
    $perms[] = 'view '. $field['field_name'];
  }
  return $perms;
}

/**
 * Implementation of hook_field_access().
 *
 * @see content_access().
 */
function content_permissions_field_access($op, $field, $account, $node = NULL) {
  switch ($op) {
    case 'view':
    case 'edit':
      return user_access($op .' '. $field['field_name'], $account);
  }
  return TRUE;
}


I had to add the form and form elements as a Form under the src/ directory and call it with

 $form= \Drupal::formBuilder()->getForm('Drupal\pup_viewfiles\Form\PagerForm', $extra);


Files in Media and Plupload module not showing in content selector

Upgrade to the latest 2.x-dev versions of media and file_entity modules.  I doubt you will see this issue anymore.


As the BaseFieldDefenitions are cached, this won't work I believe.

I think you would be better off by using SetDefaultValueCallback:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetDefaultValueCallback/8.2.x


Adding metadata to a node through a module

Your requirement seems pretty straight forward. If you want to save some time, I would suggest that you use the Field API. To make those fields non-editable by users and administrators, all you need to do is implement a hook_form_alter and hide the form elements. You can also implement hook_form_FORM_ID_alter, which I find more efficient.

Example. Hide the author field:

$form['author']['#access'] = FALSE;


In Drupal 6, this would be:

 page-node-summary.tpl.php

More information on Drupal 6 template suggestions can be found at http://drupal.org/node/1089642

In Drupal 7, this would be:

 page--node--summary.tpl.php

More information on Drupal 7 template suggestions can be found at http://drupal.org/node/1089656

In either case, I'd grab the default page.tpl.php of your theme as a basis for it.


How to get success message in popup using custom form?

You can return the messages to the ajax form by adding the following to your ajax callback function (you'll need to remove your current return value)

$messages = array('#theme' => 'status_messages');
$commands = array();
$commands[] = ajax_command_prepend('#form_id', render($messages));

return array('#type' => 'ajax', '#commands' => $commands);

Make sure to change #form_id to the actual ID of your form, or use whatever jQuery selector you want to prepend the messages to.


Migrate-d2d UI - Where does sites/default/files source content go?

I'll post this as a preliminary answer, but please feel free to comment with better suggestions.

Step 4 (Files) of the migrate_d2d UI asks for path where the source files can be found.  I took the conservative approach and uploaded the legacy sites/default/files file system to a separate source directory on the development server, but I don't see why you couldn't directly import the legacy file content into the sites/default/files directory on the destination server.

At least this seems to work so far.


Different fields in user profile for different user roles

Field Permissions will let you assign different permissions to a field based on role.

  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


Date module provides three different formats, read about them here: Difference between date, datetime, and datestamp


SOLVED:

According to the documentation, the only required properties are field_name, entity_type and bundle.  So I commented out:

'label' => t('qid'),
'widget' => array(
  'type' => 'textfield',
),

And now the field and instance install and uninstall properly.  I'm fairly sure 'textfield' is an inappropriate widget type.


That behaviour is hard-coded with a SelectQuery; the prefix will apply to all tables, without exception, and there's no mechanism in place to override it. It happens in SelectQuery::__toString() if you're interested.

If you want to change that, you'll need to subclass SelectQuery, add a mechanism to let the class know which tables should/shouldn't be prefixed, and override the __toString() method to take that into account. Then you'll need your own version of db_select(), which uses your new custom version of the class.

All that's probably not worth the effort given that you can run an arbitrary SQL string with db_query(). For example, the following won't attempt to prefix custom:

db_query('SELECT * FROM custom c')


How do you include a field.tpl.php, to a custom views field handler. outside of the theme?

If you want to have a template file being loaded from your module's templates folder, you should do the following:

Implement hook_views_api to tell Views where you keep views templates, e.g. your_module/templates
Following the naming conventions for Views and add views-view-field.tpl.php into your module's template folder, e.g. your_module/templates

After you clear your cache and rescan the template folders using Views UI, your tpl file should be selected.

Hope this helps, the main source for this answer was https://stevenyeung.com/article/template-override-drupal-views-3-from-module/


Change the default timezone variable_get from views

If you want to change the time zone, the option is available in admin menu in:

admin/settings/date-time in Drupal 6
admin/config/regional/settings in Drupal 7

And it can be defined in settings.php as date_default_timezone

It can be accessed in Database in variables table too

SELECT *  FROM variable WHERE name LIKE  '%timezone%'


How do I make a multi item table order list for Drupal Commerce?

I think you're looking for the Commerce Add to Cart Extras module. You can use this with Views to build your own lists of products and add multiple quantities of multiple products with one click.


I just did a fresh Drupal 6 install with the latest Secure Pages module. Only modules enabled are default core + Secure pages. I did not modify permissions in any way.

Using the default Secure Pages settings, including

user
user/*

in the "Pages:" textarea, navigating to /user while logged out presents me with the user login form on a secure page, and logging in sends me back to the home page (where I started).

How are you redirecting your users to their /user profile upon login? Logintoboggan or some such? Let me know and I'll dig further.


Try It works for me.

$items['package/%/edit'] = array(
'title' => 'Edit data Row',
'page callback' => 'pricepackages_form_update',
'page arguments' =>array(1),
'type' => MENU_NORMAL_ITEM,
'access callback' => TRUE,
);

function pricepackages_form_update($arg){
$my_object = db_select('your table name', 'a')
->fields('a')
->condition('your node id parameter', $arg )
->execute()
->fetchAssoc();
return drupal_get_form('your form menu', $my_object);
}


The way you are using #prefix and #suffix is wrong. It should not be a part of #upload_validators array.

    $form['cvFile'] = array(
    //'#title' => t('Upload your CV'),

    '#type' => 'managed_file',
    //'#description' => t('The uploaded file will be processed.'),
    '#default_value' => variable_get('cvFile', ''),

    '#upload_validators' => array(
        'file_validate_extensions' => array('pdf doc docx'),
    ),

    '#prefix' => '',
    '#suffix' => '',
    '#upload_location' => 'public://cv/',
    '#process' => array('gng_job_my_cv_element_process'),

    );

Check the form API for this : https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#prefix
https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#suffix


The hook implementations ARE cached inside the database.. this is why it's necessary to clear cache in order for a newly implemented hook to fire.

Taking a look, inside the cache_bootstrap table, there is a row with cid value of module_implements, and it's data value is a very large serialized string.  When unserialized, it is an array of the form

  'hook_name' => array('module1', 'module2', 'module3', ...)

The hook names have the hook_ beginning lopped off, so hook_block_info() will appear as block_info. I believe the value is the list of modules which implement that hook, so...

  'block_info' => array('views', 'webform', 'my_module')

Means that the following hooks are registered and should be fired:

views_block_info()
webform_block_info()
my_module_block_info()


Figured it out: visit admin/config/media/file-types and pick the file type you want to edit (Youtube media are Videos). Pick one of the file displays (Small, Big, Original) and enable the Youtube Preview Image display. Finally, pick an image style in the dropdown menu.

Then, visit the Manage Display tab. If you previously chose the Small file display, for example, edit the Display to make sure the File will be shown.


Change the error message "An illegal choice has been detected. Please contact the site administrator."

This is to add onto Letharion's answer. Using the same principle, we can also check for error messages to replace in the validator.

function MY_MODULE_form_validate($form, &$form_state){
    $errors = drupal_get_messages(); // (dpm()'s has to go AFTER this line--they get cleared)
    foreach ($errors as $type => $id) {
        foreach ($id as $message){
            // Loop through individual messages, looking for ones to remove or replace
            if (test_for_invalid_error($message)===FALSE){
                drupal_set_message($message,$type);
            } elseif (test_for_invalid_error($message)!==TRUE){
                drupal_set_message(test_for_invalid_error($message), $type);
            }
        }
    }
}

function test_for_invalid_error($message){
    if (strpos($message, 'An illegal choice has been detected. Please contact the site administrator.') !== false) {
        return t('Please select a category!');
    }
    return FALSE;
}

This will not only add your own custom error, but replace the "An illegal choice" error. Isn't it neat? Yay!


Did you tried to change the "Contextual filter" settings ?

WHEN THE FILTER VALUE IS NOT IN THE URL to -> Provide default value (taxonomy term from url)

or check the WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED validation


Allow block display on child nodes but not grandchildren

Hmm.  Are you sure current_path() is returning the alias?  cause I don't think match_path takes that in to consideration at all.

$path = current_path();
$path_alias = drupal_lookup_path('alias',$path);


I use Flat Rate module to do the same. You can set free shipping with help of this module very easily.

Once you enable the module, navigate to Store->Configuration->Shipping->Shipping Method->Flat Rate.

You will find Flat Rate under Shipping Method tab. Click Add a flat rate service.

Add something kind of Free Shipping, give it Title, Display title & Base Rate as 0.

Now visit Shipping Service tab. You will find your added flat rate service in there. Click Configure Component & put any condition you like e.g. Data Comparison to commerce-order:commerce-order-total:amount for any amount.

Now When ever your condition matches, this Free shipping service will apply if you have put Shipping service in Shipping pane under Store->Configuration>Checkout settings.


Drupal custom module code working differently for logged in users and anonymous users

This sounds like a caching issue. Check the cache api and make sure to set the $form['#cache'] appropriately.

When the anonymous user submits the form, it's submitted fine, but when the form loads the second time Drupal doesn't know that it should not be serving the original cached form.

You can quickly confirm that it is a caching issue by set the form to not be cached like:

$form['#cache'] = [
  'max-age' => 0,
];


For altering the saved title, try auto_nodetitle module, it can do what you want there.

Download and install the module
Enable the module in Drupal
Edit the relevant content type settings ( Admin > Structure > Content types )
Set the Automatic title generation option, using field tokens for the field values

If you want to update the display only, then you can use a node.tpl.php template preprocess function

e.g in your theme template.php file, replace THEMENAME with your theme name.

function THEMENAME_preprocess_node(&$vars){
  $node &= $vars['node'];
  if ($node->type == 'product') {
    $text = $node->field_manufacturer[LANGUAGE_NONE][0]['value'] . ' ' . $node->field_chip[LANGUAGE_NONE][0]['value'];
    $vars['title'] = check_plain($text);
  }
}

Clear theme registry cache after adding a new preprocess function


When exporting .sql via phpMyAdmin do you need to include cache tables?

You can typically skip the data in all of the cache tables.  That is temporary data that Drupal will recreate when as needed.  Basically, the cache tables store data the Drupal creates so that it doesn't need to create it the next time.

You can also usually skip the data in the watchdog table if you don't need the system logs.  Depending on your situation, you may also be able to skip sessions.

There are a few others you can skip (like flood), but they don't usually don't have much data in them in most situations.

Just remember that you want to back up the table structure (ie, the CREATE statements) and just skip the data.

The Backup and Migrate will take care of most of this for you.  drush sql-dump can skip table, data too.

Normally, I just transfer everything when moving between servers.  I just clear cache as part of the restoration process.  I would rather have a bigger file than have the chance of missing something.


How to have one node's access dependent on another node's access?

Create a custom module.

Use hook_node_view to run some code whenever a project node is viewed.

In that custom hook, find the company nid by looking at the field of the current node.

Then use node_load to get a node object of the company, check the company's access and then call drupal_access_denied if the current user does not have access to that company.


How to refresh block view of flags when the flag list is empty? Link operations issue

Since this tumbleweeded the answer is that there are a few modules that to time based refreshes of the view. Views by default, serves up content that ends up being static. Refreshing a view can be done a number of different AJAXY ways with custom code, but one of the more interesting involves using the Drupal node.js module and refreshing the view based on the execution of the flagging event. But using node.js you can have the view refreshed by server-side events (i.e. submissions by other users) all behind the scenes!.

Views Auto-Refresh is interesting but only has the on-click functionality in it's feature request que. I haven't developed a working implementation of this, but the node.js route is the one I would pursue at the moment.

A little more research turned up this little bit of jquery posted with a good explanation here Jquery views refresh

/**
 * @file
 * This JavaScript reacts to certain AJAX events on the view.
 */

jQuery(document).ready(function(){
  jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
})

/**
 * Function built on wireframe from
 * https://drupal.org/node/1781988#comment-6835168
 */
Drupal.behaviors.my_view_machine_name = {
  attach: function(context, settings) {
    if (Drupal.views !== undefined) {
      jQuery.each(Drupal.views.instances, function(i, view) {
        if (view.settings.view_name == "my_view_machine_name") {
          jQuery(document).ajaxComplete(function(event, xhr, settings){
            jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
            var response = JSON.parse(xhr.response);
            var resp_keys = Object.keys(response[0].settings.ajax);
            if (response[0].settings.ajax[resp_keys[0]].callback == "editablefields_form_update") {
              jQuery('#view-auto-refresh').click();
            }
          });
          view.$view.once('view-refresher', function() {
            var html = 'Refresh';
            view.$view.append(jQuery(html).each(jQuery.proxy(view.attachPagerLinkAjax, view)));
          });
          return false;
        }
      });

    }
  }
}


How to configure an exposed filter in a view using a date picker?

You can use the Date Popup module.

  Adds the native HTML 5 date popup widget to all date fields in views
  filters.

As the Use form element of type date instead textfield when selecting a date in an exposed filter is still in progress.


Aggregated CSS and JS files in Drupal 7 are split up into groups, so you'll naturally get more files than you're used to seeing in Drupal 6.

I won't go in to the whole thing as there's already an excellent article out there that explains it in good detail.

  D7 uses a new strategy to address this - aggregates are split into three groups:
  CSS_SYSTEM, CSS_DEFAULT, and CSS_THEME for styles, and JS_LIBRARY, JS_DEFAULT, and JS_THEME for Javascript. Each group is further subdivided into files that load on every page, and files that load conditionally based on the 'every_page' option. Note this option has some potential for confusion - it doesn't cause the file to be loaded on every page - it's merely a "hint" to the core system to place it in that group.

  Ultimately, the intent of these divisions is to group files into functional groups that are smaller and less likely to be split by an errant conditional style or script. We get separate files for core libraries, the theme, and page-specific files. Looking at the results, a stock Drupal 7 outputs eight stylesheets (including browser styles), while D6 only has three in the default install. Is this optimal? The answer will be different for each site.

If it's causing you problems, you might want to have a look at the Core Library module:

  This module changes the Drupal core aggregation mecanism process. It greatly reduces I/O and aggregated number of files, and improves chances of client cache hit, therefore while it produces bigger aggregated files, it reduces greatly the bandwidth utilization while users browse.


Choosing which comments field to display when published

You could use the template_preprocess_comment function. First you need to check the value of the "share my personal information" field or whatever you called it and act on that to display the user's email.


Entity reference - which side of the relationship is it best to put the field in?

Where you definitely have a 'container' vs 'contained' relationship, I would say the best way to go is to put the reference field on the contained field.  If you put the reference field on the container then every time you make a new item to be contained you have to edit the container as well.

Frequently I find that 'containers' end up with many more child objects than were originally intended, putting the reference field on the child object helps keep it manageable.

Also, when you are rendering the content or using it in views, you can use the reverse relationship.  So if you have books with many pages and each page references the book it belongs to, you could have a view that is based on books but also contains information about the pages.  And yes, that is using CER, so far for me it works quite well.


How can you show taxonomy child terms on the parent term page?

One way of doing this is with the use of https://www.drupal.org/project/eva which lets you attach any entity to any other entity

Just for demonstration I have setup

parent 1
  child 1.1
  child 1.2
parent 2
  child 2.1
  child 2.2

install and enable eva
create a taxonomy terms view called children with no block or page display

Then add an EVA views display from the dropdown
You will need to set a contextual filter parent term with following settings

Hide when value not available
specify validation criteria
   taxonomy term id:
      [NAME-OF-VOCABULARY]
   hide view

and on entity content settings set entity type: taxonomy term and bundle: [vocabulary name]

I had to clear cache so it does not hurt to do it and visit any of the taxonomy parent pages you should see the children terms

you can change where the children are displayed at your taxonomy term display settings page


How do I show a "read more" link in my RSS feed?

That's what Teasers are for — the Teaser is the shortened version of the content, presented in RSS feeds (among other places, such as the site's front page).

When editing a node in Drupal 6, use the "Split summary at cursor" button to split the node's body into a Summary/"Teaser" and "Full view".

Then go to your site's /admin/content/rss-publishing page, and set "Feed content" to "Title plus teaser".

Additionally, on your site's /admin/content/node-settings page, you can configure the default length to use to split nodes.

For some additional customization, try the Read More Link module (but be aware of this issue), or Display Suite, as @Decipher mentioned.


How to render an Image Field as a URL in node.tpl.php

You can do this by getting the path to the file.

<?php $file = file_load($node->field_body_image['und'][0]['fid']); ?>

Then render the path:

<?php print file_create_url($file->uri); ?>

I tested this and it works. In my case I had an event image in my local dev site and it rendered:

http://events.dev/sites/default/files/event-images/imagefield_7tgPJ7_0.jpg

In your tags, you did not specify Drupal 6 or 7 but my code above would be for Drupal 7.


That's because by default Drupal only allows GET request on default controllers. In your case you should create a custom resource.

Using resources has multiple advantages:

No custom paths per request method
Access control
CSRF protection
Using the API that the REST module in Drupal 8 provides

It basically comes down to creating a class with an annotation:

             /**
              * @RestResource(
              *   id = "my_resource",
              *   label = @Translation("Resource label"),
              *   uri_paths = {
              *     "canonical" = "/sample-page"
              *   }
              * )
              */
             class CustomResource extends ResourceBase {
                public function post($data) {
                  // Do stuff with the posted data.
                }
             }

Some more elaborate examples:

Example one

Example two

You will have to alter your jQuery POST request to something like:

 $.ajax({
         type : "POST",
         url: '/sample-page/',
         data: {'uid':2},
         success : function(response){
              console.log(response);
         },
    });

The data you post in your jQuery request will be available in $data of your resource class.


You can not query file usage with entity query, it is not entity data.

You can also not do reverse joins or load specific data. Entity query gives you entity IDs, which you need to load, and then from that get the data you want.

Meaning, to do what you are doing in an enitty query, you need to build an entity query that gives you the nodes you want, then load them, then get the referenced file and then get the created value from that.


Sure, you'll need to write a custom module and implement hook_image_effect_info() to register your effect with the system, e.g.:

function MYMODULE_image_effect_info() {
  return array(
    'mymodule_blur' => array(
      'label' => t('Blur'),
      'help' => t('Blur an image.'),
      'effect callback' => 'mymodule_blur_effect',
    )
  );
}

Then implement your callback function (mymodule_blur_effect()) to manipulate the image. Try following the function trail from image_resize() to get some inspiration on exactly how to access the image stream data.


using EntityFieldQuery, how to order results based on a node reference field title and/or field collection item field, says name

I'm afraid this won't be possible using EntityFieldQuery. You could build your own query using db_select() and have full control over it.

You can refer to this post and try to adapt it to fit your needs.


Can Display Suite be used for "Show: Fields" as well as "Show: Content" to be able to rewrite field output?

The answer is: no. But there is an alternative solution.

No - (At the time of writing), Display Suite does not appear to have functionality  for laying out fields in a view result row for “Show: Fields” format.

For laying out views row results, using display suite is only available for Views outputting the full node (i.e. Show: Content) as a row. The layout is done in the manage display section of the content type, defining a view mode for use in outputting the node in the view.

The solution therefore for laying out fields ( “Show: Fields” format ) and so making available the standard view functionality to modify each field's output behaviour for the view row result would be:

use the views_fieldsets module to group fields in parent div containers as required
use css to layout these parent divs and their children as required. for example, see: How to place Text and an Image next to each other in HTML?
access each field's settings as usual in the Views Edit Display, to customise the field's output e.g. rewrite it.


add arbitrary descriptions div in a node edit or add form

it sounds like you want a custom div to show for certain form values ... or on some conditional ajaxy thing on the form ...

I would basically use hook_form_alter with a case statement probably, or some use of nested array keys to add #prefix elements into the form.

The simplest example would be:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_content_type_node_add') {
    $form['field_FOO']['#prefix'] = '
a description goes here...
';
  }
}

You said you had a million of these, all over the place ... no big deal. Somewhere in your module as a variable or tucked away in a function:

// A simple array lookup of $form_id => $fields => $descriptions ...
$descriptions_map = array(
  'my_content_type_node_add' => array(
    'field_FOO' => 'a description goes here ....',
     ),
    'field_ANOTHER_BAR' => '...',
  ),
  'some_other_content_type' => array ...,
);

Using this simple lookup table (which could help tidy up your code) ... you then make hook_form_alter use it by looking at the array keys and eventually setting form values ... I'm leaving out an ugly bit of code with for loops and calling like array_keys but ...

$form[$field_key]['#prefix'] = $field_key_description;


How to highlight active teaser in Views?

The following does the work for me:

function YOUR_THEME_preprocess_views_view_unformatted(&$vars) {

  if (arg(0) != 'node') return; // no active node

  $index = 0;
  foreach($vars['view']->result as $node) {
    if (arg(1) == $node->nid) {
      $vars['classes_array'][$index] .= ' active';
    }
    $index++;
  }

}


Can I add custom fields to a single page?

If you are using Drupal 8, you can create a block type and add fields to it. Then create a block of your block type and on visibility rules you can assign it to a specific page.

Video Tutorial.

If you're using Drupal 7, you can do the same, but you'll need the Bean module