Insert videos from media module into Ckeditor

I believe this is just how it works with the media module.  You might could experiment with the http://drupal.org/sandbox/DevinCarlson/1823634 to select the view modes for files displayed inserted into wysiwyg editor.


How can I filter a view according to another view's results

This module might help you Views exclude previous

  The Views exclude previous module provides a views filter that
  excludes nodes that have already been loaded/displayed on the current
  page.

It excludes node in previous views loaded in your views. Example: you have two views block loading in the same page and the two block shows same node in views; you can exclude the other one in display, you can find the additional field in filter criteria in views configuration of your block. See image attached


Create a field with machine name 'views_entity_commerce_order' in the pantheon one and then import your view.


I am learning Drupal 7 and want to know the way to learn modules

I think the most important is experience. Just installing and enabling some modules, trying them out gives you a feeling of how things work. There are many youtube videos that show you exactly what to do. But I can't stress this too much: experience is what we need. Don't make the same mistake as I did in the beginning when I studied more than I tried.

Don't be afraid to try things out, even if they don't seem to work in the beginning. Be persistent and follow the guidelines out there. Should you need specific advice on a module, feel free to ask here or in drupal.org where you should become a member. (if you are not already!)

I don't think there is an "officially correct way to learn". If there is, then I bet it is called persistence! So get involved and see you out in the field :D.


How to create eshop for product hiring counting price per day

Look at the Commerce Price Table module which supports the following output for a table of prices/quantity:

  contrib project that allows to have a secondary price field that
  considers the quantity for displaying and using the prices. It also
  provides a field formatter to display the price/quantity values as a
  table.


Add trailing slash to taxonomy term. Issue with relative URL

The key to this answere is that the URL needs to end with a slash.

I turns out Redirect modules will remove trailing slashes.

You can disable clean URLs if you want trailing slash. Which is not ideal.

A workaround would be to use this code for particular links:

link

var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/"+ curHref);


How do I programatically create and display a one-off view?

I figured it out myself in the end - by looking at how Views does it itself in views_block_view().

function page_callback($my_entity) {
  //create view
  $view = new view();

   ... //Do all the views creation stuff e.g. code in export view

  $display_id = 'block_1';
  $view->new_display('block', 'Block', $display_id);

  if ($view->access($display_id)) {
    $output = $view->execute_display($display_id);
    views_add_block_contextual_links($output, $view, $display_id);
    $view->destroy();
    return $output;
  }
$view->destroy();
}

The above code renders a view that is created from scratch and never saved to a database.  If you wanted to do a page you could look at the code in views_page().


Language paths per country- how to redirect users to their respective language's path on login?

function module_user_login(&$edit, $account) {

     drupal_goto($user->language."/logindestination");

    }

Also, iirc, if your user has a language set, you can set one of the language detection method's to be "user preference", which would kick them over to the correct language after login.


how to install drupal with myisam and different collation

You can do during the installation or you can convert

For the installation, before you launch the install.php, you need to edit the "/includes/databases/mysql/schema.inc file.

// Provide defaults if needed.
$table += array(
  'mysql_engine' => 'MyISAM',    //Changed from Innodb to MyISAM
  'mysql_character_set' => 'utf8',
   mysql_collation' => 'utf8_unicode_ci',  //Added the collation
);

$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'] . ' COLLATE ' . $table['mysql_collation'];

in case  you want to convert already created tables. put the site on maintenance mode and use phpmyadmin to convert the engines and collations


how to render content type's fields in Custom Module Form

To get an empty form of a content type you would use code like this:

$node = \Drupal\node\Entity\Node::create(['type' => 'page']);
$form = \Drupal::service('entity.form_builder')->getForm($node);

To open this form with ajax, put the form in a controller:

public function contenttypeform(NodeTypeInterface $node_type) {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);
    return $this->entityFormBuilder()->getForm($node);
  }

Configure a route for this controller and open the form in an ajax modal like this example from ConfigSync.php:

$links['view_diff'] = array(
            '#type' => 'link',
            'title' => $this->t('View differences'),
            'url' => Url::fromRoute($route_name, $route_options),
            'attributes' => array(
              'class' => array('use-ajax'),
              'data-dialog-type' => 'modal',
              'data-dialog-options' => json_encode(array(
                'width' => 700
              )),
            ),
          );


how to use URL_ALIAS for search result of apachesolr module?

I am running the same configuration as you and this has the SEF urls by default.

Have you checked your URL Aliases? Does this problem occur for ALL nodes in SERPS? I would try rebuilding your aliases


How to show a view each 5 rows in another view

this can be done by overriding your View's template for the Style Output plugin (e.g. views-view-unformatted--yourview_machine_name.tpl.php). Then in that template outputting something like this:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
    <?php
      // this tells the view to do something after every 4 rows
      if (($id % 4) == 0):
      print views_embed_view('view_machine_name', 'block_1');
      } ?>

<?php endforeach; ?>

If you wanted to alternate your secondary View's blocks - you could add some logic for that too.


Beginner trying to use jQuery in a custom location, but not sure where to insert the code

If you are customising a theme, I would add a custom jquery script you have written. In your themes template.php you can then simply call the .js file from within the theme folder.

For example you could add this to your template.php file:

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/jquery.custom.js');

in the jquery.custom.js file you could have something like this:

(function($) {

 $(document).ready(function() {

  // hover effect
  $(".hover_effect").hover(function() {
    //add effects here
  }

 });

}(jQuery));


Firefox is caching ajax form values from previous submit after if I press the browser back button

It seems chrome makes a refresh of the page and firefox a cache. Seeing this question the reasons are answered here

You can try disabling caches using http headers: https://stackoverflow.com/questions/13640109/how-to-prevent-browser-cache-for-php-site


/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function MYMODULE_node_insert(Drupal\node\NodeInterface $node) {

  if($node->bundle() == 'article') { //check for a content type, ex: article
    $user = \Drupal\user\Entity\User::load($uid); // load the user
    $user->set('field_name', $some_value); // set a value for a particular field
    $user->save();
  }

}

Originally I wrote:

MYMODULE_node_create(Drupal\node\NodeInterface $node) {

Changed it as per the comment below.


I prefer to have a custom module that has dependencies for all the developer modules I need. I also set up this module to have some strongarmed variables (such as turning off preprocessing of css/js and any page caching), and enables a few developer blocks using Context (such as execute php and context inspector). This allows you to simply drush en/dis the one module to turn on/off all of your developer utilities.

Here's my Lullabot devel module that you can look at for an example.


How to disable/turn off Automatic URL alias

Automatic URL aliasing? It will be the Pathauto module doing that. You can disable it, but you will need to delete your current aliases as well, which the Pathauto module provides an interface for if you check its settings.


Where should I install the LESSPHP compiler?

In the Less Processor Module page it says:

  Requirements

  Libraries API

  less.php and unpack it so that
  'lessc.inc.php' is located at
  'sites/all/libraries/lessphp/lessc.inc.php'.

Which means:

1) you need to download and enable the Libraires API module

2) Then you need to download Less.php <-- click here to download it

3) Open the zip file, and grab the lessc.inc.php file only

4) Next you'll need to create some folders in your web directory (create a libraries folder inside the all folder, and a lessphp folder inside the libraries folder) so it looks like this

sites/all/libraries/lessphp/

5) Upload the lessc.inc.php file to the lessphp folder.


Drupal commerce order list view - payment status

It's not impossible, but the amount of Views foo required to do it is beyond most mortals.

The tricky part is that an order can have many transactions, and also several which is completed. That is the data model would allow you to pay half by credit card and half by paypal. Also different payment methods might have different status for complete/incomplete payments. That logic is hard to build into a SQL query, which is the limitations of Views.

That said you could add a custom relationship from the order to the payment transactions and probably make something that can work. Doing this will require that you can create a module, know a bit about Views and have a lot of patience, unless you have done this type of thing before.


You can able to do it using Nice Menus module. Check here for detailed step by step tutorial on how to use nice menus module.

  Nice Menus enables drop-down/right/left expandable menus. It uses only
  CSS for most browsers, with minimal Javascript for IE6. (Version 2
  uses the Superfish jQuery plugin for all browsers, with an option to
  disable JS, and falls back to CSS-only for browsers that can handle
  it.)


Using a field in many content types? Usual or completely wrong?

Deciding if what your question is about is right or wrong, is something you'd have to decide for yourself. However by reusing field you're actually using one of the typical Drupal facilities to define fields.
In the context of "reusability", one would think that it is a good practise to reuse whatever can be reused.
The challenge (problem?) is that when changes are needed to a reused field, it'll be more difficult to do so for reused fields as compared to a field that is not reused at all.
To get a feeling of this, do some experiments with the Features module, for 2 scenarios: (a) changes to a reused field and (b) changes to a field that is not reused anywhere. Just look at the size of the features created in both scenarios.
My approach is becoming more and more to NOT reuse fields, to not complicate things when later on (design) changes are needed (to ensure maintainability as much as I can). This approach is also partially based on what I've learned from what's further detailed below, which applies to any release of Drupal ... (though I'm curious myself to see how things will evolve related to Relativity for Drupal 8).
Relativity model
There is an (illuminating) article "Relativity Model for Drupal", especially the related page about "Wrapping Information Architecture and Documentation". Here is a quote from it:

To create an Event content type in Drupal is a simple task. But there's a nuance to that task that is overlooked very often. That nuance is the machine name. But why is the machine name of a content type such an important step?

It gives the content type an explicit name of your choosing and allows database indexing to act on that machine name while being queried.
All fields contained within that content type will share the same machine name before the field name. This allows the Views module to clearly gather field data in a very defined manner using the indexed machine name.
Fields that are entity references out to other content types also begin with the same machine name followed by their own machine name. This allows simple and visual identification for origination and destination of data relationship.

It also contains an interesting example of what seems to be a great naming convention.
Remark (cfr comment from Kevin): The most difficult part is knowing when you would reuse a field vs when you won't. The big obstacle is shared field settings - changing certain settings affects all fields, when you probably only want to affect that instance.


Startup Growth Lite - How To Set Width For Content Type

Typical, minutes after posting the question I finally found the answer.

What has worked for me was adding my content type to the template.php file startupgrowth_lite_preprocess_page function, our content type was called 'client_work' which once added set it to display the same as the 'page' content type.

I added the following

&& $variables['node']->type != 'client_work'

to the end of the first if statement in the function below (around line 494).

function startupgrowth_lite_preprocess_page(&$variables) {

    /**
     * Insert variables into the page template.
     */
    if (isset($variables['node']) && $variables['node']->type != 'page' && $variables['node']->type != 'client_work') {


You should not create your content type programmatically, if there's no special reason. Take a look at any intro like this https://www.youtube.com/watch?v=Nfu6nckjuno - then create a content type and fields with the excellent admin UI.

Serialization to DB is done by the Drupal core.


The problem is not the global variable, but the fact you are using a function like drupal_set_message() inside a alter hook, which is not necessarily invoked when Drupal is outputting a page.
If you want to debug a hook, it's better you go with watchdog() and check in admin/reports/dblog if there is any message. You need to enable the Database Logging or the Syslog module to see any output; in the latter case, you will see the output on the syslog of your computer, instead of admin/reports/dblog.


how to pull parent term from nested array?

If you check closely with the var_dump() output, you will see, that you actually load an array of entity objects with the type taxonomy term: https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.5.x

This object has a getter method getName() that returns the desired property:

$names = [];

foreach($parent as $term) {
  $names[] = $term->getName();
}

$names_list = implode(', ', $names);


Can we have multliple routing.yml files in a single module?

Instead of adding multiple routing files, you can define products, brands as modules inside your main module and then can define routing file for each of them like what is done in aggregator module in core.


How do I build a relation of users having a specific role, automatically?

With the Rules module, you could take action on a "user created with role student" event.


You need to describe the table for views to know which handler to use. For that you have to implement hook_views_data_alter. It looks complicated at first, but its definitely worth it :).

EDIT :
Data & Schema should allow you to set the handler, somewhere in the properties of the table. I haven't used it for a while but am quite sure its there :).


Use hook_node_access() to deny access to the not translated nodes and this will automatically hide the corresponding menu items:

mymodule.module:

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;

  /**
   * Implements hook_node_access().
   */
  function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if (!$node->hasTranslation($langcode)) {
      $access = AccessResult::forbidden();
    }
    else {
      $access = AccessResult::neutral();
    }
    $access->addCacheableDependency($node);
    return $access;
  }

You can be more specific, hide not translated nodes of specific content types. Or for specific user roles, which you probably need to do if other users than the admin wants to edit the nodes. Or you have to be specific about the operation $op. And test this with different user roles, as admin you won't see a difference, because this account passes all access checks.


Problem resolved by Drupal standard translation export. I just check "Fields" and select "Existing strings and the plural format are kept, only new strings are added." when Import *.po file.

admin/config/regional/translate/export


Strictly speaking, fields can't "inherit", no, but you can almost do it anyway.

Drupal 7 comes with a generic "File" field, and a more specific "Image" field. Technically, one could say that Image inherits from File, but the way it's done is simply that for a lot of it's hook implementations, it just calls back to file.

Example code:

/**
 * Implements hook_field_load().
 */
function image_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);
}

As far as I know, this is as close as you can get.


The problem is that addExpression() doesn't take a SelectQueryInterface as a parameter, but only a string:

  $expression: The expression string. May contain placeholders.

So the best you're going to be able to do is add the expression as a manual string. As the argument description suggests placeholders are fine so you can at least keep a bit of structure.

$query = db_select('node', 'n')
    ->fields('n', array('nid', 'title', 'created', 'type', 'status'))
    ->extend('PagerDefault')
    ->limit(5);

$expression = 'IF((SELECT nid FROM `newsletter_lists` WHERE cid= :cid AND nid = n.nid), TRUE, FALSE)';

$query->addExpression($expression, 'included', array(':cid' => $cid));

return $query->execute();


Error class not being set on form fields

The easiest thing to do, would be to save the form data in the validation step if the form has errors.

function form_validate(&$form, &$form_state) {
  // Validate
  if (form_get_errors()) {
    // This code is only run if the form has errors.
    // Save the form data
    db_query("...");
  }
}

Then you could raise the errors and let drupal do it's thing, and use the submit function for it's intended use: handle valid form data.

If you need to process the data this can be done in the validation step as well, as the info in the $form_state array will be carried to the form submit handler.


Why is my form only redirected sometimes?

The cause for the erratic behavior is probably the condition for the current route name in the form alter method. The form is not necessarily built in the same request as the custom controller, it could be served from cache or built in a POST request.

At the moment you have the condition for the route name because the controller invokes the default register form and the form alter doesn't know where it is called from. So you need to make the form distinguishable, for example by a different form handler, a field value in the new entity before you hand it over to the form builder or put the form alter code in a custom form class extending the core user form.

BTW why are you not redirecting by the destination query string you can set on the user register link, then you don't need code?


Remove empty url argument from view with exposed filter

solved the problem:

(function ($) {
  Drupal.behaviors.citatyTaxonomy = {
    attach: function(context) {

      // disable blank input fields
      function disableEmptyInput() {
        $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);
      }

      // on form submit
      $('#views-exposed-form-taxonomy-term-page').find('.views-submit-button input[type=submit]').click(function(){
        disableEmptyInput();
      });

      // view with auto-submit
      $('#views-exposed-form-taxonomy-term-page').find('.ctools-auto-submit-click').click(function(){
        disableEmptyInput();
      });

    }
  };
})(jQuery);


How to do multiple conditions for db_update by using OR condition?

Drupal 7
Yes, it is possible by using db_or() as in the following example.
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition(db_or()
    ->condition('name', 'seven')
    ->condition('name', 'rubik')
  )
  ->execute();

For db_select(), see the answers given in  "OR" condition in db_select() and Nested OR and AND condition with db_select.
Drupal 8
You can still use db_or() as in Drupal 7, but it's deprecated in Drupal 8.0.x and removed in Drupal 9.0.0. Instead, a \Drupal\Core\Database\Query\Condition object should be created as in the following code, taken from BooleanOperator::queryOpBoolean().
if ($this->accept_null) {
  if ($query_operator === self::EQUAL) {
    $condition = (new Condition('OR'))
      ->condition($field, 0, $query_operator)
      ->isNull($field);
  }
  else {
    $condition = (new Condition('AND'))
      ->condition($field, 0, $query_operator)
      ->isNotNull($field);
  }
  $this->query->addWhere($this->options['group'], $condition);
}


The search table is created on cron job. So the sites that are added before the cron job would be displayed. Could you try running the cron and then try to do the search.


Form is not rebuilding on "Add another item" in unlimited value entity reference field

What you are trying to achieve is Selecting Unique values from Multi Value Reference field... I do agree using default widget you may run into duplicates...

I would say consider using below one of the modules which supports entity reference using which you can avoid duplicate entries while adding..

You can choose one from variety of options mentioned in above article which suggests using of

Using of Multiple Selects.
Using of Chosen
An additional possibility is the Dynamic Multiselect Widget.
Another option is Entityreference Views Widget
There is jQuery UI Multiselect
Improved Multiple Select

Hope one of the above works for you :-)


How can I enable download link in the Media browser library tab

1 Create your view, add the fields you'd like displayed.

2 On the "Content: Video" field settings, choose the "preview" option under formatter - this displays the thumbnail.

3 Add the "Content: Path" field to your view

4 Uncheck the settings for label, check the box for "exclude from display"

5 Click on rewrite results and select "Use Absolute Link"

6 Next you'll need to reorder your fields so that "Content: Path" is above "Content: Video".

7 Edit your Content: Video settings.

8 Go to rewrite results and check "Output This Field as a Link".

9 Put [path] as the link path.

10 Save it.

You are done.


How to create a select drop down that opens a URL?

You can do this by using $form_state->setResponse() together with TrustedRedirectResponse.

Create the dropdown, like this:

$form['select'] = [
  '#type' = 'select',
  '#title' => t('Select'),
  '#options' = [
    'https://google.com' => t('Google'),
    // More links...
  ]
];

To open the link in a new tab, you can add this to your form:

$form['#attributes' => ['target' => '_blank']];

Then create the submit handler, like this:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setResponse(new TrustedRedirectResponse($form_state->getValue('select'), 302));
  // You can change the response code from 302 to whatever you need
}


You could still hash_hmac() in Drupal 8. Drupal 8 has a static function that returns the HMAC given a couple of data and key arguments (Drupal\Component\Utility\Crypt::hmacBase64()). The differences are the following.

Crypt::hmacBase64() returns the Base64-encoded HMAC value
Crypt::hmacBase64() replaces some characters to make the string safe to use in URLs
Crypt::hmacBase64() raises an exception when the arguments are not using the expected datatype

If you don't need to encode the HMAC value in Base64, or to pass the HMAC value in URLs, you can use hash_hmac(). You could consider Drupal\Component\Utility\Crypt::hmacBase64() a wrapper around two PHP functions, since its code is the following one.
if (!is_scalar($data) || !is_scalar($key)) {
  throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
}

$hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);


I need a .schema.yml file when I create a new custom field?

To make sure configuration and default values are using the correct types, there can be tricky bugs related to float/int for example.

If you have interface strings in your settings, you can also use the config schema definitions to make them translatable.

And it can be used to validate configuration.

Config schema is not enforced by default, see https://www.drupal.org/node/2625212. But it enforced by default in tests, so try to write a test that creates a field of your type and it will complain and tell you what schema is missing.


How do I preprocess_html() a panelized page?

Solution was to use menu_get_object(). Here is a nice article outline usages of it as well.

$node = menu_get_object('node');

Thanks you David for the answer.


hide a view field content for anonymous only?

This might be overkill for just one field, but you could take a look at the Field Permissions module: https://www.drupal.org/project/field_permissions. This module allows you to set permissions on a per-field basis, so you can just remove all permissions for anonymous users for this field.


How to display a js popup saying "Loading..." after user saves a node?

You want it to display the instant they click the "Submit" button? The issue here is that, even if the "Loading..." popped up, the user would immediately see the page go white as the new page begins to load. It seems you're wanting to combat how page refreshes work, not Drupal.

That being said, to achieve the functionality that I think you're looking for you'd want to be opening the node create/edit form in a modal or something like that so it submits via an Ajax call and not a standard HTTP refresh. You can maybe use the Popups API module to do something like this: http://drupal.org/project/popups


D8 - Using Composer to download git repo

As per @igorw's answer

{
        "repositories": [
            {
                "url": "https://github.com/w8tcha/CKEditor-CodeMirror-Plugin/blob/master/composer.json",
                "type": "git"
            }
        ],
        "require": {
            "ckeditor-codemirror-plugin": "~1.17.2"
        }

}

Then type

  composer require "ckeditor-codemirror-plugin":"1.17.2"


Views Page Not Appearing in Search Results

To answer the first of two questions: Yes, this is the expected behavior. Views pages are not indexed by Drupal core search.

For the second, Drupal core search is limited. More is possible by using Apache Solr search integration.
According to https://www.drupal.org/node/2570521, https://www.drupal.org/project/apachesolr_nan is an example of a module that may do what you need. But you would need access to a Solr server.


How do I setup download links for pdf files directly?

Try the DownloadFile module. In your content type change the field display formatter to download file or whatever suits your need.


How to use custom class methods in the .theme preprocess functions?

The dependency injection coding standards only apply to most * classes.
In functions, use $service = \Drupal::service('service_name') to get the service.

To test code written in these functions, mock the services then build a custom container for them and assign it to Drupal using \Drupal::setContainer($container).

See Drupal\Tests\Core\Annotation\TranslationTest for an example of building a test container.

* Entity types, classes implementing TypedDataInterface, and certain plugins with custom plugin managers do not support dependency injection.


Try using the Field Permissions module and only allow admin to edit and view value for the entity reference field.


Margin before admin menu with Views admin pages

The admin_menu module adds a margin to the top of the page so it can sit there.  I suspect the toolbar module does the same thing which gives you the double margin.

Looking at your screenshot you're using 3 menu modules, which seems overkill to me.  Disable the toolbar module and you should be right.  The admin and admin_menu modules can happily coexist. You can also add custom items to either or both of these menus.

Personally I'd just go with the admin module.


How do I hide/remove a views menu tab from some pages?

There are two factors to consider when determining whether the tab is displayed:

The parent menu item
The result of the access callback

You probably cannot do much about the parent menu item, because this points to the generic node/%node.

You can, however, influence the result of the access callback by configuring how to validate the argument. This allows you for example to display the tab only for nodes of a certain content type. Of course you will have to configure the view to hide the view/display 404 if the argument does not validate.

A fancier validation would be possible if the validation configuration dialog would allow you to enter PHP code. I don't know if this is the case, so you might have to look for a different solution.


You probably need to override the valueValidate method to tell it about the new structure:
protected function valueValidate($form, FormStateInterface $form_state) {
  $uids = [];
  if ($values = $form_state->getValue(['options', 'value', 'existing_element'])) {
    foreach ($values as $value) {
      $uids[] = $value['target_id'];
    }
    sort($uids);
  }

  $checkbox_value = $form_state->getValue(['options', 'value', 'new_element']);
  // Do something with $checkbox_value here as you're going to lose it

  $form_state->setValue(['options', 'value'], $uids);
}


Custom module interfering with CSS on /user page

As it turns out, my custom module folder had the same name as my site's active theme. I believe this was causing the error. Renaming the module appears to have resolved the issue.


Admin custom module not displaying in theoverlay

There is Overlay Paths

  This is a simple module that enables site builders to use the built-in
  Overlay for non-admin pages.

Refer

Working with the overlay

https://drupal.stackexchange.com/a/8265/4471


Search boxes for individuals content types

Found an answer in the end if anyone else comes here searching for a solution. Turns out you could do what I wanted with the custom searech module I mentioned in my question. If you go into modules in the admin area there's also a custom search block module that comes with custom search that can be enabled. This gives you the ability to add as many blocks with different confiurations as you please. You then just go into blocks in structure and configure to your hearts content for each block then use those blocks where you want, job done! Just need to work out how to change the template now!


Google+ button for sharing an article (just like TweetMeme) available?

For modules that implement the Google+

Google Plus One
Social media
Easy Social


It's possible but very difficult to do.

You would have to alter to output of the image formatter to inject a theme suggestion on the image_formatter template (or create your own image formatter).

Then you would need to inject the suggestion from the formatter to the image theme function (could be done in a preprocess).

The issue is that altering the output would probably be something you would handle in each unique case, so you would basically need to create your own image formatter.

It's not a lot of work, but a bit tricky.

TL:DR;
Yes it's possible but you don't want to do that.


Adding fmath editor plugin to ckeditor through wysiwyg module

This started out as hacking it in, but things are always nicer in a module. The code is on my Github but if you just want the module it is hosted here for the moment. Full install instructions are similar to your link above and are including in the README for the module.

Basically, if you have the Wysiwyg CKEditor module installed already, you'll need to:

Install fMath plugin:
Download the plugin for CKEditor from the fMath site
and unzip the package.
Copy the folder fmath_formula to sites/all/libraries/ckeditor/plugins folder
Install the fMath WYSIWIG module (linked above):

Download and add the module to Drupal and activate it.
Enable the fMath button in the WYSIWYG profiles page for the wanted formats (e.g. Full HTML).

Now, the button on toolbar should be displayed. When you click the editor, it should show up.
You will not be able to save the image to the page until you complete the next steps.
Install the server side script to generate the images:

Go to www.fmath.info/editor/ and download editorPhpServerSide-vx.x-x.zip
Unzip the file.
Create on your server a folder "capture", it must be available from www.yourserver/capture
Copy the file imageCapture.php to this folder, it must have the permission to execute.

Create a folder img in capture folder (capture/img).
Edit the file imageCapture.php and change www.yourserver.com with your server url

Edit the file sites/all/libraries/ckeditor/plugins/fmath_formula/dialogs/configMathMLEditor.xml
to add or edit the property "urlGenerateImage" to
http://yourserver/capture/imageCapture.php
Test

Clear the cache of your browser (temporary files).
Create an equation and save.


How to parse a URL's content into a Drupal node

Yes, it is possible using hook_node_insert or hook_node_presave. You will just need to implement it like:

function hook_node_insert($node) {
  if ($node->type == 'CONTENT_TYPE_MACHINE_NAME') {
    // get the URL content here
  }
}

You can do it using the hook_node_presave too. The only difference is that it is called before even the node is saved into the database.


If you have static titles of submenus I suggest you to return using 'title' value in array.

I guess: set static titles and 'title callback' to false.


add field row number
and uses this field in style:
and set field to control


What would cause certain buttons to not appear on specific fields using the CKEditor?

Wow, I am really, really, blind. I missed an errant CSS style that was hiding a child elements of the CKEditor elements in question.


This looks like a git based patch, I believe that you with drush need to use generic patched, which with git can be created like this:

git diff --no-prefix > file.patch


Solution 1: Do It Yourself

Add taxonomy terms

Status (Open, In Progress, Pending, Resolved, Closed) ,
Priority
(Low, Normal, High)

Create content type Issue,

add fields title, body, status, priority.

Set roles

Allow anonymous users to create content Issue
Allow administrators to edit and delete content Issue

Extras:

Use Views for issue reporting

Use Workbench for managing issues

Use Workflow for setting issue management workflow

Solution 2: Use an external issue management solution

Comparison of issue-tracking systems

I prefer an external solution because of its independency I can still handle issues even if my site is down.


Prepopulate from link in content only visible to users tagged within that content

So here is how to do it.

Install and activate Entity Reference Prepopulate and enable it within the Entity Reference of Parents field in Child. You can now populate that field by  example.com/node/add/child?field_parents=[parent nid].
Install and activate Views PHP.
Create a new View without any pages or blocks called "Create new Child"
Click "+Add" and select "Content Pane"
Apply the following settings:

Filter critera

Content: Published (Yes)
Content: Type (= Parent)

Pane settings

Link to view: Yes
Argument input: From context>Node Content ID

Contextual filters (under advanced)

Content: Nid

Set Format - Show: Fields and then add a field - Global: PHP
In the configuration for Global: PHP, in the Output code section write:
<?php print 'nid . '">Create new child'; ?>. (N.B. You need title field/NID field added as well for the %data->nid to work, hide it if you wish)
Add a Global: PHP in "Filter Criteria" and add the following code

$uid = $GLOBALS["user"]->uid;
$node = node_load($data->nid);
$info = field_get_items('node',$node,'field_users');
$uids = array();
foreach($info as $user)
{
$uids[] = $user['target_id'];
}
return in_array($uid, $uids) ? FALSE : TRUE;
Save everything. In in Pages now, you can add this into Panels via "View Panes".


Problem with character encoding ( danish æ ø å ) when using page handler include files in hook_menu().

The problem was, as Andy pointed out, that the file wasn't encoded in UTF-8.

The .inc file was created from the context menu in Windows: 'New' -> 'Text Document', which defaults to the ANSI encoding.

The solution is simply to convert the file to UTF-8, that can be done for example in Sublime Text by choosing 'File' -> 'Reopen with Encoding'. Other text editors have similar commands.


How to assigned specific "comment" view mode for specific "node" view mode?

You could use hook_entity_view_mode_alter() to switch it on the fly.


Ideas on collecting payment before form submission?

Have you tried the Ubercart Webform Checkout Pane module?
You could define a simple product and use the webform as part of the checkout process.
Some more details about this module (from its project page):

This module allows you to define Webform nodes as checkout/order panes in Ubercart.
This is useful if you want to collect additional information during the checkout process. For example, you may want a quick survey or require additional fields that apply to the entire order.
Using the Webform module allows for many advantages: the forms/fields can easily be modified by an end-user; less development time is required to create database tables and code to store/retrieve the data; and the form will remember the user's previous answers.
Furthermore, this module now provides tokens for every field in each of your enabled webforms, making it easy for you to insert the submitted values into confirmation emails, invoices, etc.


User relationships. Override mysite.com/relationships page with views

I'm not sure if it's the best solution or the best practice. There is a low overhead, small module called Empty Page that strips the content from a page. Use that and then put blocks in regions. It's great for creating elaborate front pages too.


I found the answer to my own question.

In the view I added a field with the taxonomy term ID / node ID which is although used for my menu and hide the output and do a rewrite of the output.
I pasted the following code in the text field for rewrite; field_categorie-tid is my reference term from the menu.

menu_tree_set_path('menu-categorie', 'taxonomy/term/[field_categorie-tid]');

Instead of taxonomy/term/[field_categorie-tid] you can also use node/[nid].

I added in the head section a global field with PHP and token, and put <?php [field_categorie]?>.

That's all; no hooks nor custom scripting in the template.


Is it possible to only update one panel (or block) as a result of a the URL clicked elsewhere?

If you want your links to stay unaffected, you need to:

Attach onclick javascript event to all links. In it, send AJAX query to server.
On server side detect when links are clicked on page supporting dynamic loading (referer is a good start). Send HTTP 204 status code to prevent full page reload. Do not avoid it by returning false from event mentioned in point 1 - if you will, address bar will not match content.
In response to ajax query, server should return what IDs are supposed to get replaced, and with what.
Javascript on page needs to accept and process data from point 3.

Little explanation: HTTP 204 from server tells the browser that http request is legit, but no data from the server is needed. Normally when you want to alter url in browser window, at least part before #, browser reloads page. This is to prevent theft page from impersonating bank page and so on. So you need server-side solution to actually allow address change without reload - target server will not impersonate itself. Or if it will, it's his right to do so.


How to show terms in a Views in its hierarchical structure?

I would recommend that you give a try to Views Tree module which installs a tree-style (adjacency) Views style plugin which allows you to list vocabulary in a hierarchical way.

Comment: Views Preview does not show the tree layout but normal page display does output as a tree.


How do I create a "quick post" bookmarklet for use with Drupal 7?

Out of the box, Drupal 7 doesn't support form population from the URL. Just like Drupal 6. That's why the Prepopulate module exists. Prepopulate is about 100 LoC, porting it to Drupal 7 is probably the best option. The effort has been started, see issue #935990.


Owl Carousel does not respect Image Styles as set in node display in custom node file

Just to summarize my comments:
 1. after getting the images' URLs, you can run them by image_style_url() function to get the URLs to the styled images.
 2. you need to update the foreach() function to include an index such as foreach($image as $key=>$value), and use the $key index to loop through the image array.


Losing SSH access to Acquia Cloud: "permission denied (publickey)"

I haven't determined the root cause of this issue, but I found a functional solution:

When I get this issue, rather than in my IDE I ssh to AC via the Acquia Dev Desktop interface (clicking the small terminal icon next to the SSH address). This runs a specific SSH connection with several options:

ssh -p 22 -i "/Users/username/.ssh/acquia_key_name" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sitename.dev@server.devcloud.hosting.acquia.com

After this command is run (in my case in Mac Terminal), I can access the git repo again via my IDE.


Adding classes to individual list items in a site map

I prefer to use Menu Block blocks on a basic page for building a sitemap - it gives more control over the menu order, title display, etc. (unless, of course, you need the RSS feed icons in the sitemap - then the Sitemap module is more useful.) With Menu Block, you get a unique mlid class for each list item.


How to clean the html output of textfield using CKeditor?

I have run into this, I'm not sure if there is a configuration value to avoid this. I usually end up installing Empty Paragraph Killer.

  Empty paragraph killer is a filter module, helpful on sites which use
  WYSIWYG editors.

  People often hit the return key twice at the end of a paragraph. Most,
  if not all site layouts manage the paragraph spacing, so the extra
  empty paragraphs created can detract from the look and feel of a site.
  This module filters out the empty paragraphs of all user-entered data
  on a site. It does so by following the fundamental Drupal way -
  non-destructively.


How to show the webform submission page as pop up?

It is very difficult (but not impossible) to target a lightbox/modal when submitting a form because the posted database has to be sent to the server.

I recommend following the below ticket on Drupal.org which could help you solve your problem using Ajax.

Allow Webforms to be submitted using AJAX


Problems with extreme slow database queries in Drupal 7

When a server's I/O performance (especially its disk write performance) reaches its limit, it'll probably show first with cache queries because they're frequent and can contain some quite big chunks of serialized data.

I recommend you take a look at your disk I/O while you're waiting for a page to render, by using iotop for example.

The best way to prevent those I/O bottlenecks is to keep page requests from even reaching Drupal by putting a Varnish cache in front of the webserver. If they need to be answered by Drupal, though, at least take the cache load from the database by using Memcache.


That happens automatically, at least by default for themes inheriting from Classy. See https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21navigation%21menu.html.twig/8:

  {%
    set classes = [
      'menu-item',
      item.is_expanded ? 'menu-item--expanded',
      item.is_collapsed ? 'menu-item--collapsed',
      item.in_active_trail ? 'menu-item--active-trail',
    ]
  %}
  <li{{ item.attributes.addClass(classes) }}>

So, make sure you are inheriting from Classy (recommended) or duplicate some of this logic in your theme.


Show taxonomy term for administrators only in node creation form

If you like to hide the whole field, you probably are looking for the Field Permissions module:

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

If you like to hide certain terms only, you could use Views as reference method and filter your terms accordingly:

Create a new view for your taxonomy terms.
Create a Filter criteria "Term ID" to filter out all terms that shouldn't be available to non-privileged users, add a "Entity reference" display to that view and configure its Term name in the format settings.
Implement hook_views_query_alter() in a custom module and remove the filter criteria, if the users have the elevated roles:

mymodule.module:

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() != 'my_taxonomy_reference_view') {
    return;
  }

  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();

  if (in_array('USER_ROLE', $roles)) {
    unset($query->where[1]['conditions']['key_of_condition']);
  }
}

Head to your taxonomy term field settings and choose your view as reference type.

You might have to fiddle a little with the conditions, as the above example is just an outline for how you could do it. I actually didn't try it myself. But it should get you going.


breadcrumbs not displaying correctly for views

Okay so it still needs some work to be a little more generic but this basically handles the case. It checks to make sure that the content-type is not a node we check to see if there's an additional argument and append that to the breadcrumbs. if it is a node we just print out hte breadcrumb trail checking to make sure that we don't repeat things. If you use a page jump, fragments, or redirects you might get a repeat, i.e. home > stories > stories.  So here it is.

function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $lastCrumb = NULL;

    $output = '
' . t('You are here') . '
';

    $output .= '

';

  for ($i = 0; $i < count($breadcrumb); $i++) {
    $curCrumb = strip_tags($breadcrumb[$i]);
    if ($i == 0) {
      $output .= $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    } elseif (strpos($breadcrumb[$i], $lastCrumb) === false) {
      $output .= '

' . $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    }
  }

  if (arg(0) != 'node' ) {
    $output .= '

';
    $output .= arg(1);
  } elseif( $currentTitle ){
    $output .= '

';
    $output .= $currentTitle;
  }
  $output .= '

';

  return $output;
  }
}


Do we have another solution for the "After cloning a node" event for the Node clone module?

Try to think of a way to better describe what you're trying to do, and for which using that specific event does not work (because of that bug).

Obviously, it doesn't matter what the subsequent Rules Condition and/or Rules Action would be (after you have "an" alternative for that Rules Event you are asking about).

But sometimes the solution for a problem, is to avoid the problem from happening, right? E.g. maybe there is some specific path you could try to intercept (also using the Rules module), right before/after that event occurred. I seem to remember node clone also has such path. And if anything else fails, use Rules Event "Drupal is initializing", followed by a Rules Condition to check such path (if needed using RegEx also ... I bet you know about that Rules trick also).


Doesn't sound any different to displaying content as long as you can access the uid you have stored in 'filters'.

Set up a relationship from the data you wish to display to the person who created the data and then make a filter for 'author uid' (or similar) = 'current user uid'.  You will probably need to use tokens for the right side of that equation.


I am using the diff module, pulled that apart to find it is using:

if ($revision-&gt;hasTranslation($langcode) &amp;&amp; $revision->getTranslation($langcode)-&gt;isRevisionTranslationAffected())

modified my view to use the filter:

Content revision: Revision translation affected (= True)

The revisions pulled by the view now match the revisions shown on the node's revisions tab.


How to preprocess file before Feeds upload

The Feeds project page doesn't advertise it, but there is an API. If you look at feeds.api.php you can view all the hooks it makes available. A few of them take action before a feed item is processed or saved.


Try this:

$form['options']['description'] = array(
'#type'          => 'text_format',
'#title'         => t('Description'),
'#default_value' => theme_get_setting('description'),
'#format'        => 'filtered_html',
);

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#text_format


How should I use hook_field_extra_fields()?

This is a simple example showing how to add an additional field to the Field UI and provides an example of one way of inserting the field onto a node.

/**
 * Implements hook_field_extra_fields().
 */
function MODULE_field_extra_fields() {
  $extra['node']['article']['display']['extended_submitted_by'] = array(
    'label' => t('Extended Submitted By'),
    'description' => t('Provides Jumper Menu for Version Selection'),
    'weight' => 0,
  );
  return $extra;
}

/**
 * Implements hook_node_view().
 */
function MODULE_node_view($node, $view_mode, $langcode) {
  // Only add if the view mode is for a full view, although we
  // could control this via the Field UI too using 'hidden'.
  if ($view_mode == 'full' && $node->type == 'article') {
    $node->content['extended_submitted_by'] = array(
      '#markup' => '
This is inserted unless hidden in the field ui.
',
    );
  }
}


You can follow document

  You may notice the 'theme' key for css which is not present for js. This indicates the style type the css file belongs to.

  You can set CSS weights with 5 different levels of styling:

base key assigns a weight of CSS_BASE = -200
layout key assigns a weight of CSS_LAYOUT = -100
component key assigns a weight of CSS_COMPONENT = 0;
state key assigns a weight of CSS_STATE = 100
theme key assigns a weight of CSS_THEME = 200

  This is defined by the SMACSS standard. So here if you specify theme
  it means that the CSS file contains theme related styling which is
  pure look and feel. More info here. You cannot use other keys as these
  will cause strict warnings.

In your case you can use key theme

foundation:
  version: 6.x
  css:
    theme:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once


How to create a view type of Entity reference display?

Create a node view with the appropriate filters etc. you need to get the results you want to have in the reference field.

Then in the top left under the heading "Displays", Click "Add" and then select "Entity reference".

Then that display will be available to your field.

Edit: It doesn't have to be a node view, if you are referencing other entity types.


Can I create a keyword filter on emails sent from an email form with Rules?

Using hook_mail_alter https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7 you can check/change all mails before they are being sent.

Setting $message->send = FALSE; will stop the mail system from sending out the mail.


How to define a non-database relationship for the Views module

You can use the views php module. And you can get the $_SESSION['my_nids'] with in view. Actually you can do anything there that can be done with PHP.

Please note that this will again have a performance hit if the code is large. for simple things you go this route.


Drupal Panels can do this using the Views module. The two modules work very well together to arrange your content on a page, but Views is the workhorse for sorting through the content and selecting what you want.  Check out the video series "Taming the Beast" at Nodeone.se for how to use Views.  They also have a series on Panels/Page Manger that shows how to link them.


This is outdated. Should be fix by having proper configuration.


How do I download a form table in CSV or Excel format?

You can use the Forena module. Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

So if you'd install Forena in your site, then these are the steps for creating such CSV files are:

a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

For an online demo (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


After crash I can't access certain sections nor login to site

My fix was to re-install the database from a backup I did.  Not exactly a solution to the problem but it worked :)


Going from an installation profile to vanilla Drupal

Once a Drupal site is installed, it doesn't really matter which installation profile you used. The only difference is that it's possible to use modules and themes that are located in the profiles folder. So in that sense you are running vanilla Drupal.

If you want to disable the possibility to use the modules from the profile you need to, once you have added the modules to sites/all, set the installation profile to "standard". The easiest way to that is to use drush:

$ drush vset install_profile standard


I used jquery to do just that.

(function($) {

$(document).ready(function() {

// make the number field uneditable!
$('#edit-field-entry-custom-id-und-0-value').attr("disabled", "true");
});

}(jQuery));

to be safer however, in case someone disables javascript you could add this to your themes template.php

function YOURTHEME_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;

  // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
  // GET FORM ID UNCOMMENT BELOW
  // drupal_set_message("Form ID is : " . $form_id);
  // GET ALL FORM ELEMENTS UNCOMMENT BELOW
  // drupal_set_message(dprint_r($form, TRUE));
 }
}


Why node object loses data after using workbench_moderation_moderate?

The Problem was that workbench_moderation_moderate() calls internally hook_workbench_moderation_transition() so I decided to do it with another technique that should cover the two ways that workbench moderation uses to change the state

First way to be covered, the links that exist in workbench moderation back end views. I implemented hook_menu_alter to intercept the request from those links to add my custom logic.

function my_custom_logic($node, $state){
   //add your logic here
}

/**
* Implements hook_menu_alter()
*/
function workflow_handler_menu_alter(&$items){
  $items["node/%node/moderation/%/change-state/%"] = array(
    'page callback' => 'workflow_handler_moderate_callback',
    'title' => 'Change moderation state',
    'page arguments' => array(1, 5),
    'load arguments' => array(3),
    'access callback' => 'workflow_handler_moderate_access',
    'access arguments' => array(1, 5),
    'type' => MENU_CALLBACK,
  );
}

function ei_workflow_handler_moderate_access($node, $state){
  return _workbench_moderation_moderate_access($node, $state);
}

function workflow_handler_moderate_callback($node, $state){
  my_custom_logic($node, $state);
  workbench_moderation_moderate_callback($node, $state);
}

Second way to be handled, the form that workbench adds in every node details page. I implemented hook_form_alter to add my submit handler before workbench moderation one and I added my logic again there.

/**
* Implements hook_form_alter()
*/
function ei_workflow_handler_form_alter(&$form, &$form_state,$form_id){
    if($form_id == 'workbench_moderation_moderate_form'){
      $form['submit']['#submit'][] ='my_custom_logic_handler';
    }
}

function my_custom_logic_handler ($form, &$form_state) {
  my_custom_logic($form_state['values']['node'], $form_state['values']['state']);
}

Hopefully this helps anyone who encounter that issue in the future.


How to show a block on specific pages using the Node ID instead of an URL?

If you just want use the node id you can use node/[id].
Example: node/1

It will works even you are using a path alias, because that route is allways avaiable for any node.


Edit:

Your small edit changes this question more than you might think.

You have two ways to solve this.

1) Implement hook_node_type_insert() and create your field config there. You need to be aware of a few things, like config sync, so you need to check $node_type->isSyncing() before making any changes. Note that core stopped doing this for the body field. We do no longer add it automatically to all node types, only when one is created in the UI, as it had undesired side effects.

2) If you really want your field to always exist, no matter the node type, you can add it as a base field, which means it will work similar to the node title for example. See entity_schema_test_entity_base_field_info() for an example or see how content_translation now works which is also using this approach. Be aware that this changes how the schema for your field is then created, it will be part of the node_field_data table and you need to run update.php after installing your module to update the table.

Old answer:

The only hook that you could use for this is hook_install(), so that the field is created when the module is installed.

However, what you really want is to export them as default configuration of your module, I recently explained that in detail here: How to extend the basic user object upon installation?.

I'm going to actively ignore the second question because it has nothing to do with the first one. Create a separate question for that.


To overwrite Drupal defalut suggestion, You can make your own suggestion for template.

In your case you have defined a menu called asia for that specific template is required, to implement this use this code

 **
 * Implementation of hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$variables){
  if(isset($variables['asia']) && arg(1) == '')
    $variables['theme_hook_suggestions'][] = 'page__asiapage';
}

create a tpl file in theme called page--asiapage.tpl.php, it will work.


Using once with proper definition helped.

(function ($) {

    'use strict';

    Drupal.behaviors.totle_widget = {
        attach: function (context, settings) {

          // Using once() so script is loaded only once
          $('#totle-widget', context).once('totle_widget').each(function () {

            const config = {
                sourceAssetAddress: null,
                sourceAmountDecimal: null,
                destinationAssetAddress: null,
                destinationAmountDecimal: null,
                apiKey: null,
                partnerContractAddress: null,
              };
              const nodeId = 'totle-widget';
              !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();

          });
        }
      };

  }(jQuery));


Why doesn't drupal.org/download give a link to the Drupal 7 version?

Most likely because they don't want people to be confused by the two different versions and want to simply funnel folks to the latest D8 version.

Here's likely the easiest download link to share for D7 enthusiasts: https://www.drupal.org/project/drupal


Image path all 404 after move my remote site to localhost

If the RewriteBase Method is not working and every other page works, try to set the $base_url variable in your settings.php file to your folder.


How to recalculate uploaded files' sizes in KB and update the values in the database?

In Drupal 7 managed files have their filesize property updated upon saving in the file_save() function. So you can just load/save each resized files to have it updated in the DB accordingly.

//@TODO: Get list of $fids corresponding to resized-files
foreach ($fids as $fid) {
  $file = file_load($fid);
  // $file->filesize reflects old size
  file_save($file);
  // $file->filesize now reflects new size
}


drupal_render() takes it's first argument by reference. This'll fix it:

$the_form = drupal_get_form('sellTickets_form');
print drupal_render($the_form);


When does hook_node_access() get invoked for $op == "create"?

It gets called from _node_add_access(), which is the access callback for the node/add path (see node_menu()):

foreach ($types as $type) {
  if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
    return TRUE;
  }
}

node_access() has this line in it:

$access = module_invoke_all('node_access', $node, $op, $account);

Which is when hook_node_access() is actually invoked.

To answer your question, it's called before the node add form is ever displayed to a user; obviously if it returns FALSE then access is denied to the form.


If you can't list all the groups' paths (if there are too many) you can use an extra module Block Exclude Pages.

Although when it comes to Edit pages it's customary to use the Administration theme for editing content instead of the default theme. This way the blocks meant to be displayed to visitors wouldn't appear when creating/editing content.

You can change this at the bottom of the Appearance page: Use the administration theme when editing or creating content.

You could also use a lot more complex solution depending on your project needs, like Context or Panels that take over the Blocks layout configuration and allow for a lot more control.


How to remove  tags when printing out Menu

Sure, it's pretty easy. But first I think you need to know what's going on here.

Drupal's theme() call above is going to look for a theme_links__system_main_menu() function/hook and failing that, will look for a theme_links() function/hook.

theme_links() is in drupal core in includes/theme.inc if you want to take a look at it, as that's "who" is putting the ULs and LIs in there.  DONT just edit that file/function/hook, but create your own in your theme.  So, to take them out, or to put whatever you want in, you just write your own theme function to do it, and then theme() above will call it for you.

Drupal's theme layer is described well here:  http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7 and here: http://drupal.org/theme-guide/6-7 and should put you on the path to doing all that.


Assigning global var to session variable?

For assigning user_name to a session variable you would directly do something like

global $user;
$_SESSION['thelovelytest2'] = $user->name;

I think the issue with your code may be:

It is not able to retrieve the global $user variable.
You might not have defined the global $user variable.
Because you did $_SESSION['loveleytest'] = $user, thats why the issue is there.

I am also curious to know which was the exact issue.


Can I disable the #required form attribute temporarily?

This is most likely because of the ordering. THe module which is altering the form and setting the required element is being run after yours.

In the system table set your module weight to be higher than the module which is affecting the form.


If you want to render full node change the view settings as follows

In your view change the FORMAT settings as follows


Views : Output the field as link - not showing the field properties properly

Check this thread: https://www.drupal.org/node/1494860

Basically, upgrade to latest version of cTools and set the admin jQuery version to 1.5 via jquery_update.


Multilanguage in IE does not allow to switch languages

This answer is as simple as ticking a checkBox for the browser language, that for some reason in IE and Edge override the manual language switcher.
The reason that i didn't find this before was that it was in a tab far from view.


How to set value programmatically for mobile number module's field using entity wrappers?

To store a value with entity wrapper set() should be used. Please read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers

So your code $wrapper->field_phone = "0777123456"; would be $wrapper->field_phone->set('0777123456'); if the field structure required just a simple string.

However, according to the error message, it is not a string as it requires additional values for {field_phone_value} {field_phone_country} {field_phone_local_number} {field_phone_verified} {field_phone_tfa}.

So to make sure I would first figure out its structure. You could do so, for example, saving any value via UI and then outputting the value of respecting variable using dpm(). However, most probably its an array and you could give a try to:

$phone = array(
  'field_phone_value' => '0777123456',
  'field_phone_country' => 'US',
  'field_phone_local_number' => 'some value',
  'field_phone_verified' => 'some value',
  'field_phone_tfa' => 'some value'
);
$wrapper->field_phone->set($phone);


Two Body/text areas for a multilingual site

Edit the content type that you are using or create a new one and add another field to it.


Superfish module seems to "Ignore" it's very own library

Download the Superfish library and extract it to sites/all/libraries/superfish (so that the superfish.js will be located at http://example.com/sites/all/libraries/superfish/superfish.js)

Also check if the permissions on the .js files are correct. Status report pages (admin/reports/status) may also be of help.


D6: Create block view which returns all nodes with related terms

You probably have to do the follwing:

create a view
add a block to that view
add a contextual filter (in Drupal 6 it is an Argument)
configure it with:

Action to take if argument is not present: Provide default argument
Default argument type: Node ID from URL
Validator: taxonomy term
You can use Term ID from the URL, or try to use the term name.

Then you have to save and configure the block to show on the desired page...

These settings in Drupal 7 (more or less, there are some slight differences in interface) work for me...


hook_permission and control access [how to redirect to the login page if user not logged in]

Easiest way will be specifying this logic in page callback function. example:

function SOME_PAGE_CALLBACK($someArg) {
  if(user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }

  // do_something();
}

another way is checking the user in hook_preprocess_page function:

function MY_THEME_preprocess_page(&$variables) {
  if(curent_path() == 'SOME_PATH' && user_is_anonymous()) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}

Access callback function checks the user's access to the request and returns boolean value, TRUE or FALSE, if you want to check if the user has an access to the page, you can do somthing like this:

$path = current_path();
if ($router_item = menu_get_item($path)) {
  if (!$router_item['access']) {
    drupal_goto('PATH_TO_LOGIN_PAGE');
  }
}


As comment said above, you have to implement Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface. Here is a working snippet that I use to implement those Breadcrumbs :

It appends a custom routename to all 'Nodes' pages :

<?php

namespace Drupal\Your_Module_Namespace\Breadcrumb;

use Drupal;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;

class Your_Module_NamespaceBreadCrumbBuilder implements BreadcrumbBuilderInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $attributes) {
    $parameters = $attributes->getParameters()->all();
    // I need my breadcrumbs for a few node types ONLY,
    // so it should be applied on node page ONLY.
    if (isset($parameters['node']) && !empty($parameters['node'])) {
      return TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

    $node = Drupal::routeMatch()->getParameter('node');
    $node_type = $node->bundle();

    // Put the needed logic here

    // addLink example
    $breadcrumb->addLink(Link::createFromRoute('My Page Name', 'drupal_internal.routename'));
    $breadcrumb->addCacheContexts(['route']);

    return $breadcrumb;
  }
}


Change module's description from another module

You can alter a module's information through hook_system_info_alter(). For example to change the description of the Views module:

function MYMODULE_system_info_alter(&$info, $file, $type) {
  $info['views']['description'] = 'Something else';
}


User registration form: Give username "username n+1" value, if and when n is already used

So here is what I used to increment the username's suffix by 1 if the initial value is not found:

function increment_string($str, $separator, $first = 1) {
    preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
    return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}

$username = $firstname . ' ' . $lastname;
$result = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $username));
$results_number = $result->rowCount();
    if ($results_number == 0) {
        $form_state['values']['name'] = $username;
    }
    else {
    while ($results_number >= 1) {
        $username = increment_string($username_to_store, ' ');
        $result = db_query('SELECT uid FROM {users} WHERE name LIKE :name_pattern', array(':name_pattern' => db_like($username)));
        $results_number = $result->rowCount();
    }
    $form_state['values']['name'] = $username;
    }


Should I change multiple text fields values via MySQL or is there any other preferable way?

The Drupal way is to iterate over the nodes of interest and modify the fields. Here is a simple example that shows how you could make modifications in the Body field of the Article content type:

  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      node_save($node);
    }
  }

One thing to note about doing it this way is the last-modified time of all your nodes will be updated. You may or may not want this. If you want to update the nodes without changing the timestamp, use this instead:

  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      unset($node->created);
      unset($node->updated);
      field_attach_update('node', $node);
    }
  }

Edit: How to modify taxonomy terms

You could use the same approach to modify taxonomy terms, i.e. load the terms, iterate over them, and do a find/replace on each.

  $vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));

  foreach ($terms as $term) {
    $text = $term->name;
    $find = 'ABCD';
    $replace = 'WXYZ';
    $text = str_replace($find, $replace, $text);
    $term->name = $text;
    taxonomy_term_save($term);
  }

Depending on how expert you are with MySQL, you could try updating the database field directly and you might have success, but it's prone to error especially if your fields have revisions.


How to use two pages of a View with the same path depending on users's profile?

In Drupal 7 this was quite easy to implement just using Views. In D8 I couldn't manage to implement it only with Views.

You can create a panel page with two different variants. Place the relevant block in each variant and control the accessibility though the 'Page access'. (I used roles but you can even create your custom condition)


You should not use a direct MySQL query to update anything.

In this case you can use user_save(); which it is basically, load the user object -> change data -> pass it to user_save(); or even better user entityAPI and entity_metadata_wrappers

The default table where drupal saves user data is users, there you can find the email and username


As per my knowledge you need to do little customization to achieve this.

Check the roles
Perform your require action(permission)

code to check logged in user has both roles?

global $user;
$roleA = 'administrator';
$roleB = 'user1';
$roleC = 'some other role';
$user_roles = array_values($user->roles);

    if (in_array($roleA, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleA, $user_roles) && in_array($roleB, $user_roles)) {
      // Do something.
    }
    elseif (in_array($roleB, $user_roles) && in_array($roleC, $user_roles)) {
      // Do something.
    }

Second option.

You can look Rules module.


Validation error on back button in Multistep Form

Enable devel module. Then put a dpm to make sure that your code is being called.

function mymodule_form_alter(&$form, &$form_state, $form_id){   if($form_id=='dataset_node_form')
{
 dpm($form, 'From my custom module');
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

If your message shows up then some other module is overriding your form_alter. You can implement hook_module_implements_alter in your custom module to make sure that the form_alter of your module is called last.


Losing superfish menu item after logging out from administration panel

When an item in a menu tree is unavailable because of a lack of permissions, the entire tree below that item will disappear.

You should probably restructure your menu to use placeholders. Have a look at the Special menu items module.


Want to add tabs from /user/* pages to other pages

You can use Tab Tamer module to arrange tabs at your user/% location or some where else too. You can change orders or enable/disable as per your requirement.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully
  when javascript is disabled.


Try it without the $query->execute(); as according to the docs for db_query the function already executes the query and returns a result.

Try this:

$args = array(':entities' => $_REQUEST['entities'], ':countries'=>$_REQUEST['countries']);
$result = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid", $args);

I would say the error is from trying to execute a result.


Is there any way to set line item status in an order?

You can try using Commerce Delivery module... It supports line items delivery status..

Project page says

  Provides basic functionalities and admin pages to handle deliveries.

  Each delivery need to be associated to an order. Each order can have
  zero, one or multiple deliveries.

  A delivery is automatically created on order save if it contains at
  least one shippable item. Further deliveries can be manually added
  from the deliveries tab under the orders menu. On the same page each
  order line item can be moved from one delivery to the other.


You just need to decode the string with urldecode():

$query_string = urldecode($_SERVER['QUERY_STRING']);


Flag count is incrementing only after page reload

I had the same problem, and find how to solve it. The Views Flag Refresh module is only available for Drupal 7, but someone ported it to work on Drupal 8, here is the download link.
I find it in this issue comment by WalkingDexter.
In my case I need it to work on Drupal 9, so it is necessary to change a line in a file in the downloaded custom module as Akash_Daimari explains in this comment.
The module would go in /modules/custom/
In the view you have to use Ajax and add the flag in 'Flag refresh' options.
As a note, in the View preview the count does not update, but on the page it does.


No Emails sent on User Creation in D8 through Rest API

I've tested this and it seems like _user_mail_notify just isn't working currently in 8.2.4, however I did find a workaround using the hook_ENTITY_TYPE_insert() still, but using hook_mail and MailManager also.

/**
 * Implements hook_mail().
 */
function custom_rules_mail($key, &$message, $params) {
$options = array(
    'langcode' => $message['langcode'],
);
 switch ($key) {

   case 'create_user':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('Welcome to the site!', $options);
     $message['body'][] = $params['message'];
     break;
 }
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 * When a new user is created, do things.
 */
function custom_rules_user_insert(Drupal\Core\Entity\EntityInterface $entity)
{
  global $user;

//  _user_mail_notify('register_no_approval_required', $entity);

  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'custom_rules';
  $key = 'create_user';
  $to = $entity->getEmail();
  $params['message'] = "Welcome to our site! \r\nYour username is " . $entity->getUsername() . " " . "\r\nIf you would like to reset your password, you can at the following link: \r\n" . user_pass_reset_url($entity);
  $langcode = $entity->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] !== true) {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }
  else {
    drupal_set_message(t('Your message has been sent.'));
  }

}

The way I have this set up works. When a user is created (through drupal GUI or REST API), they are sent a welcome email that also includes a link to reset their password. To do this, you use the user_pass_reset_url function that is defined here. MailManager was pretty simple to use and figure out.

I followed this blog to figure out how to do this.


What is the latest drush version and how do I install it?

drush dl was never supposed to be used to download Drush. It happens to work because Drush is hosted on drupal.org as module, but the latest development are done on github.com. On drupal.org, you find just old versions, dated 2013.

As per July 17, 2016, the latest version is 8.1.2. You can install it using Composer, if you are using any Linux OS, or OS X, and in this case it is easy as running the following command:

composer global require drush/drush:~8

Don't forget to add ~/.composer/vendor/bin to your shell PATH variable, or the shell will not find Drush's executable.


How to create report to list users who change only specific field?

Part 1 - Intercept these cases from now on

If you're willing to also consider using the Rules and Flag module, then it'll be a peace of cake to use Views for creating the view you're looking for. Below are the main steps to do so ...

Step 1: Create a flag to prepare for reporting such users

Using the Flag, create a non-global flag that will be used to get the users flagged that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value).

Step 2: Use Rules to flag such users

Using the Rules module, create a rule to "automatically flag users" that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value). Here are the specs of such rule:

Rules Event: after updating content (of type = ticket)
Rules Condition: only the field "Ticket Escalation Date" was changed from empty to some value (this will need some refinements from your part to actually specify such condition, refer to (*) for some guidance on this).
Rules Action: flag such user (with the flag from step 1). But make sure to use the userid of the updater, which may be different from the node author ... Probably you want to use "current user".

(*): Some more details on those Rules Conditions (ALL conditions must apply):

Add an "entity has field" (with field = Ticket Escalation Date), to make that field available in your rule. If such field (machine name) is only used for "tickets", then there is no need in the Rules event to refine with the "(of type = ticket)".
BEFORE saving the content (= value before the edit started) "Ticket Escalation Date" is blank.
AFTER saving the content (= value after the edits will have been saved) "Ticket Escalation Date" is NOT blank.
"Ticket Status" is unchanged (value BEFORE saving is equal to value AFTER saving).
"Ticket Resolved Date" is unchanged (value BEFORE saving is equal to value AFTER saving).

Step 3: Create your view

Using the Views module, create a view of "users", which were "flagged" with the flag from Step 1.

Part 2 - Report about similar cases in the past

What is explained in Part 1 can be used as a solution if it was put in place from the beginning (when the site was launched), or to intercept these cases from now on. For existing sites, you could "report" about similar cases using a custom SQL query (based on the current design and content of your Drupal tables), combined with using the Forena module (disclosure: I'm a co-maintainer of it). This module comes with quite some Community documentation. Here is a summary of this module:

  Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

  Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

  Visit the Forena HowTos page for some links (near the bottom) to some , and there is a live demo site of it.

Assume you have a query which looks like so (as in your comment to this answer):

  SELECT r.title, u.name
FROM field_revision_field_expedite_date re, node_revision r, users u
WHERE r.nid=re.entity_id and r.vid=re.revision_id and u.uid=r.uid
GROUP BY re.entity_id
HAVING min(revision_id)

It'd be straight forward to transform the query results of this SQL in a report (and/or even chart if you'd want ...). Refer to the example in my answer to "How to retrieve data directly from a Drupal database" to get an idea of what it is like to use Forena, such as the SQL query and the source of the "custom report" there.

PS: not sure what you'd want to "do" with such list (created as explained in "Part 1"), but if at some point you want to reset/re-init such list, you could do so easily using the VBO module also (= unset the flag for all users in my View).


Best using of any of below module to solve your query. I think as per your query, no any module for 1-10 rating. Hope these module help you to do same as you want.

Star Rating

  Star Rating is a simple module that provides star rating field and
  display formatter using Drupal 7's Field Type API.

Rate

  This module provides flexible voting widgets for nodes and comments.

Fivestar

  The Fivestar voting module adds a clean, attractive voting widget to
  nodes and comments and any entity.


How do I add a custom image in a block (unique for every page)?

Figured it out.  See this link for the answer.


Reset frontpage after changing it to user

That's a pickle. This should get you out of it:

drush vset site_frontpage node

Or if you don't have access to drush (why would you use drupal without drush?) you can run this sql:

DELETE FROM variable WHERE name = 'site_frontpage'


If you want to use the extended register form class, you need to put it in the place of the original form class in the user entity type:

mymodule.module

  /**
   * Implements hook_entity_type_alter().
   */
  function mymodule_entity_type_alter(array &$entity_types) {
    $entity_types['user']->setFormClass('register', 'Drupal\mymodule\MyRegisterForm');
  }


From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests using the l() function to have Drupal use "pretty paths" automatically.

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.


What are some specific reasons NOT to share a users database table between sites?

Almost any problem you see will be similar to content cache problems on a Drupal site.

The database represents your site's canonical state. Sharing a user table between 2 different sites means canonical user data reads/write can become invalid without each site knowing it, since they aren't coordinating their actions.

For example, Site A is doing a bulk operation (e.g. add Role X to all selected users) on users. It loads all users from a DB query into memory, changes a property on each user object, then executes a save to the DB. Meanwhile, Site B has a user who wants to update his email. He visits his user page, updates his email only to see it change back a few minutes later because Site A, still working through its bulk operation, has an old version of the user account and saved it after he updated his email.

Depending on the size of your site, just like with content caching, this invalid state problem might never show up. If Site A & B represent 2 different sub-sections (e.g. a blog site & commerce site) with users seldom using both, the scenario where the user state becoming invalid might never happen. But as your site grows (i.e. the number of user DB transactions) this invalid state problem will likely show up eventually.


You might be able to get the result you want using the Views Aggregator Plus contrib module.

It's still in alpha for Drupal 8, but it allows you to group and aggregate results.


In drupal 7, for field widget type, what is "server side" used for?

I can't find any reference on Google to a widget that provides this type of functionality so I can only assume it's something custom, but I think the reasoning for it would be the same regardless:

When using the Drupal form API you can add an element of type value which keeps that element server-side only...i.e. the value is available to the form submission/validation functions but it not exposed to the user. A hidden field would still be exposed in the form's HTML so could theoretically be changed by the user before the form is submitted.

I would guess in this case it applies to the node edit form, each node would essentially have a non-editable field with a constant value. I'm not actually sure how useful this would be in normal life but I guess if every node had to have, for example, a geo-location map associated with it, and the value of that location field had to remain constant, this would do it. The same map would just be outputted on each node.

To be honest that could all be nonsense though, it's just an educated guess :)


Is there any way to validate taxonomy terms?

there are these lines in shs.module:

$callbacks = array(
    'shs_json_term_get_children' => array(
      'callback' => 'shs_json_term_get_children',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_array',
        'settings' => 'is_array',
      ),
    ),
    'shs_json_term_add' => array(
      'callback' => 'shs_json_term_add',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_numeric',
        'name' => 'is_string',
      ),
    ),
  );
// Let other modules add some more callbacks and alter the existing. (!)
drupal_alter('shs_json_callbacks', $callbacks);

I think we can do something like this:

function MY_MODULE_json_callbacks(&$callbacks) {
  $callbacks['shs_json_term_add']['callback'] = 'CUSTOM_CALLBACK';
}

function CUSTOM_CALLBACK($vid, $parent, $term_name) {
  if(!NEW_CONDITIONS) {
    return FALSE;
  }

  return shs_json_term_add($vid, $parent, $term_name);
}


if this module does not respect the order, try to make a view and use its block. see here: https://stackoverflow.com/questions/3806028/drupal-taxonomy-block-vocabulary-listing


Create a view to display all nodes referencing this content

I've found my mistake :

In Relationship, I have to select the entity reference field used in Recipe.
In contextual, I select NID as usual but I have to use the Relationship I've just created. Then I select Provide default value (ID from url).

I don't need to use this relationship in the Fields I add.


How to write a CCK widget with more than one input element?

I built something like that for drupal 7. Considering CCK moved into the drupal core in d7, I'm not really sure how much different the code would be for a cck module in d6, but maybe this module will help you

I wrote this module as I had to somehow capture phone numbers, but have them split into country code / area code and number and save them into seperate columns in the database. All other field modules I tried did not allow for this!

That way all numbers can be entered uniformly and thus presented in a uniform way - especially helpful if you use it to store and manage customer information and possibly need to export it to different applications.
In my case, some users would enter phone numbers with a dash, other with a slash and others again with nothing seperating values making managing them difficult and displaying them messy.

Rip the code apart and modify it to suit your needs (like only 2 fields):

It's in my sandbox: http://drupal.org/sandbox/tecjam/1320886

in Git: http://drupalcode.org/sandbox/tecjam/1320886.git/tree/e7c97511506ee6e92a44656aa02d31f4e8f69727

I like to comment my code to help myself (sometimes there are more comments than code lol). So figuring out what does what and where should not be a problem at all.

You can always ask if you have any special questions.


Webform module have time field by default.


You should never edit core or contributed modules if it can be helped (which it almost always can).  I haven't used Feedback, but the general Drupal way of extending forms is to use hook_form_alter from your own custom module.

Basically create a simple module.  All it needs is a mymodule.info file and a mymodule.php file inside of a folder in /sites/all/modules. Here is some more info on creating a module.

Then in your mymodule.php file, add a function that looks something like this:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FEEDBACK_MODULE_FORMID') {
    $form['custom_email'] = array(
      '#type' => 'textfield',
      '#title' => 'Email',
      '#required' => TRUE,
    );

    $form['#submit'][] = '_mymodule_feedback_form_submit';
  }
}

This will add a new field to the form, and register a submit callback for the form.

Finally write the _mymodule_feedback_form_submit function to actually do something with the value when the form is submitted.


How to trigger/run/execute scheduled task manually?

This is how i do it, I use flags module, i create a user flag for each  "run manualy my special rule" assigning flag/unflag access only to admin user and i display link on user profile page, flagging or unflagging myself to trigger my special rule, then, most of the time i use views rules module to load content, products, orders or users and perform any kind of stuff with it.


To convert date format in Views, you have to go the settings field which you are added to view. In settings, there is a Date Format select list field. You can choose the default time format provided or you can make your  custom date format by selecting the Custom from select list. A new textfield will appear "Custom Date Format". In this field, you can make your own custom date format using the link PHP Manual link provide in the description of this field.


Jquery Validation & number field with comma

Browser support may vary, but essentially you want to add an attribute of step="any":

$form['poidsMin'] = array(
    '#type' => 'number',
    '#title' => $this->t('Poids minimum en gramme'),
    '#default_value' => $frais_port_entity->get('poidsMin'),
    '#description' => $this->t("Poids minimum du produit"),
    '#required' => TRUE,
    '#attributes' => ['step' => 'any'],
);


Instead of calling directly the view you call a rules link.

The rules link is calling the view with the desisered parameters for the view. In this case the filter can be used as a contextuel filter.

No programming needed.


Check with the styles/css hiding the administrator menu.
style-src is script-src’s counterpart for stylesheets.


Override user register default URL to set up password

I think no need to override the default register url.

To prevent Anonymous from register users, Just go Administration >> Configuration  People http://example.com/admin/config/people/accounts.
and check Administrators only in REGISTRATION AND CANCELLATION fieldset like the following:

If you have another raison to change the default url follow this tutorial just change route name from user.login to user.register.


Search inside the view, if not found, how to set up no results behaviour?

Please set this at the field level or at the right corner at the views edit.

No Result Behaviour. If you want to set this with all the views than select All display at field level.