Allow photos in advancd forum replies? I'm currently using the insert module to allow forum users to easily upload a image and insert it into the forum topic body. I'm looking for a way to allow users replying to a topic to do the same thing. So, for example, user A could create a thread titled "Post your photos on mountains here" and users could reply to the thread and post their photos.

I'm sure this is possible through the text editor with IMCE or similar, but I find that route to confusing for simple forum users. That's why i like the insert mod, select your file and hit upload/insert. simple. So, any alternatives or something I'm overlooking?

There is an option to add fields to comments.

From Structure -> Content Type select manage fields for the content type that needs image attached

There is a tab called "Comment Fields".

Select that, add and image field to it and that should do it. You would see an upload button in the comment.


Why does template.php override not work? I'm trying to get links from the PDFPreview module to open in a new tab. As described in this issue, overriding the formatter function in template.php does not work.  One can modify the function in the actual .module file, but this is obviously not good practice.  Why does it not work?

Code from the module:

/**
 * Theming functions for our formatters
 *
 * @todo Clearify the image cache thing...
 * @todo Let user choose what preview image to show on non-PDF files
 */
function theme_pdfpreview_formatter($variables) {
  $img_tag = '';
  $item = $variables['item'];

  $image = array(
    'title' => $item['description'],
    'uri' => $item['preview'],
  'alt' => $item['description'],
  );

  $element =array();
  $element['item'] = $image;
  $element['image_style'] = $variables['settings']['image_style'];
  switch ($variables['settings']['image_link']) {
    case 'file':
      $element['path'] = array(
        'path' => file_create_url($item['uri']),
        'options' => array(),
      );
      break;
      case 'content':
      $element['path'] = array(
        'path' => $variables['entity_type'] . '/' . $variables['entity']->nid,
        'options' => array(),
      );
      break;
  }
  $img_tag = theme('image_formatter', $element);
  $wrapper_tag = $variables['settings']['tag'];
  $description = $variables['settings']['show_description'] ? '<' . $wrapper_tag . ' class="pdfpreview-description">' . $item['description'] . '</' . $wrapper_tag . '>' : '' ;
  return sprintf(
          '
'
          . ' <%s class="pdfpreview-image-wrapper">%s</%s>'
          . ' %s'
          . '
',
          $variables['instance']['field_name'],
          $item['fid'],
          $wrapper_tag, $img_tag, $wrapper_tag,
          $description
  );
}

Code from template.php:

/**
 * Theming functions for our formatters
 *
 * @todo Clearify the image cache thing...
 * @todo Let user choose what preview image to show on non-PDF files
 */
function my_theme_pdfpreview_formatter($variables) {
  $img_tag = '';
  $item = $variables['item'];

  $image = array(
    'title' => $item['description'],
    'uri' => $item['preview'],
  'alt' => $item['description'],
  );

  $element =array();
  $element['item'] = $image;
  $element['image_style'] = $variables['settings']['image_style'];
  switch ($variables['settings']['image_link']) {
    case 'file':
      $element['path'] = array(
        'path' => file_create_url($item['uri']),
        'options' => array('attributes' => array('target' => '_blank')),
      );
      break;
      case 'content':
      $element['path'] = array(
        'path' => $variables['entity_type'] . '/' . $variables['entity']->nid,
        'options' => array(),
      );
      break;
  }
  $img_tag = theme('image_formatter', $element);
  $wrapper_tag = $variables['settings']['tag'];
  $description = $variables['settings']['show_description'] ? '<' . $wrapper_tag . ' class="pdfpreview-description">' . $item['description'] . '</' . $wrapper_tag . '>' : '' ;
  return sprintf(
          '
'
          . ' <%s class="pdfpreview-image-wrapper">%s</%s>'
          . ' %s'
          . '
',
          $variables['instance']['field_name'],
          $item['fid'],
          $wrapper_tag, $img_tag, $wrapper_tag,
          $description
  );
}

Use my_theme_pdfpreview, because even though there's a specific function assigned to it in hook_theme(), you should use the key to override.

I admit I got confused as well at first :)


How to identify which Rule is triggered? I have a collection of email notifications created with Drupal Rules module and a separate custom database table with the ID's of the rules and emails to exclude from individual notifications.

I need to know which rule is being triggered so I can query my custom table for the correct emails to exclude. Creating custom conditions would not work because I have 20+ rules using the same custom action.

The only hook that I can find that is triggered after a rule is executed is hook_rules_config_execute but it does not give me information only on the specific rule that triggered.

Below are 2 approaches that might work ...

Approach 1

Create a NEW Rules Component like so:

It uses some "identifier" as a parameter, of type something like "text" or "integer".
All this component does, is to also perform your custom action.

For each of your existing rules, rework that Rules Action like so:

Replace it by performing the new Rules Component.
For the (required) parameter of the Rules Component, use some unique value (just an integer, or maybe the machine name of the rule?), so that when the Rules Component is executing, you do know which rule it was that triggered the execution of the Rules Component.

Approach 2

Update each of your rules to contain and pass in a unique identifier. You can just do that by adding another parameter to the existing Rules Action in your rules_action_info hook. Though you'd have to update all your existing rules to make that work.


I want to enable a disabled input format I considered 'restricted HTML' as unnecessary and set it ‘disable’.
Because I thought it possible to re-enable.
However, I have not found a disabled format on UI.

Since there is no choice, I decided to newly register.
The same registration as the default machine name 'restricted_html' conflicts.
Imagine the data is left somewhere.
I could not find it even if I looked for a database.
Is it possible to restore by setting file or something?

I am using Drupal 8.4.2.

This is a known issue, though you are warned before you disable the textformat that this cannot be undone. See the issue Disabled text formats can't be seen in the GUI and the comment #60:

  It is possible to reenable disabled text formats with the
  configuration manager:

  go to /admin/config/development/configuration/single/export
  choose Text format as the Configuration type
  choose the disabled text format as Configuration Name
  copy the configuration
  go to /admin/config/development/configuration/single/import
  again choose Text format as the Configuration type
  paste the configuration
  change "status" from false to true
  click on import

  Voilá, the text format is available again. This is working but not
  user friendly :(


How do I create product and product display once, like in Commerce Kickstart? In Kickstart you just go Add Product and it creates both, the Product for admin area product list and the Product Display. How do I do that in regular Drupal install with regular Commerce module? Because now I have to go each time to create the actual product for admin product list and then go create a product display for users. Isn't that a bit annoying?

I cannot use Kickstart, it's too late already and it's too big and overcrowded with too much of not needed features.

This is through the contributed module Inline Entity Form.


Three level tab on user profile page I am trying to show a 3 level tab on the user profile page, but I cannot find a way of doing it.  I've managed to get a second level working, on my custom module on drupal 7.

<?php
/**
 *patners page with all the tabs
 */

$items['user/%user/patners'] = array(
    'title' => t('My deals'),
    'description' => t('this is to show patners ther items'),
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access arguments' => TRUE,
    'type' =>MENU_LOCAL_TASK,
    'weight'=>-18,
);
$items['user/%user/patners/coupon'] = array(
    'title' =>'??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/statistics'] = array(
    'title' => '?????????',
    'page callback' => 'partners_statistics',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/all'] = array(
    'title' =>'??? ??????',
    'page callback' => 'patners_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['user/%user/patners/coupon/used'] = array(
    'title' =>'????????????',
    'page callback' => 'patners_coupon_used',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
$items['user/%user/patners/coupon/pending'] = array(
    'title' =>'??????',
    'page callback' => 'patners_pending_coupons',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);
return $items;
?>

Drupal doesn't provide third level local tasks by own. You have to implement it, something like this:

/**
 *  @see: menu_local_tabs()
 */
function my_module_menu_local_tabs() {
  return array(
    '#theme' => 'menu_local_tasks',
    '#primary' => menu_primary_local_tasks(),
    '#secondary' => menu_secondary_local_tasks(),
    '#tertiary' => my_module_tertiary_local_tasks(),
  );
}

/**
 * @see: menu_secondary_local_tasks()
 */
function my_module_tertiary_local_tasks() {
  // The index of local task starts from 0, so you need the 2 level of local tasks.
  $links = menu_local_tasks(2);
  // Do not display single tabs.
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
}

function my_module_preprocess_page(&$vars) {
  $variables['tabs'] = my_module_menu_local_tabs();
}

All of this code based on core's localtask generation function, it's normally alterable, translation-ready, access checked:

menu_local_tabs()

menu_secondary_local_tasks()


check if user exists I want to check if user exists based on some profile2 field. I have tried the following. Works fine. I want to know if it is proper or not. If it is not proper, is there any other way around?

function checkUserExistsByProfile($company_id){

        $query = 'SELECT field_somefield_value
        FROM {field_data_field_somefield} AS fn
        WHERE fn.field_somefield_value  =:rids';
        $result = db_query($query, array(':rids' => array($company_id)));

        $field_value = $result->fetchCol();
        return count($field_value);

    }

Please suggest.

UPDATE:

I have tried solutions suggested by  Mołot, Bulat as follows.

Profile Field name is field_ngouniqueid

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->fieldCondition('field_ngouniqueid', 'value', (int)$company_id, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));

But users is an empty array always. But it has a record with value $company_id

Solution:
it should be $query->entityCondition('entity_type', 'profile2')

To get the users filtered based on profile2 field, field_ngouniqueid is created through profile2

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
->fieldCondition('field_ngouniqueid', 'value', (int)$company_id, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));


Feed's Regex find replace problem Hello Drupal community,

I'm finding some issues in a tamper used in feed's module. I want spaces to be deleted in a field that contains numbers. Something that changes "00 00 00 00 00" into "0000000000".
I've tried the following :

    Regex to find : #(\d{2})[ ](\d{2})[ ](\d{2})[ ](\d{2})[ ](\d{2})#
    Replacement pattern : $1$2$3$4$5

Note that the expression was validated in https://regex101.com/ :

But it doesn't seem to work.
Anyone please ?

Try giving Limit number of replacements  value as -1 This will solve your issue.


Cause for Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: error Currently trying to port over a Contrib module and learn the new Drupal 8 architecture.

A google search revealed a possible issue related to this.

The cause could be that there's an underscore in the file name which violates psr-0 naming standards. Looks like i had that before and have renamed it just now and still have that issue after clearing the cache.

What would likely be the cause of the following error?

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  You have requested a non-existent service
  "\drupal\form_example\forms\formexampleformone". in
  Symfony\Component\DependencyInjection\Container->get() (line 304 of
  /home/chris/workspace/d8/core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

The error occurs when i visit /examples/form_example/tutorial/1

form_example.routing.yml

form_example:
  path: 'examples/form_example'
  defaults:
    # _form: '\Drupal\form_example\Forms\FormExampleForm'
    _content: '\Drupal\form_example\Controller\FormExampleController::description'
  requirements:
    _access: 'TRUE'
form_example_tutorial_1:
  path: 'examples/form_example/tutorial/1'
  defaults:
    _form: '\Drupal\form_example\Forms\FormExampleForm'
  requirements:
    _access: 'TRUE'

form_example.module

<?php
function form_example_menu() {
//   $items = array();
//   $items['examples/form_example'] = array(
//     'title' => 'Form Example',
//     'route_name' => 'form_example',
//     'access callback' => TRUE,
//     'expanded' => TRUE,
//   );
  $items['examples/form_example/tutorial'] = array(
    'title' => 'Form Tutorial',
    // 'page callback' => 'drupal_get_form',
    'route_name' => array('form_example_tutorial'),
    'access callback' => TRUE,
    'description' => 'A set of ten tutorials',
    // 'file' => 'form_example_tutorial.inc',
    // 'type' => MENU_NORMAL_ITEM,
  );
  $items['examples/form_example/tutorial/1'] = array(
    'title' => '#1',
    // 'page callback' => 'drupal_get_form',
    'route_name' => array('form_example_tutorial_1'),
    'access callback' => TRUE,
    'description' => 'Tutorial 1: Simplest form',
    // 'type' => MENU_DEFAULT_LOCAL_TASK,
    // 'file' => 'form_example_tutorial.inc',
  );
  return $items;
}

/lib/Drupal/form_example/Forms/FormExampleForm.php

<?php
/**
 * @file
 * Contains \Drupal\form_example\Form\FormExampleForm
 */
namespace Drupal\form_example;

use Drupal\Core\Form\FormInterface;

class FormExampleForm extends FormBase {
// form...
}

Looks like the namespace defined in your class file does not match the one you put into the resource, there's a "Form" sub-namespace missing.

Also make sure that the class is placed in the right folder.

The reason for that error is apparently that for some reason, the specified class can't be found, so apparently the router then falls back to the service. So the _ thing is just one possible reason.

Also, there are some errors in your hook_menu(), route_name is a string, access callback can be removed and you still need the first entry for now so that you have a menu link to it.


How do I allow users to determine which other users can edit their content? I'd like to let users specify which other users may edit their content. Basically a user would be able to create a piece of content, which they are then allowed to edit but no other users can edit (accept "admins"). This is all standard Drupal stuff so far and very easy. But now I'd like to let the user give permissions to other specific users to edit the content they created. So, the "creator" can now assign "editors", letting other users edit the content the original user created.

In case this isn't quite clear yet, here is a use case...

A site sells subscriptions which allow privileged users to create a Project on the site (Project in the sense of a software development project). The user who purchased the subscription can now create nodes of various content types that make up the content of the Project. But since no one likes to work alone, they can invite others to their Project. The invited users can edit any content created by the user who purchased the subscription.

So... how do I allow a user to specify certain other users which can edit his/her content and give those selected users edit permissions on all nodes created by the original user?

Node access user reference worked for me, and was quite easy to use from the users perspective.


How can I change field suffix due to its value I have a field which is of type number.

I have a view where this field is shown with its suffix. I want it to change when the value of a field is more than 1.

Is it possible to do something? Maybe some preprocess function or some module?

Thanks for any help.

Views Conditional would be worth giving a try. The module pages says -

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To Not Equal To Greater Than Less Than Empty Not Empty Views
  conditional allows you to output text based on the result of the
  condition.


Drupal 7 live preview module I have recently been looking for module that will allow you to preview the page you are creating, in real time as you are creating it (just like SE questions). I came across the live module, but I realized that it was only for drupal 5 and 6. Is there a similar module that allows you to preview your page live, for Drupal 7?

I've given this problem some thought (actually began writing code for a D7 live preview), and as it happens I simply don't think live preview is that simple in Drupal.

Live preview on SE.sites is efficient because there are no AJAX requests going on for rendering the preview. In a nutshell SE.sites merely clone the text from the editor textarea into the preview div, where CSS classes are applied to it. In reality there is more processing happening in the background as the text that you enter must be converted into real markup (ie, when using lists).

In Drupal however there can be a lot of pre-processing of text, depending on what modules you have enabled. For instance, take the <!--break--> control sequence (which is part of core behavior, btw). Does that really mean something in HTML? No, it must be preprocessed by Drupal into teaser and full body text snippets; take the CKEditor and the IMCE modules for example, they also depend on preprocessing text to translate special markup for images into actual <img> tags.

What that means is that in order to have a live preview that is faithful to it's final state, you must run whatever text you enter through a number of hooks, preprocessors, renderers and what have you. Else your live preview will not represent the final product. Therefore, having a faithful Live Preview in Drupal would mean sending an AJAX request to the back-end every time the editor in the front-end is updated. And then, you can ask yourself the question? Is this scalable? That would probably depend on your use case. If you want Live Preview for a site with a big editorial team (think www.nowpublic.com, a Drupal site), the answer would probably be no. But maybe if it is for a small site, with a few visitors or editors, then the answer would be maybe, but it still raises performance concerns.

So taking those points into consideration, what kind of preview would you be looking for? Slow & Faithful or Fast and Unfaithful?


Filter product displays by parent taxonomy term I'm running a music store and have a taxonomy term field on products that that is used for the product's format. We tag the products from the following vocabulary.

Vinyl

140g vinyl
180g vinyl

CD

Jewelcase
Digipack

Digital

Mp3
FLAC

I'd like create an exposed filter on the product catalog using the parent terms, Vinyl, CD, Digital. When one of taxonomy terms is selected, the filter should display all products tagged with the child terms.

The Content: Has taxonomy terms (with depth) filter doesn't seem to work with referenced products. I'm not seeing a solution in the Taxonomy Entity Index module either (but I might be wrong).

With a view using Products as base_table:

Add a relationship using the taxonomy reference field you're using and do not require the relationship
Add an exposed filter `Content: Has taxonomy terms (with depth)
In the settings, set the depth to the level you want
In the exposed filter itself, you can configure whether multiple values can be selected or not.

But before all that, you need to make sure that only the child terms are selected on the products.


how can i get Drupal webform confirmation message on popup? I have been surfing for a solution since yesterday, got hell lot of irrelevant solution.
My requirement is very simple,

  I just want to get the conformation message(Thank you, your submission has been received.) in a popup window.

tried several modules not satisfied. Friends please help me out, its urgent for me.

Here is an example using a custom module (called it wcm_overlayer). Basically, this will show the confirmation message in an overlayer using the jQuery Fancybox library. For the webform configuration (under form settings), you need to set the redirection location setting to No redirect (reload current page).

wcm_overlayer.module

/**
 * Implements hook_init()
 */
function wcm_overlayer_init()
{
    // Add library & js file
    drupal_add_library('wcm_overlayer', 'fancybox');
    drupal_add_js(
        drupal_get_path('module', 'wcm_overlayer') . '/js/wcm_overlayer.js');
}

/**
 * Implements hook_node_view()
 *
 * @param type $node
 * @param type $view_mode
 * @return boolean
 */
function wcm_overlayer_node_view($node, $view_mode)
{
    // Verify if webform is attached to a node
    if (!isset($node->webform)) {
        return false;
    }

    // Retrieve confirmation message
    $confirmation_message = check_markup(
        $node->webform['confirmation'], $node->webform['confirmation_format']);

    // Retrieve all status message
    $messages = drupal_get_messages('status');

    // None is found, don't do anything
    if (!isset($messages['status'])) {
        return false;
    }

    // Loop through all messages and get confirmation message
    foreach ($messages['status'] as $message) {
        if ($message !== $confirmation_message) {
            drupal_set_message($message);
            continue;
        }

        $found = true;
    }

    // Confirmation message is not found, don't do anything
    if (!isset($found)) {
        return false;
    }

    // Confirmation message is found, pass this as a setting
    drupal_add_js(array(
        'wcm_overlayer' => $confirmation_message,
    ), 'setting');
}

/**
 * Implements hook_library()
 *
 * Define the jQuery Fancybox 1.3.4 as a library
 * @return string
 */
function wcm_overlayer_library()
{
    $path = drupal_get_path('module', 'wcm_overlayer');

    $libraries['fancybox'] = array(
        'title' => 'jQuery Fancybox',
        'version' => '1.3.4',
        'js' => array(
            $path . '/js/vendor/jquery.easing.js' => array(),
            $path . '/js/vendor/jquery.mousewheel.js' => array(),
            $path . '/js/vendor/jquery.fancybox.js' => array(),
        ),
        'css' => array(
            $path . '/css/vendor/jquery.fancybox.css' => array(),
        ),
    );

    return $libraries;
}

js/wcm_overlayer.js

(function ($) {
    Drupal.behaviors.wcm_overlayer = {
        attach: function(context, settings) {
            if (!settings.hasOwnProperty('wcm_overlayer')) {
                return false;
            }

            this.showOverlayer(settings.wcm_overlayer);
        },
        showOverlayer: function(message) {
            $(window).load(function() {
                $.fancybox({ content: function() {
                        return $(message);
                }});
            });
        }
    };
}) (jQuery);

Hope it helps.


Is it possible to create 'grouped' fields of related data? I have a content type (Recipe) in which my users can add ingredients (terme references). I also have a text field to enter quantity
How is it possible to link this "ingredient" field to the quatity field?

I want to recreate something like this (from Recipe module) :

You could use the Paragraphs module OR Field Collection module

Example (from paragraphs):

Then with a little CSS magic, you can put them side by side, if you really want it like that.


Order item with persistent custom field value Goal
With Drupal Commerce, my goal is to have a customizable product with persistent user entered text.
I have added a text field to the order item type and I can see the custom field in the "add to cart" form. When customer enters a value in that field and adds the product to the cart, I can see the value of that field in the cart form view.
I want to have a link to the purchased entity in the cart form view so I checked "Link label to the referenced entity" in the view field configuration.
When I hit that link, I get back to my product page, with the correct variation selected, but the custom text field will be empty.
Question
How can I make this custom text field persistent, that is, "save" its value so that when I click the item link in the cart view, I get back to the product variation with the custom text field already filled in?
Note: I could have multiple products/variations in the cart, each with a different custom text so I need to keep the value on the order item level.
What I have tried
I thought about having that custom text field value as a parameter in the cart form view purchased entity link URL so I tried to rewrite the output of that field/link, but I don't have access to the product entity from that view and I'd need it to compute the new URL... so that won't work.
Any idea?

I couldn't find a more elegant way but this works for me.
First I rebuild the purchased entity link in the commerce cart form view to include the custom text field value as a parameter in the link URL for when I navigate back from the cart to the product variation:
/**
 * Implements hook_preprocess_views_view_field().
 */
function MYMODULE_preprocess_views_view_field(&$variables) {

  $view = $variables['view'];
  $field = $variables['field'];

  // Commerce cart form
  if (isset($view) && ($view->id() === 'commerce_cart_form')) {

    switch($field->field) {
      case 'purchased_entity':

        // Get purchased entity
        $purchased_entity = $variables['row']->_relationship_entities['order_items']->purchased_entity->getValue();
        $purchased_entity_id = $purchased_entity[0]['target_id'];

        // Load product variation
        $product_variation = $variation = ProductVariation::load($purchased_entity_id);

        // Get product variation URL
        $url = Url::fromUserInput($product_variation->toLink()->getUrl()->toString());

        // Get custom field value
        $custom_field = $variables['row']->_relationship_entities['order_items']->field_custom->getValue();

        // Rebuild url with variation & custom field value
        $url->setOption('query', [
          'v' => $purchased_entity_id,
          'custom' => $custom_field[0]['value'],
        ]);

        // Output
        $variables['output'] = Link::fromTextAndUrl(t($product_variation->label()), $url);

        break;
    }
  }
}

This will output a link like /product/1?v=2&custom=MYVALUE
And then on the product add to cart form, if the param is in the URL, I set the default value of the custom field:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if (strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce_product_') !== false) {

    // Set custom text form field value from URL
    $form['field_custom']['widget'][0]['value']['#default_value'] = \Drupal::request()->query->get('custom');
  }
}


Moving, Removing, Disabling Administration on live server On my staging server people should be able to access the administration to add, delete or edit content. The complete installation including the database is then deployed to a live server. On the live server I don't want anyone to be able to access the administration. In other words if a user goes to mylivesite.com/admin the response would be a 404 - not found. What would be the best approach to achieve this?

The best approach would be to deny access to the administration pages for certain roles on your live site using standard Drupal permissions ( http://example.com/admin/people/permissions ).

The permission you're looking for is called "Use the administration pages and help".

Returning a 404 for all admin pages doesn't seem like the correct thing to do here, as the page has been found. A 403 is the correct semantic response for this.

If you're desperate, having the following code in a module on your live site only would do the trick:

function MYMODULE_init() {
  if (arg(0) == 'admin' && $GLOBALS['user']->uid != 1) {
    drupal_not_found();
  }
}

But I can't say I'd recommend it :)


Custom tpl for view mode for all contenty type I've saw How to provide template for particular view mode?, but I don't to create a single tpl for every content type for a particular view mode, but a tpl used for every content type for a particular view_mode, something like node--search-results.tpl.php

Is it possible?

Certainly, just add the following code to your theme's template.php file (replacing MYTHEME with the name of your theme):

function MYTHEME_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
}

And remember to clear the caches


Simple node access control for users Users have 'edit own content' permission for content type 'diary'. When viewing own diary node, I would like to present a simple checkbox to 'make private'. Then only that user can view the node.

I've looked at some options for doing this:

1) Write a module that uses hook_node_access() - overkill?

2) Perhaps an existing content access module provides a useful hook?

3) Create a 'private yes/no' field, then use Editablefields module to expose it on view. Then use theming layer to hide if set to 'yes'. - clunky?

I'm learning to write simple modules so perhaps a good learning opportunity here, but not sure where to start.

I think you should create the field as suggested in 3 regardless of which method you choose for authorizing users to view content. Your first suggestion seems reasonable.
I would personally opt for method two, and use the Page Manager in Ctools. PM is a tool however, and as such requires both understanding and configuration to do what you ask.
Your third option, hiding in the theme, seems wrong however.


How to run `drush make` on the existing Drupal installation? Whenever I try to run this command for a second time I get an error.

drush -v make /home/testdev/xipdrupalbasic.make /home/testdev/drupal

Loading release_info engine.                                            [notice]
Base path /home/testdev/drupal already exists                           [error]
Command dispatch complete

I get why it gives me this error, but I would like a way of giving a force or overwrite command with it so it still runs. I get the error because it tries to make a directory that already exist.

I already tried  the adding -r to it but it will then just install it in the directory you execute the command.

When i just do:

drush -v make /home/testdev/xipdrupalbasic.make

in the directory where I want it, it will work without a problem.

You can run drush make again on the existing Drupal installation, but you've to specify --no-core parameter.

  drush make --no-core                      Build an installation profile within an existing Drupal site


How can I add points for selected answers to questions implemented using Polls? The users of my page have to answer a test, which I'm making with the Polls module.

I have a custom currency called "points". The users points have to grow when they answer the test correctly, in order to buy things in the store with Drupal Commerce.

I really don't know how to do this, any suggestions?

By using the Rules module, and some extra work, you can get this to work, as detailed below ...

Step 1: Use Rules to grant User Points

Use Rules to create a custom rule with a Rules Action that grants points (using the User Points module). Have a look at the rules exammple included in my answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?", especially the very first Rules Action in it. Here is how that Rule looks like:

{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

The 2nd and 3rd Rules Action is rather to facilitate testing (you may want to ignore those Actions after QA-testing).

Step 2: Make (core) Poll trigger the Rule

To continue with the Rule from Step 1, you don't want to use that Rules Condition there, so just delete that. However the crucial part for your case is to have an appropriate Rules Event to replace the event used in the Rule from Step 1. In your case you want to use a Rules Event like "When user casts a vote".

Guess what, there seems to be a (sandbox) module that provides exactly that Rules Event: the Poll Rules Integration. If you don't want to use a sandbox project, then just look at this project to see what's needed for that event to build your own custom module to create such event.

Step 3: Further complete your Poll-puzzle

After you complete Step 1 and 2 above, the only thing left to complete your "puzzle", is to implement an appropriate Rules Condition to check "if they answer the test correctly" (as in your question, for which you did not specify any further details).


How to show in pop up box message in D7 I am developing custom module in D7. And created one custom block. And how can show the conent in the block as pop up box?sample block code is  `

  $block['content'] = t('Test message');

I want show 'Test message' as in pop up..

`

There are several modules that you may be able to use or deconstruct to help with your custom module.

Popup (D7)
Lightbox2 (D6, D7)
Shadowbox (D5, D6, D7)
Popups (AJAX) (D6)


Uncaught exception thrown after moving my website to localhost My website works right on server, I took a backup from database and public_html in order to have a copy of my webstie in localhost.

I imported the database but it reported an error, some thing was wrong with content of  cache_views table, so I emptied this table and database successfully imported. I replaced public_html with the old one and configured settings.php. but it doesn't work, it reports this error :

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = &#039;default&#039;; Array ( [:language] =&gt; fa [:source] =&gt; Makes the view results available as a context for use in Panels and other applications. [:context] =&gt; ) in locale() (line 684 of C:\xampp\htdocs\test\modules\locale\locale.module).

Additional:

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] =&gt; 0 [:db_insert_placeholder_1] =&gt; php [:db_insert_placeholder_2] =&gt; %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] =&gt; a:6:{s:5:&quot;%type&quot;;s:12:&quot;PDOException&quot;;s:8:&quot;!message&quot;;s:455:&quot;SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = &amp;#039;default&amp;#039;; Array ( [:language] =&amp;gt; fa [:source] =&amp;gt; Makes the view results available as a context for use in Panels and other applications. [:context] =&amp;gt; ) &quot;;s:9:&quot;%function&quot;;s:8:&quot;locale()&quot;;s:5:&quot;%file&quot;;s:52:&quot;C:\xampp\htdocs\test\modules\locale\locale.module&quot;;s:5:&quot;%line&quot;;i:684;s:14:&quot;severity_level&quot;;i:3;} [:db_insert_placeholder_4] =&gt; 3 [:db_insert_placeholder_5] =&gt; [:db_insert_placeholder_6] =&gt; h t t p://localhost:81/test/ [:db_insert_placeholder_7] =&gt; [:db_insert_placeholder_8] =&gt; 127.0.0.1 [:db_insert_placeholder_9] =&gt; 1389935326 ) in dblog_watchdog() (line 154 of C:\xampp\htdocs\test\modules\dblog\dblog.module).

I solved the problem this way: set max_allowed_packet = 4M to the file php.ini


Creating and storing data in the database I have created a forum in administer->modules in Drupal 6, and I have set the permissions also, but it is not showing in my site.
I do not know how the forum contents will be stored in database, and how to establish a connection to the database.

You don't have to worry about the database. But do some reading on how the forum works. If you're not getting any error messages you probably didn't set it up correctly.

Visit this page to see a list of all your forums: www.example.com/admin/content/forum/list

And some reading:

The Drupal forum tutorial
Forum: create threaded discussions - there are sub-menus depending on your version of Drupal


How to use hook_block_view_MODULE_DELTA_alter on Views-exposed form? I want to use hook_block_view_MODULE_DELTA_alter to modify a Views-exposed form. The URL path to the configuration page for the block is:

admin/structure/block/manage/views/-exp-resources_by_subject-page/configure

As you can see, it's delta value is -exp-resources_by_subject-page, which means my hook_block_view_MODULE_DELTA_alter now becomes:

function mymodule_block_view_views_-exp-resources_by_subject-page_alter(&$data, $block) {}

This, of course, returns an error:

Parse error: syntax error, unexpected '-', expecting '('

I don't want to use hook_block_view_alter as mentioned here because, as that is called for all blocks.

I think this is an issue with block module and may be you get your answer here. Please check the url

https://www.drupal.org/node/1076132
https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view_MODULE_DELTA_alter/7


add product with special price to cart drupal7 I used the following code to implement "add to cart" in my tpl.php file, and it works fine:

$product=commerce_product_load($node->field_product['und'][0]['product_id']);
$line_item = commerce_product_line_item_new($product,1);
$line_item->data['context']['product_ids'] = array($product->product_id);
$show_quantity = TRUE;

$form = drupal_get_form('commerce_cart_add_to_cart_form', $line_item,$show_quantity);
print render($form);

Right now, it can only use its original price. However, I want to add this product with a special price to the cart and use this special price to checkout.

I have already created a "Price" field named "field_special_price", and if I use print_r($product), I can see its value and can use the value by $product->field_special_price['und'][0]['amount']

You need to use a rule that acts on the "Calculating the sales price of an item" and then set the price using that rule. Here is an example: https://drupalcommerce.org/user-guide/sell-price-calculation


How do I get line breaks when using Plain Text format? I feel like this should be reaaaaaally simple, but it's driving me crazy.

I have 'plain text' selected for all my Body elements. I don't want anyone to be able to put in any html at all when filling out forms.

However, I do want the line breaks preserved.  On the configuration page for plain there there is indeed a 'check this box to to turn line breaks into br and p, but no matter what I check or how I rearrange the weight of the filters, I cannot get it to preserve the breaks.

What is the correct configuration to get this to work so that I can preserve returns in the texts?

This seems like a Drupal 7.x bug.
Changing the order of filters doesn't work in my case.

My short term solution was to throw this inside my theme's template.php (ref):

<?php
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}
?>

For fields in views, it's needed to set this option separately in the "Rewrite Results" section of the field settings.


Select users with only one role How can i select all users wich have only 1 role.
For example i got 4 users:

User 1:

Role 1,
Role 2

User 2:

Role 1

User 3:

Role 1,
Role 2

User 4:

Role 1

How can i retrieve a list of users wich only got Role 1? But not Role 2.

$query = db_select('users', 'u');
$query->leftJoin('users_roles', 'ur', 'u.uid = ur.uid');
$query->leftJoin('field_data_field_full_name', 'n', 'u.uid = n.entity_id');
$query->condition(...);
$query->fields('u', array('uid','name','picture'));
$query->fields('n', array('field_full_name_value'));
$result = $query->execute()->fetchAll()

EDIT:

SELECT
u.uid AS uid,
u.name AS name,
u.picture AS picture,
n.field_full_name_value AS field_full_name_value,
f.field_function_value AS field_function_value,
pi.field_phone_intern__value AS field_phone_intern__value,
ur.rid AS rid,
COUNT(*) AS rolecount
FROM `dev_drupal_wurth-intranet`.users u
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.users_roles ur ON u.uid = ur.uid
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_full_name n ON u.uid = n.entity_id
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_function f ON u.uid = f.entity_id
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_phone_intern_ pi ON u.uid = pi.entity_id
GROUP BY u.uid;

This give me the result all the users and their number of roles. Now i tried to filter on this role count with 'WHERE rolecount = 1' but this just gives and sql error.

I'm not very advanced in sql :), still learning.

Thx

If I were you (and with my poor level), I would proceed in 2 steps:

Get all the users with the role that interests you. Maybe inspire yourself for the query here: Get all users with specific roles using EntityFieldQuery
Browse the query result by loading each user and check if $user->roles has another role than the one you are looking for.
Push the final results in another array.

I don't know if it is a good way to proceed or if there is another way to achieve this, but I think it could do the trick.


Outputting recent comments in a different part of the node I have created a custom node, and at the bottom of this node I would like to show the latest three comments made on that node. I have added the code below to my template.php, and then loop through the array to get the data in my node:

if ((arg(0) == 'node') && is_numeric(arg(1)))
{
    $result = db_query_range('SELECT c.cid, c.nid, c.subject, c.name
    FROM {comment} c WHERE c.nid = :cid ORDER BY c.cid DESC', 0, 3, array(':cid' => arg(1)));

    $i = 0;
    foreach ($result as $record) {
        $variables['NewComments']['NewSubject'][$i] = $record -> subject;
        $variables['NewComments']['NewName'][$i] = $record -> name;
        $i++;
    }
}

else {
    $variables['errorCheck'] = t('nope fail');
}

However, I am having trouble outputting this into the node.tpl. Is there an easy way to do this, or should I try something else to tackle this issue?

Thanks

You can do that using views.

Then you can either add this view as a block or you can use http://api.drupal.org/api/views/views.module/function/views_embed_view/7 in node.tpl.php


Mime mail system attaching two files I am trying to send pdf through using mime mail module + mailsystem module + smtp authentication module

function send_mail(){
$to='xx@gmail.com'; $subject='xxxx'; $message='aaaaa';
$from='x123@gmail.com';
$my_mail_token = microtime();
$message = array(
'id' => $my_module . '_' . $my_mail_token,
'to' => $to,
'subject' => $subject,
'body' => array($message),
'headers' => array(
'From' => $from,
'Sender' => $from,
'Return-Path' => $from,
'Content-type' => 'text/html; charset=UTF-8',
 ),
);
 $attached=$message['params']['attachments'][]  = array(
'filename' => $filename,
'path' =>DRUPAL_ROOT.'sites/default/files/pdf'.'/'.$uid.'/'.$filename,
'filecontent' => file_get_contents('sites/default/files/pdf'.'/'.$uid.'/'.$filename),
'mime' => 'application/pdf',
'Content-type' => 'application/octet-stream',
'encoding' => 'base64',
'disposition' => 'attachment',
'list' => TRUE
);
$system = drupal_mail_system($my_module, $my_mail_token);
//unlink('sites/default/files/pdf'.'/'.$uid.'/'.$filename);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
}
else {
return FALSE;
    }
}

This is the code its sending two files as mail attachments instead of one. Why its doing that i cant understand. Looking for help.

This happens usually when you provide both filepath and filecontent.

Please check this answer: https://drupal.stackexchange.com/a/186157


How do I render this code in block/node page? print render($page['content']['system_main']['nodes'][$nid]['rc_core_item_avail_form']);

I tried putting this into a node in the Omega theme and also in a block directly but nothing at all. Can anyone help?

You cannot use that code in a node or in a block, since in both the cases the $page variable is not available. It seems that code is taken from an implementation of hook_page_alter() or adapted from code used by an implementation of hook_page_alter(). In fact:

hook_page_alter() receives $page as argument
The documentation for hook_page_alter() shows that, for a node page, $page['content']['system_main']['nodes'][$nid]['body'] is the content of a node body

If rc_core_item_avail_form is a node field, in a block you could use code similar to the following one.

// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
print render($elements);

In the case the field could not be visible to every user, but you want to make that field visible to every user when it is shown in the block, then I would use the following code.

// Load the currently shown node.
$node = menu_get_object();

// Render the field.
$elements = field_view_field('node', $node, 'rc_core_item_avail_form');
$elements['#access'] = TRUE;
print render($elements);


How to hide blocks from administrator? I need to hide some blocks from priviledged user so he won't be able to attach them to regions via the Block layout. What is the proper way of doing this?

Please open a feature request in the core queue for 'no ui' blocks. This currently does not exist but it's an interesting (and probably necessary one).


Adding Google maps to a page I'm trying to add google maps into the header of a view, nothing fancy, as I just used the demo code from the google maps page.

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=myKey"
          type="text/javascript"></script>
        <script type="text/javascript">

        jQuery(document).ready(function() {
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);

            var marker = new GMarker(map.getCenter());
            GEvent.addListener(marker, "click", function () {
              marker.openInfoWindowHtml("Hello");
            });
            map.addOverlay(marker);
          }
        })

        </script>

But for some reason I'm getting this error:

  Uncaught TypeError: Cannot read property 'firstChild' of null

I have no idea what is going wrong.

Do you have an HTML element with the id of "map_canvas" anywhere on the page?

Also I'm assuming you actually have your API key in your first script tag and it doesn't actually say "myKey".


Drupal node_load display all fields I have a template for a view in which I load a node. Is there a way to get the value of all fields from that node? Like, if I add another field in CCK it will appear automatically in the template.

Something like:

foreach $node->field
     print $value

Thanks!

Try node_view

<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

Read: Rendering Drupal 7 fields (the right way)


How to pass arguments from views to node.tpl.php Is there a way to pass arguments from views to a node template other than via selecting build modes? I use node as row style.

I used display suite + node displays to set up a custom build mode. In my node-"content type".tpl.php I then can decide via

$node->build_mode

what to render.

But first I feels like way over the top to install display suite + node displays just to pass one argument and second I ran into problems with this configuration. Everything looks fine in view's preview but after saving the view I got a "merory size exhausted" error.

So when there's time I try to reproduce this with a clean install an file a bug but at the moment I would be happy to know if there's another way to pass parameters from views to my node templates.

I finally got it. There's the Build modes module that does exactly what I want and only that.


External login , in case internal login fail I have a website which needs to authenticate users using drupal users table.

If authentication fails, then I want to run the authentication against users table from another database.

lf authentication is successful , then I want to register this user inside drupal, so the next this user next time he logs in , he get authenticated from drupal users table , not the external users table.

I wish to get a complete solution for that.

the following code is my attempt :

function external_auth_form_user_login_alter(&$form,$form_state){

$form['#validate'] = array( 'user_login_name_validate' );
user_login_authenticate_validate( $form, $form_state );
if(!empty($form_state['uid'])){

db_set_active('barakah');
$result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =>$form_state['input']['name'],':pass'=>$form_state['input']['pass']));
db_set_active('default');
if(!empty($result)){
$username = $form_state['input']['name'];
user_external_login_register($username, 'external_auth');

}

}

}

but as if the code doesn't exist, nothing happens

You can use:

drupal_external_login_register

  Helper function for authentication modules. Either logs in or
  registers the current user

An example implementation is detailed here:

https://api.drupal.org/comment/13434#comment-13434


How to make a 2-line menu link title? I have set up a menu with a list of menu titles which is working fine. But as I want to style the link li with a background-color and rounded corners, I need to be able to manually insert a break in longer length menu titles, rather than rely on the width controlling the line break automatically.

From what I've been able to glean from searching online, there is some way to do this by modifying a copy of a template file from core into my theme, but I'm not sure how to do this or if there is a simpler way.

Using Drupal 7.

You need to override theme_menu_link(), so in your template.php file from your theme put this code:

function MYTHEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  //Split titles using a
 when longer than 20 characters
  $element['#title'] = wordwrap($element['#title'], 20, "
");
  //Set HTML to TRUE to display properly the HTML
  $element['#localized_options']['html'] = TRUE;

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Change MYTHEME by your theme name.
I used wordwrap() to split long menu title in small chunks but you can implement your own logic there.


Conditionally load PHP class I made 2 custom modules: boutique and paypal. paypal is a dependance of boutique.

I check if paypal is enabled, with the following code.

namespace Drupal\boutique\Form\Multistep;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\paypal\Controller\PaypalController;

abstract class MultistepFormBase extends FormBase {
  protected function saveData() {
    if (\Drupal::moduleHandler()->moduleExists('paypal')) {
      $test = new PaypalController();
      $test->setPaiement(10,0,1);
    }

    $this->deleteStore();
    drupal_set_message($this->t('The form has been saved.'));
  }

}

All is working good, but use Drupal\paypal\Controller\PaypalController; is always be here; if the paypal module is not present, does it create problems? How can I conditionally use use Drupal\paypal\Controller\PaypalController;` only when the module is installed?

You don't have to prevent anything.

The use is just alias information. It doesn't care if the class that you're aliasing doesn't exist. As long as you don't actually use it, it won't fail.


StackExchange-style "related tags" block using drupal views? StackExchange sites, and various other site around the 'net, have a nice tag drill-down feature: You can go to a tag page, like https://drupal.stackexchange.com/questions/tagged/views, and then you can select tags from the "related tags" block, and you are sent to a page that filters contents on the union of the two tags. You can do this as many times as you want, and you end up with only content that has all of the tags you've selected. The tags in the "related tags" block are sorted by popularity, and list the number of items tagged.

Is it possible to do this in drupal? How would one go about this? I'm imagining something like a content-view for the tag page, filtered by tags; and then a taxonomy-view for the block, filtered by relationships with contents in the first view. Seems like a bit of a complex mission. Is there a simpler way?

There's a module that I believe does what you want: Similar by Terms

  This Drupal module attempts to provide context for content items by
  displaying a block with links to other similar content. Similarity is
  based on the taxonomy terms assigned to content. Blocks are available
  based on similarity within each of the defined vocabularies for a site
  as well as a block for similarity within all vocabularies.


Date range or date with operation (greater than, etc.) contextual filter I get date with contextual filter in views and i want set "greater than" my date. This option not exist in contextual filter. I cannot use argument in filter criteria.

In drupal 7 we can use "2017-01-01--2017-12-18" for range date with contextual filter, but in drupal 8, this trick not work.

Someone can help me, with date and contextual filter ?

Thank you

I don't understand why we don't have operator (>=, <=, etc.) in contextual filter...

Temporary solution... affect all views with argument :

File :

\core\modules\views\src\Plugin\views\argument\Formula.php

Change :

$formula = $this->getFormula() . ' = ' . $placeholder;

to

$formula = $this->getFormula() . ' >= ' . $placeholder;

Function :

public function query($group_by = FALSE) {
    $this->ensureMyTable();
    // Now that our table is secure, get our formula.
    $placeholder = $this->placeholder();
    $formula = $this->getFormula() . ' >= ' . $placeholder;
    $placeholders = [
      $placeholder => $this->argument,
    ];
    $this->query->addWhere(0, $formula, $placeholders, 'formula');
}


How to render language select block in page template? Background information:
I used the following script to list all the twig blocks: drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()))" and when I tried the following twig : {{ drupal_entity('block', '') }} and it is not rendering the twig block–

I developed a Twig page in Drupal 8 to allow my website visitors the ability to select the language they want. I downloaded all the multilingual contrib modules.

I am facing two issues:

How to render a block in the middle of my twig page to display the language drop-down menu? (I already have a block that displays a drop-down menu language from a contrib module).
The CSS background image I had setup is covering one of the Twig field I wanted to test. How can I tweak the CSS in order to display the twig block?

drupal_entity() is for rendering entities. For rendering block plugins use drupal_block() instead.
The difference is explained very well in the following guide.
https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak


Ubercart - hook for modifying the order review page What's the ubercart hook for modifying the table when visiting: /?q=user/%/order/%

I'm looking to remove columns in the orders node.

Documentation is lacking. This is the only documentation i could find and it's here: http://www.ubercart.org/docs/api

but not exactly what i want.


Auto Complete for product variations use Is there a way, when hiring for Attribute field setting

  (admin/commerce/config/product-variation-types/bags-cases/fields/field_color)

to add an additional choice added.

I need urgently an auto-complete feature in the frontend for the field type term reference.

For a very large amount of product variations, it is otherwise with a 5 meter long drop down menu very user unfriendly (+4000 zip codes for a single service).

With the Finder module, I could not solve the problem unfortunately.

You will need to write your own module and implement a hook_form_alter to override the normal Commerce way of displaying attribute selection.

A good example to look at is the Commerce Fancy Attributes module, which replaces the drop down with image selection. http://drupal.org/project/commerce_fancy_attributes

You can change the input type to autocomplete and point it to the correct callback url which returns your zipcode options in the format required for the product field.

$form['attribute_field_name']['#type'] = 'textfield';
$form['attribute_field_name']['#autocomplete_path'] = 'path/that/returns/list/of/zip/codes';


How to see all keys for a PrivateTempStore? The Drupal class PrivateTempStore allows for setting and getting key-value pairs within a temporary data store. The class includes the $storage property which then has a getAll() method for retrieving all items in the store. However, this is protected, and so cannot be used by an instantiated PrivateTempStore object.
Is it possible, given a PrivateTempStore object, to retrieve a list of all keys currently used in the store?

No, with the current PrivateTempStore you don't have access to the list of keys. You're welcome to create your own TempStore class if you want different functionality, but I don't see why that is needed here.
The whole point of PrivateTempStore is to stash temporary data for a user, under a given key. If you don't know the key, then you have no knowledge of the type or structure of the data stored there, so in general you won't know how to use it. If your intention is to store a collection of data of a known type (stored in an associative array, for example) so that you can iterate over it later, then store the array itself under a known key, don't store each array element separately. Then you can retrieve the array later from the known key and do a foreach over each element of the array.


I want to create a view with filters filters I want to create a view with Better Exposed filters, filters exactly like in
http://www.shopmgd.com/gold-jewellery.html. I am new to drupal, so somebody please help How can i do dis? I am using drupal 7.

Not sure how to close this question but I'll add my comments as answer so that Jumma can approve and close it.

You need to expose your filters using the Better Exposed filters module, see this tutorial.

To place your exposed filter in one region and the result of the view in another region you need to expose your filters in a block. See this tutorial learn how to do that.


How to rename a content type programmatically There are many answers and tutorials addressing the problem of changing the machine name of a content type, or migrating content types. However, I would like to rename a content type, without changing the machine name. This is what I tried:

$type = node_type_load('my_content_type');
$type->name = 'A new name';
node_type_save($type);

But this has no effect. What is the proper way to do this?

Looking back on this after a year, I can't reproduce my own problem. This code works, even for content types defined by modules, not created through the UI:
$type = node_type_load('my_content_type');
$type->name = 'A new name';
node_type_save($type);


Bought Drupal Organization Membership But Cannot Create Listing Recently, I bought DRUPAL ORGANZIATION MEMBERSHIP at $200 but now i am unable add my listing in drupal organzation list. And it also shows "not a confirmed user". Can someone help me with this ??

I understand that you've already created an organization page for Elsner Technologies Pvt. Ltd. on the Drupal marketplace, but that you want the listing to appear as a Drupal services provider.

If this is not yours, you may request its removal, or that ownership of the node is transferred to you so that you can edit it in the Drupal webmasters issue queue.

I've found this 4 year old application – which was denied.

The guidelines for being listed in Marketplace still apply, and you still do not qualify.  Unfortunately, having a Drupal organization membership does not qualify for a listing.  I suggest you re-read the comment given by lizzjoy as it contains good advice.


VBO action 'Modify OG user roles' does not show custom OG roles on the 'Add roles' list I have added new OG roles like 'tutor' or 'contributor'. I am using the view og_members_admin that comes with drupal commons, which uses view bulk operations 'Modify OG user roles' to give an admin the ability to add or remove certain roles. However, the only role selectable that I can add or remove is the default 'administrator member', despite the fact that I am user 1. Is there any further configuration that needs to be done to expose those custom added roles to that list?

Edit: when I try to add a user (through group/node/%/admin/people/add-user) the only role shown in there is also 'administer member', so this must be some site-wide configuration that is missing?

It turns out that new roles are not visible to already created groups. When I create a new group I can see the added roles. However there should be a way to make existing groups 'see' newly added roles...


Integration with third-parties? I'm trying to integrate Drupal Commerce to a File Maker. Why ? Because my client staffing have been using File Maker for over 15+ years. We are trying to integrate both systems.

So my goal is to be able to send the order information every time a purchase is complete to the File Maker server so they can re-created their order information into File Maker as well.

I started to write my custom module to send the order ID to the File Maker server. Here is how I did it.

/**
 * Implements hook_commerce_checkout_complete().
 */
function commerce_external_call_order_commerce_checkout_complete($order){
  $script_variable = variable_get ('external_script');
  // Combine the URL with the OrderID.
  $final_variable = file_get_contents($script_variable . $order->order_id);

}

And this actually works.

I'm wondering if there is a module that allows me to export my order information every time an order is complete or updated? Ideally would be an integration with Rules and the Service module.

You can use https://www.drupal.org/project/services_rules . It creates actions (usable in rules) for the services module. It's in beta because it has a limited amount of features. It is stable though.


how do I sum a table column? Is there a  way to sum a numeric value and display it from a field column data in a table view format using search api? I have a DB server (not solr). I need facets.

I've tried the following methods:

1.- search api node index views has no "aggregation settings" (not possible here).

2.- Views calc module (goes out of memory).

3.- Views Aggregator Plus module, "it works", but always result is equal to zero.

I'm run out of posible sulutions, please help.

This module does the job, https://www.drupal.org/project/views_summarize, also I'm using a bootstrap sub-theme and all modules above mensioned break css, and this module does not.


Disable Panels Preview when adding new Panes in Layout Editor Some of my pane's are causing the pane's editor to crash (some cause the grears to dissapear, some cause the add new panes element to break). We'd therefore like to disable the preview option in Panels, it looks like Panopoly has the option to do this: https://www.drupal.org/node/2171809. "Enable Previews when adding Panes"

Does anyone know how this could be done on the panels module for Drupal 7?  We're not using Panopoly.

The reason behind it not working is that Panels was written against jquery 1.4 and some of my blocks that are being previewed when adding panes to the page manager are panels 1.9+

I had same problem in one of my project. Then what I did, I added a custom code to remove all the js files except drupal core js, Panels js, Token Js, Ctools js and Views Js. And it is only for the panel pages so it solve the issue of jquery version.
We also have a drupal module jqmulti for this. But in some cases it also do not work well. That is why I removed all the unwanted js files from panel page.
Here is the sample code for this.

function custom_module_js_alter(&$js){
  if(arg(0) == 'admin' && arg(1) == 'structure' && arg(2) == 'pages'){
    $allow = array('modules/filter/filter.js', 'modules/field/modules/text/text.js', 'modules/file/file.js');
    foreach($js as $key => $value){
      $pos =  strpos($key, 'misc');
      if(strstr($key, 'misc') == '' && $key != 'settings' && strstr($key, 'ctools') == '' && strstr($key, 'panels') == '' && strstr($key, 'views') == '' && strstr($key, 'token') == '' && strstr($key, 'admin_menu') == '' && !in_array($key, $allow)){
        unset($js[$key]);
      }
    }
  }
}


Submit AJAX form and update database then show all database results Is what i am trying to do is on this page it will display all items from the database that currently exist. Then at the top of this list will be a small form that will allow someone to add an item to the list. After someone submits the data and posts the form I want the list below to automatically populate with the updated data. I am having a really hard time trying to figure this out.

function clay_mod_blacklist_form($form, &$form_state) {
drupal_add_css(drupal_get_path('module', 'clay_mod') . '/css/clay_mod.min.css');
drupal_add_js(drupal_get_path('module', 'clay_mod') . '/js/jquery.maskedinput.js');
drupal_add_js(drupal_get_path('module', 'clay_mod') . '/js/clay_mod.js');

$form['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Name'),
    '#required' => TRUE
);
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Contact Name'),
    '#required' => TRUE
);
$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#required' => TRUE
);
$form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#required' => TRUE
);
$form['submit_button'] = array(
    '#type' => 'button',
    '#submit' => array('clay_mod_blacklist_form_submit'),
    '#ajax' => array(
        'callback' => 'clay_mod_blacklist_form_ajax',
        'wrapper' => 'box',
        'method' => 'after'
    ),
    '#value' => t('Add To Blacklist'),
    '#id' => 'ajax-save-form-values'
);

$form['results'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
'
);

if(isset($form_state['values'])) {
    $form['results'][] = $form_state['values']['results'];
}
// This is where I was display info from database before the form was submitted
//    if(!empty($form_state['values']['results'])) {
//        $form['results'] = $form_state['values']['results'];
//    } else {
//        $rows = db_select('blacklist', 't')
//            ->fields('t')
//            ->execute()
//            ->fetchAll();
//        foreach($rows as $k => $v) {
//            $form['results'][$k]['#markup'] = "
x{$v->name}y
";
//        }
//    }

return $form;
}
function clay_mod_blacklist_form_ajax($form, $form_state) {
    return $form['results'];
}
function clay_mod_blacklist_form_submit($form, $form_state) {
   ddl('ajax submit');
   $form_state['rebuild'] = TRUE;
   clay_mod_blacklist_form_save($form, $form_state);

}
function  clay_mod_blacklist_form_save(&$form, &$form_state) {
$companyName = $form_state['values']['company'];
$name = $form_state['values']['name'];
$phone = $form_state['values']['phone'];
$email = $form_state['values']['email'];
$query = db_insert('blacklist')
    ->fields(array(
        'company_name' => $companyName,
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
    ))->execute();
}

Add a wrapper around the entire form, and return the entire form from your ajax callback. Then just build the rows reguarly in your form definition - The newly added rows will be shown since all the data is pulled from the database when the from is generated.

function clay_mod_blacklist_form($form, &$form_state) {
  $form['#prefix'] = '
;
  $form['#suffix'] = '
';

  // Add the rest of your form definition here

  $form['submit_button'] = array(
    '#type' => 'button',
    '#submit' => array('clay_mod_blacklist_form_submit'),
    '#ajax' => array(
      'callback' => 'clay_mod_blacklist_form_ajax',
      'wrapper' => 'clay_mod_blacklist_form_wrapper',
      'method' => 'after'
    ),
    '#value' => t('Add To Blacklist'),
  );

  $rows = db_select('blacklist', 't')
    ->fields('t')
    ->execute()
    ->fetchAll();
  foreach($rows as $k => $v) {
    $form['results'][$k]['#markup'] = "
x{$v->name}y
";
}

function clay_mod_blacklist_form_ajax(&$form, &$form_state)
{
  return $form;
}


Installing an alpha dev version with composer Block class module has a 8.x-1.x-dev version.  Installing using the recommended command from the specific release page

composer require 'drupal/block_class:1.x-dev'

installs a versionless block_class.

Why is that and what are the implication on future composer update ?

UPDATE: when installing with drush

drush dl block_class --select

and choose latest dev version that version is 1.0-alpha1+10-dev
how can one install the latest alpha-dev ?

As I said, just don't specify a version and composer will automatically pick a version constraint that installs the most stable version:

$ composer require drupal/block_class
Using version ^1.0@alpha for drupal/block_class
./composer.json has been updated
Gathering patches for root package.
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/block_class (1.0.0-alpha1): Loading from cache
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles


How to how a table with previously collected data in a custom form page? I have a table named "Table1" in my Drupal, where I added fields by getting the inputs via form. The form is created by custom module. My next requirement was to again create another form, but this time I want to show the user by means of a Table format, the previously collected data in the form page itself. But I got stuck in this part.

The idea is: I want to bring the contents of "Table1" having attributes "empid" and "empname" in the right side of Form Page, so that the user can check the contents and enter current input accordingly. How is it possible?

Yes you can do this.
First of all you need to fetch the 'Table1' data in top of the form.

$query = db_select('Table1' , 'tb');
    $query->fields('tb');
    $results = $query->execute()->fetchAll();

//table structure

$Details = '

	Employee Id	Employee Name
';
    foreach($results as $res)
    {
        $Details .= ''.$res->empid.'	';
        $Details .= '$'.$res->empname.'	';
    }

$form['details'] = array(
        '#type' => 'item',
        '#markup' => $Details,
        '#suffix' => '
'
    );

$form['eid'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Id'),
    '#maxlength' => 45,
    '#required'=> true,
);
$form['ename'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Name'),
    '#maxlength' => 45,
    '#required'=> true,
);

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


Drupal 8: Webform - how to programmatically prevent or call a form submission? I build a form with the webform module and hooked it to be able to submit it via AJAX:

function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) && $form['#webform_id'] == 'myform' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' => '\Drupal\mymodule\Controller\DefaultController::submitMyForm',
      'event' => 'click',
    );
  }
}

Now i'd like to prevent the form submission in the submitMyForm-function when a certain condition takes place. How can I achieve that?

And how can I submit it when the condition doesn't take place?

EDIT

This worked:

function submitMyForm(&$form, FormStateInterface $form_state, $form_id)
{
   if ( $condition ) {
      $form_state->setErrorByName('field_name', t('error message'));
   }
}

Sitepoint has a nice example of Ajax form validation in Drupal 8:

https://www.sitepoint.com/using-ajax-forms-drupal-8/


Drag function in Blocks is Gone In one of my Drupal installations I suddenly noticed I can no longer drag and sort the order of my blocks. The image shows on the left the admin with now drag handles and a screenshot of another admin with the handles.

What could have happened? I think its AJAX/JavaScript related.

It's definitely js related, most likely a conflict/error from something in the theme or a contributed module. If you switch to a core theme, are the blocks draggable? If not, it's probably a module (or a script coming from somewhere else, like a block).

If you need to change block position ASAP, you can temporarily disable your browser's javascript, which should then cause the weight positioning drop-downs to appear, which you can use to adjust the order.


Drupal 7: can't get SQL query to work that works outside of Drupal I have a SQL query that works just fine on it's own as follows:

SELECT timestamp FROM accesslog
WHERE uid = 1
AND path = 'mypath'
AND timestamp > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 4 WEEK));

I've tried two methods, and the first one returns all values for the user from the beginning of time, and the second results in a PDOException.

Method 1:

$ts = 'UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL '.$interval.'))';
$query = db_select('accesslog', 'a');
$query->addField('a', 'uid');
$query->addField('a', 'path');
$query->addField('a', 'timestamp');
$query->condition('a.uid', $uid);
$query->condition('a.path', $path);
$query->condition('a.timestamp', $ts, '>');
$result = $query->execute();

Method 2:

$result = db_query("
SELECT timestamp
FROM accesslog
WHERE uid = :uid
AND path = :path
AND timestamp > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL :interval))",
array(':uid'=>$uid,
      ':path'=>$path,
      ':interval'=>$interval))->fetch();

I'm guessing the issue is with the timestamp > part, but I'm just not sure how to get that part done.

Can someone point me in the right direction?

Thanks

Instead of the above one try the following query,

$date = date_create();
date_modify($date, '-4 week');
$interval =  $date->format('U');

$result = db_query("
SELECT timestamp
FROM accesslog
WHERE uid = :uid
AND path = :path
AND timestamp > :interval",
array(':uid'=>$uid,
      ':path'=>$path,
      ':interval'=>$interval))->fetchAll();


Subscribe all users to Simplenews Newsletter We just installed Simplenews module. Is there a way to subscribe all our current users to one of the newsletters we created. This will be used to send important website updates. Therefore we don't want to skip users that have been registred to date.

We have a few thousands users, so a manual process will not work. Can this be done in the mysql database?

Figured it out.

Go to Mysql and output the user_field-data table as a csv. Delete all
the columns except the user emails.
Copy all the user emails to the clipboard.
Go to Admin  People  Simplenews

You will see options to Mass Subscribe.
Paste the emails on the form. Select the newsletter and wait for a
while.

If you have a long email list break it down in 500 or 1000 records at a time or the server may time out.


Is there a way to send an email to a mailchimp list on the event of a content type being published? The title says it all, really.

I want to trigger the dispatch of an email to a list of subscribers on mailchimp every time a certain content type is published.

Using rules I can see that the only mailchimp action available is to sign a user up to a list, so if there is a way of adding a new action to send an email to all users in a list that would be exactly what I need.

Any other methods are welcome too.

Thanks very much.

I don't think you can do that directly from the interface. You need to create a hook function hook_rules_action_info in your custom module's .rules.inc file which will describe what the action actually does. See the link http://www.drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook_rules_action_info/7
Even I'm looking for some good example or tutorial for this. Cheers!


Multisite with search functionality I was facing an decision about a project. We have a website in drupal 7 that talks about cars. Now we want to talk about motorcycle. The basic layout will be different, i mean the header and footer.

We want to be able for example a user in motorcycle if search for a car can show (if exist) the result  from the cars sites and the link will get him to the main site.

Can we achieve this kind of behavior ?

How i want to look
So we have Option A : moto.mysite.com
Option B will be mysite.com/moto/

I would not use a multisite for this.  Instead, I would do Option B (mysite.com/moto).

Then I would use the Themekey module to set up different themes.  If you want the two parts of the site to basically look the same, you can make the motorcycle part a subtheme of the theme you are using for the car part.

If you do this, then you don't have to worry about integrating the data; you will have two parts of the website that look different, but on the backend all the data will be kept together.


Finding correct twig file for page Consider, I have created two pages using Views for content types Activites and Articles viz. Latest Activities and Latest Articles. I have made a view to display the grid structure for these contents. However, if I modify the views-view-grid.html.twig, it affects the both views. What twig file I should create so that I work on separate view for each pages? eg. something_view1.html.twig for Activities and something_view2.html.twig. Thanks.

Views uses a different mechanism to provide variations of twig templates that doesn't work yet with the debug feature from twig.

The logic that builds those suggestions is in \Drupal\views\ViewExecutable::buildThemeFunctions(), you can debug that or ad some php statements to dump the $themes variable for a certain hook to get what you need.


How to show the body field in a custom template? I'm stuck with this problem. In the following code, I want to replace the "field_portfolio_categories" by the "body field" in a custom tpl file.

<?php print $title; ?>

    <?php print render($content['field_portfolio_categories']); ?>

So I change it to:

<?php print $title; ?>

<?php print $body; ?>

In the node, instead of body content, I see "Array"
And this is the error message:

Notice : Array to string conversion in include() (ligne 41...

Any idea what's wrong?

Here is the complete template code:

    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
hide($content['body']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '&nbsp;';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>

        <?php print render($content['field_image']); ?>

                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip">

<?php print $title; ?>

    <?php print_r($content['body']); ?>
    <?php //print render($content['body']); ?>

<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>

Your code should be:

    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '&nbsp;';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>

        <?php print render($content['field_image']); ?>

                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip">

<?php print $title; ?>

    <?php print render($content['body']); ?>

<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>


How to prevent Drupal export XML formatter adding paragraphs? I'm exporting nodes as XML and with fields in most nodes set to "Plain text" format. Everything is fine when I'm editing them, but when exporting an extra paragraph (
) tag is added around text (using "Default" formatter).

The mentioned field has a variable length text (some are short like "Book" and some have long HTML). Some longer texts are exported fine, but those short ones all have extra paragraph around them (e.g.
Book
).

So is there some option I can check to disable adding those paragraphs or even disable any formatting? Or maybe I have to install/make some special module for formatting?

PS: I'm using Views data export (version 7.x-3.0-beta8).

I don't think there is a need to make a "special module". Instead you could install the Forena module (with quite a few official D7 releases ...), as an alternative to what you're trying to do with the Views Data Export module (or the Views Datasource module as suggested in one of the comments to the question here).

You could use the Forena module to create an appropriate report. As per your comment like "Full nodes, no. Only some choosen fields, but all of a single content type." such report should be straight forward to create. And then create an XML file from the report data (= query results). Similar solution for somebody who rather wants/needs a JSON format. Refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?" for more details about all sorts of export formats, and some online demo samples.

Using this alternative, you probably don't need your (not ideal) work-around anymore which is to disable changing new lines to HTML new lines.


Tutorial for creating website using existing MySQL db? I'm an experienced web developer, but I'm new to Drupal.

I have an existing MySQL database and I would like to build a website around it, with one page for each record in the main table. That would mean a few thousand pages for the site right from the start.

Are there any good tutorials that explain how to do this in Drupal?

It's not too hard. Assuming Drupal 7 and a one-time import:

Create a new content type in Drupal with the fields you want
Export a CSV file of your records with a header row from your legacy database with the fields you want.
Use Feeds to import the csv file.  You will setup a mapping between the csv fields and your content types fields (from within the Drupal UI).  This is pretty straightforward and the feeds module guides you through it.
Feeds will create one node per record (line) in your csv file.

Now if you will continue to use your existing database and want to import new records as they are added, I believe Feeds has some support for this but I haven't personally used it.


Set permissions to specific node in php Is there any way to add a role permission to specific node? I have a block-view Home slider, and I want to add a php validation to a specific slide.

I have to edit the node.tpl of my slide ? Or maybe the view output tpl? I'm in a Drupal 7 installation.

Content Access

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

Nodeaccess

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.

If you want to add it by custom code use hook_node_access

function mymodule_node_access($node, $op, $account) {
  // We are interested to existing objects. When the node is being created, Drupal passed the node type instead of the node object.
  if (is_object($node)) {
    $check = (
      ($node->type == 'node condition')         );
    if ($check) {
      if ($account->uid == $node->uid) {
        return NODE_ACCESS_ALLOW;
      }
      else {
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;
}


Send data from controller to hook_form_alter() I created a module for searching movies in different external databases.
I use the Drupal node add page to handle the insertion of the movie. Now I need to know a way to send the data from my custom controller to the /node/add/movies_movie page.

In the controller I use the following code to send data to the module page.

if ($system === "IMDB") {
    $database = new ImdbDatabase;
    $movie = $database->getDataById($id);

    $tempstore = \Drupal::service('user.private_tempstore')->get('movies');
    $tempstore->set("newMovie", $movie);
}

$option = [
    'guid' => $guid,
];

$url = Url::fromUri('internal:/node/add/movies_movie');

return $this->redirect(
    $url->getRouteName(),
    $url->getRouteParameters(),
    $url->getOptions(),
    302
);

My hook gets the value using the private tempstore service:

function movies_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    if($form_id === 'node_movies_movie_form')
    {
        //$movie = null;

        $storage = $form_state->getStorage();

        $tempstore = \Drupal::service('user.private_tempstore')->get('movies');
        $movie = $tempstore->get('newMovie');

I use hook_form_alter()to place the objects inside the add form. How can I send data from my controller to hook_form_alter() to place the custom values on the form?

To better understand my problem I will explain my situation in normal English without any technical terms.

The site contains a page to search to movies using a search bar. It will show the result of all the movies in a table with an add button after each movie. When pressing on a add button it will get all the data from the movie and will automaticly place the received movie data, in the movie insertion form. On the movie insertion form can be user change all the values and save it.

I think you should not load the data in your controller but in your hook_form_alter. Redirect the user to a path containing a query parameter in Url, so that the url may look like "http://www.yoursite.com/node/add/movies_movie?guid=123" and change the guid paramter to the value of the movie.

Then in your hook_form_alter:

$request = \Drupal::request();
$guid = $request->query->get('guid');

if ($system === "IMDB" && $guid) {
    $database = new ImdbDatabase;
    $movie = $database->getDataById($guid);

    // fill in the values of the movie into the form fields
}


How to add a "read more" link on User profile teaser display? I'm using Drupal 8 and I want to have a "Read More" Link on my User profile, that links from the Teaser display to the Full display. How can I do that?

Content types for nodes bring the "Links" field out of the box on the teaser display.

This you can do using Views and providing the code for Link on User page, follow following steps.

1. Creating the Complete User profile at default Drupal account page:

1.1 Add the all the fields on the Default user-profile what you want on fullDisplay(Admin/Configuration/Account setting/Manage field). So any user when creates a account, he will have all section to fill-out. For example My Full user-profile has the following fields.

Name
Picture
Bio

2. Create the teaserDisplay

2.1 Hide the fields which you do not want on the teaserDisplay. So, on the User-profile setting page(Admin/Configuration/Account setting/Manage Display), now hide what you do not want to show on Teaser Display. Now for my setting I want to Hide Bio. So I will just hide this field at Manage Display.

So current user-profile field settings are:

Name
Picture
Bio - Hidden

Now, till this stage, we set our Drupal's default account page as teaserDisplay but simultaneously we created those fields which we want on fullDisplay, hence we kept hidden but we will display all those hidden fields using Views.

3. Create the Views-fullDisplay

3.1 Create a new view page, Select USER under Views setting. Under pager, choose 1 item.
3.2 Now on the setting page, add all following setting as shown in teh following image. So here we are accessing that Bio field which we hide on User profile page.

Contextual filter setting: Under contextual setting select User: User ID and under that select Display all results for the specified field.
Path: Now as shown in the view set the path /user/%/view-page. I have kept last part here, /view-page as I was just trying previously, you can change to full-profile, but you have to change that at all places.

4. Setting the Link on the teaserDisplay page (so we can re-directed to fullDisplay)

To provide the link, the link should take the User-Id from the URL and can able to pass that User-Id in views URL, so Views contextual filter can provide the result of that User, from where we have redirected. Hence, to solve this I raise separate question and you can follow answer as shown below. I am not providing answer as you have to just copy from there.

@ShawnConn has provided answer for how to add link on user-page. Full Credit goes to @ShawnConn for this answer.

How to get current path for user profile field?

5. Output Image:

teaserDisplay- Default User Page

Full Display - Views with bio field

Now, this way you can add as many as field you want, just hide them so they does not display on teaser display and show in views so they display on fullDisplay page.


Smart quotes creating a problem with anonymos user role I have create a view. The content of the view loads fine when logged in as admin. But in some of the content when you copy paste from MS Work, certain characters changes.

For e.g. " becomes “

Now the content which contains such characters is not displayed in that view.

But when logged in as admin, I see those content. What could be the problem ?

I checked using devel. The number of results which are fetch is different. Those with special characters are not fetched when viewing as anonymous user.

Without more information it's hard to tell exactly's going on but there's a couple things that come to mind:

Copying and pasting from MS Word/other rich text editors is notoriously problematic and both TinyMCE and CKEditor have built-in settings for pasting data from Word & stripping the extra formatting
In case you're not using any WYSIWYG you should always paste your code in Notepad or another plain-text editor and then re-copy it to lose the extra formatting
Finally, I don't really think it applies to viewing content at all but the visibility thing might have to do with the text-format used in the body field, it's common to edit content using Full HTML and then users without access to it (only Filtered HTML for example) can't edit it


How to change an existing theme to a responsive bootstrap theme? I wonder how to update an existing non-responsive Drupal 7 theme to a responsive bootstrap theme? Any hints for that?

The following steps are required:

Install bootstrap theme.
Create a bootstrap subtheme.
Make sass tools ready to compile scss files.
Start theming.
Create a new bootstrap subtheme that looks like the old non-responsive theme.

So how can I create such a new responsive subtheme?

If you want to create a responsive site in drupal with bootstrap.then follow steps:

Install bootstrap theme.(https://www.drupal.org/project/bootstrap).
Copy the bootstrap_subtheme, Place in theme folder and rename with your subtheme.
3.Copy and include the css and js of the existing site to the bootstrap_subtheme.
See the structure of the existing site and create regions in the new theme according  to requirement and apply the css.
Check the section one by one and apply the css according.
Like this you can easily convert the non-responsive site to responsive.

Notes:

You will be create a regions in the tpl.php , this Link will help you.
In this theming there is no that much different to normal theming . if you install bootstrap then it automatically give you the responsive platform, only one difference you can use the bootstrap class in html structure and also use the bootstrap module. Follow This.


Which PHP file would a custom theme_link function go into? For some Taxonomy term pages I would like to change the "Read More"

link to "More info". Using theme developer, I see it’s using the theme_link function and gives a candidate function name.

If I re-write this function, in which PHP file would I put this custom function?

theme_link() doesn't use a template file. You can override its output by placing your own theme function in your theme's template.php file:

function MYTHEME_link($variables) {
  //Alter this as you see fit
  return '' . ($variables ['options']['html'] ? $variables ['text'] : check_plain($variables ['text'])) . '';
}


How to show comment reply form I have installed ajax comments module. There is a "reply" link to show comment reply form. I want to show comment reply form under comments without click reply link. Is it possible?

if (you = JS) {

use document.getElementById('yourLinkID').click();

} else if (you = JS && you = jQuery){

use $('.content-type #LinkID').click();

} else {

// can't think of anything, either then an option in the UI. I don't have much experience with Drupal comments.

}