Drupal.settings merging when using AJAX I have an AJAX form. I'm using drupal_add_js() after AJAX calls to update 'settings' and pass new information to my Drupal.behaviour object. However, the results are being merged instead of replaced. I know this is by design but it's messing up my Javascript code because I end up with information from the last callback. Does anyone know of a good workaround for this?

Update:

Current workaround is overriding the code so settings is replaced rather than merged, though only for the page my form is in.

Drupal.ajax.prototype.commands.settings = function (ajax, response, status) {
  ajax.settings = response.settings;
};

Feels wrong, but things are working as expected.

Solution:

The final solution I used, as solved by Alice Heaton, isn't to override code in ajax.js, instead I returned both the form and an AJAX command in the forms AJAX callback:

function my_ajax_callback($form, $form_state) {
  $commands = array();
  $commands[] = ajax_command_settings(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  $output = drupal_render($form['locator']);
  $commands[] = ajax_command_insert(NULL, $output);

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

So when you use drupal_add_js to add settings during an ajax callback, this indeed merges the results. On the server side this is done in ajax_render (called from ajax_deliver or equivalent) which adds an ajax_command_settings command, instructing it to merge the results.

On the client side the merging is done by calling jQuery.extend, which causes the behaviour you have seen, and cannot be changed.

There is no work around if you want your results to be inserted into Drupal.settings. However you can pass your settings to your behaviour directly without using Drupal.settings. For this you would add a call to ajax_command_settings yourself. It would be something like this:

function mymodule_ajax_callback() {
  $commands = array();
  // ...
  $commands[] = ajax_command_settings(array(
    'key1' => 'value1',
    'key2' => 'value2',
  ));
  ajax_deliver(array(
    '#type' => 'ajax',
    '#commands' => $commands
  ));
}

Note that if your callback is called fom the Form API's #ajax['callback'] then it runs ajax_deliver on the value returned by the callback, so you shouldn't call it yourself.

On your script on the client side, your settings will be available as the second parameter of your behaviour attach method:

Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    // Here settings contains your settings
  }
};

(edit: sorry, previous answer was very wrong)


Quiz Module persistance implementation details In which part of the code is a new quiz stored in the database? What are the functions responsible for storing a new quiz in the database upon the submission of the form for creating a new quiz?

I'm trying to accomplish two things:

Timer per question
Dynamic question selection strategy

Quiz Module Version: 7.x-5.3

You need to be familiar with Drupal concepts like Nodes and Entities because they are used to model a Quiz.

The logic to keep the pieces synchronized is implemented via Hooks, like _hook_insert_ and _hook_update_, located on the quiz.module file.

Quiz 2.0 Architecture Information

  A Quiz is a Drupal node, and thus the node table contains a row for
  each Quiz. Similarly, a Question is also a Drupal node, so it too has
  an entry in the node table. Additional properties for Quizzes can be
  found in the rows of the quiz_node_properties table. Similarly, all
  question-types have a table called quiz_node_question_properties to
  store additional data. Each question-type also makes it's own set of
  tables to hold answers and user feedback. That means the
  multichoice.module question-type gets a quiz_multichoice_answers and a
  quiz_multichoice_user_answers.

From Community Documentation: Chapter 3 ~ Under The Hood

hook_insert

/**
 * Implements hook_insert().
 */
function quiz_insert($node) {
  // Need to set max_score if this is a cloned node.
  $max_score = 0;

  // Copy all the questions belonging to the quiz if this is a new translation.
  if ($node->is_new && isset($node->translation_source)) {
    quiz_copy_questions($node);
  }

  // Add references to all the questions belonging to the quiz if this is a
  // cloned quiz (node_clone compatibility).
  if ($node->is_new && isset($node->clone_from_original_nid)) {
    $old_quiz = node_load($node->clone_from_original_nid);

    $max_score = $old_quiz->max_score;

    $questions = quiz_get_questions($old_quiz->nid, $old_quiz->vid);

    quiz_set_questions($node, $questions);
  }

  _quiz_common_presave_actions($node);

  // If the quiz is saved as not randomized we have to make sure that questions
  // belonging to the quiz are saved as not random.
  _quiz_check_num_random($node);
  _quiz_check_num_always($node);

  quiz_update_defaults($node);
  _quiz_insert_resultoptions($node);
}

hook_update

/**
 * Implements hook_update().
 */
function quiz_update($node) {
  // Quiz node vid (revision) was updated.
  if (isset($node->revision) && $node->revision) {
    // Create new quiz-question relation entries in the quiz_node_relationship
    // table.
    quiz_update_quiz_question_relationship($node->old_vid, $node->vid, $node->nid);
    drupal_set_message(t('Some of the updated settings may not apply to quiz being taken already. To see all changes in action you need to start again.'), 'warning');
  }

  // Update an existing row in the quiz_node_properties table.
  _quiz_common_presave_actions($node);

  quiz_update_defaults($node);
  _quiz_update_resultoptions($node);

  _quiz_check_num_random($node);
  _quiz_check_num_always($node);
  quiz_update_max_score_properties(array($node->vid));
}


How to display all product prices on the page at once with Drupal commerce? I have several products related to a single product display node using Drupal Commerce.

Currently this page only shows a single price (related to the product option currently selected in the dropdown). The only way you can see the prices of the other products is to change the dropdown, which invokes an AJAX request to reload the current product options (including price).

Obviously this is counter-intuitive for customers, who are used to seeing all of the prices available at one time, and not having to change to a new option with the dropdown just to see the price of that option.

How do I change this display so it functions like a traditional e-commerce website? By that I mean either a dropdown that contains the product name AND product price, or (far more preferably) a table with the list of available products, with their prices in one of the columns?

I can only assume that this very basic functionality must exist somewhere in the Commerce configuration settings somewhere, but as yet I haven't been able to find it.

I could easily write a module to code round this problem, but I'm currently evaluating Commerce to see whether it's good enough for our agency to use in future e-commerce projects, without having to re-invent the wheel over and over again. To that end, answers involving code probably won't be too useful.

Muchas gracias

If themeing is considered "involving code", then you could create a view block.

Using Contextual Filters and Relationships, a View will be able to list all the referenced products on a node (including their fields).

Start by creating a View listing all the nodes that have a product
reference field (ex: Product Display).
Add a Contextual Filter for the Nid that defaults to use the Nid from the URL
Next add a Relationship (Product) using the product reference field of the Product Display node
Then add another Relationship (Line Item) for the Commerce Line Item of the referenced product

After that is all setup, you can add fields that use the Line Item relationship to get product titles, calculated prices, etc.


Image upload & gallery Is there a way to limit the number of imagefield fields present in a node?
I am using iTweak Upload, which allows to upload an unlimited number of images, but I need something that can limit the number of uploads.

I want to make a gallery per node with the uploaded files; what module do you recommend?

If you use standard CCK imagefield, you can set the number of images that can be uploaded within one field. For example, you could allow just one image, or up to 10 images, or an unlimited number of images.

Providing you don't have hundreds of images per node, CCK imagefield is fine for having a gallery of images on each node, and we've implemented galleries quite successfully in this way.


How do I execute a function every 3 months? What's the proper way to execute a function every 3 months? Watchdog variables don't seem to be available after a certain time. I could create another table to insert the execute function date to compare, but it doesn't seem to be the best approach.

The functionality of such functions are:

Send an eMail
Tag an inactive user

watchdog() is not appropriate place for storage; the $variables parameter is for formatting the display of variable data (e.g. the USERNAME in "User USERNAME has logged in"), not for long term storage of application data.

Instead, use a combination of hook_cron() and the persistent variable functions (variable_get() and variable_set()) to execute a cron task that remembers when it was last run.

/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Look up last time MYMODULE_function() was run compared to 3 months ago.
  if (variable_get('MYMODULE_function_last_run', 0) <= strtotime('-3 month')) {
     // Run my function
     MYMODULE_function();

     //Store the time when MYMODULE_function() was last run.
     variable_set('MYMODULE_function_last_run', time());
  }
}


Creating a form thats gives user chance to filter nodes Im quet new to Drupal and i dont know how to search for the module i need.

So the idea is...
I made a content type with the following fields: Name, Description, Country, Category.
The Country field is a list item and the Category is a checkbox item.

So the idea is that the users can submit they nodes. I undestand that part.

The problem is i want to display the nodes based on the Category and Country items.

When the user comes to the home page, they should first see a form in witch they chose the Category and Country, so the nodes get displayed based on that pick.

It should be a filter sistem where they can pick one country, and multiple categorys to display the Name and Description fields.

Can anyone give me a idea how to make that form?

In Views:

create a new view, page or block limited to that content type, as the display format you want (table, teaser, etc)
create a filter field, choose the Country
click on 'Expose this filter to visitors, to allow them to change it'
Filter: operator - is equal to (you can expose this operator if desired, allowing the user to choose is equal to, is not equal to, contains, etc)
if you want the View empty to start, click on 'required' in the filter field set up
create a new filter field for Category and repeat the same steps

You will want to play around with the settings to get it exactly how you want, but this should get you going in the right direction.


Comment body field is missing I enabled the forum module, and when I add a comment on a forum post, there is no body field. I disabled both the Comment and the Forum modules, and re-installed them, but I still have the same problem.

If I manually create a body field (field_comment_body), I get the following error message:

  Notice: Undefined property: stdClass::$comment_body in comment_admin_overview() (line 107 of /var/www/lms/modules/comment/comment.admin.inc).

Is there any solution to make the comment body appear as it happens with other content types?

disable comment module
uninstall comment module
enable comment module


Term name converted to term id filter removed? I am currently working on a view that should show all items from a content type with the given taxonomy term name (not id) in the url.

While this was easy to achieve in D7 (by following the answer on this question: Views contextual filters taxonomy name), I can't seem to find the validator filter now.

The predefined view "taxonomy term" might have the answer.
It will always show results based on the TID.
I believe that if you just add an alias to your URL, it will work just fine. You can use the module pathauto to automatically create an alias.


How can you get the route name/path of groups? I am new to Drupal 8. I am working on groups module and want to assign different themes to different groups.So i need route name of groups. how to find route name of groups. Thanks in advance.

/**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // Use this theme on a certain route.
    return $route_match->getRouteName() == 'i need route name of groups here';

  }

There is probably a *.routing.yml in the group module where you can find the route name, but routes can also be defined dynamically. So better use a tool, for the command line Drupal Console or for UI the devel module:

Install the devel module, visit the page you want to find out the route name for and click on "Current route info". The route name is in the variable _route. You find also the route parameters you might need to further narrow down the route.


How to selectively disable CKEditor on specific pages? On a site I am developing, I have installed and enabled CKEditor version 7.x-1.13.

On two of the pages, I need to completely disable the editor from being active when accessing the admin to edit the page.

I am not sure how I can do that. The only thing I have been able to do is either enable or disable the editor globally.

Can someone point out to me how I can get this done?

AFAIK, you can only control access to the wysywyg editor on a per-user basis, not on a per-node basis.  If the user shall be allowed to use the wysywyg editor in general (but be banned from doing it only on specific pages, you need to create write PHP-code that prevents the user selecting the wysywyg text format on the pages were this shall not be allowed).

What you can control on a per page/node basis is the default editor.

To not make the wysywyg default for an existing page, open up the page as Admin, locate the box labeled "Text format" below the main edit area, and select a format (e.g. "Plain text" *) that has not been set up to use wysywyg.

Save the node.  Wysywyg will no longer be default when it is reopend for editing (but it can be selected).

However: If that user has global access to at least one text format tied to wysywyg, he or she can restore the wysywyg for that page at will.

To stop the user from doing this, you must prevent the user from changing the text format.  You can do this by using hook_form_alter() to remove the pull-down menu that changes the text format for the node edit form.

*) If you want something more advanced than "Plain text", and the "Filtered HTML" (for instance) format has been assigned to wysywyg, just clone the text format you want to use, but do not set it up to use wysywyg.


Change default language from the database? I have made a stupid mistake:

I installed the .po for another language and set it as default (instead of English) even though I did not install/configure all the prerequisites. Now, each time I try to access my website, it goes into an endless loop and I can no longer access its configuration panels.

How can I reset the default language back to English? Is there any file to configure or database entry to change?

In the setting.php file used by your site, add the following lines:

$conf['language_default'] = (object) array(
  'language' => 'en', 'name' => 'English', 'native' => 'English',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

This will force Drupal to use English as default language. Once you removed the language files for that language, remove those lines from the settings.php file, or Drupal will always use English as default language, indifferently from what you set from the setting page.

The same trick works also for Drupal 6.


How do I remove a node from the front page after a certain period of time? Can I use the Rules module to remove a node from the front page after a period of time determined by the administrator user when creating the node?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below. These steps are based on the assumption that your content type is article (adapt to whatever else fits).

Step 1: Create a field to store the expiration date

Add a field to the article content type (to store the "expiration" date), with these specs:

Machine name (say) field_expiration_date.
Use "date" as field type, for which the date module (and data API) needs to be enabled first.
Allow only 1 date.

Step 2: Create a Rules Component

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_unpublish_a_node" : {
    "LABEL" : "Unpublish a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_be_unpublished" : { "label" : "Node to be unpublished", "type" : "node" } },
    "DO" : [ { "node_unpublish" : { "node" : [ "node-to-be-unpublished" ] } } ]
  }
}

If you do not want the node to be unplublished, you can also replace the Rules Action by another one to just perform a "remove sticky" for the node.

Step 3: Create a Rule using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, then "enable" the rule also):

{ "rules_schedule_the_unpublish_of_a_node_as_requested_by_author" : {
    "LABEL" : "Schedule the unpublish of a node as requested by author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_a_node",
          "date" : [ "node:field-expiration-date" ],
          "identifier" : "Unpublish-node-[node:nid]",
          "param_node_to_be_unpublished" : [ "node" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step. Make sure to only perform the import of this rule only after you completed step 1, if not the import will fail ... Should you want to use another machine name, then change field_expiration_date in the rule above to what you prefer, prior to importing this rule.

Be aware: the above rule is only triggered once, i.e. when the node (of type article) is first created (as in the question). It will right away schedule the unpublish of the node (as requested in the expiration date). If the node gets edited later on, and/or the expiration date is changed afterwards: too bad, that won't change anything to when the scheduled unpublish is going to happen.


Implementing CKeditor's plugin I need to add the Templates plugin into Drupal8 CKeditor. So far it is available on the editor configuration page, but not on a node edit page. The code:

namespace Drupal\module_name\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

class ContentTemplates extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

  public function getButtons() {
    return array(
      'ContentTemplates' => array(
        'label' => t('Content templates'),
        'image' => drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/icons/templates.png',
        'image_rtl' => drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/icons/templates-rtl.png',
      ),
    );
  }

  public function isInternal() {
    return FALSE;
  }

  public function getDependencies(Editor $editor) {
    return array('dialog', 'dialogui');
  }

  public function getLibraries(Editor $editor) {
    return array();
  }

  public function getFile() {
    return drupal_get_path('module', 'module_name') . '/js/CKeditor/Plugin/templates/plugin.js';
  }

  public function getConfig(Editor $editor) {
    return array();
  }

  // TODO: to be sure, should be removed and served by config
  function isEnabled(Editor $editor) {
    return TRUE;
  }
}

I also could see the methods injected by templates/dialogs/templates.js while inspecting the CKEditor object, but the file is not listed in the Chrome's resources inspector. I also don't see any code changes in this file takes effect (browser and drupal cache disabled, aggregation disabled).

I used this two classes in modules/custom/my_ckeditor/src/Plugin/CKEditorPlugin:

<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "dialog",
 *   label = @Translation("CKEditor Dialog"),
 *   module = "ckeditor"
 * )
 */
class Dialog extends PluginBase implements CKEditorPluginInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/dialog/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }
}

<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "templates",
 *   label = @Translation("CKEditor Templates"),
 *   module = "ckeditor"
 * )
 */
class Templates extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array('dialog');
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getButtons()
  {
    return array(
      'Templates' => array(
        'label' => t('Templates'),
        'image' => drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/icons/templates.png',
      ),
    );
  }
}

The CKEditor plugins (Dialog & Templates) are placed in modules/custom/my_ckeditor/js/plugins

You also need a custom JS-file for your templates:

(function ($, Drupal, CKEDITOR) {
  "use strict";

  Drupal.behaviors.myCkeditor = {
    attach: function (context, settings) {
      var templates_path = '/modules/custom/my_ckeditor/templates/ckeditor/';

      var templates = [
        {
          title:       Drupal.t('Title'),
          description: Drupal.t('Description'),
          image:       'preview.gif',
          html:        'My Template'
        }
      ];

      // Remove default templates
      CKEDITOR.on("instanceLoaded", function () {
        CKEDITOR.config.templates_files = [];
      });

      // Load tempaltes
      CKEDITOR.on("instanceReady", function () {
        if (CKEDITOR.plugins.get('templates')) {
          CKEDITOR.config.templates_replaceContent = false;
          CKEDITOR.addTemplates('default', {
            imagesPath: templates_path,
            templates:  templates
          });
        }
      });
    }
  };

})(jQuery, Drupal, CKEDITOR);

This talk can help you: https://www.youtube.com/watch?feature=player_detailpage&v=h9KV_VRvIG8#t=1965


"Languages" not found in Admin/Configuration I have a Drupal 7.41 in a remote server linux configuration

Installed and Enabled

Internationalization
Locale
Variable
Entity Traslation
Content Translation

Next, want to Add the Spanish and French languages. But, there is no Languages option seen under "Regional and language" in Admin/Configuration.

What is missing?
Tried flushing all caches. No difference.
Logged in as admin user/1

I found a permission named Administer languages, I make some test with it and I can reproduce your issue. Go to YOUR_SITE/admin/people/permissions and search under the Locale section the Administer languages permission and give the permission to your user.


View in block doesn't sort by date whereas page does I've got a 'archive' view in a block on my openblog drupal blog. In the view, the page view sorts ok, but in the block sorting by date doesn't work - it is always sorted by ASC.

I figured out I needed to change the sort option inside the contextual filter.


How to replace current symbols with font awesome icons in every pager? I want to replace current symbols with font awesome icons in every pager on my site. Problem is, the icon tag is printing as text, not as html. Here's my code:

function default_preprocess_pager(&$vars, $hook) {
  if ($vars['quantity'] > 5) $vars['quantity'] = 5;
  $vars['tags'][0] = '<<';
  $vars['tags'][1] = '<';
  $vars['tags'][3] = '>';
  $vars['tags'][4] = '<i class="fa fa-arrow-double"></i>';
}

If you look at function theme_pager you see this line:

 $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

which eventually leads you via theme_pager_last to function theme_pager_link which has this bit of code:

return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';

where check_plain is the function that converts html to text.

so you need to supply your own version of theme_pager_link. Look at this post and others for information on how to do that:

How to override theme functions in Drupal 7


How do I filter a view by the node taxonomy you're currently on? I've built a content type and added taxonomy to it. The user can choose one of the 10 terms from that vocabulary when they are building the content. On the node I want to build a sidebar that lists all the other nodes from this content type but filtered to be only the same taxonomy choice. I assume this is done through views but I can't figure out how to build that contextual filter that looks at the current nodes taxonomy.

To visualize what J. Reynolds said above.
Add Contextual Filter - Content: Has taxonomy term ID with following settings

then add contextual filter - Content:Nid (provide default value -> Content ID from URL) and in "More" section of that filter check "Exclude" checkbox, which will remove the currently viewed node from the list of nodes related by taxonomy term.


How to send E-mail and SMS notifications when one user outbid another user in drupal 7? I am new to auction idea of drupal 7. My client wants an checkbox to be implemented ,where users can select whether they require any e-mail notification /sms or both or none.I want to send e-mail and sms notification to the respective logged in user on the basis of bids placed by them!

I configured the mail and sms notifcation part .Can anyone let me  know how to send notifications when user checks the checkbox in drupal 7 on the basis of bid?

I would look at the Message module

  The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.


Site dead after Devel Module and Library sethtmldom After installing Devel Module (and Library simplehtmldom), the Drupal7 site is completely dead. Have already set the module to 0 on System table in database, and the module files removed by FTP. But still no recovering. How to remove simplehtmldom Library? What else to recover the site? Thanks.

You can try using Registry Rebuild

Project page says..

  THIS IS NOT A MODULE. YOU CAN'T ENABLE IT. FOLLOW THE INSTRUCTIONS.

  Make a backup of your database before running this. It won't break
  your database, but we can't improve this unless we have broken
  databases that it doesn't quite do the job for.

  There are times in Drupal 7 when the registry gets hopelessly hosed
  and you need to rebuild the registry (a list of PHP classes and the
  files they go with). Sometimes, though, you can't do this regular
  cache-clear activity because some class is required when the system is
  trying to bootstrap.

  When would you need Registry Rebuild? You might get something like:

  PHP Fatal error:  Class 'EntityAPIControllerExportable' not found in
  ...sites/all/modules/rules/includes/rules.core.inc on line 11


How do I get link the files in libraries.yml with absolute url path In my libraries.yml files the css files are linked with the relative url paths.

  Eg : /css/mycss.html

So when in the page source the linked url shows as relative. How do I link those files with absolute URL path?

This is the example from the official documentation, notice this bit type: external:

angular.angularjs:
  remote: https://github.com/angular/angular.js
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }


Multiple blocks on single page, pager issue I have 3 blocks made by views on the front page. Each have 4 of the newest node teasers showing with a pager to see the rest. However, when I click on one of the pager's next button, it will load the next 'page' for all the blocks on the page.

What would be the best way to make it so pressing the next button will only load that specific blocks next page and not the other blocks?

You can configure each block's pager to have a different pager ID and then they will/should only update the one you clicked on.


How do I perform a 301 redirect for all old .asp pages? I am trying to figure out a way to redirect all the old .asp pages to a specific page in my Drupal site.

Is there a way I can accomplish this with a web.config file? I cannot use a .htaccess file because the site will still be running on IIS.

Why not use Drupal 7's core URL redirect interface? It has an option for 301 redirects: Configuration > Search and metadata > URL redirects.

I like it because it captures stats on how many redirects are happening.


Display long text fields as type text input not as textarea on node forms I have some fields which are configured as long text fields, which I need to display as <input type="text /> instead of <textarea></textarea>.

I'm trying to find the correct naming convention so that I can have some theme overrides in my templates folder.

Is that the correct approach?  Is there documentation about overriding specific field outputs on edit screens?

Drupal textfield widget can only be applied to string fields.
https://git.drupalcode.org/project/drupal/blob/8.7.4/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/StringTextfieldWidget.php#L9

However it's not a big deal to alter its definition and make it support long strings.

/**
 * Implements hook_field_widget_info_alter().
 */
function HOOK_field_widget_info_alter(array &$info) {
  $info['string_textfield']['field_types'][] = 'string_long';
}

After having this done it should be possible to assign textfield widget to long text fields on "Manage form display" page.


How to get File entity in media_presave hook? I want to get the file entity out of an media image bundle to the get the filename to check if the image is cmyk or not.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function hook_media_presave(MediaInterface $entity) {
  if ($entity->bundle() == 'image') {
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($field_definitions as $field_definition) {
      if ($field_definition->getType() 'image') {
        // get File entity here.
      }
    }
  }
}

How do I do this?

I've found a solution.

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function hook_media_presave(MediaInterface $entity) {
  if ($entity->bundle() == 'image') {
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($field_definitions as $field_definition) {
      if ($field_definition->getType() == 'image') {
        /** @var FieldItemListInterface $field_value */
        $field_values = $entity->get($field_definition->getName())->getValue();
        if (is_array($field_values)) {
          foreach ($field_values as $field_value) {
            if ($field_value['target_id']) {
              /** @var File $file */
              $file = File::load($field_value['target_id']);
              $image = getimagesize($file->getFileUri());
              // If the image has channels '4' it is cmyk.
              if ($image['channels'] == '4') {
                $imagick = new Imagick($file->getFileUri());
                $imagick->setImageColorspace(Imagick::COLORSPACE_RGB);
                $imagick->writeImage($image);
                $imagick->destroy();
              }
            }
          }
        }
      }
    }
  }
}


How to hide the 'Format Options' / 'Help Text' Guideliness from the bottom of comments textarea? How can I remove or hide Format Options / Guideliness under the comments textarea in my theme?

Check out the Better formats module. It allows you to hide the format options and tips link per user roles and fields.


How to import taxonomy from Json format I have taxonomy in Json file. I need import this file into Drupal into exist vocabulary.how can I import data from Json file to exist vocabulary?

Here are some resources if you opt to use Migrate Framework in 7.x to do this (which is how I would personally approach it).

https://www.drupal.org/project/migrate
https://www.drupal.org/project/migrate_source_json
https://www.drupal.org/project/migrate_plus

There are examples in Migrate/Migrate Plus on getting it setup. It looks like migrate_source_json was deprecated in favor of migrate_plus, but I included it for any historical references in it's issue queue.

There is probably a solution via Feeds as well but as stated, I am not experienced with Feeds.

If you can convert your format to CSV, there is also this one off module, Taxonomy CSV.


get menu link Page Settings from View configuration When I have a node on the main menu, I can find its Menu Settings with an entityQuery on the content entity for its menu link, for example:

$system_uri = "entity:node/42";
$query = \Drupal::entityQuery('menu_link_content')
  ->condition('menu_name', 'main')
  ->condition('link.uri', $system_uri);
$result = $query->execute();
$menu_link_id = reset($result);
$menu_link = MenuLinkContent::load($menu_link_id);

... then get the Menu Link Title and Parent Item with these methods from the relevant class:

$menu_link_title = $menu_link->getTitle();
$menu_link_parent = $menu_link->getParentId();

I can't do the same thing with a view.  Even an entityQuery of all menu_link_content entities on the main menu doesn't return views that are on that menu: only nodes and taxonomy term entities.

And I can't see these settings in what I believed would be the corresponding configuration entity for a View, for example:

$view_id = 'frontpage';
$query = \Drupal::entityQuery('view')
  ->condition('id', $view_id);
$result = $query->execute();
$view_id = reset($result);
$view = \Drupal::service('entity.manager')->getStorage('view')->load($view_id);

The resulting Drupal\views\Entity\View object doesn't look like it has any properties or methods to access the configuration data in the Views UI, specifically the Menu Link Title and Parent under Page Settings.  What is the correct way to extract this information?

The menu tree is built from two sources, menu link content and menu config. For views you find the menu configuration in each view. There are several ways to access this information. You can use the config api to read the values in php, export the view to a yml file and inspect it or use drush.

For example to show the view for block content with drush:

drush cedit views.view.block_content

This contains this configuration for the page:

 page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: admin/structure/block/block-content
      menu:
        type: tab
        title: 'Custom block library'
        description: ''
        parent: block.admin_display
        weight: 0
        context: '0'
        menu_name: admin
    cache_metadata:
      max-age: 0
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user.permissions
      tags: {  }

After inspection the structure of this array you can use the configuration api to access it in php:

Simple Configuration API


Drupal path linking to wrong content I have a content type for news. All my news nodes use the pathauto path: "node/[title-raw]". However, when I click to go to view any of my news items, instead of displaying the news item, the page displays a newsletter that was created using Simplenews. None of the normal Drupal content codes is being added. It's like it's just viewing a basic HTML page of the newsletter. Something is going wrong with the paths.

It seems like this newsletter has taken over all paths beginning "news...".

I'm not sure where to start looking for the problem. I would be grateful for any suggestions anyone has.

To see what I mean you can see the website at www.signamic.co.uk, and then click on any of the news items near the bottom.

Thanks in advance,

Ben

@citricguy exactly - seems that any URL you type after /news/ ends up showing your newsletter.

You probably have an index.html file there with that content.

Example:

http://www.signamic.co.uk/news/something-that-should-not-exist

Gives the same output as:

http://www.signamic.co.uk/news/full-time-pacourse-adminstrator-vacancy

Check your folder structure in root and .htaccess file.


Permission settings for Edit Node Link to show up? I have a view that includes the Node: Edit link field. When the view gets rendered and the user is logged-in, only an Admin can see the link. What permission settings do I need to have enabled for that link to show up in a role with custom permissions?

Additional details:

Edit link was added to view in the standard way. See screenshot:

go to:

  admin/people/permissions

and check:

  Content type name: Edit own content.

if you want that this role can edit ANY content of this type, not only their own conent, then check:

  Content type name: Edit any content.


Show only specific fields on Edit page when a Term is selected How do I show on (content type) Edit page only specific fields?
For example if I have selected the Laptop term then I should see Procesor, RAM and HDD fields and if I select TV term then I should see Screen size, Brand, Screent type fields.

conditional fields  is very powerful you can achieve your need with it. read README.TXT file carefully


On submission function is not being called in custom module I have written a custom module for form submission the first time but submit button is not working.

Here is the code:

function my_form($form, &$form_state) {

$node = array();
$pl_name=array();
$pl_name=getplaylist_to_edit(arg(1));

$node['text'] = array(
'#type' => 'textfield',
'#id'=>'edit-playlist-name',
'#value' => $pl_name[1],
);

$node['submit'] = array(
'#type' => 'submit',
'#value' => 'Update',
'#submit' => array('test'),
);

return $node;
}

function test()
{
echo '<script>alert("You have submitted the form.");</script>';
}

Could you try like this:

function my_form($form, &$form_state) {
  $pl_name=array();
  $pl_name=getplaylist_to_edit(arg(1));

  $form['text'] = array(
    '#type' => 'textfield',
    '#id'=>'edit-playlist-name',
    '#value' => $pl_name[1],
  );

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

  return $node;
}

function my_form_submit($form, &$form_state){
  echo '<script>alert("You have submitted the form.");</script>';
}


What's the difference between 'commerce-line-item-unchanged' and 'commerce-line-item' In drupal commerce rules there are selectors like 'commerce-line-item' and 'commerce-line-item-unchanged' – what is the differnece between them? When should i use the one or the other?

Commerce line items are Drupal Entities (enhanced a bit by the Entity module) and, like other entities, the "entityname-unchanged" is present in some rules just so you can see what the entity was like before it got changed.

There isn't a specific use case intended for it but there are cases where being able to see the original state of an entity would be good.  Specific to a commerce line item, maybe you'd want to reset the line item's quantity to its old value if they chose some crazy number like 10000.


How to clear image (or file) field data for specific node programmatically? I need to clear/remove image (or file) field from specific node.
I have before:

I want to get after code execution for the field:

What code should I use to properly clear image (file) field data?

I assume that your field accepts only one file at a time. This is the code you need to use:
// Replace this with the ID of the node you want to update.
$node_id = 123;

/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal\node\Entity\Node::load($node_id);

// Step 1: remove the file. This will actually delete the file from the
// filesystem, so in case you want to keep it just remove the next two
// lines.
/** @var \Drupal\file\FileInterface $file */
$file = $node->get('field_NAME_OF_YOUR_FIELD')->entity;
$file->delete();

// Step 2: remove the field data.
// The 0 in this case is the index of the item you want to remove. It simply
// means the first value in that field needs to be removed.
$node->get('field_NAME_OF_YOUR_FIELD')->removeItem(0);
// We have to save the changes to the node.
$node->save();


How to extend entityreference field by another custom field? I want to add another field, which needs to be accessible by views (for display and ordering), to the entityreference table field_data_field_FIELDNAME. Structure of that table is:

entity_type VARCHAR(128)
bundle VARCHAR(128)
deleted TINYINT(4)
entity_id INT(10)
revision_id INT(10)
language VARCHAR(32)
delta INT(10)
field_FIELDNAME_target_id INT(10)

I want to have a column storing DateTime information here, so I can attach information about when this reference was added/ updated for that referenced entity. There also needs to be a way to save the newly added field directly in the array structure for that reference such as:

$node->field_reference['und'][] = array(
  'target_id' => 123,
  'my_new_column' => '2014-03-13 15:29:29'
);

I know I could solve this by using field_collections or relation module, but both would cause significant performance issues.

Gave an approach here https://www.drupal.org/node/2001822#comment-9165509

Hope that it will work for you


How to display time with different field in calendar? How to display time on calendar if time is different field created usin CCK Time Module.

Solved this by adding field group in calendar style display.

Added time field in views and edit the settings of calendar style plugin. There is a option to group field by hour. I selected my field.


Calendar - Adding relationship to contextual date filter I would like to create an Calendar view of some interships for a certain student. But when I change the Contextual (Date) filter to use an relationship no results are shown in the calendar.
When I construct a similar view page in a list instead of an calendar view mode, with identical filters, the results get returned.

Below an image of my attempt to get the relationship in a contextual date filter.

As J. Reynolds suggested some settings in the Calender Entities must be set. Changing the relationship fixed my problem.


Why is #attached library load not working, but drupal_add_library works? This question is specific to D7:
I'm trying to load in jQuery UI modal into the theme. I've put the following in my THEMENAME_preprocess_html:

$variables['page']['content']['#attached']['library'][] = array('system', 'ui.dialog');

This isn't loading the library at all.

DPM-ing the $variables array after the above line shows that it's all added correctly (There's even other stuff in there like, addthis.js):

Direct link: http://i.imgur.com/iTeynMR.png

Obviously all caches were cleared. At this point the console shows an error that dialog is not defined. But as soon as I add this (in the same function, just below the #attached line):

drupal_add_library('system', 'ui.dialog');

then the dialog modal opens and starts playing nicely. Am I doing something wrong with #attached? I'm really puzzled as to why one's working and the other doesn't. Ideally I'd like to use #attached in the cases where the variables array gets cached and the preprocess doesn't get called.

Because the render array has already been rendered before the preprocess functions, '#attached' is not supported in preprocess functions until Drupal 8.

The issue where it was added is https://www.drupal.org/node/2346369

The related Drupal 8 change record is https://www.drupal.org/node/2352319 - this also shows the supported way of doing it in Drupal 7.

Using drupal_add_library() will work, but it will not be cached, so you will take a performance hit. You are better off adding it to the #attached array at a different step in the process.


How to display multiple fields from a taxonomy term on a node (and control the html) I have a content type (product) with a term reference field (colour).

When I create a new product and select a colour I would like the display of that node to render the taxonomy items term name and an image that I've attached to each term + control the html markup.

Via the Display Suite module I've managed to render the term's title and colour on the node using "Rendered taxonomy term" format on the field (screenshot below), however I want more control in how the title and image are outputted in the html markup. This is halfway there.

[![enter image description here][2]][2]

The title and image appear right after each other in the markup (as it is correctly rendering the taxononmy term) but to achieve the layout the designer wants I need to be able to render the title and image individually (essentially separate fields "taxonomy title" and "taxonomy image" on my "Product" node's display, instead of just the single "Rendered taxonomy term" that I currently have configured.

Any help would be greatly appreciated.

Edit:

"Product" and "Colour" were just an example. In reality my site has a content type called a "lift" and it has a term reference field linking to a "location" vocab.

So if I add a "lift" and say the location is "Sydney" then when viewing that node I want to be able to pull the "Sydney" term's title and image..but as explained I need greater control over the positioning of the markup (specifically in relation to the "lift" nodes other fields)

Example of what I want the node to look like:

Sounds like this this could be achieved with Inline Entity Display.

  Overview
  Make available the fields and text properties from referenced entities into the parent entity template and the manage fields display overview.

This should allow you to move individual fields from your referenced taxonomy terms aroung independently on you node's manage display setting page.


Sort content in a view by taxonomy term and use terms as headlines in drupal 8 Say I have a content type books and a taxonomy vocabolary book categorys i.e.

book categorys:
 - Novel
 - Short Story

Now, what I would like to display in a view is:

Novel

Novel 1
Novel 2

Short Story

Short Story 1
Short Story 2

I sure can make one block for each taxonomy term and filter by term, but I also create regulary new ones so that is not an good option.

To do this you need a Taxonomy term view with a Content using field_xxx relationship.

Here are the steps needed:

Create a new view with Show: Taxonomy terms of type: Book category (or whatever your vocabulary is called).
Under Advanced settings add a Relationship of type Content using field_bookcategory
Under Fields, Add a Content Title field to the view. A relationship to your field_bookcategory should be automatically selected at this point.
You now need to group your results by taxonomy term. Do this under under Format: Settings and set Grouping field Nr. 1 to Taxonomy term: Name
Lastly, you'll want to hide the term name in the results, since you're already displaying it in the group heading. To do this set the Taxonomy term: Name field to Exclude from display


How to auto-assign a user a particular role when that user gets autocreated in a content form? I need to auto-assign newly autocreated users from the content editing
form a particular role.

I created this new content-type : Music Track and created a new field - Artist for it. The Artist field is entity referenced to Target type - USER. I was expecting a Roles list under Entity Selection area so that I can restrict only Artist role users to be created when creating a new content and adding new artists but its not available.

Note:
Users are being autocreated using Entityreference Autocreate module.

Note: I use this in a project and it works (it does not use the Entityreference Autocreate module).

First alter the artist form and add a custom validate and a custom submit

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'artist_node_form') {

            //hidding the Entity Reference field (User), it will be created in the process
            unset($form['field_user']);

            if (!isset($node->nid) || isset($node->is_new)) {
                $form['field_username'] = array(
                    '#type' => 'container',
                    '#weight' => 3,
                    'field_username' => array(
                        '#type' => 'textfield',
                        '#title' => t('Username'),
                        '#maxlength' => 60,
                        '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
                        '#required' => TRUE,
                        '#attributes' => array(
                            'class' => array(
                                'username',
                                ),
                            ),
                        '#default_value' => '',
                        '#access' => TRUE,
                        '#weight' => -10,
                        )
                    );

                $form['field_password'] = array(
                    '#type' => 'container',
                    '#weight' => 4,
                    'field_password' => array(
                        '#type' => 'password_confirm',
                        '#size' => 25,
                        '#description' => t('Provide a password for the new account in both fields.'),
                        '#required' => TRUE,
                        ),
                    );

       $form['#validate'][] = 'artist_node_form_validate';
       $form['#submit'][] = 'artist_node_form_submit';
    }
  }
}

In the custom validate you need to validate the username and check if the username is available.

function artist_node_form_validate($form, &$form_state) {
    $valid_user = user_validate_name($form_state['values']['field_username']);
    if(!is_null($valid_user)) {
        form_set_error('field_username', $valid_user);
    } else {
        $user = user_load_by_name($form_state['values']['field_username']);
        if($user){
            form_set_error('field_username', t('The username @username already exist.', array('@username' => $form_state['values']['field_username'])));
        } else {
            $form['field_username'];
        }
    }
}

In the custom submit you will create the user

function artist_node_form_submit($form, &$form_state) {
    $new_user = array(
        'name' => $form_state['values']['field_username'],
        'pass' => $form_state['values']['field_password'], // note: do not md5 the password
        'mail' => $form_state['values']['field_email'][LANGUAGE_NONE][0]['email'],
        'status' => 1
        );

    //The first parameter is sent blank so a new user is created.
    $new_user = user_save('', $new_user);

    //assigning the role
    $role = user_role_load_by_name("artist");
    user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);

    //field_user is the Entity Reference field
    $form_state['values']['field_user'][LANGUAGE_NONE][0]['target_id'] = $new_user->uid;

}


Show 2 content types in a view that share same field value Hi i have 2 content types:

Agent
Organisation

they both have fields for id:

ID ( agent content type)
Org ID ( Organisation content type)

Now i need to create a view that will list fields from both of the content types, and only relation between them is same value in fields ( field_id and field_org_id ).

Since content is already there and there are more than 200 nodes in each content type, i need to work with what i have. That means i cant add new fields ( like node reference ).

Is there a way to make a view that will list fields from two content types that share same value in 2 fields with different name? And in each row to have mix of fields from both content type with relation of this ID.

Since field_id and field_org_id are two separate fields, you'll need some way to tie them together. A custom entity could do that, but you could also cheat a little and use a taxonomy vocabulary that contains these two fields.

You could then build a view that displays all content and add a relation to the vocabulary and restrict the results to only the content that possesses this relationship.

Cheaty, but I think it might be the easiest solution.

Edit:

I wouldn't modify the content or content types, but rather, add the field_id and field_org_id fields to the taxonomy vocabulary, then iterate through your Agent and Organization nodes and generate taxonomy terms that associate one field's value to another by populating each term's field_id and field_org_id fields from their respective Agent and Organization nodes.

So, some code...

Create the vocabulary

$vocab = new stdClass();
$vocab->name = 'Organization to Agents';
$vocab->machine_name = 'org_to_agents';
taxonomy_vocabulary_save($vocab);

Add the fields

$fields = array(
    'field_id',
    'field_org_id',
);

foreach($fields as $field) {
  // Replace my)taxonomy_vocabulary with your chosen vocabulary name.
  if (is_null(field_info_instance('taxonomy_term', $field, 'my_taxonomy_vocabulary'))) {
    field_create_instance(array(
      'label' => $t($field),  // <-- This doesn't need to be pretty.
      'widget' => array(
        'type' => 'textfield',
      ),
      'field_name' => $field,
      'entity_type' => 'taxonomy_term',
      'bundle' => 'my_taxonomy_vocabulary',
    ));
  }
}

Get the list of IDs

// Credits to https://www.drupal.org/node/1079616#comment-10864932 for example.
$agents = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'agent'))
  ->fetchCol();
$orgs = db_query("SELECT nid FROM {node} WHERE type = :type", array(':type' => 'organization'))
  ->fetchCol();

// Should result in a list of unique Node IDs that exist in
// at least one node for both content types.
$nids = array_intersect($agents, $orgs);

Create your taxonomy terms

$vocab = taxonomy_vocabulary_machine_name_load('my_taxonomy_vocabulary');
foreach($nids as $key => $nid) {
  $term = (object)array(
    'name' => $key, // Use any unique value that makes sense here.
    'vid' => $vocab->vid,
  );
  $term->field_id[LANGUAGE_NONE][0]['value'] = $nid;
  $term->field_org_id[LANGUAGE_NONE][0]['value'] = $nid;
  taxonomy_term_save($term);
}

Again, this is a bit "cheaty", and a custom entity would probably be considered more proper, but I think this should help.

Hope it helps!


Drupal views print date 'time ago' as a PHP conditional field I am trying to make a custom PHP field that returns the value of 'user last access' field as an integer of minutes 'time ago'.

I have created a normal views field for 'user last access' which returns almost exactly what I want from the normal field value:

x mins - this being x mins time ago, created by using 1 as the time units to display.

I just don't know how to return this value through a new PHP field that just references and displays the integer value for this field without ' mins' text ?

I want to then take this raw value and use a conditional statement of:

If user last access is less than 3 minutes print 'Online'
else
Print 'Offline'

In User Last access field UI, under the Date Format, select 'Custom' and then enter custom date format. For minutes you can enter 'i' which will show the number.

Refer http://php.net/manual/en/function.date.php for date formats.

Thanks


Trouble setting up field instance I have isolated my error to the field_create_instance($instance) line but can't make sense of what I'm doing wrong.

function my_module_quote_add_qid() {
$field = array(
    'field_name' => 'qid',
    'type' => 'text',
  );
  field_create_field($field);
  $instance = array(
    'field_name' => 'qid',
    'entity_type' => 'node',
    'bundle' => 'product',
    'label' => t('qid'),
    'widget' => array(
      'type' => 'textfield',
    ),
  );
  field_create_instance($instance);
}

my_module_quote_add_qid();

This is what my error looks like:

Notice: Undefined index: view modes in EntityDefaultRulesController->eventInfo() (line 51 of /var/www/seven/sites/all/modules/entity/entity.rules.inc).
Notice: Undefined index: schema_fields_sql in DrupalDefaultEntityController->buildQuery() (line 265 of /var/www/seven/includes/entity.inc).
Recoverable fatal error: Argument 2 passed to SelectQuery::fields() must be an array, null given, called in /var/www/seven/includes/entity.inc on line 284 and defined in SelectQuery->fields() (line 1300 of /var/www/seven/includes/database/select.inc).

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.


Should Features modules be unit tested? When you write a module, you write unit tests (or you should - I don't because I am a bad person, but I want to change - honest).

Should modules generated with Features be unit tested where applicable/possible, or is a suite of Selenium tests enough?

For example, say I have a Feature that has a node type and a couple of user roles and/or permissions for said content type.  Is it good practice (or even necessary) for SimpleTests to be written to test creation of my content type?

For clarity, I am aware of Unit test for custom content type, but I am after an answer regarding all unit testable functionality, not just content types.

The Features module has its own tests that verify that the operations done on a feature (e.g. adding or reverting it) as successful. Drupal already has tests to verify that for example, users with the right permission can read/write/update a node, or that a Drupal variable is effectively saved. The Views module should have its own tests to verify that exporting/importing a views is done correctly.

Apart from those tests, you should not have any reason to write tests for the Feature module, as the existing tests should already covers any possibility. The only case I would write a test for a feature is when the feature is using custom code you wrote.


How to have a content type that displays a title, a description and a list of feeds imported from an external URL such as blogspot? I know this is already discussed, I read many answers, but I am unable to make this simple operation.

I want a content type that displays a title a description and a list of feed items from an external URL that user can set when creates this content type node.

Ok, I installed feeds module, created an importer.
Before this I created a content type named "blogger" (for test only).
So I created an importer also named "blogger" and I attached to "blogger" content type.

Then I set fetcher as http download and parser to rss.
Now, in processor settings I can see bundle that are my content type installed, so I selected blogger, but I tried to select feed item, the result is the same.
In mapping I am confused: I tried to set all possible combinations; I set item guid as unique field.
I then create a node type of blogger content type, and I added URL of my blogspot page. I named this node "test page".
When I view "test page" I can't see feed items that are imported.
Drupal creates 25 node of "blogger" type, that are my feed items, but I don't want this.

Now, I wrong something in settings of feeds module? Or feeds module is not my way?

I only want see my blogspot items all in my test page; that's it...

Can anyone help me?

Drupal creates 25 node of "blogger" type, that are my feed items, but I don't want this.

There is a difference between attaching an importer to a content type and selecting a content type on the node processor. The first one is meant as a sort of "container" - you'll need to create nodes of this type in order to import content. The content type select on the node processor is the type of nodes that Feeds will create when you import content. Make sure that these two settings are always different.

So you need to make sure that you have two content types:

One content type - called "blogger" for example - is the content type that you attach the importer to. This setting can be found under "Basic settings". This means you need to create a node of this type in order to import content.
The second content type - called "blog item" for example - is the type of content that you want Feeds to create. Select this content type on the node processor.

When you now create a "blogger" node and provide a source - in your case an URL since you selected the HTTP fetcher for your importer - Feeds will create nodes of type "blog item".

In order to show the blog items on your blogger node, you'll need to create a View and find a way to display that View on your blogger node. One way of doing that would be using a block that is only shown on your blogger content type.

If you want to have a head start with this, I recommend to install the Feeds News module (this module is included with Feeds). This demonstrates how to use the attach to content type feature. It also includes a View for displaying the imported items (though on a separate page).


How do I apply a patch file? I downloaded a patch file from mailhandler module and need to apply the changes in order to fix the problem of pop3 accounts not deleting emails after download (import).  How do I install it?

Here are a few links that may help you learn more about patching:

Applying a Patch Manually
Making a Drupal patch with Git (also covers applying)
HowTo: How to apply a patch to a contributed module - Beginner's version (Windows)
Apply Patches on Windows (more methods)
Apply patches on Mac OS
How to apply patches for Drupal modules and files


Module Block does not show up Possible Duplicate:
  Block not showing up in drupal

For some odd reason, This very simple module block does not show up in structure
under the list of viable blocks. Am I doing something wrong here?

[quick_links.info]

name= Quick Links
description = Simple block with links
package = Mpackage
core = 7.x
files[] = quick_links.module

[quick_links.module]

function quick_links_block_info() {
  $blocks['quick_links_staff'] = array(
    'info' => t('Quick Link'),
    'status' => 1,
  );
  return $blocks;
}//TODO add caching option

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'quick_links_staff' :
      $block['subject'] = t('Quick Link');
      $block['content'] = t('links go here');
      break;
  }
  return $block;
}

I don't have a real explanation why my solution worked; I only replaced quick_links_staff with quick_links in both places.

function quick_links_block_info() {
  $blocks['quick_links'] = array(
    'info' => t('Quick Link'),
    'status' => 1,
  );
  return $blocks;
}//TODO add caching option

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'quick_links':
    $block['subject'] = t('Quick Link');
    $block['content'] = t('links go here');
    break;
  }
  return $block;
}

Make sure to clear Drupal cache after you implement the change.


How do I add a simple form to the node edit page? I've spent a grand total of 8 hours trying to solve this problem. The form needs to be separate from the node edit form so I can't use the form_alter hook. It needs a separate submit button. It only needs to appear on admin screens ... I've tried overriding page.tpl.php (the one used by me admin theme, seven) with no luck. See the code below ... absolutely nothing happens. When I add html into the page.tpl.php file (located in my modules folder), the html does not appear.

/**
 * Implements hook_theme_registry_alter()
**/
function my_module_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'my_module');
  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'seven', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _my_module_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}
/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _my_module_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}

Also, I realize I can create forms the drupal way with the form hook (and page call backs). I've had success creating forms and showing them on custom urls, but I can't seem to programatically add the forms on pages I want, such as the node edit pages. If I could figure out how to do that, it would be preferable to just adding an html form into the template folder.

It sounds like you want to let the author notify your module of significant changes to a node.  Another approach you could take is to add a field to your node type, such as "field_change_notification" (boolean/checkbox) ... then look to check if the author selected the checkbox in hook_node_presave.  You can even set it back to unchecked so they can again notify your module on the next update.

function HOOK_node_presave($node){
  if ($node->type == 'article'){
    if ($node->field_change_notification['und'][0]['value']){
      drupal_set_message('A change has been made...');
      $node->field_change_notification['und'][0]['value'] = 0;
    }
  }
}


How do I show the image in a node enlarged? I use the TinyMCE editor as site's editor. When I publish an image, I want the users click the image to view it enlarged.
How can I do this? The image is not a field; it is an image in the node.

This can be accomplished using Image Resize Filter

Here is a nice tutorial by Lullabot: Effortless Inline Thumbnails: Image Resize Filter


Product price not showing up in views without Disable SQL rewriting I got a Commerce Product set up in Drupal 7 with a content-type Product Display that have a product reference to it. Users have read access to Product Display but not direct access to the Commerce Product.

I am now trying to set up a Pane in Views 3 that list Product Display nodes in a table. I want to include the Price in every row. I have added the referenced product in relationship and were about to add the price field from the product.

This view however does not display at all for normal users. I suspected that normal users don't have access to the Product entity, so turned on Disable SQL Rewriting and now Views displays the table as intended for normal users.

I am wondering if this is the right way to get the price to show up in Views? I can see that the Product Display node can actually display the price on its page without giving access to the Product to normal users, but cannot find how to access that display field within just the node in Views.

This has been discussed in a lengthy thread on drupal.org. The recommendation apparently is indeed to disable SQL Rewriting. There is a pretty good explanation of the ramifications in the middle of the thread along with alternative suggestions. But it appears that you got it right for now.


How can we create a search form to display a specific node I need to create a result publishing system in drupal.

there must be a search page to enter the student register number.

when the user enter the register number it should take it to a single specific node.

here the register number is a nodeid

so when a user enter the node id and hit show button, it should display that specific node.

which method is best.

i think with views we can do this.

but how

thanks

Make an exposed filter (with autocomplete) of the register number in your view (showing all these desired nodes), enable it's exposed filter block (Advanced > Exposed form in block : Yes)

Now place this block where ever you want, hit apply, you should be taken to the views page, only showing one result. (Make sure the full rendered node entity is shown)


How to programmatically uncheck 'Generate automatic URL alias' option for all nodes I've created some nodes programmatically and set the path alias. But when I then go into edit the node the 'Generate automatic URL alias' option is still checked, even though my alias is shown in the 'URL alias' textfield underneath, so consequently gets overwritten on save.

Also, when editing the node using the Entity module and entity_metadata_wrapper(), the alias is generated again and my alias is overwritten because of this problem.

When I load a node using node_load() I expect to see $node->path['pathauto'] but I don't, so I can't seem to disable it this way. Anyone have any advice?

Figured I'd help out -- took me a while to find it.

Pathauto doesn't implement hook_node_load, so you won't see it there.  My case was I needed to remove an alias in an update hook, and make sure that checkbox is unchecked.

So that's what I did

  $node = node_load(17);
  $node->path['pathauto'] = FALSE;
  node_save($node);
  pathauto_node_delete($node);
  node_load($node->nid);


How to display a views slideshow placeholder? I have a site where the user can add images to the content types page and (custom) project. These images are displayed in a views slideshow based on contextual filter on each page/project in a block. The slideshows are header slideshows, so there must be a placeholder slideshow, if no images are added. How can i accomplish this ? I need a solution where no further maintenance by the user is needed.

Do i have to put some if/else in the page.tpl.php or is there some more elegant way ?

Your slideshow is a View. So:

Go to edit page of your view
Expand "Advanced" field set
Add new item into "NO RESULTS BEHAVIOR"
Choose "Global: Text area"
Add your placeholder html there. E.g.
NO-IMAGES

Save View


How to hide "Include file in display" in File Field? I'm using File Field in Drupal 7 to let users upload files, but after uploading there is a choice for users to let the file be included in display or not (radio button with "Include file in display" description). Now I want to remove this choice, because I need all of the files display for download, OR at least hide this for non-admin users. What should I do?
Thanks.

You need to set that in the field's settings page.

Structure > Content Types > [your content type] > Manage Fields > Edit [your file field]

You will see settings for the Enable Display Field Option. The caveat is that if you already have data in this file field, unchecking this may not have an effect.

(See my screen capture)


How to send a push notification with Rules to specified user by grabbing UID from content field? I want to send a push notification to a single Drupal, which, seems simple given the below screen shot.

This works great when the user is always the same (I simply type in the UID). However, in my case, the UID is always different. Is it possible for me to grab the UID from a content field (e.g. from Content Type 'Friends', I have a field named field_target_user) using a token, and have it populate in my Rules' User Identifier field?

Use the button that says Switch to direct input mode. And verify if you can use any of the tokens shown there as the identifier you're looking for.

If no appropriate token is shown, then try to add an appropriate Rules Condition with Entity has field, to make the field you need available for further processing in the rule. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

However, as per your "... content field ... from Content Type 'friends'*" (as in your question), the above may not be sufficient yet (= the appropriate token is still not shown). I.e from the label(s) it sounds that this could well be a multi value field (of type entity reference?). In that case you first need to add a "Rules loop" to iterate of the list of friends, so that inside that loop you can use a token related to the uid of the current list item being processed.

The above are just 3 of the typical/possible approaches to get access in a custom rule to some token you're looking for. There are others though, such as:

using Rules Action to "Fetch entity by ID", or
getting the Views Rules module involved,
etc.

Note: In case you're using the Push Notifications module, you may want to have a look at its community documentation related to Rules integration, especially this screenprint on that page seems pretty similar to what you're looking for (if you can reference the node:author token, it should also be possible to reference some other field of a node).


Pre-select Group Audience for Organic Groups Here is my situation.

I am using the latest version of Organic Groups on Drupal 7. Every user on my site is part of one group and one group only. Is there a way to make it so that when users are creating group content, the group they belong to is automatically pre-selected? Again, every user is only in one group (but there are numerous groups), so it's superfluous to force them to make a group selection whenever they are creating group content.

You can use Field Permission module to not allow a user to see the group field on content type.
Use  hook_form_BASE_FORM_ID_alter() to set a default field value for group field based on current logged in user.

as a sample code (not tested)

function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    global $user;
    $groups = og_get_groups_by_user($user);
      if(is_array($groups)) {
      // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
      $form['group_field_name']['#default'] = $groups[0];
      }
  }
}


Redirect a form to an external URL Want to redirect $form_state to external URL after successful registration of the user. Like, need to redirect to facebook after user registration.

  $query = "http://facebook.com";
  $url = Url::fromRoute('user.register', [], ['query' => ['service' => $query]]);
  $form_state->setRedirectUrl($url);
  //$url = Url::fromUri($query);
  return RedirectResponse::create($url->toString(), 302);

  $form_state>setResponse(newTrustedRedirectResponse('https://google.com', 302));
  return new RedirectResponse($query);
  $form_state->setRedirect($query);
  $form_state->setRedirectUrl(Url::fromUri($query));
  $response = new RedirectResponse($query);
  $response->send();

tried above all methods, but nothing works.

The method that you missed is $form_state->setResponse(). In combination with a TrustedRedirectResponse object, which exists for security reasons (to prevent users from accidentally being redirected to another site), you can use code similar to the following.

$response = new TrustedRedirectResponse('https://facebook.com');
$form_state->setResponse($response);


How to delete a vocabulary terms programmatically? I want to remove all the terms from a vocab but not delete the vocab itself.

I can do it on the database, but Id rather use the api if available in D8.

$existingTerms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('mycustomvocab');
foreach ($existingTerms as $existingTerm) {
  // Delete vocabulary term *** This function is not available in D8 ***
  taxonomy_term_delete($existingTerm->tid);

  // Delete vocabulary - *** Not what is required ***
  /*
  $vocab = Vocabulary::load($existingTerm->vid);
  if (!is_null($vocab)) {
    $vocab->delete();
  }
  */
}

This is how Im doing it at the moment until I find a better solution

db_query("DELETE FROM {taxonomy_term_hierarchy} WHERE `tid` IN (SELECT tid FROM {taxonomy_term_data} WHERE `vid` = :ctype)", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_field_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));

$tids = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'mycustomvocab')
    ->execute();

  $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  $entities = $controller->loadMultiple($tids);
  $controller->delete($entities);


Is there any "block_user" module? After moving my sites to the new server, and some updates in the mean time. I have found one of the sites displaying the

"The following module is missing from the file system: block_user bootstrap.inc:276"

warring.

Have search the DB and it seems the only "block_user" string is located inside the key_value table, it's raw definition looks like that:

INSERT INTO `key_value` (`collection`, `name`) VALUES ('system.schema','block_user')

It has one more binary column as well.

To test the issues have changed the field value to "block_user_1234", it changed the warring message so it's the point for sure.

Should I remove the row ??

There is no block_user module so far as I can see or find.

You can delete the row from the key value table, yes. It should get rid of the error. You can do it with drush if you want.

Back up your database
drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='block_user';"

This assumes a Drupal 8 site.


Display file upload images in webform view I have a webform where users can upload images. For easier administration, I created a view of these submissions.

The default behavior of the field is to display as a link. However, I would like to preview the images by displaying them in an image tag.

I looked at the field re-write behavior, but it only gives me the entire href.

How can I display image field values as images in a webform view?

This can not be done with webform module alone.
All you need to do is get help of 2 extra modules.

File Entity
Views Field View

Further you need to do following things.

Download and enable both of the modules and clear the cache.
Webform is storing file, not only image. I am assuming here you are only uploading image files, you can further get idea to show any type of file there. So go to Image File Type Display: admin/structure/file-types/manage/image/file-display and set the preview/image style. Or if you do not want to change settings for default view mode of the file, download another module Entity View Mode. Go to it's configuration and create specific display and set image style accordingly in file display settings.
Create a view of files, it should be a block. and there add contextual filter for the fid and add field "File: Rendered". You can set file view mode by this field. For your convenience I'm exporting the view below, you just need to import this.

    $view = new view();
    $view->name = 'file_view';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'file_managed';
    $view->human_name = 'File view';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'File view';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: File: Name */
    $handler->display->display_options['fields']['filename']['id'] = 'filename';
    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
    $handler->display->display_options['fields']['filename']['field'] = 'filename';
    $handler->display->display_options['fields']['filename']['label'] = '';
    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
    /* Field: File: Rendered */
    $handler->display->display_options['fields']['rendered']['id'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['table'] = 'file_managed';
    $handler->display->display_options['fields']['rendered']['field'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['label'] = '';
    $handler->display->display_options['fields']['rendered']['element_label_colon'] = FALSE;
    /* Contextual filter: File: File ID */
    $handler->display->display_options['arguments']['fid']['id'] = 'fid';
    $handler->display->display_options['arguments']['fid']['table'] = 'file_managed';
    $handler->display->display_options['arguments']['fid']['field'] = 'fid';
    $handler->display->display_options['arguments']['fid']['default_action'] = 'default';
    $handler->display->display_options['arguments']['fid']['default_argument_type'] = 'node';
    $handler->display->display_options['arguments']['fid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['fid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['fid']['summary_options']['items_per_page'] = '25';

    /* Display: Single File View */
    $handler = $view->new_display('block', 'Single File View', 'block');

Now in your main view (where you are showing submissions). Add a new relationship for Webform submissions: Data. You'll need to set the nid for the webform here and select the image component.
Add new field to the view submission data: Value (raw). This will give you the file_id for the associated file. Exclude it from display.
Add another field Global: View. Select the view you imported and the block display. In contextual filter set [!data] from replacement patterns. It was the raw value of the field which you excluded from the display. And Here you go, save the view and rock :). Thanks for asking such good question. Still if you face any problem during this tutorial, ask me.


default field permissions I have created a module that adds a an extra field for each user. I do this by first creating the field using field_create_field and then I bind it to the user object using field_create_instance. This is standard practice I think.

Now, I would like to add so that by default only administrators should be able to change the value of this field. I would like to keep down the number of external modules, so if possible I would like this to be the default behavior after installing my module, without relying on other modules such as field_permissions to achieve this.

Is this possible?

Thanks in advance!

I found the answer. It is done using the hook_field_access. In my case, what I did was:

function my_module_field_access($op, $field, $type, $entity) {
    if ($op=="edit" && $field["field_name"]=="my_field") {
        if (!user_access("administer users"))
            return FALSE;
    }
}


Am I able to use dynamic parameters in libraries configuration files? I have hard coded GMaps API key in URL inside in the libraries.yml file.

Would I be able to use a dynamic parameter for this key?

You should be able to use hook_library_info_build(). It's a new (to D8) hook that allows you to define libraries at runtime.
Here's the change record that talks about it's introduction. It's unlikely to go anywhere, but here's the description from the change record:

There was no way to dynamically register libraries. Using hook_library_info_alter() to register new library is possible but doesn't end well in alter/weight.
Therefore a new hook is created namely hook_library_info_build()

Alternatively; you could potentially add the hook as normal in your example.libraries.yml file, and then use hook_library_info_alter.


How do I display fields in my product type in a product display? I have the unique parameters for my product.  Sometimes I want to display some parameters, and sometimes I don't.  So, I defined them in my product type.

My question is how do I display these fields for a product display?  I don't want to create a duplicate when the values are already defined in the product type.

Fields from the referenced product entity are automatically available on the product display node.

Set the fields to visible on the product at

admin/commerce/products/types/subscription-product/display

Then, set the fields to display at:

admin/structure/types/manage/product-display/display

Update: As noted by vintorg below when creating your product reference field on the product display node, ensure "Render fields from the referenced products when viewing this entity." is checked.

That should do it.


How do I get the password from form API to use to log into external site? I have these functions, one is for the Form API and the other, git pull, is called on a cron hook. The password is coming up blank and therefore the git pull is not working.

function cronmonitor_admin_form($form, &$form_state) {

  $form['cronmonitor_account'] = array(
  '#title' => t('Github Account'),
  '#type' => 'textfield',
  '#description' => t('Github ID'),
  '#default_value' =>  variable_get('cronmonitor_account'),
  );

  $form['cronmonitor_pass'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#maxlength' => 64,
  '#size' => 15,
  );
 ...more form elements....
}

function git_pull(){

  $localRoot        = variable_get ...
  $localRepoName    = variable_get ...
  $localRepo        = "{$localRoot}/{$localRepoName}";
  $username         = variable_get('cronmonitor_account');
  $password         = variable_get('cronmonitor_pass');
  $remoteRepoName   = variable_get ...
  $remoteRepo       = "https://{$username}:{$password}@{$remoteRepoName}";
  if( file_exists($localRepo) ) {
      shell_exec("cd {$localRepo} && git pull");
  }
  else {
      shell_exec("git clone {$remoteRepo} {$localRepo} ");
  }
}

I went with the
Encrypt Form API module.


Why do so few code examples use the ::load($id) method for loading entities? Over at How to get term name from a tid? the accepted answer for "how do I get the name for a Term" is this:

use Drupal\taxonomy\Entity\Term;
...
$term = Term::load($tid);
...

That's really nice, easy to read code (and very easy to remember). It's also, as it turns out, applicable to all entity types in Drupal (just substitute the Term class for the type of entity you want).

Why then, do the overwhelming majority of the code examples and tutorials published around the place seem to advocate this monstrosity? ...

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

That approach bakes in one of my [many] grievances with PHP in general - it's full of magic strings! How the hell am I supposed to know at "compile time" whether 'taxonomy_term' is the right argument to getStorage()?? There's not a PHP IDE in the land that'll catch me sticking 'taxonomy' in there instead.

Looking at the contents of that ::load method (which is defined in \Drupal\Core\Entity\Entity and shared by all Drupal entities), it's got all the dependency-injection cleverness of that second-approach - plus it fills in the right argument to getStorage() for you automatically!

So why does more of the Drupal community not use it? Is there something I'm missing? Or is it just to teach us "first principles" so that we can write shared code that works with any entity type? (you'd need the long-hand way in a hook that was intended to work across all entity types).

There is actually an issue about adding this info to the docs.

In short, the long winded version is unit test friendly.

A comment by one of the Core's contributors fully detailed explains why. Just to highlight the main point:

  If we call Node::load() in OO code we are breaking this principle (dependency inversion),
  because we are hardcoding the specific implementation
  (\Drupal\node\Entity\Node::load() to be exact). This code path is hard
  coupled to \Drupal::entityManager() which is hard coupled to
  \Drupal::$container. So now our code becomes impossible to run outside
  of Drupal.

  Furthermore, since code that uses the dependency inversion principle
  is fully standalone it is very easy to unit test it by mocking the
  dependencies according to the requested interfaces. If we introduce
  Node::load() then it becomes really hard to "properly" unit test the
  class, since it will start polluting the test environment with
  external code, and the dependency injection container is not available
  in unit tests.

Now if you wonder then why does Entity::load exists

  There were many loud voices at the time that D8 was going to be a DX
  disaster, that the OO approach was too difficult to understand and
  write, that it would never get adopted by the wider community. There
  was a huge push going on to make D8 more DX friendly, mainly driven by
  the Backdrop fork that was announced a few months earlier.

  So we created these static methods that wrap the loading of the entity
  manager from the container, and can be called directly from the
  procedural side. It was great, since it offers a drop-in replacement
  that works and looks very much like the original code. This made
  porting of procedural D7 code vastly easier:

// Original D7 procedural code.
$node = node_load($nid);

// New D8 procedural code.
$node = Node::load($nid);


validating textfield input with ajax on every key entry I'm new to Drupal and Javascript, so please bear with me. I have a simple class project to create custom validation on textfields without using select options or checkboxes. For one of the fields, the only valid inputs are 'right' or 'left'.

I have validation upon submit working, but I wanted to use ajax to check user input key by key, and display an error message before clicking the submit button. (As soon as it's clear the input will not be 'right' or 'left').

The function is working, but drupal pauses for a half second or so with every keyup while it does the ajax call, making it not very user friendly or practical to use. Hitting backspace to clear the field before drupal 'resumes' even navigates away from the page.

I have looked extensively online for resources on this, and have not found an example or module that seems to address this particular issue. Modifying autocomplete_path seemed like the best option, but I can't figure out how to modify it for my purpose.

I have the module on my github here, or here are the parts in my module dealing with ajax.
In my form:

$form['direction'] = array(
    '#title' => 'Direction',
    '#type' => 'textfield',
    '#description' => 'Enter the shift direction',
    '#element_validate' => array('validate_direction'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#required' => TRUE,
    '#ajax' => array(
            'event' => 'keyup',
            'callback' => 'validate_direction_callback',
    ),
);

and then the actual ajax callback

function validate_direction_callback($form, &$form_state){
    $commands = array();
    $commands[] = ajax_command_html('#error_message', render($form['direction']));
    $commands[] = array(
        'command' => 'validateDirectionCallback',
        'selectedValue' => $form_state['values']['direction'],
    );
    return array('#type' => 'ajax', '#commands' => $commands);
}

I didn't include the js file here because it didn't affect the pausing even when it was commented out. Thank You! Oh, and I am using Drupal 7.39.

The ajax callback in drupal is nearly as slow as a complete page load and this takes between 200 und 1000 ms. So checking every key stroke is no option.

If you don't check against the database, there is no need for an ajax callback. I would check "right" or "left" in javascript. If you need a server side check, you can write a stand-alone php file, that does this check without drupal, then your response time will be between 10 and 20 ms.

To replace the slow ajax with javascript you can start with this script:

val_left_or_right.js:

(function ($) {
  $('#edit-direction').keyup(function(){
    var direction_text = $('#edit-direction').val();
    if (direction_text != 'left' && direction_text != 'right') {
      $('#error_message').html('Please type left or right');
    } else {
      $('#error_message').html('OK');
    }
  });
})(jQuery);

attach the js to the form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'your_module') . '/js/val_left_or_right.js',
);


Render template for HtmlResponse In my controller I want to return Drupal\Core\Render\HtmlResponse, and also I want to take HTML content from the template. The problem is that if I will try to render() a rendereable array before returning HtmlResponse - I'm getting "The website encountered an unexpected error. Please try again later." error. Array is being rendered correctly when I will just return it as it is, but with all Drupal HTML, which I don't want. What am I doing wrong?

Added #1: Discovery - all works well when I return Zend\Diactoros\Response\HtmlResponse . Now I'm even more confused. Why is that?

Added #2: When I use "renderPlain()" renderers method it also works, but I'm not sure of drawbacks yet.

Oh, I believe I should use "renderRoot()" method of renderer in case where I'm rendering HTML for response just to be send. Please correct me someone if I'm wrong.


Purpose of the Tag field on Add View page? Under the Tag field on the Add View Page is such note:

  Enter an optional tag for this view;
  it is used only to help sort views on
  the administrative page.

But I also noticed that when I fill this field out another template becomes available with tagname in it's name. I should say that that might be quite handy in my case, when I kinda need to narrow the hit to specific views only. Can I perhaps use this feature to granulate templates for the views?

Any other usage case for the Tag field?

To me, the tag field is handy for sites that have a lot of views.Different views have different purposes; for instance admin/editor tasks, front end pages and blocks, or as source for node reference fields. If you tag your views consistently, it's easier to find a view when you need to edit it.