Rules to create an autoresponder for a Webform submission?

You do have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So in your case, you should be able to get it to work using something like [data:email-id] (assuming that's what corresponds to the "email field" in your case).

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= "When the form is submitted the rule should fetch the 'email account' entered in the email form field", as in your question).
However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:EmailAccountField-value-raw] (and with an appropriate data type). I'm assuming your eMail field in your webform has a machine name like EmailAccountField (adapt to fit your machine name).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

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


How to assign certain themes to certain to Content Types?

I know you said that you don't want to use a module, but ThemeKey does exactly what you need. There is no Drupal core functionality that provides this functionality.


How can I use Views to create a page with 3 Content Types, grouped by type, limited to x number of each type?

Here's a solution using only the Views UI.

Create a view with the following master settings: display 3 items, sort post date descending with the node tile included in your fields. Probably as you have it already.
Add a page or block display with type == News articles. This will be your parent view display. Again, you might have this already, but your type filter may need to be adjusted. We just want 3 news articles here.
Add an attachment display with title as Events and update type == events. Attach this to your parent view display above.
Add another attachment display with title as Press Releases and update type == press releases. Attach this to the parent view in the second bullet point above.

You can find the attachment to setting in the second center column on the views ui, assuming this Drupal 7.

Jason.


How to generate pdf file from a specific type of content?

You can achieve this functionality with print module. For documentation click here.
This module depends on the libraries you can install any of them.
1. dompdf
2. mPDF
3. TCPDF(Best in performance)
4. wkhtmltopdf


No, you can't change the base class. This is a PHP language construct, it's not possible to override it.

I'm not exactly sure what you are trying to do but it is likely that what you are looking for is a plain old hook_form_alter() + third party settings on the block config entity.

The Block class D8 sandbox is a simple module that is doing exactly this and allows to configurabe custom CSS classes for every block.

Note that this is on a different level, you are altering the block config entity and it will only apply to how Drupal core/block.module uses block plugins but not e.g. page_manager. Doing it in a more generic way is simply not possible.


How to change a collection field value with presave

This code worked for me need to add  in presave hook
//field collection field
  $item = $entity->get('field_items')->value;

$fc = FieldCollectionItem::load($item);

foreach ($fc as $fckey => $field) {
    if ($fckey == 'field_name') {
      $value = $field->getValue();
      $value = strip_tags($value[0]['value']);
      $summary_value = $entity->get('field_fc_child')->value;
      $entity->set('field_fc_child', $value);
    }
  }


How to create a new custom content type record when a user registers

Since you are deeply in your project I see two possibilities right now:

Site builder

Add all the required fields to your user profile, and use something like complete_profile to force completion. Maybe profile2 might help as well. Once you gathered a complete profile use rules to create a node of the content type you strive to create. Upon creation, you might want to drop the profile field contents etc., I think profil2 might be the better solution, so you don't have the to use drupals core profile, and can drop that filled profile once you don't need it, or even disallow changes after creation / hide fields of it etc.

Developer

try to get the node fields of the node add form for your specific content type and merge them with the registration form.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
     dpm($form);
     module_load_include('inc', 'node', 'node.pages');
     $node_form = node_add('nodetype');
     // $output = drupal_render($form);

     // this copying probably has to be done in a better way, e.g. by only the fields you need.
     $form['node'] = $node_form;

     // register a submit handler, so you can create the node/ do validation whatsoever
     $form['#validate'][] = 'mymodule_user_register_validate';
     $form['#submit'][] = 'mymodule_user_register_create_node';
   }
}

If your node form has a file upload widget, you should add the following lines to the menu array:

'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

submit handler:

There are probably better ways to do this, e.g. reuse the existing node submit handler, instead of mimicking it's behavior.

// validation option 1: do it manually
function mymodule_user_register_validate($form, &$form_state) {
  // Extract the submitted data
  $name = $form_state['values']['node_title'];
  // Check it according to your own logic
  $is_valid_name = your_check_for_valid_name();
  // File error, when not valid
  if (!$is_valid) {
    form_set_error('name', t('Name already taken, please choose a different one'));
  }
}

// validation option2: forward it to node_submit
// this way you will have to mock a node object before though.
// node_validate($node, $form, &$form_state);

function mymodule_user_register_create_node($form, &$form_state) {
  $node = new stdClass();
  $node->type = 'nodetype';
  $node->title = $form_state['values']['node']['title'];
  $node->language = LANGUAGE_NONE;
  $node->uid = 0; // you probably have to somehow find out the created uid from the registration and link this here
  node_object_prepare($node);
  $node->field_something[LANG_NONE][0]['value'] = $form_state['values']['node']['sometextfield'];
  node_save($node);
}

This code is far from being ready to use (I just drafted it straight from my head, you will have to dpm() some values and see how it fits together, but the logic/ workflow is there.

extra:
look at how entity_form_submit_build_entity(); is used to see how core get's the form, form state values and creates an entity with the given input, instead of doing this by hand. Be aware that at that stage you probably have to make sure that everything required is available, which might be harder than doing that stuff in custom code in the first place.

extra2:
to link this created node with the user created, you might want to put the created node id in global space and retrieve it in a hook that is called after user save.

  // mymodule_user_register_create_node() ...
  node_save($node);
  $GLOBALS['user_register_linked_nid'] = $node->nid;
  // ...

  function mymodule_user_insert(&$edit, $account, $category) {
    //maybe the submitted values are in $edit as well, than we dont have to do the node creation stuff in the user submit handler and we could do it here.
    // else you can still fetch the global variable
    if (isset($GLOBALS['user_register_linked_nid'])) {
    $account['field_node_reference'][LANG_NONE][0]['target_id'] = GLOBALS['user_register_linked_nid'];
    field_attach_insert('user', $account);
    }
  }


Unable to use a hyphen in a Drupal 7 text field

The zoom behavior of the map is responsible for this unwanted behavior.
You need to disable keyboard controls on the map in your node edit form.
This could be the default map or the default map installed by geofield.


Allow users to set permissions for profile fields

Without information on what version of Drupal you are using or what you are using for profiles, here is a suggestion for each type of profile on Drupal 6:

Using the core profile module, check out Profile Privacy

Using Content Profile, take a look at CCK Privacy


Fivestar: How to display description text inline

It's doable with CSS. You need to declare the parent of the description and the stars as flex or inline-flex or -webkit-inline-box: .field-type-fivestar .form-item { display: -webkit-inline-box; }


Getting the display value for a form option with webform 3.x while processing submissions

I've run into the same issue, could not find a predefined function and ended up writing one that loops over the select options in the text area and returns an associative array.

The basic principle is described in this article:
http://blog.raisedeyebrow.com/2009/01/displaying-webform-results-in-a-block/

For my project I used the webform_submission_insert hook instead of form_alter, but I hope it works for the variables that you have available in form_alter as well.

If it is likely that you'll need this feature more often you may want to use a function to extract the data for any textarea using the same principle.

function mymodule_webform_submission_insert($node, $submission) {

   switch ($node->title) {

    case "Test form":

    $options = array();

    // fill options field with options from select textarea via custom function;
    // field number of my particular webform select field is 12, hence:
    $options = _extract_select_options ($node->webform['components'][12]['extra']['items']);

    // output key and value of chosen select option
    $chosen = $options[$submission->data[12]['value'][0]]);
    drupal_set_message ("key / value: ".$submission->data[12]['value'][0]." / ".$chosen;

    break;
   }
}

// declare function with text area content as parameter
function _extract_select_options ($mytext) {

    $options = $pairs = $temp_array = array();

    // split text into chunks after each line-break;
    // if not visible here, use "backslash n" as explode parameter
    $pairs = explode("\n", $mytext);

    // split each line into pairs of key and value
    foreach($pairs as $pair) {
      $temp_array = explode('|', $pair);
      $options[trim($temp_array[0])] = $temp_array[1];
    }

    return $options;

}


Is Drupal following W3C standards? How to change the DOCTYPE?

This would completely depend on the theme you are using on the Drupal site, as the markup of the site is handled on the theme layer.
If you are using an HTML5 theme, then the it will show the appropriate DOCTYPE i.e. <!DOCTYPE html>. In short, your theme should support HTML5 in order to get the DOCTYPE.

To answer your question, you'll need to either make your theme compatible to HTML5, or use any other HTML5 theme.
There is a very good article for Converting Your Drupal 7 Theme Into HTML5 which could give you a good start.


Change mark-up with a textfield using Ajax

I could make what I was trying to do:

<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '
';
$form['submitted']['saldo']['#suffix'] = '
';
$form['submitted']['saldo']['#value'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>


You need to mimics the user's behaviour.

You need to submit individually each form in multiple steps.

You must write correctly the field names (look for input names in the DOM with Firebug or Developer Tools)

  $edit = array();
  $edit['title'] = 'Sample webform';
  $edit["body[$langcode][0][value]"] = $this->randomName();
  $this->drupalPost('node/add/webform', $edit, t('Save'));

then submit the fields individually:

  $edit = array();
  $edit['add[name]'] = 'Sample webform';
  $edit['add[type]'] = 'textfield';//or whatever, optional
  $this->drupalPost('node/webforms/components', $edit, t('Add'));

Rinse and repeat.

You can create a custom function to perform that.


template suggestion not working (page--front.tpl.php) in windows 7 env

I've seen this happen when there is another page--front.tpl.php lurking around in your directory structure and it is being picked up and used instead of the one you are looking at.  And, if that one is a copy of page.tpl.php, it will appear that it isn't being picked up. So, I'd look around and make sure you don't have one anywhere in your theme directory as Drupal will recurse through the entire tree looking for templates.  Another edge case is permissions so make sure it is readable to the world.  If all else fails, strangling the pc with the mouse brings some level of relief and entertainment :)


appened custom text to content in template_preprocess_taxonomy_term drupal 8

Ok, so here is how I did it.

function cars_theme_preprocess_taxonomy_term(&$variables) {
      if($variables['view_mode'] == 'full'){
         $variables['cars_view'] = "this is test";
     }
}

And then in my twig file I output the cars_view as {{ cars_view }}


Attach js file to every page w/term reference widget in Drupal 8

'#attached' works for any element. You should have an element in scope in that alter hook. Also you should have a mymodule.libraries.yml to declare your script.


How to return [error] in a rest api build with view?

If you are using Views, I would add a "no results behavior" that outputs the error message of your choice.


How to auto submit only after typing at least three character in view exposed filter

Attach custom_form_validate for that form using
form_alter
Do what ever you want in this custom_validation.
Reference


How do I redirect a node to a path followed by a wildcard?

A view with a page display instead of the block display would generate the route automatically.


Probable database character encoding error with chinese multilingual translation

Ok So the problem was actually not the Chinese text but that I was copy-pasting from a PDF file that seemed to have injected some unwanted characters in the body that the database was rejecting.


How can we check whether block is enabled or disabled in .theme file?

Use ConfigEntityBase::status:

if (isset($lang_block) && $lang_block->status()) {
  // block is enabled
}


Can't find cookie for validation in EventSubscriber

Some ideas:

Like for the config you have to add a cache dependency for the cookie, too:

  $response->getCacheableMetadata()->addCacheContexts(['cookies:' . $config_cookie]);

Or use an uncacheable RedirectResponse to simplify things.

And try to set a priority for the event subscriber, for example 31, because your code depends only on routing, which has 32:

  $events[KernelEvents::REQUEST][] = ['modifyIntercept', 31];

You don't need to get a response in an request subscriber, because there isn't one yet. Get the request instead and make sure that you are in a master request. So this would be how the subscriber starts most times:

  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    $request = $event->getRequest();
    ...

Simplifying a bit more and using dummy values for testing:

  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    $route_match = \Drupal::routeMatch();
    if (!$route_match->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($route_match->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if (!$request->cookies->has('foo')) {
        $redirect = new RedirectResponse($request->getBasePath() . '/node/2', 302);
        $redirect->headers->setCookie(new Cookie('foo', '123', '+30 seconds'));
        $event->setResponse($redirect);
      }
    }
  }

This is working on my local dev environment.

Complete code (including dependency injection):

/src/EventSubscriber/MymoduleSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;

/**
 * mymodule event subscriber.
 */
class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    if (!$this->routeMatch->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($this->routeMatch->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if (!$request->cookies->has('foo')) {
        $redirect = new RedirectResponse($request->getBasePath() .'/node/2', 302);
        $redirect->headers->setCookie(new Cookie('foo', '123', '+30 seconds'));
        $event->setResponse($redirect);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 31],
    ];
  }

}

mymodule.services.yml

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    arguments: ['@current_route_match']
    tags:
      - { name: event_subscriber }


A question about performance with Form API and Ajax callbacks

I build such a dynamic form recently and asked me the same question. I did go with the Drupal-way and only used the Form API with zero lines of custom JavaScript. In general you have to weigh the pros and cons of server-side vs. client-side processing. For me these are:

Form API approach

(+) No custom JavaScript/jQuery code neccessary.
(+) You have the full power of the Form API including validation and storing of data inside $form_state (This was one of the main reasons for me since I was using this inside a multi-step form).
(+) Logic stays on the server. You probably need some server-side functions or do not want to expose your logic to everyone.
(-) It will be slower then a JS approach (depends on your server's performance).

JavaScript approach

(+) Fast. Since you do all processing on the client, you can update values instantly.
(+) May be easier to implement. It can be more straight-forward since you don't need any deep Form API knowledge.
(-) You have to fiddle around with jQuery selectors to somehow pass data to Drupal (maybe using hidden fields). This is not always nice and things can break if the HTML structure changes.

Normally I would prefer a JavaScript approach since the user experience can be much better. But in my recent case I really liked it to not have to write any custom JS code and let Drupal handle all the AJAX stuff. I was really impressed by the capabilities of the Form API.


How to Display Image after submitting webform in the confirmation message page

Instead of it you can directly try to add image in Confirmation message.
You can find that under form settings in webform.

like this : <img src="[submission:values:image_key]"/>


Drush make project versions when there is only dev available?

If the project has both a stable release and a dev version available, you can force usage of the dev version using something like

projects[geocoder][version] = 1.x-dev

You can also directly pull the project from its Git repository with

projects[geocoder][download][type] = git
projects[geocoder][download][url] = "http://git.drupal.org/project/geocoder.git"
projects[geocoder][download][branch] = 7.x-1.x


How to block all users not containing a pattern?

I suggest use drush block

drush ublk $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

before that make sure the query is correct and it respond what you want by

drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"

and finally, make sure they are blocked by checking "User status" column of the result of the following command

drush uinf $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

PS:

YOUR_ROLE_MACHINENAME: change it with your desired role.
PATTERN: you can use MySQL LIKE statement


My site was hacked, how can I use chmod permissions to avoid this?

See: Securing file permissions and ownership

You also might want to try adding the Security Review module to help make sure your site is following the correct file permission settings.


The redirect is specified in the login form forst_state array under the redirect key, that's why. You can change that by altering the user login form.


Change language programmatically after login

It should not be necessary to do it from code, as one of the settings present in admin/config/regional/language/configure allows to set the language to the one selected from the users in their user profile settings.


How to display a form filled by a VBO-submission?

As per the "I'm not very experienced in development", you may want to use an alternative approach which only requires site building skills, as further explained below ...

Use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the Views Bulk Operations module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted (so this is just a minor variation of the VBO based view you seem to already have in place).
create a Rules Component which uses Rules action "Send a message" (provided by the Privatemsg module). If you'd add 2 "variables" to this Rules Component, named something like "MsgSubject" and "MsgBody", you might want to use those variables as "tokens" for constructing the actual Subject and Body of your message.
Within your VBO settings, just execute this Rules Component. If you then use this VBO-view, you can specify the desired values for the variables used to create your Rules Component (like "MsgSubject" and "MsgBody"). So you avoid hardcoding the "Subject" and "Body" for the "Send a message" action (without those variables it would only allow you to send predefined messages). And this simply by using these variables of your Rules Component (to implement that "Subject" and "Body" of the message). That way, each time you use your VBO to send such messages, you can enter the desired "Subject" and "Body" for each of those messages.

Done, no (custom coding) involved ...

For some other illustrations about using VBO in combination with Rules Components, refer to the answers to these questions:

How to bulk update select list fields?
How to bulk delete selected content/nodes?


How to login into Drupal using Google Apps username and password?

To integrate your Drupal 7 site with Google Apps, you need to:

Enable the OpenID module on your drupal site
Enable the Federated Login Service using your Google Apps control panel at http://www.google.com/a/cpanel/yourdomain.com/SetupIdp
Add an X-XRDS-Location header at yourdomain.com/openid  For example, if yourdomain.com is a PHP site, upload this as /openid/index.php

<?php
header('X-XRDS-Location: https://www.google.com/accounts/o8/site-xrds?ns=2&hd=yourdomain.com');
?>

Go to your drupal site's login page. You'll see a new 'login with open id' link. Click it. Enter: https://google.com/accounts/o8/site-xrds?hd=yourdomain.com and click submit
The first time you do this, you'll be asked if you want to allow your site to authenticate. Click yes.
Subsequently, if you try to login using the above URL and you are logged in to Google Apps, you'll be logged in directly.


How do I use Font Awesome on a form submission button?

I normal replace search button value into Fontawesome Unicode code.

In your css just define fontawesome font-family.

E.G  In your own module call hook_form_alter()

if($form_id = 'search_block_form'){
  $form['actions']['submit']['#value'] = decode_entities('&#xf002;');

}

remeber use decode_entities() to parse the Unicode code.

CSS

.block-search input[type="submit"]{
  border: 0;
  font-size: 1.3em;
  vertical-align: top;
  margin-left: -45px;
  font-family: 'FontAwesome';
}

You should get search icon on button and place inside of your text input field.

ref. Font-Awesome cheatsheet


Print url to image from profile2 field with mutiple images

To get just the path of an image, use file_create_url
To get the path of an image using an image style, use image_style_url

e.g, in the context of your code:

<?php
  $uid = 24;
  $user_fields = user_load($uid);
  $profile2 = profile2_load_by_user($user_fields->uid);
  $images = field_get_items('profile2', $profile2['side'], 'field_baggrundsbillede');
?>
<?php foreach($images as $key => $image): ?>
  $url = file_create_url($image['uri']);
  // $url = image_style_url('medium', $image['uri']); // example image style url

   <?php print $url; ?>

<?php endforeach; ?>


How to file_save_data with utf encoding?

you do it with UTF8 add BOM

file_put_contents($File_name, "\xEF\xBB\xBF".  $content);


Which variables do I need to export with Strongarm?

Yes if the paths match up exactly on the other setup.
No if the paths don't.

Ideally you want to avoid putting platform specific options into features/code as they might not be the same across multiple environments.


Create a View with Previous Next and Return to Parent options

These are rough suggestions, have you tried custom pagers and eventually views slideshow for the previous/next links ?

For the back link, you can call your views with an URL parameter and build a footer link using this parameter (somewhat do the "destination" parameter).


Should you use check_plain() prior to inserting into database?

I downvoted Devaraj Johnson's answer because it suggests to check_plain() data before saving it to the database, which is wrong.

The idea behind check_plain, filter_xss and filter_xss_admin is to prevent XSS attacks, which are related to the front end.

When you handle database queries, use parameters and the DB API to prevent SQL injection attacks. Whenever you output data to the browsers, use check_plain, and other security methods.

Note that check_plain(), filter_xss() and such functions do change the data. When you save data into the database, you are only escaping specific characters, but you do not alter the original text. If you use check_plain() in database insert/updates, saving data a few times can mess up your data with a lot of &amp;, &lt;, etc character replacements and some HTML tags stripped out.

Here are some good reads:

Why Does Drupal filter on output (explains why you should not check_plain database data)
Handle text in a secure fashion


What does the votingapi_set_votes function in the votingapi module actually do?

Here is a working example:

function YourModule_menu(){
  $items = array();
  $items['the/menu/path/1'] = array
    (
    'title' => 'Voting button',
    'page callback' => '_YourModule_voting',
    'access callback' => TRUE
    'type' => MENU_CALLBACK,

    );
  return $items;
}

function _YourModule_voting(){
  $nid=arg(3);
  $votes = array(
    'entity_type' => 'node',
    'entity_id' => $nid,
    'value_type' => "points",
    'value' => 1,
    'tag' => "like",
    );

  $criteria = NULL;

  if (module_exists('votingapi')) {
      votingapi_set_votes($votes);
  }

  return "true";
}


How do I get a dashboard like the one drupal.org is using?

The dashboard on drupal.org is made using Homebox module.

  Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.


You can override the theme function for the date range date field formatter: theme_date_display_range().
For example, in your theme's template.php file you can add this:
/**
 * Override the themeing of a date field date range.
 */
function THEMENAME_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '' . $date1 . '',
    '!end-date' => '' . $date2 . $timezone . '',
  ));
}

Replace THEMENAME with the name of your theme.
Note in the return line the dash.
The default is for that to be 'to'.


How to hook into field creation (form successfully processed)?

Field storage configs and field configs are config entities hand have the standard hook_ENTITY_TYPE_presave/insert/update/delete() hooks.

/**
 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
 */
function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
}


How to load and display a view with Ajax in Drupal 7?

For anyone who ends up here looking for an answer, this is how you do it. First you need to enable "Use AJAX" under Other settings in the view and take note of the "Machine Name" as that is your display ID:

Then, this is how you pull it with JS using jQuery ajax:

$.ajax({
  url: Drupal.settings.basePath + '/views/ajax',
  type: 'post',
  data: {
    view_name: 'your_view_name',
    view_display_id: 'page', //your display id
    view_args: VIEW_ARGUMENT_HERE, // your views argument(s)
  },
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      console.log(response[1].data); // do something with the view
    }
  }
});


How can I get a list of all available entity view modes?

I think you are talking about view modes for entities.

$entity_info = entity_get_info('node');
debug(array_keys($entity_info['view modes']));

It would result as

array (
  0 => 'full',
  1 => 'teaser',
  2 => 'rss',
  3 => 'search_index',
  4 => 'search_result',
)


Assuming that your images are being built by theme('image',...) you can override its default...

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

}

...in your template.php file along the lines of this:

function YOURTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

}

and now those pesky height=s and width=s should be gone.


Turns out I needed to use the relationship on the filters as well.


How to get notified when a user is blocked?

There is hook_user_update() for this. Below is an example on how you can use it for your purpose:

/**
 * Implements hook_user_update().
 */
function my_module_user_update(&$edit, $account, $category) {
  // Check if the user was blocked
  if ($account->original->status != $account->status && $account->status == 0) {
    // Handle notification here
  }
}

To send an email programmatically from Drupal, you can check out this question.

Another way to do this, would be by using the Rules module and following the steps below:

Create a new rule that reacts on the user event "After updating an existing user account".
Add a condition of type "User is blocked" and save it with the defaults.
Add another condition of type "User is blocked", but this time use "account-unchanged" for the Data Selector and check the Negate checkbox.
Add an action of type System > "Send mail" and play with it.


How to write phpUnit tests for hook_form_alter?

It is technically possible to write a unit test for this. You'd need to manually require your .module file though.

It might be easier to use a Kernel test, as these will automatically load module files, fire hooks, etc.

MyTest extends KernelTestBase {

  /**
   * Modules to enable.
   */
  public static $modules = ['my_module'];

  /**
   * Test the function.
   */
  public function testCancelButton() {
    // The .module file will already be loaded, so you can call your custom function directly.
    $form = [...];
    _cancel_button($form, ...);
    // Now make assertions about expected changes.


hide all of node form except a file upload field

You can use Field Permission module to hide all those fields which you don't want to show on node edit or node create form for all user type which you want.


Drupal 7 Simple Ajax Module returning 404

The first arg to user_access is mandatory, so you need to provide it in hook_menu via access arguments. The default for access callback is already user_access as it happens, so you can omit that:

$items['ajax-bookmark'] = array(
  'page callback' => 'bookmark_ajax_add_article',
  'access arguments' => array('access content'), // Or whatever permission makes sense.
  'type' => MENU_CALLBACK,
);

After you clear caches the page should be accessible.

Incidentally, you don't need to use jQuery.ready when you're inside a Drupal behavior attach method, as those are only ever invoked on DOM ready anyway.


Views Output Field as Link: Change link text

While editing your view, open the field you want to modify.  In your case it would be your Image field that current output's Download

Scroll to 'Rewrite Results' and check the box next to 'Rewrite the output of this field.'

Enter the text that you would like to display instead of 'Download.'

I believe if you use the Tokens module, you will have several variables accessible to you as well.  See "Replacement Patterns" in the same menu to see what is available.


How to force Local Task Menu to display on specific pages

I managed to solve this be engineering a fix with ( https://www.drupal.org/project/local_tasks_blocks )

There is a patch here at https://www.drupal.org/node/2141653 for 'Fixed path for displaying tabs'  which sounds like the same issue I had .  However the patch didn't work for me.

Checking the value of $tasks['#primary'] ; I concluded that if I could keep this array for a session then I could use the Local Tasks Menu on all the pages I wished while the User is logged in.  Ie something like

if (empty($tasks['#primary'])) {

// 1.  Check the cookies if we have one then use that
if (isset($_SESSION['usertasks']['primary'])) {

$tasks_primary = $_SESSION['usertasks']['primary'];
$tasks['#primary'] = $tasks_primary;
}
else {
$usertasks = &$_SESSION['usertasks'];
// well need to create a new instance of this array so we don't    effect it for the page we're on
$tasks_primary = $tasks['#primary'];
$usertasks['primary'] = $tasks_primary;
  }
}

My next step is to make a patch for this if anyone else may find it of use.


Taxonomy terms manipulation on node.tpl.php

Finally I did it as shown below (thanks SO):

  <?php if (isset($node->field_my_taxonomy_term[LANGUAGE_NONE]) && $node->field_my_taxonomy_term[LANGUAGE_NONE]): ?>
    <?php $allOf=''?>
    <?php foreach ($node->field_my_taxonomy_term[LANGUAGE_NONE] as $obj): ?>
        <?php $exp = explode (" ", $obj['taxonomy_term']->name);
            $exp_last = array_pop($exp);
            $eachOne = $exp_last .', ' .implode(' ', $exp);
            $allOf .= $eachOne . '&nbsp;-&nbsp;';
         ?>
    <?php endforeach; ?>
    <?php print trim($allOf, '&nbsp;-&nbsp;'); ?>
  <?php endif ?>

This is working correctly.


Add custom attribute to an external JS script

I solved the problem using drupal_add_html like this,

$data = array(
  '#tag' => 'script',
  '#value' => '',
  '#attributes' => array(
    'src' => 'https://code.jquery.com/jquery-3.4.1.js',
    'integrity' => 'sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=',
  ),
);
drupal_add_html_head($data, 'unique_key');


Views get total row count in views-view.html.twig

This can be achieved as follows. NB this outlines a simple approach which works. It can be finessed and improved upon by stripping our unnecessary divs, applying classes more elegantly, etc, but this will work:

Adding a views attachment display and attaching it to your main
display of the slides (display: after);
Set this attachment with an ordered list display format with List class = carousel-indicators;
Add one custom text field (it will not be displayed so it does not really matter what this is);
Set it to evaluate the same conditions as your main display (eg content filtered by a boolean "display in slider" = TRUE ... or whatever). This way number of bullets definitely = number of slides;
Copy the core views-view-list.html.twig to your theme and override with your
display name (see api.drupal.org/api/drupal/core!modules!views!views.theme.inc/group/views_templates/8.3.x for general suggestions);
Return the rows as follows:

{% for row in rows %}
     {% if loop.first %}

{{ row.content }}

     {% else %}

{{ row.content }}

     {% endif %}
    {% endfor %}

This gets the active class on the first item and includes the index number, thus matching the requirements at: getbootstrap.com/javascript/#carousel

Controls and required wrappers can be set simply in the views-view.html.twig:

 {% if rows %}

 {{ rows }}

`
(...etc..)

Slide wrapper and active class can be set in views-view--unformatted.html.twig for the slides themselves:

 `<!-- Wrapper for slides -->`

{% for row in rows %}
   {% if loop.first %}

    {{ row.content }}

{% else %}

    {{ row.content }}

{% endif %}
 {% endfor %}

Working example: http://wri.netuxosandbox.co.uk/en


Your queries should look something like this:

$query = "SELECT t1.tid, t1.parent FROM {taxonomy_term_hierarchy} t1 JOIN {field_revision_field_pubissue} t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = :nid";
$result = db_query($query,array(':nid' => $node->nid));
// Result is returned as a iterable object that returns a stdClass object on each iteration (@see http://api.drupal.org/api/drupal/includes--database--database.inc/function/db_query/7#comment-7019)

After all I would suggest you check out the drupal taxonomy api. Using something like taxonomy_get_tree() could be much better.

EDIT:

Using the taxonomy api I would say what you want to do would be something like:

$parents = taxonomy_get_parents($tid);
if(!empty($parents)) {
    // use whatever you need from your $parents
}
else {
    $term = taxonomy_term_load($tid);
    // use whatever you need from the term (No parent, top level)
}

EDIT 2: fixed code example...


How can I change the "content type" field name particularly in a view?

Add a field to each of your content types, let's call it "Nickname" and enter the value you want to appear in your view, ie for Case Study enter "Case Studies". Now add Nickname to your View fields, and it should output the right text for each content type.


hook_form_alter() only firing after cache clear

I think your problem stands in cascading caching logic : your form must be called by something (a block, a template, a function...) that must be itself cached.

What you have to think about is "When, and by who, is my cache warmed up, with which conditions ?" : the most logical answer is that when your cache is created for the first time, conditions in your hook_form_alterare not TRUE.

For example, are you searching, in your alter, for infos coming from the session, or user roles, or static variables...

We could do more with your code :)


"Non-existed service" errors after clearing the cache

It seems that a class is requesting the password_migrate service which does not exist.

This is usually caused when the module that supplies this service is not installed.

I suggest you search the project code for the string password_migrate to find both the requester and the provider.


Drupal 7 does not have this feature.

All you have to do is create your own javascript/jquery (.js) file and do something along these lines.

(function ($) {
     $(".commentbody").hide();
          $(".commenttitle").click(function() {
          $(this).parent().find(".commentbody").slideToggle();
          });

})(jQuery);

Here is an example JS FIDDLE


You can alter your exposed form and print needle select list.
Than you hide your exposed filter with betweeen operator. E.g. display:none.
Than you write js that fills your hidden filter when user change select value.


Smart paging rendering pager different from the Devel model

I found the solution: go to the Smart Paging settings page and uncheck "Use javascript pager as progressive enhancement for Drupal native pager"... as simple as that...


Trying to render a custom date format with Twig

Here is an approach that uses just Twig (no preprocess functions needed):

<p>{{ node.createdtime | date("d F Y") }}</p>


CSV Feeds import troubles with CiviCRM entity reference field

Not sure if https://www.drupal.org/project/civicrm_user_reference will work for you, but I wrote that when having issues with CiviCRM Contact Reference Field in another use case.


Error when trying to migrate comments to a clean D8 site: What's wrong with my .yml file?

keys:
    - id

The yml is using a key 'id' that is not defined in the column_names. Since you have a 'nid' column, I suggest changing 'id' to 'nid'.


Detect when a user clicks file download link

Module Track da files (despite its goofy name) tracks both public and private files. Here is a quote about it (from the module's project page):

... enables the possibility to track how much visitors are viewing files on site.
Every link to a file can be configured to be tracked. Then, a record is registered each time a visitor access the file from this specific link.


You can use Postal code module to integrate postal code in your site.

Please note at the moment the module only support:

USA, Canada, UK, Germany, France, Italy, Australia, Netherlands, Spain,Denmark, Sweden, Belgium, India, Poland


Where is the email New release(s) available coming from

It's configured on the "Available updates" settings page at /admin/reports/updates/settings:


Javascript translation broken - fixed after cache clear

You can refresh the cache with drush: drush cc css-js to clear only Javascript (the admin module allows you to do this from config), or you can just go to performance and clear all the cache.

It does seems like clearing cache is important in these cases:
https://www.drupal.org/docs/7/api/localization-api/translating-strings-in-javascript


Varnish causes page load time to increase

I cannot comment yet as a new user so here goes my response.

For starters 1 second to 1.3 seconds is not all that much of a difference, and you dont seem to have an overabundance of misses so its doing its thing. Run some tests that simulate a lot of page requests on the same content and watch the hits/misses.  Also did you test again without Varnish on the same site?

One other thing is to be sure you've properly sized the Varnish storage to match your servers available resources.  This being off too much can drag the system for obvious reasons.

Any reason your not using Drupal 7?  Pressflow 7 is available now too.

There is also the option to use Boost + Varnish.
http://www.trellon.com/content/blog/boosted-varnish-high-performance-caching-made-easy


How do I rewrite Solr search results to show related entity reference field?

Assuming you are using the apachesolr module, implement hook_apachesolr_search_result_alter() in a custom module. The function you create will receive the $document object that you may modify. You will have to add logic in there to locate and load the appropriate related entity.


When creating content with new term, show all term fields for input also

You can use combination of two modules. First is Entity Reference, where you have to create your taxonomy term reference field. Then install module Inline Entity Form and use widget Inline entity form - Multiple values (in number of values of this field select: 1).

In node create form you will have then field, where you can select from existing terms (autocomplete) and also you will be able to create new term, if term does no exists - this will create inline form, which would have all fields specified in taxonomy vocabulary structure (see image below).

If you select existing term, or create new, it will looks like this:


Migrating only articles with a specific taxonomy term

Besides setting up a process plugin for the migrate import mapping (via code) as suggested by Berdir in the comments, another option is to setup a views data export on the legacy site to output only the select articles or "interviews".

This approach also allows non-database admins or developers to easily audit the content being migrated (because you can setup an alternative view display as a webpage, or excel spreadsheet, for use as a checklist).

To setup a view in JSON format:

install the Views Data Export module
install one of the add-on modules for JSON, such as Services Views or Views Data Source.

Refer to this StackOverflow answer/post about setting up a JSON view display mode.


Remove Block Directly From Database - Drupal 7

To delete a block programmatically using the Database API, try this:

$module = 'block';
$delta = 1;

// Get the block id (bid) required to delete the correct block from table 'block_custom'
$result = db_select('block', 'b')
         ->fields('b', array('bid'))
         ->condition('module', $module)
         ->condition('delta', $delta)
         ->execute();
$bid = $result->fetchField();

db_delete('block_custom')
  ->condition('bid', $bid)
  ->execute();

db_delete('block')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

db_delete('block_role')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

When creating custom blocks through the Drupal Block UI, the module name is block and the delta value is an integer. Be sure to use the correct delta value to delete the desired block.


The module rules_scheduler present inside rules module is giving you what you need.

Details of implementation are here:

https://www.drupal.org/node/2720421
https://www.drupal.org/node/1300068


You cannot disable menu cache - if you could, Drupal would need to scan all modules on every request and it would kill your site. You can use Cache Actions:

  It currently provides actions for:

  Clearing Drupal cache bins
  Clearing CSS/JS cache
  Clearing The cache of specific views
  Clearing The cache of specific panel pages
  Clearing The cache of specific mini panels

Just clear menu cache in the same rule you use to add a role to your user. After adding that role, of course.


The store address is used for calculating taxes. It doesn't have to be a physical store address, enter the address the business entity is registered to.

On the store edit form select a single "Allowed billing country".
That will hide the country selector on all of your address fields.

Then go to admin/config/people/profiles/manage/customer/fields/profile.customer.address and under "Field overrides" select "Hidden" for each field.
That will hide the other address subfields.

You need to be on the latest Commerce release for this to work.

(And yes, an empty profile with just the country code will be created for each order. There is no way around that currently)


You need to use views as described below

1. Create a user view (not content view)

2. Add contextual filter user id with default value current logged in user

3. Add relationship on terms referenced from field skills (of user)

4. Add relationship with term from skills

The previous relationship should be autoselected

5. Now you can add content fields to view and the field skills relationship should be autoselected

when a user visits the view page the jobs will be contextually filtered based on their profile selections


How can I insert many field values under one term?

You needn't have to do aggregation via temporary tables, it can be done in your query via a GROUP_CONCAT expression & GROUP clause:

$query = \Drupal::database()->select("excel","m")->fields("m",["stokkodu","grupadi"])->condition("grupadi", "","!=");
$query->addExpression('GROUP_CONCAT(m.stokkodu)', 'stokkodus');
$query->groupBy('m.grupadi');
$results = $query->execute()->fetchAll();
foreach ($results as $result) {
  $result->stokkodus contains a comma-delimited list of values that you can split with explode()
  $stokkodus = explode(',');
  // @TODO: add transform logic
}

In the example above, you can transform the exploded array then create an array of values for your multivalue field_stok_kodu field:

  // @TODO: add transform logic
  'field_stok_kodu' => [
    ['value' => $stokkodus[0]],
    ['value' => $stokkodus[1]]
  ];


How to restrict taxonomy term reference with certain terms?

You seem to be asking 2 questions here:

Restricting Terms: You can edit the entity reference field's Reference method to use a new custom view that filters only the criteria you're looking for.
Parent/Child Widget: The Hierarchical Select did have this widget functionality in D7, in D8 there are a few modules out there, like Simple hierarchical select & Client-side hierarchical select, that have similar dual-selection functionality.


Taxonomy term not translated in edit node

It seems you are using 'Entity Translation' module and a field type 'Term reference'.

In the content type 'Article' you could try to create a new field type 'Entity Reference' with Target type 'Taxonomy term' and Entity selection
'[Your category vocabulary]'

It should works.


Appropriate way to include a PHP file in a theme tpl

I think the "Drupal Way" would be to create a variable in your template.php file, and then just call the variable in your page theme.

http://drupalize.me/videos/overview-templatephp


How to resolve an XMLReader warning produced by Wordpress Migrate module?

I had the exact same error.  I uninstalled all the WordPress migrate and migrate modules (uninstalling migrate may not have been necessary), removed from site directory and then reinstalled.

I re-installed Migrate 7.x-2.6 and WordPress Migrate 7.x-2.3-beta2+4-dev.

After that the import worked.


Is this possible to copy Views fields declarations to another view?

Try export view and look in export's code


How to find out the combinations of Views arguments that have the most Views result

Inside Drupal, this would take some real custom magic. But, let's say for example, you wanted to show

pets/birds,

pets/cats

both birds and cats would be arguments off the main Views page of pets. BUT - if you had a Google Analytics account, which does not understand Drupal arguments, you could easily decipher which page received what number of visitors.

Because Google will never discriminate vs what is a page and what is an argument, you can easily see what would be most popular as a result.


How to display a taxonomy term's immediate children on its page?

Given your additional information, this short step-by-step guide, that should give you the desired results:

Duplicate/disable the original Taxonomy view / alter it as follows.
In "Advanced/Contextual filters" remove "Content: Has taxonomy term ID"
Add a new Contextual filter "Content: Has taxonomy term ID (with depth)":

Depth: 1 (will show content for the next level child terms as well)
When the filter value is NOT in the URL:

Provide default value
Type: Taxonomy term ID from URL
Load default filter from term page: checked

When the filter value IS in the URL or a default is provided:

Override title: checked, use the variable {{ arguments.term_node_tid_depth }} (this will make sure the term name will be shown in the page title)
(Optionally, but strongly suggested) Specify validation criteria: checked
Validator: Taxonomy term ID
Vocabulary: (your vocabulary name checked)
(Optionally) Validate user has access to the taxonomy term: checked

As you'd like to show an image, you may also wish to change the Format of the view from Content to Fields and add the image field of your tagged content.

Please note, that the depth modifier may lead to duplicates. So within the Advanced / Other section's Query settings, you should enable the "Distinct" option.

You can further improve your view results by adding relations to the actual terms, the term name and adding grouping. But this seems out of scope for your initial question.

I did the above steps on a clean D8 test instance with auto-generated content and vocabularies, and it was working fine.

EDIT:

According to your comments, you actually like to show fields of the child taxonomy terms only. So here is how to do that:

disable the default taxonomy view
create a new view
in View settings / Show choose "Taxonomy term"
"of Type" is your vocabulary
in "Page settings" check "Create a page" and provide the URL "taxonomy/term/%"
click "Save and edit"
in Advanced / Contextual filter add the filter "Taxonomy term: Parent"
apply the same settings as in my above solution to the contextual filter, except for the title variable, which should now be '{{ arguments.tid }}'

As result, you should see the first level children of the taxonomy term in the view.

If you like to see some of their properties only, switch the type of the view to fields and add the field you like to display.


Views Slideshow Stops Working Alongside Other Slideshows

After some inspired messing around, I determined that the issue only stopped slideshows that were displayed after a certain slideshow. Using that information, I deleted the isolated block, and re-created it in the same form as the other slideshows.

This appears to have solved the problem. I guess something was corrupt with that particular view. It was the one I was originally using as a clone base for all the other slideshow blocks.

Hopefully this "fix" persists!


User cannot change password due to lack of "current" password

Not requiring the current password seems like a huge security problem. Anyone who turns their back to the computer for a moment can have their password changed without their knowledge.

A user that finds oneself in this situation will need to request a new one time login link.

I would also suggest the box where a new password is entered should be better highlighed if this is a common problem.


Is there a token for the body of a content type?

There is a feature request opened for the Token module: Token for body of node.   Essentially, the reason it has not been implemented is performance issues, as modules are queried for the values of the tokens they implement, independently from the fact those tokens have been requested. This means the content for, e.g., [body] would be generated even if the string passed to Token doesn't contain that tag.
The Drupal 7 code that handles tokens is changed, and the modules that implement tokens gets the list of tokens that need to be replaced; the content of tokens that are expensive to generate is generated only when required.

In short, the only module that could implement that kind of token is the Token module, but so far it doesn't implement it for implementation issues. Any other module that implements it would have the same performance issues.


how to display entity references as numbered list?

Its pretty simple, in this example I will use title instead of an entity reference field, but it's the same process.

Step 1) add Global: View result counter as a field.

Step 2) Uncheck create label, and checkmark hide from display.

Step 3) Re-arrange so your counter is above your entity reference field.

Step 4) Re-write results and use replacement patterns to format your title field.


Do you use many modal frames or many functions like $result = drupal_http_request($url, $options); on your site?

In both these cases the user agent is set to "Drupal".


You need to create symbolic links in order that your drupal7_sub1 and drupal7_sub2 directories works. Those symlinks needs to target your drupal7_main directory.

To create a symlink, open a commandline tool and execute following commands (if your on a Windows machine). You need to put the correct paths depending your localhost configuration.

First go to root directory of your localhost

cd C:/wampp/htdocs/

Create symlink for each subwebsite (drupal7_sub1, drupal7_sub2)

mklink /D drupal7_sub1 C:/wampp/htdocs/drupal7_main
mklink /D drupal7_sub2 C:/wampp/htdocs/drupal7_main

Executing this will already give you a result when visiting localhost/drupal7_sub1. If everything went well, you should see your localhost/drupal7_main website.

Because your working with a localhost URL (and not real domain name, can be a development URL only existing on local, i.e. dev.yourproject.com), you need to slightly adapt your folder structure in order that each subwebsite uses its own settings.php and file folder for the files (uploads, css, ctools, js).

You need to prefix your subfolders under drupal7_main/sites/ with localhost.

drupal7_main/sites/drupal7_sub1 --> drupal7_main/sites/localhost.drupal7_sub1
drupal7_main/sites/drupal7_sub2 --> drupal7_main/sites/localhost.drupal7_sub2


Creating a page to display several content types

The Views module might help you for this purpose. It is highly configurable, and it allows you to display several items on a single page. Other modules can add functionality, like the Views Slideshow module.

Learning how to use Views takes some time, but there are many Views tutorials available in the web. A possible starting point might be this one:

https://dev.acquia.com/blog/a-totally-beginner-tutorial-to-views-for-drupal-7/22/01/2016/9576


How to theme the register page (mysite.com/user/register)

To theme that path via a template file, you can use:

page--user--register.tpl.php

copy page.tpl.php to that filename, clear theme registry cache to apply.

Note, you may need to copy page.tpl.php from your base theme to your sub theme /templates folder to bring it into scope.


How can I turn a list of Aliases into a menu structure?

I'd give the Menu Export/Import module a go.

  This module helps to export and/or import menus. Using it you can
  easily copy menus from one Drupal site to another.

  It also allows developers to quickly build a new Drupal site by
  creating empty content and menu items referencing it. The module may
  be used in ensemble with Node export that allows to add content to
  your Drupal site. In this case, menu import allows to batch-arrange
  existing content into a given menu structure, using a very simple text
  file.

I guess you could possibly use Excel or something to take your list of aliases and split the paths to columns which would give you the menu title (in the last column of the split).

From there you have the menu link titles and paths, so it's just a case of getting it into the format that the module expects.


Are there plugins available for an "improved" Find Content admin interface?

Have you tried VBO module? that, allows you create custom admin interface.


Views: how to display different buttons before/after associated date?

There are three ways to do this kind of conditional logic:

Use the views_php module
Make a views field template
Write a views widget (or formatter, or something - what is the correct terminology?)

I ended up taking a bit of a shortcut and going ahead with views_php for now.  I'm never going to be dealing with more than a few hundred rows, so I'm not to shaken up over the poor performance of views_php.

This module is pretty easy to use.  Add a "Global: PHP" field.  I found dpm( $data ) and other variations to be very useful.


Including Google Maps in my custom module

I didn't dig into the exact methods you are using, but if all you want to do is embed a very simple map graphic you could use something like this:

if (isset($currentclient->street_number) && isset($currentclient->street)) {
      $address_var = $currentclient->street_number . " " . $currentclient->street;
      if (isset($currentclient->city)) $address_var .= "+".$currentclient->city;
      if (isset($currentclient->state)) $address_var .= "+".$currentclient->state;
      if (isset($currentclient->postal_code)) $address_var .= "+".$currentclient->postal_code;
      $address_var = str_replace(' ', '+', $address_var);
      $output = "";
    }

Or, I suppose a render array would simply change the $output= line above to be something like this:

$output =  array(
    'map' => array(
      '#type' => 'markup',
      '#markup' => '',
    ),
);


Filter a view result by matching a view field to a URL term

Use contextual filter in views and set raw value as second argument from the url (here second argument will be username).


How to open pop up window in javascript in drupal 6?

Use the Colorbox module.

  Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.

  Images, iframed or inline content etc. can be displayed in a overlay
  above the current page.

You need to activate the iframe method and add the custom iframe class to your link.


You need to separate your sessions from your course type. The ideal solution would be to implement Field Collection.

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

It is an actively maintained module with views integration. For a quick intro look at this tutorial.


How do I create custom 403/404/406/503 pages in Drupal 8?

To bundle and create programatically, you would need to create a custom module and inside that module: you could create a route for each specific page. That module could also update the config that is found in the system basic settings to use your custom pages.

Using this custom page you could call a custom page.html.twig and  override with the html you need.

Here are two resources:

https://www.drupal.org/node/2116767
How do I update the configuration of a module?


The module weight won't do anything here. You set the priority in the service tag.
You have to look what other path processors do at which priority to find the right place for your custom code. And use an inbound path processor to remove the x you have added outbound.
The outbound processor is called multiple times while building a page, because you usually have more than one link on the site (and not all are visible).
(question in comments) You can do this, outbound transfer query parameters to the path and inbound transfer parts of the path again back to the query parameters. Internally Drupal sees only the short base path with query parameters, externally you see the full path without query parameters. An example for inbound is PathProcessorFiles::processInbound


Module submission guideline - configuration storage

My advice to you is to submit your sandbox to Drupal.org Project Applications, and see what people say.  Its fairly rare to get an outright rejection.  People will inspect your code, offer suggestions for improvement, etc.  Better to get started ASAP.

As for your specific issue:  I think the way you are going about it is not in accordance with The Drupal Way ™.  Your best bet would probably be to generate a PHP file, only allowing your module to access this sort of administrative control from the site in Default.


Add entity reference field to content type

You would need to use the "Views: Reference by entity reference view" Mode.

You then need to have created an Entity reference view display to correspond to this. In this view you need to pass the current node author as an argument / contextual filter and show all the nodes you want to display there.

Select this view in the entity reference field's settings as attached, an that should do it.


Aquia Desktop - How to import a MySql database that is too big

configure Mysql my.ini

change the value of myisam_sort_buffer_size from 8M to whatever your sql size is.

I will say if your file size is 100 change the value to myisam_sort_buffer_size = 156M.

Restart your mysql.
using terminal navigate to mysql bin directory
run the command: mysql -u username -p yourdatabasename <yourmysqldatabasefile

enter the password for the user, if there is no password the user than just press enter.


PHP Fatal error: Call to undefined function chdir()

chdir() and max() are built in functions that always exists in PHP. They are in no plugin, just a core. Even in safe mode both should be defined.

There is one way to disable them and make them non-existent from the script's point of view. disable_functions section in php.ini does the trick. Usually it is used for safety, like this:

disable_functions=exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

and whilst I can see some illusionary* safety in disabling chdir(), disabling max() must have been a mistake. Note that on some configurations you can alter ini settings in .htaccess and via ini_set() too.

*Illusionary due to the same reasons that made Safe Mode deprecated.


How to setup drupal multisite in cpanel?

I have found the problem. My settings.php file had redis configuration, and that was the problem. I found it because I added this line to settings.php file:

$config['system.logging']['error_level'] = 'verbose';


Migrate nodes from D7 to custom entity defined in D8

It looks like you're very close. Is your entity called "phase" or "phase_entity"? If it is "phase", then you should adjust that under destination. Here is what I would recommend:

id: phases
label: Phases nodes migration
migration_group: phases
source:
  plugin: d7_node
  node_type: phase
destination:
  plugin: entity:phase
process:
  id: nid
  type:
    plugin: default_value
    default_value: phase
    langcode: language
  name: title
  user_id: uid
  changed: changed
  created: created
migration_dependencies: { }


In the "Default front page" field at /admin/config/system/site-information, instead of leave it blank, insert /node which is normally what drupal places by default.


How do I bypass cart and go straight to checkout?

If you use the last development version of commerce, and look for file commerce\modules\cart\src\Form\AddToCartForm.php which lives under the Drupal\commerce_cart\Form namespace, you can see that cart_id was set, and it is the order ID too.

$form_state->set('cart_id', $cart->id());

Therefore, in hook_form_alter(), we can get the order ID (the cart ID).

$order_id = $form_state->get('cart_id');

The complete code would be this.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Implements hook_form_alter().
 */
function <MY_MODULE>_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // Add to cart form id for product 5 is: commerce_order_item_add_to_cart_form_commerce_product_5
    // Then it's enough to check $form_id contains the string 'commerce_order_item_add_to_cart_form_commerce'
    if(strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce') !== false) {
        $form['actions']['submit']['#submit'][] = '_redirect_to_checkout';
    }
}

// Callback for form submission
// @see hook_form_alter().
function _redirect_to_checkout(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $cart_id */
  $cart_id = $form_state->get('cart_id');

  $url = Url::fromRoute('commerce_checkout.form',
    ['commerce_order' => $cart_id]
  );

  $form_state->setRedirectUrl($url);
}


I left it overnight, and by the following day, the issue was gone.... :-/


Custom image style used on image upload causing errors

Files will be renamed to prevent collisions. Off the top of my head it adds something like _1 to the filename.
Yes that's correct. I'm not sure about the scale but that sounds like it would work. If the image is too small, it will get scaled up. If the image is too big, it will be resized down then scaled and the scaling shouldn't have any effect.
That all sounds like it's working as intended. You have a simple problem with directory permissions within your sites/default/files directory. If you're in a dev environment try doing chmod -R 777 files (Then you know it's a permissions problem and you can set them properly). Problems like this are usually either because the file cannot be read or written, in your case it looks like writing. The PHP stream wrappers mentioned in the error message are enabled and working, don't worry about that, it's standard PHP. If chmod doesn't work, try changing ownership with chown.


Concatenating user submission fields or components in webform Drupal 7

If you'd be willing to also use the Rules module for actually sending such eMails (together with Webform Rules), you'd have all sorts of flexibility about how you want those eMails to look like.

As an example, consider this custom rule for sending an eMail (in Rules export format):

{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using such basic rule, you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail]. In other words, you don't need a Rules Action like "fetch entity by ID" for these kinds of tokens to be available.

But wait, there is more ... You can also include any of the "Webform data" in such eMails. To do so, you could use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
In your subsequent Rules Actions (e.g. in which you create an eMail) you can refer to the value of these variables you just added (that's the clue!).


How to assign a role to a user depending on order subtotal using Ubercart?

If you want to use that "Order subtotal" in a Rules "Condition", you could try to first add a Rules condition Entity has field (related to the field containing that "Order subtotal").

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition, somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

So if you don't have an appropriate "field" for it, then you may be able to get it to work also by using that 'content is of type'.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Thanks kiamlaluno for the first guide. I'm really lost about writing even a mini-module.

Here's the code for what i was needing:

// Cancel / subtract user vote from 'poll_choice' table, when user account is cancelled.
// The code (db_update) which subtract users vote is a copy from poll.module
function MODULE_NAME_user_delete($account) {
    $uid = $account->uid;
    $votes_id = db_query("SELECT chid FROM {poll_vote} WHERE uid = :account_id", array(':account_id' => $uid))->fetchAll();
    foreach ($votes_id as $vote_id) {
        db_update('poll_choice')
        ->expression('chvotes', 'chvotes - 1')
        ->condition('chid', $vote_id->chid)
        ->execute();
    }
}

This is for MODULE_NAME.install. We need it to make sure poll_vote table is not update before this module function is executed.

function MODULE_NAME_install(){
  db_update('system')
    ->fields(array('weight' => -1))
    ->condition('name', 'MODULE_NAME', '=')
    ->execute();
}


How add new tab in structure when manage it?

You need to create a menu with type as MENU_LOCAL_TASK. Can refer to menu 'node/%node/edit' in node.module.

Hope it helps


I solved the previous problem as follows:

1.In my block view I added the field "Type", and i clicked the option "Exclude from Display"

2.In the field "Title" of the view, I disabled the option "Link this field to the original piece of content" and i rewrote the title with the rule: [type].

3.I added a redirection rule from each type to the corresponding link


Drupal Commerce Adding fields to Add To Cart page

Thanks all of you for your valuable time and suggestions. More or less all suggestions 'll be required in near future. I have up-voted all of you for your help. However on other side I got the answer, what I was looking for.

  It sounds like you need the Customizable Products module.

  Once you have that module installed, you can go to Administration > Store > Configuration > Line item types. Add a custom line type and add as many custom fields there as you'd like. You'll see - the
  interface for adding fields to the custom line type is the same as
  when you create a content type, so it's easy to use.

  Then, when you've added all the customer info you need in your new line item, go ahead and modify your 'Exam' product to include
  those fields in the product display. Hit the 'Display' settings for
  the content type, and configure the settings for the 'Add to cart'
  field. Make sure you choose the correct line item for it to use and
  Save!

  Helpfull screencast could be found at http://vimeo.com/36106455


menu_local_tasks() is a good place to start looking. This calls theme_menu_item_link() which is the pertinent theme function to look at. It makes sense to do any access checks in the preprocess and you'll also need a custom theme function to handle the variables you set. You mention user_access() in the Q, but it's important to remember that the access callback could by any function. For that reason it's necessary to impersonate the anonymous user (note the link isn't specifically for anon users, but the fundamentals are the same). You can get the menu item type, access callback, and access arguments from $link. The bit of code to do the actual checks would look something like:

if ($menu_item_type & MENU_LOCAL_TASK) {
  global $user;
  $original_user = $user;
  $old_state = session_save_session();
  session_save_session(FALSE);
  $user = drupal_anonymous_user();

  if (!call_user_func_array($access_callback, $access_arguments)) {
    // Anon's don't have access to this local task
  }

  $user = $original_user;
  session_save_session($old_state);
}

A note regarding performance: none of the calls access the database, except possibly the access callback (which could do anything). user_access() caches a role's permissions, so that would only access the DB the first time. Other access callback's might not do this. It wouldn't be particularly difficult to cache the results of the access callback yourself (keyed by access callback and serialised arguments).


You have two problem.

page--front.html.twig is special suggestion template for front page. Any url set to front page always use this template => You don't need set alias for this.Just set page you want to front page.
Don't add html tag to page template. The tree of template is html=>page=>region=>block... Html tag exited in template html.html.twig.

And more you can setting twig debug to see current home page use template?


How to redirect anonymous users to a login page?

If you use the LoginToboggin Module. It Provides a login form on Access Denied pages for non-logged-in (anonymous) users, instead of just the standard "Access Denied". (Also, good for admins, who forget to login when trying to access admin areas too)


How can I restrict view pemissions to a node related child nodes?

Looking at the comments I realized that in my case at least the best way of limiting the access  for unauthorized users (anonymous mainly) is to not publish the child nodes. And I removed the 'published'='yes' filter in the view itself so I can show those nodes in the parent template. And it works nicely. Thank you for the tips.


How to convert user menu tabs to menu links?

By creating an extremely simple custom module, you can Remove tabs using hook_menu_alter. Make sure to also clear the cache when you experiment with this.

Note: Consider refining your question to specify the path of each of those tabs you want to replaced.


Changing permission on node access that linked with other nodes

You can do this in hook_node_access().

You didn't mentioned if this is for D7 or D8, but this hook is available in both.

This hook provides the node and the account object. So you have all data you need to calculate the permission.


I followed all 10 steps at this article in detail to get a fully functional boilerplate subtheme for the Commerce Kickstart Theme in just a couple of minutes.

In case the article goes offline, you can find a mirror here.

Info :

  How to subtheme the Omega Kickstart Theme

  Posted by sja1 on August 4, 2013 at 12:31pm

  Hi guys, first off thanks
  for the all the work you've put into make Commerce Kickstart such an
  oustanding platform. I wanted to create this issue in order to help
  those who are having trouble creating a subtheme of the commerce
  kickstart theme. There is good documentation for subtheming omega, but
  I had a harder time finding information on subtheming a subtheme of
  omega (Commerce Kickstart is a subtheme of Omega Kickstart, which is a
  subtheme of Omega). With some trial and error I have come up with the
  following procedure which is working for me, and thought I'd present
  it to the community for others to benefit from and hopefully improve
  upon. All comments welcome.

  Steps to subtheme Commerce Kickstart theme

  [ For the detailed 10 steps, go to one of the two provided links ]


Implement template_preprocess_node in your .theme file and get the page's node with the following code.

/**
 * Implements template_preprocess_node().
 */
my_theme_preprocess_node(&$vars) {
  // This will fire for any node type with the teaser view mode
  if ($vars['view_mode'] == 'teaser')
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You have the full node object and can access fields as needed.
      // You can even check the $node type in the above if statement to only add
      // this value to the teaser for nodes when you're on the type with your EVA
      // Make sure to add them to the $vars array to see them in your template.
    }
  }
}

See this post re: how to access fields from a node object.

Note: This doesn't do exactly what you're asking, but will work if you're viewing the full page of the node with the EVA.


How do I check if a user has view access to a node, in a template file?

Not really an answer, more like a suggestion for an alternative suggestion where that problem should exist, at least not exactly like that.

They way I handled similar problems before (paywall for newspapers in my case) is to not use the node access system for this. In my case, I did it using logic in the template/preprocess as well as dynamically switching the view mode. If you can handle it on a field-by-field basis, then you can also implement hook_entity_field_access() and deny view access to just those specific fields.

That said, I would expect that the method isn't allowed to be called due to the twig sandbox that only allows is/get method calls, but then I'd kind of expect it to throw an exception.

I guess also with my suggestion, you'll need a way to check for something in the template but I would simply do that in hook_preprocess_node() then, add it as a boolean variable to $variables.


Well, now I feel stupid. Eventually it seemed to be a file permissions related issue.

I took this https://www.drupal.org/node/244924 script and modified it per server spec.

After few trials it worked...It certainly didn't seem like a permissions related but maybe they cause various situations.


The module versions must match the core version to work. Drupal 6 modules will not work on Drupal 7.


What are the equivalent functions that I should use for HTTP handling?

These are the functions/methods/classes that should be used in Drupal 8.6.x code.

drupal_access_denied() has been replaced from the AccessDeniedHttpException class. Page callbacks that need to return the Access Denied error should used code similar to the following one.

// system_batch_page()
public function batchPage(Request $request) {
  require_once $this->root . '/core/includes/batch.inc';
  $output = _batch_page($request);
  if ($output === FALSE) {
    throw new AccessDeniedHttpException();
  }
  elseif ($output instanceof Response) {
    return $output;
  }
  elseif (isset($output)) {
    $title = isset($output['#title']) ? $output['#title'] : NULL;
    $page = [
      '#type' => 'page',
      '#title' => $title,
      '#show_messages' => FALSE,
      'content' => $output,
    ];

    // Also inject title as a page header (if available).
    if ($title) {
      $page['header'] = [
        '#type' => 'page_title',
        '#title' => $title,
      ];
    }
    return $page;
  }
}

Instead of drupal_get_query_array() there is parse_query() (a function in the GuzzleHttp\Psr7 namespace), which is part of Guzzle.
drupal_goto() has been replaced from the RedirectResponse class. Page callbacks that need to redirect users should use code similar to the following one. (Notice that form submission handlers should not use this class.)

// AddSectionController::build()
public function build(SectionStorageInterface $section_storage, $delta, $plugin_id) {
  $section_storage
    ->insertSection($delta, new Section($plugin_id));
  $this->layoutTempstoreRepository
    ->set($section_storage);
  if ($this->isAjax()) {
    return $this->rebuildAndClose($section_storage);
  }
  else {
    $url = $section_storage->getLayoutBuilderUrl();
    return new RedirectResponse($url->setAbsolute()->toString());
  }
}

drupal_http_request() has been replaced from a Drupal 8 service that implements the ClientInterface interface. Drupal 8 code should be similar to the following one.

// system_retrieve_file()
try {
  $data = (string) \Drupal::httpClient()->get($url)->getBody();
  $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
} catch (RequestException $exception) {
  \Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]));
  return FALSE;
}

drupal_not_found() has been replaced from the NotFoundHttpException class. Page callbacks should use code similar to the following one.

// BookController::bookExport()
public function bookExport($type, NodeInterface $node) {
  $method = 'bookExport' . Container::camelize($type);

  // @todo Convert the custom export functionality to serializer.
  if (!method_exists($this->bookExport, $method)) {
    $this->messenger()->addStatus(t('Unknown export format.'));
    throw new NotFoundHttpException();
  }
  $exported_book = $this->bookExport->{$method}($node);
  return new Response($this->renderer->renderRoot($exported_book));
}

drupal_site_offline() should be replaced by an event subscriber, similar to the following one.

public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = ['onKernelRequestMaintenance', 30];
  $events[KernelEvents::EXCEPTION][] = ['onKernelRequestMaintenance'];
  return $events;
}

public function onKernelRequestMaintenance(GetResponseEvent $event) {
  $request = $event->getRequest();
  $route_match = RouteMatch::createFromRequest($request);
  if ($this->maintenanceMode->applies($route_match)) {
    // Don't cache maintenance mode pages.
    \Drupal::service('page_cache_kill_switch')->trigger();
    if (!$this->maintenanceMode->exempt($this->account)) {
      // Deliver the 503 page if the site is in maintenance mode and the
      // logged in user is not allowed to bypass it.
      // If the request format is not 'html' then show default maintenance
      // mode page else show a text/plain page with maintenance message.
      if ($request->getRequestFormat() !== 'html') {
        $response = new Response($this->getSiteMaintenanceMessage(), %03, ['Content-Type' => 'text/plain']);
        $event->setResponse($response);
        return;
      }
      drupal_maintenance_theme();
      $response = $this->bareHtmlPageRenderer->renderBarePage([          '#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page');
      $response->setStatusCode(503);
      $event->setResponse($response);
    }
    else {
      // Display a message if the logged in user has access to the site in
      // maintenance mode. However, suppress it on the maintenance mode
      // settings page.
      if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
        if ($this->account->hasPermission('administer site configuration')) {
          $this->messenger->addMessage($this
      ->t('Operating in maintenance mode. Go online.', [':url' => $this->urlGenerator->generate('system.site_maintenance_mode')]), 'status', FALSE);
        }
        else {
          $this->messenger->addMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
        }
      }
    }
  }
}

drupal_encode_path() has been replaced by UrlHelper::encodePath()
drupal_get_query_parameters() has been replaced by UrlHelper::filterQueryParameters()
drupal_http_build_query() has been replaced by UrlHelper::buildQuery(), which will be removed once Drupal core requires at least PHP 5.4 (At that point, it will be possible to directly use  http_build_query().)
drupal_parse_url() has been replaced by UrlHelper::parse()

Notice that, compared with earlier Drupal versions, there are some important changes. For example, some methods that were in the Url class has been moved in the UrlHelper class; some of the Guzzle classes aren't used anymore.


Why isn't the image added in the block settings shown in the front end?

I applied a patch for this module. This got disturbed due to the media module update.

At line no 300 in bb_animation.module.I changed the code

from

$file = file_load($background_image['fid']);

To

$background_image_data_type = gettype($background_image);
switch ($background_image_data_type) {
        case 'array':
            $file = file_load($background_image['fid']);
            break;
        case 'string':
            $file = file_load($background_image);
            break;
    }


Maybe you are using an old version of PHP. Have you tried also running "php -l your_file.php". That will run just the parser to see if you have any php syntax problem.


Remove number and reference list from mime mail plaintext emails

I have found the solution. Mimemail creates the plaintext version of the mail in mimemail.inc, in the beginning of the function mimemail_html_body():

  if (empty($plaintext)) {
    // @todo Remove once filter_xss() can handle direct descendant selectors in inline CSS.
    // @see http://drupal.org/node/1116930
    // @see http://drupal.org/node/370903
    // Pull out the message body.
    preg_match('|<body.*?</body>|mis', $body, $matches);
    $plaintext = drupal_html_to_text($matches[0]);
  }

And here the drupal_html_to_text() creates the plaintext mail with the footnotes and the url numbering. The plaintext is created here if one is not provided already. So, the simple solution is to provide the plaintext version ourselves.

My email templates are defined by my implementation of hook_mail, as text without html (and mimemail in itself creates a html version of my emails, and in the above function, creates again a plaintext version of the mail, with the footnotes and url-numbering). So, I can provide a plaintext version of the email in my implementation of hook_mail_alter:

    function mymodule_mail_alter(&$message) {
        $message['params']['plaintext'] = drupal_html_to_text(implode("\r\n\r\n", $message['body']));
}

(The $message['body'] is the array containing the message, with message rows as entries in the array). This might not need to be wrapped around the drupal_html_to_text() function, but in case i go nuts and start inserting html into my messages, that function will strip it off. If i start to write my emails in html, I need to write a custom function (almost a straight copy of the drupal_html_to_text() function) to create the plain text version of my mails, but without the footnotes and url numbering.

Thanks for your help, I would not have found this solution by my self.


How to call js and css file and replace the script in code

Create the JS and CSS files and then in the block view add them in the following way:

drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_css_file.css');
drupal_add_js(drupal_get_path('module', 'my_module') .'/js/my_js_file.js', 'file');

We have done something similar at a module we develop:
Guardian news


Bookings API versus existing spaghetti code

In answer to part (a) there is the Resource Conflict module, which appears to be similar in goal to the modules you mention above.

As for part (b) I'd argue that it is typically better to update or replace custom spaghetti code in such a way to work with existing modules--doing so will greatly ease the work of future maintainers of your code, and allow it to benefit from future enhancements to the Bookings API.


In template file for your field you can use good old PHP sprintf:

$right = sprintf("[%10s]\n",    $s); // right-justification with spaces
$left  = sprintf("[%-10s]\n",   $s); // left-justification with spaces

$right === "    monkey";
$left  === "monkey    ";

In your case
    <?php print $output; ?>

should turn into:

 <?php printf("[%10s]", $output); /* if you want spaces before string */?>


In the File Entity module, what is the purpose of multiple "Enabled displays" and "Display precedence order" for a single display mode?

I just can't think of a use-case where I would need more than one "display" for a single "display mode", where the first would not "validate" and therefore look at subsequent ones that are defined.

It's not a feature that I expect it used very much, but that is exactly the purpose.

An example, where one looks at the user agent, could be:

Let's say you're showing a video, a video player is your primary option.

Then there's a user agent that you recognize as a screen reader. Suddenly, showing video doesn't make sense. However, the audio still does, so you fall through the first option, to your second, which is an audio player, that only pulls in the audio stream, significantly reducing the bandwidth usage for both server and client.

Finally, a really low powered mobile device comes along, and then you simply default to displaying an image of the videos first frame, together with a link "Mail me this video", making it convenient for the user to find the video again when using a more powerful computer.


How can I validate a fieldset or any other kind of group in drupal Form API?

You could do it with custom code by implementing hook_form_alter() and then adding a custom validation function and checking for the relevant field values (I don't know anything about your form so I'm not going to write any code).

Or, you can use the field validation module, which allows you to configure via the drupal UI, extra field validation requirements.

It is a very flexible module and a couple of its validation options are:

Require some of several fields (in the field validation extras sub-module).
Require at least one of several fields

There are many more options so it would be worth playing with it to see if you can achieve what you want.


Here is an example of sortable table with pagination.

$header = [
  'id' => [
    'data' => $this->t('ID'),
    'specifier' => 'nid',
  ],
  'title' => [
    'data' => $this->t('Title'),
    'specifier' => 'title',
  ],
  'created' => [
    'data' => $this->t('Created'),
    'specifier' => 'created',
    // Set default sort criteria.
    'sort' => 'desc',
  ],
  'uid' => [
    'data' => $this->t('Author'),
    'specifier' => 'uid',
  ],
];

$storage = \Drupal::entityTypeManager()->getStorage('node');

$query = $storage->getQuery();
$query->condition('status', \Drupal\node\NodeInterface::PUBLISHED);
$query->condition('type', 'article');
$query->tableSort($header);
// Default value is 10.
$query->pager(15);
$nids = $query->execute();

$date_formatter = \Drupal::service('date.formatter');
$rows = [];
foreach ($storage->loadMultiple($nids) as $node) {
  $row = [];
  $row[] = $node->id();
  $row[] = $node->toLink();
  $created = $node->get('created')->value;
  $row[] = [
    'data' => [
      '#theme' => 'time',
      '#text' => $date_formatter->format($created),
      '#attributes' => [
        'datetime' => $date_formatter->format($created, 'custom', \DateTime::RFC3339),
      ],
    ],
  ];
  $row[] = [
    'data' => $node->get('uid')->view(),
  ];
  $rows[] = $row;
}

$build['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => $this->t('No content has been found.'),
];

$build['pager'] = [
  '#type' => 'pager',
];


The Menu position module will solve your problem.

  Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.


How to import multiple images with Feeds importer from CSV?

You can accomplish this with choosing a character to separate your image urls with in the CSV file and using the Feeds Tamper plugin "Explode".

Separate the image URLs in your CSV file with a certain character, for example a pipe character: "|". Your CSV file could then look something like this:

title,image
Lorem Ipsum,http://www.example.com/image1.png|http://www.example.com/image2.png
Install the module Feeds Tamper. Also enable the Feeds Tamper Admin UI module (included with Feeds Tamper).
Go the Tamper page of your feeds importer (/admin/structure/feeds/[importer_id]/tamper).
Click "Add plugin" for the "Image: URI" mapper.
For the plugin to add, select "Explode". As string separator, choose the character that you used to separate your image URLs. If you followed the example, then this would be the pipe character: "|". See also the image:

The explode tamper plugin cares that your input data (for example "http://www.example.com/image1.png|http://www.example.com/image2.png") is handled as multiple values.


Custom content type on registration form. No node title field

Do you need title or you want it because form gives you error? Maybe Automatic Nodetitles (http://drupal.org/project/auto_nodetitle) can help you? You can use that to have node automatic title like "Profile of [Name] [Surname]" and title will not be required field.


How can I programmatically set date field Month, Day, Year dropdowns in Paragraphs?

After trying just about every solution for the date I could find, I finally figured this out.

It seems that it doesn't even matter what the DB is wanting to save the date as. Looking in the DB, the date is being stored as Y-m-d without the trailing H:i:s. Most examples are saying that you need the full date in Y-m-d\TH:i:s format.

This particular dropdown widget for the date field wants only Y-m-d and I only found that out after trying to pass it all kinds of different date strings and it gave me an error message back about the format without the trailing H:i:s.

So all of that garbage that I tried to pass it earlier and formatting was way off. All I needed to do was this, and the paragraph saved properly and the form fields are reflecting the proper date now.

'field_program_year' => date('Y-m-d', strtotime('2011-11-12')),
'field_eligibility_range' => [
  'value'=> date('Y-m-d', strtotime('2011-11-12')),
  'end_value' => date('Y-m-d', strtotime('2011-11-12'))
],