Block email from submitting webforms I have a list of email addresses that I would like not be able to submit in webforms. I can't seem to find a setting for this? Is this currently possible or do I need to make a custom module to implement this?

You can probably add a validation pattern to the email address and block a list of email addresses for submitting the form. Or you need to create a custom module.


Array Field for a Content Type. Is it possible? I'm new in drupal and I'm about to use drupal for my expanding site.
This is my issue:
I have some documents which segmented to sentences and words and each word has a tag for example:

Document:
   This is a test text to show what I say. This is the second sentence. This is the third.
Sentences:
   1. This is a test text to show what I say
   2. This is the second sentence
and so on.

Tagged words:
   This => ABC
   is => DEF
   a => EE
   test => NME
and so on.

I would like to make a node for each document not each word or sentence and store sentences and words as fields.
This data is stored in a mysql database and I can export it in any form.
How can I implement this structure in Drupal?
Is there any module for it? or I should develop a new module?
or any other solution?

Thank you all so much

In case you want to store complete array as a single input in a field, you can do so by serialize the array.

Create a long text field and serialize the array before input by calling hook_node_submit().


tb-megamenu how to click to open/close sub menu in mobile We are attempting to get submenus to only appear when the user "taps" the menu option on a mobile browser. This functionality works good on hover but some mobile devices don't work with hovering. We need the ability to click submenu titles in order to drop them down and then click them again to collapse them.

Then look far, the best I found in my case has been the following:

I have overridden the method (js) of tb MegaMenu and done through the function drupal

I created a copy of tb-megaMenu-frontend.js file and called tbmega-custom.js and saved in the js folder of my theme.
What added to the system through the function drupal js_alter.
In my theme in the file called template.php

function mytheme_js_alter (&$javascript){
    $javascript[drupal_get_path('module', 'tb_megamenu') . '/js/tb-megamenu-frontend.js']['data'] = path_to_theme() . '/js/tbmega-custom.js';
}

I have adjusted the code to my needs. Just change the behavior of tbMegaMenuAction:

 Drupal.behaviors.tbMegaMenuAction = {
    attach: function (context) {
        $('.tb-megamenu-button', context).once('menuIstance', function () {
        var This = this;
        $(This).click(function () {
            if (parseInt($(this).parent().children('.nav-collapse').height())) {
                $(this).parent().children('.nav-collapse').css({height: 0, overflow: 'hidden'});
                Drupal.TBMegaMenu.displayedMenuMobile = false;
            }
            else {
                $(this).parent().children('.nav-collapse').css({height: 'auto', overflow: 'visible'});
                Drupal.TBMegaMenu.displayedMenuMobile = true;
            }
        });
    });

    //Comment this for mobile click
    //var isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
    //if (isTouch) {

        $(document).ready(function ($) {
            var mm_duration = 0;
            $('.tb-megamenu').each(function () {
                if ($(this).data('duration')) {
                    mm_duration = $(this).data('duration');
                }
            });
            var mm_timeout = mm_duration ? 100 + mm_duration : 500;

            $('.nav > li, li.mega').click(function (event) {
                event.preventDefault();

                var $this = $(this);

                if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                    $('.nav > li, li.mega').each(function () {
                        $(this).removeClass('clicado open');
                    });

                    $this.addClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.addClass('open')
                    }, 100));

                } else {

                    if($this.hasClass('mega') && $this.hasClass('clicado')) {

                        $this.removeClass('clicado');
                        $this.addClass('animating');
                        clearTimeout($this.data('animatingTimeout'));
                        $this.data('animatingTimeout', setTimeout(function() {
                            $this.removeClass('animating')
                        }, mm_timeout));
                        clearTimeout($this.data('hoverTimeout'));
                        $this.data('hoverTimeout', setTimeout(function() {
                            $this.removeClass('open')
                        }, 100));
                    }

                }

            });
        });

    //}

    $(window).resize(function () {
        var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
        if (windowWidth != Drupal.TBMegaMenu.oldWindowWidth) {
            Drupal.TBMegaMenu.oldWindowWidth = windowWidth;
            Drupal.TBMegaMenu.menuResponsive();
        }
    });
  }
 }


Where is the code for added user registration fields? I've added a few extra fields relevant to my interests to the user registration form. The problem being, I'd like to insert a db_insert function to make use of those fields, but I don't know where the code for the extra fields are. That being said, I'm not entirely sure if altering that code is even necessary.

I'm very new to all this. I'd really appreciate some help, have a good day.

In the field settings, tick "display on user registration form".

All of the database stuff is taken care of automatically in drupal so you'll rarely have to worry about that stuff unless you are adding your own custom modules that require tables.

What are you trying to accomplish with these tables? Views etc. will have access to them.


Problem with drupal_valid_path In my custom module I'm using drupal_valid_path to check if a given alias exists before I create such.

$target_alias = 'some/path';
if(drupal_valid_path($target_alias, FALSE) === FALSE){
  // create 'some/path'
}

The function always returns FALSE and thus creates tons of identical aliases. What could be wrong?

I have tried various boolean expressions, such as: !drupal_valid_path or weak type test ==. To no avail.

I would guess the problem is that drupal_valid_path() is expecting a system path, and you're passing it an alias.

Fortunately there's a function to determine the system path from the alias, drupal_lookup_path(). I would have thought a simple change to your code like this would make it work:

$target_path = drupal_lookup_path('some/path');
if(drupal_valid_path($target_path, FALSE) === FALSE){
  // create 'some/path'
}


Price display on node-product .tpl I have one product with 5 variations

book:
paperback, hard cover; audio; ebook(epub, mobi)

How do i display the individual prices per item on node

Since you have Product Referenced field hanged on your content type you can access your Product ID in content 's $product_id = $vars['node']['field_product'] then you can get commerce product item with commerce_product_load($product_id) and then access field_price.


How do you get the url of an image in a view twig template? I want to check the fields.field_image.content to see if it is empty or not.  I want the view to display differently if there is no image in the page field_image field.

I was thinking I could just get the URL of the field_image and do a simple if statement, but I don't see a way to do that.

Is there to check if the fields.field_image.content field is empty?

I've tried a few different things like:

{% if fields.field_image.content is empty %}
{% if fields.field_image.content0|striptags|trim is empty %}

I'd like to dump fields.field_image to see the whole object, but my local setup always crashes.

Is this even possible?

The answer is yes it is possible to check if the image is present or not.

Here is how to do it:

{% set fieldimage = fields.field_image.content|render|striptags('<img>')|trim|length > 0 %}
{% if fieldimage == false %}
  image is empty
{% else %}
  image is not empty
{% endif %}

There is a raw variable available - you can use it to get raw result from the query, with all data it fetched.
You can inspect it with the devel or twig_vardumper module using xdebug or dump(raw). More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables


Are Drupal .php files associated with a module cached? I am wondering if they are, as that would explain why a simple change to one of my variables in my config.php file is not showing up in the DOM.

Here is what is making me suspect this.

In my fls_price_calculator_2012 module in my includes directory I have a file called config.php.

I am trying to change my $START_DATES_OPTIONS_COMBINATIONS['Specialty Tours'] variable to look like the following:

$START_DATES_OPTIONS_COMBINATIONS['Specialty Tours']['Surf Camp - Saddleback College'] = array('June 29, 2014', 'July 6, 2014', 'July 13, 2014', 'July 20, 2014', 'June 28, 2015');

Simply adding June 28, 2015 as a last option to the array.

The php file is included in my .module file for the module, following this line:

include_once('includes/config.php')

in my fls_price_calculator_2012.module file.

The variable itself is added into a hidden <input> variable in the DOM in the same .module file like so:

$tour_start_dates = '<input type="hidden" id="tour_start_dates" etc...>'
foreach ($START_DATES_COMBINATIONS['Specialty Tours'] as $key => $value){
  //populates the above created input with the keys and values
}

once it is all loaded in the DOM, I search via the Javascript console for the #tour_start_dates element but I get the only the old value for Surf Camp - Saddleback College and I don't understand how that is happening.

To answer it literally - probably, yes, on many levels:

Filesystem cache
Opcode cache
Possible other caches, depends on your configuration

Above caches should not create the effect you are seeing, but outout of the whole page is also cached, in your browser. Inspect headers to make sure it was not the case, and if so, clear caches and try again. If you have any proxy or reverse proxy, make sure they are not interfering, too.

If you are sure pages are not cached at output, and you didn't make Drupal to cache your variable, it shouldn't be cached. So there are two options:

Problems with include path:

  Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.

Maybe there is another instance of this file somewhere, one that gets higher priority in including? That's one of the reasons to use module_load_include instead.
Problems with uploading. You know what you sent to your server. But have you inspected (from console, for example) what really is there? Maybe you are looking for something that isn't even there.


Remove specific stylesheets from a given page Adding a stylesheet to specific pages is easy: implement hook_preprocess_page(), call drupal_add_css(...) and set $vars['styles'] = drupal_get_css().

But what is the proper way to remove a stylesheet (or in my case, all "media=screen" stylesheets) for a specific page, without interfering with the caching system ? (e.g. not some regex applied to the output)

You can't just do unset($vars['css']['screen']) because $vars['styles'] has already been generated at this point and there exists no drupal_remove_css() function.

This seems to be the cleanest way, in hook_preprocess_page():

$css = drupal_add_css();
unset( $css['screen'] );
$vars['styles'] = drupal_get_css($css);


How to display only "after now" dates (of multiple) of a date-field in a node? I have an 'event' node-type with just a body and a date-field. For that date-field, multiple dates are allowed.

I'm listing event-nodes in a view and already use filters to only display nodes when the latest date is after 'now', so that completely outdated events do not get listed automatically. However, when I have multiple dates and at least one of those is still in the future, the node gets displayed.

In the latter case, how can hide all dates that are in the past, and only display the ones that are still in the future? I didn't find an option for that for the date-field in the node-type display settings.

I guess I could override my node.tpl.php with a custom node--event.tpl.php, but how do I parse out single dates of my date-field then, check if they are in the past and hide those that are? I'm totally lost when it comes to PHP and Drupal content-arrays.. I'd appreciate any help with that!

Ok, I dived into the drupal variables with the help of the devel module and came up with a solution (first version, see better version below the edit):

I now parsing all dates directly from the content in my specific node--event.tpl.php. I then iterate through them and store all dates that are in the past in a new array. In the end, if that array contains any values and my new option is activated (differentiating between teaser and full display), I remove those past-dates from the date-field array in the content:

<?php
// remove dates in the past from the date-field if enabled
if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    $past_date_array = array();
    foreach($content['field_eventdate']['#items'] AS $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        array_push($past_date_array, $date_array);
      }
    }

    if (count($past_date_array) > 0) {
      $only_future_date_array = array_filter($content['field_eventdate']['#items'], function ($var) use ($past_date_array) {
        return !in_array($var, $past_date_array);
      });
      $content['field_eventdate']['#items'] = $only_future_date_array;
    }
  }
}
?>

Maybe there is a cleaner way of preprocessing the content (let me know), but this was the quickest I could come up with and I now have the option per-node.

== EDIT ==

Why make it complicated: I forgot about hiding fields, so no more array-assigning, just on-the-fly hiding of past-dates:

if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    foreach($content['field_eventdate']['#items'] AS $key =>  $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        hide($content['field_eventdate'][$key]);
      }
    }
  }
}


Display ubercart product image given a product nid How do I display a product's image given the nid?

It's tricky without some more information but something like this:

$product = node_load($nid);
$image_path = $product->field_image_cache[0]['filepath'];

print theme('imagecache', 'product', $image_path, $product->title, '');


Create a form for editing a single field of an entity I need to find a way for users just to edit a specific node field. We have a quite large content type and in a review process we would like some fields of a node to be editable for the revisioning user and some not. To avoid that the revisioning user needs to scroll through a large node form it would be very handy if he/ she would find a link on node detail page close to the text of the field where he/ she is pointed to a form just showing the field.

I found "Editable Fields" and "Quickedit" module which work not so well in our project due to some JavaScript conflicts. Additionally they do not really meet our needs as our main aim is not to make nodes editable on detail page. We just want to show a reduced form to the user for one specific field.

Does anyone has a solution how to create such a form? I think of something like calling the path "custom-form/[NID]/[REVISION_ID]/[FIELD_NAME]" which is connected to a page callback which renders a form for field [FIELD_NAME] in node [NID] of the corresponding revision version and validating and saving the input respecting the field's widget settings.

You can install the Field Permissions module.


How can I create some specific content with a cron job I need to create a specific content, for instance, a Page, every 15 days.

Of course that goes into some cron job.

But how can I do that? Do I need to implement the hook_cron at my .module?

You got it!  Implement hook_cron and inside that function create a node using the node_save().

Each time you run cron by going to /cron.php or each time it is called from your cron job, your hook will automatically be called.

Here's some sample code, partly borrowed from http://drupal.org/node/1111514

So your .module file should at least have the following,

// Implementation of hook_cron
mymodule_cron {

  // add node properties
  $newNode = (object) NULL;
  $newNode->type = '{NODE_TYPE}';
  $newNode->title = '{NODE_TITLE}'
  $newNode->uid = {USER_ID};
  $newNode->created = strtotime("now");
  $newNode->changed = strtotime("now");
  $newNode->status = 1;
  $newNode->comment = 0;
  $newNode->promote = 0;
  $newNode->moderate = 0;
  $newNode->sticky = 0;

  // add fields
  $newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
  $newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

  // save node
  node_save($newNode);
  }

After you enable your new module, just run cron by hand (go to /cron.php) and test it out to see if your node was created!


Delete option 'None' of the select list of a cck field How can I delete the option -None- of the select list in a cck field.  The field is not required.

Make the field required in Global Settings.


how to access configuration module from service I have module config, something like:

modulename.config.yml:

modulename:
  core_address: 107.101.xx.yy
  core_port: 153759
  core_user: superuser
  core_pass: superpass

And I have module service, something like:

modulename.service.yml:

services:
    modulename.my_service:
        class: Drupal\modulename\group\MyService

MyService.php:

/**
 * @file
 * Contains \Drupal\modulename\group\MyService.
 */

namespace Drupal\modulename\group;

/**
 * MyService.
 */
class MyService{

  public function __construct() { }

  public function getDemoValue() {
    $config =  \Drupal::config('modulename.my_service');
    $core_port = $config->get('modulename.core_port');
    return $core_port. 'asdf';
  }

}

problem is:

that's $core_port return empty value...

and the question is:

how i can get access (read/write) my config from my module service?

not sure if this relevant, but getDemoValue() is called from different module as follow:

/**
 * @file
 * Contains \Drupal\anothermodulename\Controller\MyForm.
 */

namespace Drupal\anothermodulename\Controller;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * MyForm.
 */
class MyForm extends FormBase {

  protected $demoService;

  /**
   * Class constructor.
   */
  public function __construct($demoService) {
    $this->demoService = $demoService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('modulename.my_service')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() { /** nothing interesting here **/ }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    /** nothing interesting here **/
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state){ /** nothing interesting here **/ }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value . '  ' . $this->demoService->getDemoValue()); // i try to print here but didn't happend
    }
  }

}

To read the variables (configs) you'd do this:

$config = \Drupal::config('modulename.my_service');

$core_port = $config->get('modulename.core_port');

To write to the variables (configs) you'd do this:

// Set and save new message value.

$config = \Drupal::service('config.factory')->getEditable('modulename.my_service');
$config->set('modulename.core_port', 153760)->save();

There's an example you can look at in the core module aggregator.

It has a settings form at /core/modules/aggregator/src/Form/SettingsForm.php

and then it adds a route to access the settings form:

aggregator.admin_settings:
  path: '/admin/config/services/aggregator/settings'
  defaults:
    _form: '\Drupal\aggregator\Form\SettingsForm'
    _title: 'Feed aggregator settings'
  requirements:
    _permission: 'administer news feeds'

You could pretty much copy the form into your module and change the variables to match your config.

Generally you'll want to add the config in your service constructor.

namespace Drupal\modulename;

/**
 * Example Service with config.
 */
class MyService {

  /**
   * Drupal's settings manager.
   */
  protected $settings;

  /**
   * Constructor.
   */
  public function __construct() {
    $this->settings = \Drupal::config('modulename.my_service');
  }

}

Then you'd access the variables like this:

$this->settings->get('modulename.core_port');


How to add fields wrapper in field preprocess My code:

function MYTHEME_preprocess_field(&$vars, $hook) {
  $element = $vars['element'];
  if($vars['element']['#field_name'] == 'field_example') {
    foreach($vars['items'] as $key => $item) {
      $vars['items'][$key]['#prefix'] = '
';
      $vars['items'][$key]['#suffix'] = '
' . $item['#item']['alt'] . '
';
      $vars['items'][$key]['#suffix'] .= '
';
    }
  }
}

I want to wrap all items in a div. I should use some code outside the foreach, but I hadn't found any solution. Can you help me?

Based on the question I'm assuming you are asking for D7 ...

You should use a "container" for this. Something like this:

$element = $vars['element'];
if($vars['element']['#field_name'] == 'field_example') {
  foreach($vars['items'] as $key => $item) {
    // Do whatever you want...
  }
  $vars['items']['#type'] = 'container';
  $vars['items']['#attributes'] = array(
    'id' => "some-id",
    'class' => array(
      'some-class',
    ),
  );
}

See this other question for more details. Also, if you want to get a little more fancy you can look at using theme wrappers.


User Revisioning and Workbench moderation modules only on certain content type Is it possible to limit the revisioning and Workbench Moderation modules only on certain content types?
On my site there are different content types that can be created but i need the features of these 2 modules to be used only on 1 of these types. Is there some way to do this?

You can most definitely configure only one content type to use revisoning and content moderation.

For example, once the Workbench Moderation module is enabled, the Basic Page content type can be configured here: admin/structure/types/manage/page

Click the "Publishing Options" vertical tab, and you will see you have the option to check the "create new revision" checkbox, which will enable content revisioning.

Below that you can click the "Enable moderation of revisions" checkbox to engage the workbench moderation module features.

You must enable revisioning to enable workbench moderation.  See image below:

For each content type which you desire content revisioning and workbench moderation, follow this procedure.


Hide taxonomy term in specific node form I have a select list of taxonomy terms, all terms are needed for searching in views, but I don't need for insert new content. I wrote a custom module, which Hook should I use to hide some terms of my select list?

Use hook_form_FORM_ID_alter

/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_module_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $vocabulary_machine_name = 'my_vocabulary'; // Makes the search faster.
  $term_names = array(
    'Term 1',
    'Term 2',
    'Term 3',
  );

  foreach ($term_names as $term_name) {
    $term = taxonomy_get_term_by_name($term_name, $vocabulary_machine_name);
    unset($form['my_field']['#options'][array_pop($term)->tid]);
  }
}


How to update content type field programmatically I try to update content type field MYFIELD with code

$update = db_update('field_data_field_MYFIELD')
    -> fields(array('field_MYFIELD_value' => $result))
    -> condition('entity_id', $nid)
    -> execute();

I see changes in database but they not reflected in node view. Also I applied this code to field_revision_field_MYFIELDtable and got the same result. How can I update MYFIELD programmatically?

It's better to use Drupa API to do that instead of missing with the database directly. you can use field_attach_update to update your field value

$node = node_load($nid);
$field = field_language('node', $node, 'field_your_field');
$node->field[$field_language][0]['value'] = 'Your New value';
field_attach_update('node', $node);


Custom theme doesn't show up in Blocks section I've looked through different threads about this issue and didn't see any answers. I have a fresh install of Drupal 7 with no extra modules enabled. I've started building a custom theme but it doesn't list itself in the blocks section even though it's enabled. It shows the original bartik theme and the admin seven theme. The odd part is I added a new block under Header which I have listed in my .info page and it showed up in my theme but I can't edit the block because the it only gives access to those two themes and not mine. How can I fix this?

I also have all of these error messages in the admin and I've barely added anything to my theme. Not sure what I'm missing.

  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/beta/modules/system/system.module).
  Notice: Undefined index: name in _ctools_list_themes() (line 574 of /home/infanity/public_html/beta/sites/all/modules/ctools/includes/plugins.inc).
  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/beta/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/beta/modules/system/system.module).
  Notice: Undefined index: name in _ctools_list_themes() (line 574 of /home/infanity/public_html/beta/sites/all/modules/ctools/includes/plugins.inc).
  Notice: Undefined index: name in system_sort_modules_by_info_name() (line 944 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_sort_modules_by_info_name() (line 944 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Warning: uasort() [function.uasort]: Array was modified by the user comparison function in system_themes_page() (line 139 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_themes_page() (line 148 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in system_themes_page() (line 190 of /home/infanity/public_html/beta/modules/system/system.admin.inc).
  Notice: Undefined index: name in theme_system_themes_page() (line 2728 of /home/infanity/public_html/beta/modules/system/system.admin.inc).

I've stripped my theme to just the .info file which the manual says is all that's required and I still get errors and although enabled still doesn't show up as the default theme in the block section. Here is my .info file labled fod.info in a folder labeled fod in the sites/all/themes folder.

name = fod
core = 7.x

stylesheets[all][] = css/style.css
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[navigation] = Navigation
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

And here are the errors I'm still getting in the admin.

  Notice: Undefined index: name in block_help() (line 69 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 146 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in block_menu() (line 165 of /home/infanity/public_html/betaD/modules/block/block.module).
  Notice: Undefined index: name in system_menu() (line 647 of /home/infanity/public_html/betaD/modules/system/system.module).

If you want to skip the full story

Search for any "*.info" file in your drupal repo that has no line similar to "name = xxxx".

My problem was due to a file named "lcov.info" in a grunt module (grunt-svgmin) in my theme.
I happended "name = lcov is not a theme" at the beginning of the file and the issue fade away.
I'll check svg-min later.

Full story

I had the same notice problem for few days.

The notice was a pattern of 3 lines :

in block.module :

line 146 :

'title' => check_plain($theme->info['name'])

and line 165

'title' => check_plain($theme->info['name']),

in system.module line 647 :

'title' => $theme->info['name'],

This pattern is replicated a variying number of times depending on the pages.

I've tried switching theme in vain.

I first tried to cleanup - hence the last part may apply.
It worked at first (which explains my first response), but came back.

*What I did : *
Open system.module and go to line 645

  foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

insert these two var_dump lines :

 foreach (list_themes() as $theme) {
    var_dump("-----------------");
    var_dump($theme->info['name']);
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],

Visit your site. It should show something like

string '-----------------' (length=17)
string 'A Theme' (length=5)
string '-----------------' (length=17)
string 'Bartik' (length=6)
string '-----------------' (length=17)
string 'Garland' (length=7)
string '-----------------' (length=17)
null
string '-----------------' (length=17)
string 'Seven' (length=5)
string '-----------------' (length=17)
string 'Stark' (length=5)
string '-----------------' (length=17)
string 'Zen' (length=3)

See this empty line where it is written null ????
This is the F....g theme.
So I looked up to the admin theme to find the culprit and got rid of "engines" folder
...But discovered engine is not a theme, so added it back.
I then went

drush pm-list --type=Theme

And found a disabled theme named *lcov (lcov) *

Believe it or not : it is not a drupal theme !!

it is a file named lcov.info in a node module -- grunt-svgmin -- in my theme

*TADA !!! *

First attempt

The sub theme I heritated was based on ZEN, but zen was not inclued any longer.
Also, theme name included numbers abc123

On a another instance of the local site I :

Added a fresh version of zen and activated it

ran drush zen "My human readable Theme name" mymachinethemename
/* the latter will generate a clean version of your ZEN subtheme */

Adjusted the subtheme.info file for regions, assets and optins

Moved the badly named theme to another folder outside of the site

started adding back assets from the old theme, then templates and includes, piece by piece,
renaming functions to match the theme name

No need to say you need to backup and work on a dedicated branch and database.
You might have to reposition blocks in admin.

Not sure it was the most efficient but as I'm roughly new to drupal it was a great way for me to dig in this legacy theme.

Charles


how to replace title field with some other field in entity reference field list? I created a content type 'country' with three fields title,description,code and i referred this content type 'country' in content type 'city' using entity reference module. In the creation page of the content type 'city' it displays a dropdown with the list of 'country's  title. every thing working fine.

but i want concatenated value of title and code in the drop down list is it possible ?

Create a view and add the Title and Code fields.
Add an Entity Reference display to your view. In the View edit page, under the Settings for the Format: Entity Reference list, check one of your fields.
On your City content type, under the Country reference fields settings, change the target type on the Mode field under Entity Selection to View: Filter by an entity reference view. After selecting, the fields in that fieldset should update making your newly created view available under the View used to select the entities field. Select your view and save the fields settings.

Your dropdown should now have your Title and Code fields.


Limit Change to Read More Link in Node Teaser to One Content Type Building on this answer:

/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#title'] = t('Read more custom text');
    }
}

does anyone know how to build the if statement to further limit the change in the read more link to a particular content type? I'm working in Drupal 8, not 7.

Add following to your THEMENAME.theme file

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function THEMENAME_preprocess_node(&$variables) {
    // ...
    if ($variables['teaser']) {
    $node_type = &drupal_static('node_type');
    $node_type = $variables['node']->getType();
  }
}

/**
 * Implements hook_preprocess_links().
 */
function THEMENAME_preprocess_links(&$variables) {
  $node_type = &drupal_static('node_type');
    if (isset($variables['links']['node-readmore'])) {
        // Change link title according to machine name of node_type
        if ($node_type == 'article') {
            $variables['links']['node-readmore']['link']['#title'] = t('Custom Text');
        }
    }
}

Clear Cache.


How to allow users to rotate a picture upon upload? On my site, users are able to upload images one at a time as nodes of content type Picture.  The Picture content type uses the core (D7) image field.

Some of my users have pictures which are taken such that they need to be rotated 90 or 180 degrees.  These users do not have easy access to image editing software, so I'd like to allow users to rotate the image on the edit node screen.

After the image is saved, I want to apply an image style (that forces scaling and cropping, etc.)  I'm also using the Manual Crop module to allow users to crop the image if necessary.

Is there a module for this, or some easy way to do it in code?  (I'm not a developer.)

I would prefer to have a solution where I can present users with a button to rotate the picture; I don't want to give them a full image editor.

If such a solution is impossible, is there an easy way to rotate the images on the back end (for admins)?  I'm happy to do it myself, as I have to check all the images anyway.

I've been fighting this issue for some hours now and have something that seems to work for me. It's not extensively tested yet, though.

My setup:

ImageMagick instead of GD as Image Toolkit (because GD strips EXIF data)
Imagecache Autorotate, part of [Imagecache Actions](Imagecache Autorotate) that provides an Image Action that automatically rotates pictures according to their EXIF orientation
EPSA Crop module: EPSA crop was the only cropping module that allowed me to use its after the Autorotate action in my image style preset (I tried at least with manualcrop, imagefield_crop, simplecrop)

In my image style I use the following actions:

Autorotate Autorotate image based on its EXIF data
EPSA Image Crop, 150x150 (with Aspect Ratio of one, as the resulting image has a square AR)
Scale and Crop, 150x150, scale and crop it even if it wasn't manually cropped.

Only drawback so far:
EPSA Crop doesn't show you the cropped image on the thumbnail of the edit page, so users might be confused if their cropping was successful after all.

Hope this helps others saving some hours of research.


How to Write Browser Tests on Custom Theme? I'm writing front end tests for a custom webform. These tests work fine when testing on the webform page of the form.
$this->drupalGet('/webform/custom_form');
$this->assertResponse(200);

However, testing the form using a custom theme and the page that the form is displayed on, does not work and the assertion fails returning a 404 response.
<?php

namespace Drupal\Tests\test_module\Kernel;

use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\webform\Functional\Element\WebformElementBrowserTestBase;

class WebformValidationTest extends WebformElementBrowserTestBase {

  public static $modules = [
    'webform',
    'test_module',
  ];

  public static $testWebforms = ['custom_form'];

  protected $defaultTheme = 'custom_theme';

  /**
   * Test custom_form page from site with custom_theme theme install.
   *
   * @throws \Exception
   */
  public function testThemeFormPage() {
    $this->drupalGet('/page-that-displays-form');
    $this->assertResponse(200);
  }
}

I have also tried creating a submodule that imports the full config and installs all dependent modules from the site. This also did not work.
Is writing front end tests for specific nodes something that is possible with Drupal Browser Tests? If not, how does one write tests for webforms (validation, fields, display, etc)?
Thanks.

I Would recommend reading
https://www.previousnext.com.au/blog/introducing-drupal-testing-traits-drupal-extension-testing-existing-sites
in this article it explains using https://gitlab.com/weitzman/drupal-test-traits
in this way you can do...
use weitzman\DrupalTestTraits\ExistingSiteBase;

/**
 * Test webform on theme
 */
class WebformValidationTest extends ExistingSiteBase
{
    public function testThemeFormPage()
    {
        $this->drupalGet('/page-that-displays-form');
        // Assert stuff here.
    }
}


How to enable configuration translation on custom module I wrote a module where I using a form for editing my module's configs. My current goal to be able to translate some of my config field's values with configuration translation. I already implemented the followings:

For the menus:

mymodule.links.menu.yml
mymodule.links.task.yml

For the translation:

mymodule.config_translation.yml
config/schema/mymodule.schema.yml (I indicated also which should be translated and which shouldn't)

I also added language into my config, however, I don't think there's any meaning for it

My current problem is: when I going to my settings page, I go to the translate tab, add a language and that form is totally empty. There's no field listed where I can write anything, just a save button... what am I missing?

config/install/mymodule.mymodulesettings.yml

service_id: ''
normalized: true
success: 'Successfully subscribed!'
langcode: en

config/schema/mymodule.schema.yml

mymodule.mymodulesettings:
  type: config_object
  label: 'Mymodule settings'
  mapping:
    success:
      type: string
      label: 'Success message'
      translatable: true
    normalized:
      type: boolean
      label: 'E-mail address should be normalized?'
      translatable: false
    service_id:
      type: string
      label: 'Service id'
      translatable: false

mymodule.links.menu.yml

mymodule.mymodule_settings_form:
  title: 'Mymodule Settings'
  route_name: mymodule.mymodule_settings_form
  description: 'Configure Mymodule integration'
  parent: system.admin_config_system
  weight: 99

mymodule.links.task.yml

mymodule.mymodule_settings_form_tab:
  base_route: mymodule.mymodule_settings_form
  title: 'Mymodule Settings'
  route_name: mymodule.mymodule_settings_form

mymodule.routing.yml

mymodule.mymodule_settings_form:
  path: '/admin/config/system/mymodule-settings'
  defaults:
    _form: '\Drupal\mymodule\Form\MymoduleSettingsForm'
    _title: 'Mymodule Settings Form'
  requirements:
    _permission: 'manage mymodule settings'
  options:
    _admin_route: TRUE

mymodule.permission.yml

manage mymodule settings:
  title: 'Manage mymodule settings'
  description: 'Allows users to configure mymodule'

mymodule.config_translation.yml

mymodule.mymodule_settings_form:
  title: 'Newsroom Mymodule Form'
  base_route_name: mymodule.mymodule_settings_form
  names:
    - mymodule.mymodulesettings

The problem as commented above is the type of the translatable properties on the schema. Needs to be changed from string to label also the translatable: false can be safely removed since is default behavior, and also no needed for label or text types.

For more information about config translation check the cheatsheet.


Access Drupal7 Database Nodes without actually having anything installed (simple php + mysql) The last days I got some trouble with the drupal database schema. I don't know anything about Drupal7 except that database entries are saved in several fields.

I need to read out all the different nodes and their attributes of a mysql server in Drupal Scheme (in the best case without actually using the Drupal environment) with a simple .php page. Is there any chance to do so?

Example: Car Entries - what I need are

field_data_field_speed

field_data_field_weight

and more.

Would be grateful for help!

UPDATE:
Database Drupal relationship between tables,  to get a node schema and node data.

If I'm not wrong you want a 'query' that connect a content type with all its fields.

Each field has it own table.

But you can connect the dots using a few queries ([content_type_name] could be article, car_entry or whatever the name of your content type is):

*Getting all the entries for a content type

  SELECT * FROM node WHERE type = '[content_type_name]'

  column id would be the [entity_id]

*Getting all fields from a content type

  SELECT * FROM field_config_instance WHERE entity_type = 'node' AND bundle = '[content_type_name]'

  this table contains column field_id [field_id] and column field_name [field_name]

Now that you have the fields:

*Get the field info using field_id and/or field_name

  SELECT * FROM field_config WHERE id=[field_id] AND field_name='[field_name]'

*Get the field data by node

  SELECT * FROM field_data_[field_name] WHERE entity_id = [entity_id]

Play around with those queries, so you get a better idea of the columns that each one of those tables contains. Then you can create mysql joins to create the queries that you need.


How to set the parent of menu items creating using hook_menu()? I need creating a series of menu items dynamically based on values from the database.

Here is a example of my hook_menu() function; in this snippet, I removed the DB queries and just added an array to prove the concept:

function MYMODULE_menu() {
  $years = array(2011, 2010, 2009);

  foreach ($years as $year) {
    $items['events/' . $year] = array(
      'title' => $year . ' Events Archive',
      'page callback' => 'page_archive',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'main-menu',
    );
  }

  return $items;
}

This works and I get three menu items in the Main Menu titled 2011 Events Archive, 2010 Events Archive and 2009 Events Archive.

The problem I am having is the position of the dynamically created menu items in the Main Menu tree; they appear at the top level, but I want they appear under the parent Events menu item.

Currently, my menu tree looks something similar to the following.

Home
Events
About Us
Contact Us
2011 Events Archive
2010 Events Archive
2009 Events Archive

It should look like the following.

Home
Events

2011 Events Archive
2010 Events Archive
2009 Events Archive

About Us
Contact Us

I know you can move the menu items using the Menu editor UI when logged in, but as these will be automatically created by the system; they need to appear automatically under Events without human intervention.

How can this be done? Is there an easier way to do this?

Since the Events menu item links to a node, for which events is a path alias, what you are trying to achieve should work if you define the menu items using the following code (I use "11" as node ID).

function MYMODULE_menu() {
  $years = array(2011, 2010, 2009);

  foreach ($years as $year) {
    $items['node/11/' . $year] = array(
      'title' => $year . ' Events Archive',
      'page callback' => 'page_archive',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'main-menu',
    );
  }

  return $items;
}

This is necessary because, if events is a path alias for node/11, Drupal doesn't expand events/2011 to node/11/2011. In the same way, it will not expand events/edit to node/11/edit, even thought the Node module defines nodes/%node/edit as one of its menu items.


Point me in the direction of developing new forum features? Probably the most confusing part about Drupal for a beginner (read: Me!) is figuring out which modules should be used to develop new functionality. I'm looking for the path I would need to take to develop the specific functionality I'm trying to create.

This is what I'm looking to accomplish:

-Attach a user created "idea" or "opinion" to a forum post or thread

-Allow users to vote on & modify these "ideas" and "opinions"

Any leads are appreciated.

In order to create a forum in drupal, you can start with the forum module. It is a core module, so it will already be installed. The following steps can make forum development simpler:

Enable the module-

Go ahead and navigate to Site Building>>Modules and check the box next to forums to enable the module.

Set up containers-

you need to navigate to administer >> forums to start setting up your new forum

Set up forums-

Each container "contains" several forums. In other words, your
containers are children of the root node and your forums are children of
your containers

Customize your forum for adding content or ideas-

The following modules can be used for content entry:

BUEditor or wysiwyg
Live
Quote
Smileys
Signatures for Forums
Comment Upload

In order to add the voting/rating features, use the following:

VotingAPI
Rate

Advanced Forum may also be used if you wish to enhance Drupal's core forum module features.


How to use Output as a link and replacement patterns to get friendly URLs In a View, with a list of fields, I have the Rewrite results --> Output this field as a link, and a replacement pattern [title]. However, the URL is not completely friendly, although I can substitute white space for dashes "-", it still can have accents or other symbols which simply do not appear when using the module PathAuto and the function ´pathauto_cleanstring´ in which they are substituted. As the links are completely dynamical, I cannot find any option in the Config of the module to have the patterns substituted.

Summarizing, I have a field "title", and I get the output rewrite as

my-page/[title]

if I have a node titled "Atención: no beber", I would like to have the URL:

my-page/atencion-no-beber

and I am getting, instead,

my-page/Atención:-no-beber

The only way I have found is programmaticaly rewriting the output again, but I am confident that it can be done without a single line of code somehow.

How can output this URL without programmatically rewriting it?

If I understand your problem correctly, it sounds like you're trying to redo the aliasing work PathAuto does in Views.

If that's the case, you can add a Content: Path field to your view (using the Exclude from display option if you don't want it visible) and use [path] in your link output to link it to your pathauto alias.


Drupal response time incredibly slow, but only from some end-users I am running across a super strange issue that is killing me. I am seeing response times coming back from my Drupal site of nearly 5+ minutes, but only for some end-users.

I have tested and ruled out a DNS problem. Pings comeback with 100ms response times, and when I swap the Drupal index.php out for a static index.html file, response time is lightning for all users.

I have an end-user in Argentina that sees 4 sec response times, and then when I try from my machine here in Los Angeles, 5+ min. The server is hosted on EC2 in their Virginia data center.

I have also tail'd the access logs and I see the Argentina user's traffic come in right away, but my traffic takes forever to show in the logs.

Is there anything in the Drupal configuration that you can think of that would cause something like this?

These kind of problems are extremely hard to debug, because it can be one of a million things. My bet is that there's some server misconfiguration.

If I was in your position, here's what I'd try to do:

Try to reproduce the problem reliably - If you can reproduce this 100% of the time, then you know you have some method to reliably recreate the problem that you're facing. Try to identify any recent changes that might have caused this -- has it always been like this, or did you do something recently to cause this?
Isolate the problem - You're most likely running on a LAMP stack. I doubt your OS is a problem, but it's most likely related to the Apache, MySQL or PHP side of things. Double check your php.ini settings, then your mySQL settings, and then your Apache settings.
Debug / Profile - There's a bunch of ways to do this. Try the devel module and performance modules. If you're comfortable writing code and developing modules, try using debug statements to figure it out. If you're more advanced, profile your site using xdebug.

Good luck.

EDIT: I missed the part of about you running on EC2 -- still, the issue still stands. See if you can reproduce it reliably, and jump straight to profiling / debug.


Omega & delta: rendering node title in a block Is it possible to render node fields as blocks with the omega theme and delta module? If I build a complex layout with zones and regions there can be situations where I need just the node title for example to be rendered in a block and then I can place it in the correct region.

Delta Blocks (sub module included with delta) makes that available as a block, as well as things like the author, terms, and post date. Combine with the context module and you can place the blocks in whatever order you like for particular content types.


Custom fields in User registration, how to save? I thought that I needed to, in my submit handler function, call user_save() to save my user profile data.  But when I call user_save I get duplicate entry errors because it appears user_save is being called twice.

here's a snippet of code:

function all_data_form_submit($form, &$form_state) {

  $fname = $form_state['values']['field_first_name']['und'][0]['value'];
  $lname = $form_state['values']['field_last_name']['und'][0]['value'];

$edit = array(
  'name' => $form_state['values']['name'],
  'pass' => user_password(),
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['init'],
  'status' => 0,
  'access' => REQUEST_TIME,
    'field_first_name' => array(LANGUAGE_NONE => array(array('value' =>
$form_state['values']['field_first_name']))),

);

user_save(drupal_anonymous_user(), $edit);
<snipped>

If you insist use code I suggest below method

function all_data_form_submit($form, &$form_state) {
$fname = $form_state['values']['field_first_name']['und'][0]['value'];
$lname = $form_state['values']['field_last_name']['und'][0]['value'];
$name=trim($form_state['values']['name']);
$myuser=user_load_by_name($name);
if(!empty($myuser)){
        $edit = array(
                'field_first_name' => array(LANGUAGE_NONE => array(array('value' =>$form_state['values']['field_first_name']))),
                // .. and every field you want to save
                );
        user_save($myuser, $edit);
    }
}


Twig template name for field when content type is viewed in particular view mode Based on twig template naming conventions I have created twig for any field type of given content:

field--node--myContentType.html.twig

Is it possible to use different twig when myContentType is visible in "full" view mode? I've already tried:

field--node--myContentType--full.html.twig

But it does not triggers. I can use node--myContentType.html.twig and node--myContentType--full.html.twig for full view of the node, but it doesn't work for field twig.

Field templates have no name suggestion for the view mode.

From the linked page:

  This page lists the conventions used for the base html structure, the
  page, regions, blocks, nodes, fields, and other core components. (It's
  good to know that it is possible to create custom template name
  suggestions using function hook_theme_suggestions_HOOK_alter.)

You have to create a custom name suggestion.

You find the view mode in the variables of the field: Getting node view mode in field preprocess


Create a list of taxonomy terms which filter specific nodes I would like to add a list of taxonomy "links" within my view so when ever a user clicks a specific term, only nodes tagged with that term will show up in the view.

Is there a module that can create a navigation of taxonomy terms within a view, to filter for specific nodes?

There is no need to install module. create a field of taxonomy terms, in the view create a contextual filter of that field and it will work.

To create a navigation you need to loop through the taxonomy terms. it is something like this code. I am not able to execute the code right now to give you the exact code but using Devel module and looping (foreach)throught the objects you can get the terms and use them to build the navigation.

$name = 'YOUR_VOCAB_NAME';
$myvoc = taxonomy_vocabulary_machine_name_load($name);
print kpr($myvoc);

This code will print out the list of terms and their properties.


Cannot move block Main Page Content to different region Realy need your help. I'm working with quite old Drupal 7 site and for some reason I cannot move the Main Page Content block to any different region. When I drag&drop it to the Header region (on block management page) and then click save, looks like it sucessfully moved, but when I go to the actual page I can see that it still located in the Content region.

Looks like something is preventing Main Page Content block from moving to different region but I don't know exactly what. I've updated Drupal to the latest release - no difference. I've switched to another theme - no luck.

What might be the problem? I'd be very gratefull for any idea.

Something similar happened to me.  The problem was that the main content block was configured to show on "all pages except those listed" and the one listed was front.  When I removed front, I was able to move the block, or rather my changes showed up on the front page too.


How can I create a select list with all languages? I need to have a field on a form, where the user can choose from the set of world languages for an event.

It's going to be an Autocomplete term widget (tagging) field.

How can I reuse the inbuilt language list in Drupal for this purpose?

there is the _locale_get_predefined_list which return you an array.
so you need to do the field yourself.

you also could try language_field, you should be able to use that directly in your form.


My "install module" link "install module" link disappears from module section in "Drupal 7" for some reason.How can this link enable to install my new modules.

Go to admin/modules and
Enable Update Manager under CORE modules list

Update Manager: Checks for available updates, and can securely install or update modules and themes via a web interface.


How do you create a CCK field that presents a node creator with a list of the website's users? I'm trying to add a CCK field that will present a site manager with a list of instructors which are actually a sub-group of already-authenticated users with the role name of "instructor" for a "class" content type.

The list of instructors is pretty large, and I'd rather use the actual users that are already on the site to populate that field instead of just having a plain select list.

The "class" content type will have a couple other fields, like location, day of the week, and class type. The problem is figuring out how to add the instructors, who are already authenticated users to the content type via a select list of some kind. Does anyone have any ideas on how to best accomplish this? I can't find a suitable CCK field to do what I'm trying to do, and as mentioned previously, I don't want to use just a text/select list.

You can setup a view for those users and then install Views Field View module. With this module you can add a new field to your node which is a link to that view.

That view will be able to get arguments coming from the node where it's linked from.


How to enable install from url in Drupal Commons? I cannot find any option to install the modules from a url.
Currently, I am installing them through cpanel by manually uploading, unzipping etc.
Can anyone suggest a solution?

Also you can try Drush

  Drush or drupal shell is a command-line utility to help the site
  building and maintenance workflows.

The following will download and enable the module:

drush en module_name -y

Example Commands

drush dl cck zen

Download current recommended versions of CCK module and Zen theme.

drush en content

Enable the content (cck) module.

 drush vset theme_default theme_name

make theme_name theme default theme


In drupal 7, what does make a menu link a stale item? I'm creating menu links with this kind of code:

$item = array(
  'link_path' => drupal_get_normal_path('link-path'),
  'link_title' => 'link-title',
  'menu_name' => 'menu-name',
  'weight' => 0,
  'expanded' => 1,
);

// Look the table first if the data does exist
$menuId = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>
$link['link_title'], ':link_path' => $link['link_path']))->fetchField();
if ($menuId === FALSE) {
    $menuId = menu_link_save($item);
    echo "New entry " . $menuId . PHP_EOL;
} else {
    echo "exists " . $menuId . PHP_EOL;
}

Later on, if I call any of these functions:

menu_rebuild()
drupal_flush_all_caches()
Or if I clear the cache from the web ui.

All my menu links are deleted. According to the documentation, these functions "remove stale items from {menu_links}". And I am unable to find out what is missing in the parameters of menu_link_save or if I need an extra step. If I stop the script before flushing, the content table menu_link looks OK.

I'd like some explanations about the workflow of menu_rebuild that causes some objects to be deleted (i.e. is there a flag or something, etc.).

Is it related to Stale menu link static caches? https://www.drupal.org/node/2425261


Cached rendering depending on a parameter I'm trying to render a template given a request parameter but I get the same result once the cache is set.

Let's say I have this template :

-- {{ step }} -- {{ xxx }} --
{% if not step %}not step{% endif %}
{% if step == 1 %}step 1{% endif %}
{% if step == 2 %}step 2{% endif %}

And this preprocessor

function themename_preprocess_page(&$variables) {
    $request = \Drupal::request();
    $variables['step'] = null;
    $variables['xxx'] = rand ();

    if ($request->query->has('step')) {
        $variables['step'] = $request->query->get('step');
    }
}

When I work with the cache template disabled, I get the expected resut, e.g when requesting page?step=1, I get step 1, page?step=2, I get step 2 and so on. However, when the cache is enabled, the first page load is correct and the subsequent loads take the same markup (if I first load page?step=1, I get step 1 whatever parameter I use after that).

How can I tell Drupal to process my variable even if the cache is enabled?

Add the cache context url.query_args in preprocess:

function themename_preprocess_page(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args';

Or more specific:

  $variables['#cache']['contexts'][] = 'url.query_args:step';


How can I translate the field group description? I have created two field groups on the manage form display tab for a content type. I have added some description also.

On the interface translation, I can translate the field group labels but there I can't translate the description of a field group. As when I search the description there I can't find any results.

I also checked it in the config translation but field group is not present on that page.

Is there any way I can translate the field group translation?

As far as I know there is no proper UI for this yet, but field groups are config, so you should be able to translate all strings by creating/editing translated versions of those config files.

First, export your current config, e.g. drush config:export

Then, in your config/sync directory look for files like core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml. In those files you will see a structure like

langcode: ISO2CODE
status: true
depenencies:
  config:
    - ...
third_party_settings:
  field_group:
    GROUP_ID:
      children:
        - field_foo
        - field_bar
      label: MY_GROUP_LABEL
      format_settings:
        description: 'MY DESCRIPTION'
...some more stuff...

The third_party_settings/field_group contains your group labels in your primary language. To translate a label, create a file language/LANGCODE/core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml below your config/sync directory.

This file must contain the same structure as the one in the main config file, but remove everything that is not translateable:

third_party_settings:
  field_group:
    GROUP_ID:
      label: MY_TRANSLATED_LABEL
      format_settings:
        description: 'MY TRANSLATED DESCRIPTION'

Finally, reimport the config with the translated labels, e.g. drush config:import


Non-blocking asynchronous HTTP requests I need to send asynchronous and non-blocking POST HTTP requests from a Drupal service.

Using Drupal 7, I used HTTP Parallel Request which worked fine.

But this module is not available on Drupal 8. And it seems that the default D8 HTTP Client, Guzzle, doesn't allow to do this : https://stackoverflow.com/questions/35956516/send-asynchronous-request-without-waiting-the-response-using-guzzle.

Is there some way I can achieve that with Drupal 8 ?

Edit: If I don't find how to do it with Drupal mechanisms, I will go with this fsockopen...

I ended up implementing a custom function on the base of this post :

private function async( $method, $url, $params = array() ){
    // Get URL parts
    $url_parts = parse_url( $url );

    // If needed, append params to query url
    if( $method === 'GET' ){
        $url .= '?' . http_build_query( $params );
    }

    // Open socket
    $port = isset( $url_parts['port'] ) ? $url_parts['port'] : 80;
    $fp = fsockopen( $url_parts['host'], $port, $errno, $errstr, 30 );

    // Build HTTP request
    $request = $method." ".$url." HTTP/1.1\r\n";
    $request.= "Host: ".$url_parts['host'].":".$port."\r\n";
    $request.= "Connection: Close\r\n";
    if( $method === 'POST' || $method === 'DELETE' ){
        $post_string = Json::encode( $params );
        $request.= "Content-Type: application/json; charset=utf-8\r\n";
        $request.= "Content-Length: ".strlen( $post_string )."\r\n";
        $request.= "\r\n";
        if( isset($post_string) ){
            $request.= $post_string;
        }
    } else {
        $request.= "\r\n";
    }

    // Send request and immediately close the pointer
    fwrite($fp, $request);
    fclose($fp);
}


Calendar: How to add additional month specific calendar views By default - calendar will create Month, Week, Day, Year views for a calendar.  The month view is for the current month.  I need to create a Next Month view as well.  Or perhaps a view for a specific upcoming month.

How can I do this?

Mike R

A view of the calendar should have previous and next buttons to link to views of the previous and next months. each of these have a specific url that you can reference or use if you need to access them other than through the buttons.


Use functions: uc_file_user_downloads function and theme function I would like to print files user download from ubercart on  a new page. I find this theme function "uc_file_user_downloads" but i don't know how to use it.

To print the table i write this little code:

<?php

 print $user->uid;
 $account = $GLOBALS['user'];
 print theme('uc_file_user_downloads', $account);
?>

And the result i have:

  26 Fatal error: Cannot use object of type stdClass as array in
  /code/includes/theme.inc
  on line 1070

Could you explain me the correct way to pass the parameter on this function. I tried to cast the stdclass to array but this is not working.

If it is drupal 6 in order to print the  table you can simply do print uc_file_user_downloads($account); ,this function will internally call the theme function theme_uc_file_user_downloads

What you are trying in your code is combination of both.So in drupal 6 try witih the following code.

global $user;
print uc_file_user_downloads($user);

In drupal 7 the function uc_file_user_downloads($account); returns array unlike html in drupal 6. So try the following with drupal 7

module_load_include('inc', 'uc_file', 'uc_file.pages');
global $user;
$table = uc_file_user_downloads($user);
print drupal_render($table['downloads']);


How to edit webform's email field default error message? How to edit  webform,s email  field  default error message ?
My case is:
I have to place error message just below the email field for this purpose i have used inline error message module and client side validation ,these modules worked well for me .

But the problem is that  webforms default error message of email field  commimg below the email text (say: your email address is not valide) but i dont want this default error message .suppose i want to print error message (say: you must provide a valid email address) for this i have created a custom validation function but after creating custom validation fuction my error message showing above the text box not below the textbox only default error message showing below the email field by using inline error message module that is not my requirement.

If i change the default error message(say: your email address is not valid) to  (say: you must provide a valid email address) i can acheive the desired task

But how to achieve?

String Overrides module may be an alternative.

  Provides a quick and easy way to replace any text on the site.


HTML tags in views field label. Is it possible? By default in views field label it possible to put only plain text, so the markup looks like:

  Price: -10%
  9.99

But I need to add some text wrapped with tags, like

  Price: -10%
  9.99

How it is possible?

Uncheck create label

Click on rewrite results, check mark override out and put:

  Price: -10%
  {{ field_price }}

I'm not 100% that it's {{ field_price }}, but you can click on replacement patterns to see the pattern name.


How do I force a new module to inherit the file permissions the modules directory has, after update? I'm using Drush 7 on Windows Server 2012 and IIS 8. Whenever I use drush up to update a third-party module, IIS can't access the files because during the update process, when drush is replacing the module files, the entire module folder contains permissions assigned to only the administrator, with inheritance disabled.

I need Drush to replace the module files with inheritance enabled; otherwise, Drupal will complain that it can't read the module files and break my site.

How can I achieve this?

I know this is old but recently I stumble upon the same problem:

Site installed on IIS 8 under Windows Server 2012 R2
After updating with Drush core and modules, permissions of modules
and updated files get messed up.

Solution I found is:

right click on website folder> Security > Advanced
check: "Replace all child object permission entries with inheritable
permission entries from this object"
Apply

If files don't shows navigate to /sites/default/files or whenever files are stored and change permission to this folder and subfolders.


Get drupal form structure I have created content type with CCK in which there are fields like taxonomy, filefield, textfield etc.
Now i want form structure of this content type.

Try hook_form_alter

function hook_form_alter(&$form, &$form_state, $form_id) {
 // If you can find the $form_id you can print the exact form.
 print_r($form);
}


DB queries fast, Apache response slow, high PHP CPU Working with D6, trying to get a page running more efficiently. I made a lot of progress by installing the Cache Backport module and configuring Redis, so devel shows my DB queries are a fraction of what they were before. Load testing shows that the site can handle a much heavier load than ever. Making progress.

The problem now is that the initial connection to the site is slow, usually 2-3 seconds but often as high as 5 or 6. It's not the database doing it, Devel shows queries are very fast, less than 500 ms on average. It seems to be pretty random. I'm working off a test server right now, I'm the only one on it, but I know it's not just me because any tests with external services show the same thing. My log files are clean, both Apache and syslog. The only other symptom I've seen is that prior to the page's load, PHP will spawn 6 processes and CPU will be high.

I've tried using XDebug to trace PHP's behavior but nothing is jumping out at me. It's definitely loading a few different files, including the Domain module, but I can't really tell what's happening.

I'm using fcgi, Debian 7, Apache is using mpm-worker, if that matters at all.

I would suggest trying to use drupals caching to cache the page and installing a php caching system such as APC or OP cache (if using php 5.4 or higher for OP caching) and this should speed up significantly.  If you really want a performance hit then try using varnish to cache the pages.

The reason is by default apache does not do a very good job rendering pages in the sense of requests per second and can significantly increase when caching and exponentially increase using varnish caching.

So in short the following is good for performance:

PHP:
1. ) APC cache or OP caching.
2. ) Varnish caching
3. ) MYSQL caching such as memcache


Is it possible to export only specific content types? While I was working on the theme update on my test server, original website got quite a lot of updates. But I can't just re-import the whole database, since I've got some new blocks and views here now. Can I somehow export only specific content types and import only them?

Any handy feature in Drupal itself, or maybe module? It should be a wide-spread requirement, since Drupal is such content oriented.

Take a look at the Node export module.  From the project page:

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site. The idea is similar
  to the way you export/import Views or Content Types.


How do I get all the options of a field? In Drupal 7, we are using the following code.

$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

What can we use in Drupal 8?

Drupal 8.9.x still has the options_allowed_values() (a function implemented in the Options module). If the field uses a selection, check box, or a radio button widget, you could use the following code. The same function is still implemented in Drupal 9.3.x, the latest Drupal version under development, at the time I am adding this note.
$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('entity', 'bundle');
if (isset($field_definitions['field'])) {
    $allowed_options = options_allowed_values($field_definitions['field']->getFieldStorageDefinition());
}

Replace 'entity' with the entity ID (for example, 'node' for nodes), 'bundle' with the bundle machine name (for example, 'article' for Article nodes), and 'field' with the field machine name.
Keep in mind that this code requires the Options module. The module using the code I shown should declare its dependency from it.
Using options_allowed_values() has the benefit that, if the field has a function returning the allowed values, that function is called. The following is the code used by options_allowed_values() to achieve that.
if (!isset($allowed_values[$cache_id])) {
  $function = $definition->getSetting('allowed_values_function');
  $cacheable = TRUE;
  if (!empty($function)) {
    $values = $function($definition, $entity, $cacheable);
  }
  else {
    $values = $definition->getSetting('allowed_values');
  }
  if ($cacheable) {
    $allowed_values[$cache_id] = $values;
  }
  else {
    return $values;
  }
}

Using options_allowed_values() also allow to cache the allowed values. In this way, calling options_allowed_values() for the same field (and same entity type) multiple times has a minimal impact on performance.


Language switcher give 404 I need to translate part of a website.
So I had enabled necessary modules : content translation, i18n + i18n sync.
Then create some translation of 2 differents content type (after setting them to enable translation).

Put the Language switcher block active, and it appear on translatable contents.
But when I want to switch, the link is good but system give me a 404.

In permission level, I see nothing to do .

What is missing in my settings ?

Thanks

Solution was here : https://drupal.stackexchange.com/a/150657/8753

For D6 the path is : admin/settings/language/edit/en

No need to set the prefix into the URL provided by pathauto here : admin/build/path/pathauto

in admin/settings/language/configure , both choice between Prefix only or Prefix and alternative solution seem to work.


Exporting a View CSV during Cron I'm working on a drupal 7 site and my client would like to have a certain view export as a CSV once a day into a folder. My initial thought was to tie this functionality to our cron schedule, but I'm running into a wall. How can I add functionality to cron? And more specifically, how could I get a specific view to export as a CSV during cron?

Thanks!

You might want to look at the Views Data Export contrib module:
https://www.drupal.org/project/views_data_export

This module exposes a drush command that can execute the view and save its results to a file.

drush views-data-export [view-name] [display-id] [output-file]

Since you can call this command via drush from the shell, you should also be able to add the drush command to the operating system crontab (not Drupal cron) so that it executes on a schedule:

https://www.ostechnix.com/a-beginners-guide-to-cron-jobs/


Not showing clickable links in search results I'm fairly new to Drupal but have gotten a hang of installing modules and setting up there configuration pages.
The company site i'm working on is running on Drupal 7.1.4 and is using Node Search to look through books that they have created for documentation of their products. The problem with the node search was the lack of proper phrase search and partial words not being found.  I have Search API, Search Facets, Search Pages and Fuzzy Search modules installed and it appears to be working but not as expected.

Unfortunately the results come back as unclickable links, with some results coming back as text only excerpts of certain books and most results coming back as what appears to be just the author name with a time stamp of the books that are available.

I'm having a bit of trouble finding a way to display these search results as proper links and text excerpts with highlighted search terms.

Was hoping someone here would be able to assist.

A couple of possibilities. Is the site using Search API views? If so perhaps there is a search results view that you can adjust.

Another idea might be that someone has customized the search results templates in the theme to be unlinked or otherwise weird. Check in your theme folder for any search related templates.


Display price on Views for product variation I'm confused, how to display on Views just one price for product with variations? I have product with 2 variation, and both prices are displayed, like:
Price: 1-Price for 1-Variation-Product , Price: 2-Price for 2-Variation-Product
I mean the created from me some custom view-page, like "/all-products" (like some catalog page) where are displayed all of products or goods with their prices. And for the products with variations I see, that there will be displayed all of prices of this product.
In the Settings of View-Page ("/all-products") I have in Format section: "Show:Fields | Settings".
In RELATIONSHIPS:
Variations: Product variation
(Variations: Product variation) Product: Product
And in Fields I have:
(Variations: Product variation) Product variation relationship: Price
where in the Setting I have:
"Use entity field rendering"
There are no Setting to handle multiple values.
If I check out "Use entity field rendering" then will be shown some settings for handling of multiple values, but in this case it will be no price displayed on view-page (/all-products), because the prices are rendering from product entity, as I understand.
So, this is the problem
In addition: the product with variation has all the same price, not different prices for different variation.
What is teh best way to handle it?
I have Drupal 9, Commerce 2
Thanks

I think I found a solution, in "Fields" just instead
"(Variations: Product variation) Product variation relationship: Price"
need to use:
"Product datasource: Variations", and there are some settings to handle multiple values.
In "Formatter" need to set "Rendered entry", instead default "Label"


Is there a way to setup a site monitor on drupal? I have the current question: https://drupal.stackexchange.com/questions/37712/ubercart-items-wont-add-to-cart-unless-cache-is-cleared. In order to try and narrow down what the issue is. I'm curious if there is a way to setup a sort of monitor or logs to be able to get some more insight as to what is going wrong. I know of the typical status reports, Log messages & server logs. But is there anything that might be able to give me more drupal related details?

mysql and httpd logging on your server should help a bit.  turn them on (and adjust reporting levels) but make sure you don't fill up your disk with logs.  turn the logging level back down to something normal once you've looked for a while.


Pathauto menu token duplicated for a menu added in hook_node_insert I have a content type using the following pathauto-token pattern: [node:menupath]/[node:title], I added manually a menu using a hook_node_insert (see my previous question: creating a menu in a hook_node_insert()).
When the node is saved it doesn't have the [node:menupath] token in the URL, just the [node:title]. I decided to generate the path using pathauto API and this code:
$options = array(
  'language' => isset($node->language) ? $node->language : LANGUAGE_NONE,
);
module_load_include('inc', 'pathauto');
$uri = entity_uri('node', $node);
$path = pathauto_create_alias('node', 'insert', $uri['path'],
  array('node' => $node), $node->type, $options['language']);

Doing this lead to duplicates in the url_alias table, the [node:menupath]/[node:title] alias being created first then the title.
I tried to add a $node->pathauto_perform_alias = FALSE; in a presave, but seems to be inefective.
Also I tried to set my new path in the hook_node_insert but had no success:
$path = pathauto_create_alias('node', 'insert', //...
$node->path = $path;

My code doesn't feel right, what would be the normal way to avoid duplicate and getting my pattern to work ?
Thanks

I finally moved the insertion of my menu in hook_node_presave() and then pathauto worked normally.


Render array to markup after submitting a form In my Drupal 7 custom moudle, i would like to output result of form as an formatted array.
Simmilar like you can print_r or printf arrays.

 $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $form_state['temporary']
)

so  $form_state['temporary'] is array, but i do not want "array" text to show up but formatted array representation, whatewer is in it.

Thanks!

Just try like:

'#markup' => '<pre>'.print_r($form_state['temporary'], true).'</pre>';

you could just save the print_r() value to variable and then output that to a Div or something ...


How do I alter the behavior of the form fields contained within the paragraph field? Using the Paragraphs module in Drupal 8, I am attempting to alter the behavior of the form fields contained within the paragraph field. This is so I can add behavior like AJAX callbacks, hide show other fields using states etc.

I can access the paragraph parent field using this function:

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
}

But how do I access the fields inside the paragraph?

I have tried hook_field_widget_form_alter but to no avail.

How do I do this?

Note: I am still quite new to Drupal development.

Since paragraphs^1.3 you can use hook_field_widget_WIDGET_TYPE_form_alter() (I linked the 8.2 version because there is a good comment about using the hook).

You can see the following example in modules/contrib/paragraphs/tests/modules/paragraphs_test/paragraphs_test.module

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function paragraphs_test_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'altered_paragraph') {
    $element['subform']['field_text']['widget'][0]['#title'] = 'Altered title';
  }
}


Views slideshow displaying multiple items Under view action advanced Options of 'Views slideshow' I have defined 4 items per slide which is displaying 4 items one under each other. Is there a way we can display them in a single row?

You need to add views slidehshow cycle module as well


Alternatives to Messaging and Notifications I maintain a Drupal 6 site for a team of scuba-divers.
Given the discontinued support for Drupal 6, I am looking at upgrading the site to Drupal 7.

We primarily communicate by e-mail, so we have set up a Messaging+Notifications thing, where users can subscribe to new nodes of a given node-type, with one primary purpose: When a boat-commander arranges a new diving trip (node-type) all interested divers receive a notification mail, so they can sign-in to the trip.
The same functionality goes for clubhouse events and articles in general (secondary).

Mails are formatted so, that they contain a link to the node on the site (obviously), and they also contain a link to unsubscribe to further mails of same kind.

It seems Messaging+Notifications are not (actively) maintained on D7, so I am looking for an alternative.

I have tried a Commons distro, but I just cannot get the grasp of the Messages (log?) and Flags concept. It seems to me that it is build to click-to-follow existing posts, but I want to have the option to always follow posts of a certain kind.

Am I misunderstanding the Messages module, or am I looking at a wrong module?

A project that is similar in scope to Notifications and is actively supported for Drupal 7 is Subscriptions.

You may also want to look at some of the more lightweight notification modules. The project Notify is designed to send out notifications whenever new content of a certain content type appear (Disclosure: I am the maintainer of Notify).

There is a Notifications via e-mail comparison at Groups.Drupal.org. This gives you a good idea of what is available for Drupal 7.


Mapping Drupal User to SalesForce User What is the best approach to map Drupal Users to the same user profile that is in SalesForce? Essentially I would want to add the User UID to their corresponding SalesForce User profile. But if there is a better way I would love to know. Thank you.

You can use Salesforce module.

  This suite of modules supports integration with Salesforce by
  synchronizing Drupal entities with
  Salesforce objects

please refer to this link.


Drupal 6: Move the 'Add new comment' link to the bottom Like the subject says. I'd like to move the 'Add new comment' link to the bottom of the comment list. The only thing we're using them for a is a forum, and this is how we want them set up. I can't seem to find out to move this section in the template.

Since Drupal is such a highly configurable system, there are a few ways to accomplish what you want. Here's just one example.

The first part of the equation is to remove the link from the node's links array. This approach removes it during the theme call.

<?php
/**
 * Override theme_links() so we can remove or alter any links we don't need.
 */
function MYTHEME_links($links, $attributes = array('class' => 'links')) {
  unset($links['comment_add']);

  // Rather than include all the original theme_links() code in this function,
  // we can just call it directly here.
  return theme_links($links, $attributes);
}
?>

After that, you have a few options of where to readd the link. The primary function that builds the display for comments and comment controls is comment_render() in comment.module. It builds the comments display using a few different theme calls, so it's up to you where you want to add the link back in. Probably the easiest approach is to copy the file /modules/comment/comment-wrapper.tpl.php into your theme folder and add the code for the link there. Alternatively, you could either put it above or below the comment controls form (by overriding theme_comment_controls), or by overriding any of the other comment theme functions. Whichever approach you take to adding the link back in, you can get the code for the link from the comment_link() function -- open up comment.module and search for "Add new comment" to find the link code.

Good luck!


How can I indicate "NEW" content in faq module after updating an entry? I use the faq module in Drupal 7.

After I update an entry, I want to display a visual indicator (e.g. "NEW!) if the node has been changed/updated recently.

if I don't use views module.

To do this you can use the Computed Field module.

Add a field to your FAQ content type and select Computed Field as the type.

In the Computed Code (PHP) box add the following code:

$entity_field[0]['value'] =node_mark($entity->nid, $entity->changed);

In the Display Code (PHP) box, enter the following:

$display_output=theme('mark', array('type'=>$entity_field_item['value']));

Set the field NOT to store the value in the database.

Go to admin/structure/types/manage/faq/display, move your field above the answer field, set the label to Hidden and the display format to Unsanitized.

This will display either 'New' or 'Updated' as the case may be for the FAQ page, just as it is displayed on the content list..


Using Views' Contextual filters in a Panel for one taxonomy term I have one taxonomy term, Country, which is linked to another, People. One people is from one country.

How can I make a view in my Panel, using Contextual filters, in order to show the specific view I prepared for "Country" ? I tried to use contextual filters to do so, and it works when I use the preview with the Country ID - but not in Panels.

If you want to display a different view for a country, I think what you probably want to do is use the Taxonomy Term override page rather than using contextual filters.

To do this, go to the pages admin screen (/admin/structure/pages).  Then, enable the Taxonomy term template panel to override the display of taxonomy terms using Panels.

To show a custom view, you can edit the Taxonomy term template panel.  This will allow you to use the taxonomy term as arguments for your view, because Panels understands that you are overriding the taxonomy term display.


How do I change a field description using hook_form_alter()? I used to simply replace the string in the #description property, but now it isn't a string and I am not able to change it.

I found a solution.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['field_myfield']['widget'][0]['value']['#description'] = \Drupal\Core\Field\FieldFilteredMarkup::create(t('My custom description'));
  }
}


Best way to trigger multiple Feeds importers? I have three importers set up and working fine; all creating nodes from an XML file using HTTP fetcher.

The created nodes reference each other (using Node Reference), so the importers must run in a certain order.

To automate this, I'm not using the periodic import option as it won't keep things in sync. Instead, I created a simple Rules action:

<?php
function my_import_action_import($importer_name, $feeds_node) {
  while (FEEDS_BATCH_COMPLETE != feeds_source($importer_name, $feeds_node)->import());
}
?>

Then I created a rule that runs on cron with three actions (one to trigger each importer).

As far as I can tell, it seems to work. But I get a warning notice that doesn't happen when I run the importers manually:

  Notice: Undefined offset: 2 in references_feeds_set_target() (line 203
  of
  /home/mysites/drupal7/sites/default/modules/references/references.feeds.inc).

I also have a feeling that Feeds was meant to use job scheduler for a reason, and not run on cron in this way?

Thanks!

I had almost the exact same need where I had to import data from xml files usinf HTTP fetcher. I had 5 importers and had to run one after the other.

I declared a function that triggered the importers programmatically one after the other.

For triggering each importer this is what I did -

$feeds_source = feeds_source($importer_id);
$feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
$feeds_config['source'] = $url;
$feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
$feeds_source->save();
$feeds_source->startImport();

where $importer_id is the machine name of the importer; you can find it in the table 'feeds_source' and $url is the url where you have your xml file. feeds_source()

And there's this awesome cron module - Elysia Cron which gives in its own words 'a fine grain control over each task and several ways to add custom cron jobs to your site'.

With Elysia's hook_cronapi() you can set up a cron job which calls your function at your set up intervals.

Though it seems really a long since your question.....I hope this is of some help.


How can you price attribute options in drupal commerce properly? Currently I am creating a site for a repair shop. Say I am repairing a laptop motherboard:

Motherboard Repair = $100

As with a motherboard repair, it could consist of a power slot repair, cpu replacement, memory replacement, or video card replacement. I charge $100 for any of those repairs, but I consider them as a Motherboard repair. I want to create a page where they can select one of those, but not create a SKU for it. How can this be done?

In Ubercart, it would just be 1 product and 1 attribute with those 4 options. Since they aren't tangible products they don't need an SKU. Its more of a reference for the business owner to know what to repair which is selected by the customer on checkout.

Now say if I did have varying prices for each of those options. How can that be done too?

As per your requirement you want to give option to the user to select one from many option from your given list while purchasing the product, but you don't want to create separate SKU for each of them. I think Commerce Option module will work for you in this case...I hope it help...Good Luck :)


Menu not updated after role purchase after a user purchases a certain role (i use UC and a rule to do so) the main menu is not updated automatically. The user had access to everything that belongs to the new role, but the menu only gets updated when i manually clear the cache on the site.
In searching for a solution i found this has to do with menu caching.
I don't use drush or devel and need a solution that suits a production site. Is it best to completely disable menu caching? And how do i do that? Is there a module for that?
Thanx,
Cas

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

  It currently provides actions for:

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

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


How to get $_POST and $_GET parameters I ajaxly call a route and pass data to it, In my controller, I want to get $_POST['var'] , $_POST['var2'], it seems because of using HttpFoundation in drupal 8, $_POST and $_GET are not exists in old method, How I can access $_POST parameters in custom Controller?

From the change record:

$name = $_POST['name']; // form param

becomes

$name = \Drupal::request()->request->get('name'); // form param

Incidentally, for GET vars, you would use:

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


How do I add a new group permission? How to add new group permissions? describes how add new group permissions when using the Drupal 7 version of the module.
function [mymodule]_group_permission() {
  return array(
    'schedule publishing of nodes' => array(
      'title' => t('Schedule content publication'),
      'description' => t('Allows users to set a start and end time for content publication'),
    ),
    'view scheduled content' => array(
      'title' => t('View scheduled content list'),
      'description' => t('Allows users to see all content which is scheduled.'),
    ),
  );
}

This does not appear to be the case in Drupal 8.
How can I add my own custom permissions to the group permissions screen, in Drupal 8?

I found the answer to this question here: https://www.drupal.org/project/group/issues/2959912

Create a .yml file, for example: my_module.group.permissions.yml

It should contain:

access group menu edit:
  title: 'Edit group menu'
  description: 'Allow users to edit the group menu'

First line is the permission itself.  I did this. Flushed cache, and my permissions now appear in Group module permissions screen under "My Module".


How to combine different node in single views I'm currently doing recruitment system by using drupal 7..

First..
In my system, applicant need to fill up the "Applicant Profile" (node) before they can apply for the job.

Second..
i am using flag module..if applicant want to apply the job, they must flag the job..after that, they need to fill up their "name" and make some "pitch" (Flagging form)..

Third..
In my views, i add "flag" at relationship so i can add the flagging form details in the fields.At filter criteria, i add the "content:type (Applicant Profile)"

My question..
how i want to combine the details in flagging form and applicant profile in single views?
because currently the views fields only can display the flagging form details..

i already add two different "content:type" at filter criteria. but it does't work..it only show the details on one content type only..
Thank You in advance..

For Applicant Profile use Profile 2 module instead of node. Then when you create the View of Job List, add relation to Flags, Content: Author and User:Profile, in that way you will get all the fields you need.


Print current logged in user without link I'd like to print out the name of the user that is currently logged in, but not have it be a link.

Currently I have:

<?php print l($user_name, 'user/' . $user->uid);?>

But this prints out a link to their user profile. Any way to make their name just text and not a link?

l() is the function that creates a link, so...

<?php print $user_name; ?>


Installing Drupal module requires ftp access - macOS localhost I have Drupal 8 running on localhost on macOS Catalina. When I try to install a module, I get prompted to enter ftp credentials (which I don't know). See the following screenshot.

I've seen solutions that suggest this ftp prompt is caused by a permission issue in sites/default folder and can be fixed with chown www-data sites/default or chown apache sites/default for linux but those commands on a mac throw 'chown: www-data: illegal user name' or 'chown: apache: illegal user name' error. What do I need to do to enable installing modules/themes without being prompted for ftp?
EDIT
I'm specifically asking about installing modules by the url method from the admin interface.

Depending on how you are running this locally (native, Docker, etc) this can differ, but I will assume you are using what comes with macOS to run Drupal.
The difference here is Mac does not have a www-data or apache user like Linux does. If you are running with the defaults, the user you are looking for is _www (unless you have modified this in Apache confs).
So, you will want to do:
chown _www (directory)

Technically, this is probably better asked on ServerFault, but I can imagine there are a lot of people trialling or demoing Drupal who just use what is on Mac to do it, and will come across this post finding it helpful.