Can't get hook_field_attach_view_alter to set the value of the field I'm using some hook code I got from Drupal 7 show empty fields in order to show all of the empty fields on my node when viewing it. I would like to put a simple - as the displayed value when the field is empty.

function mymodule_field_attach_view_alter(&$output, $context) {
    // other stuff clipped...
    $output[$field_name] = array(
        '#theme' => 'field',
        '#title' => $instance['label'],
        '#label_display' => 'inline',
        '#field_type' => $field['type'],
        '#field_name' => $field_name,
        '#bundle' => $node->type,
        '#object' => $node,
        '#items' => array(),
        '#entity_type' => 'node',
        '#weight' => $display['weight'],
        0 => array('#markup' => '-'),
    );
}

I pulled the code from the linked page above and just changed the one line at the end that has #markup. As far as I can tell from the api docs, this code should work, but nothing that I put into that #markup value shows up.

All of the empty fields DO show up, it's just that the value shown is empty instead of - or blah or foo, because I've tried those as well. :)

How do I set the value to display when I use hook_field_attach_view_alter?

Ok, I found the answer: the key "#items" in the output array needs to have an array with an array as the value - not just the array:

$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => '&nbsp;'),
  );

becomes

$output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'above',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(array()),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => '&nbsp;'),
  );


rewriting results in view: trim from the back I am working on Drupal 7 Omega Subtheme, Panels Views.
In one of my views I have a path field which displays the whole url and I need only the last 6 characters (6 digits, to be precise. Also, if it helps - part of the URL I want to get rid of is fixed.)
Under REWRITE options there is 'Trim this field to a maximum length' but I need to trim it from the end (i.e. from the right).
Do I have to use php? Do I require views_php module?
Thanks.

Yes. You will have to use something like

$newstring = substr($dynamicstring, -6);

in the php code for the field.


How to filter a view when day, month and year are separate fields I am trying to filter a view to show content that happened today on this day in previous years.

We have day, month and year fields but they are not dates.

How can I filter on day = today's day and month = today's month without converting them to date fields.

Current fields are:

Day - integer
Month - List (integer)
Year - integer

You can do that with views php.

Construct your view to take two contextual filters. Do not append any placeholder (%) to the path.

First filter: Add the month field as a contextual filter. Select from the section that reads: When the filter value is not in the url, Provide a default value. A select list Type opens up and from it you select PHP Code and in the PHP contextual filter code you enter:

date('F');

This will match it against today's month in the format of a full string ie. January. Adjust it if your month format is different (if for 3 letter abbrev, use date('M');)

Test this by typing in the month for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month.

Second Filter: Add the day field as a contextual filter, and as above select PHP Code for default value. Add this code:

date('j');

This will filter on the day in the format of 1-31. If you want 01-31 then use date('d');

Test this by typing in the month/day for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month and day.

You can also access the view as such: VIEWPATH/MONTH/DAY and it will show you a result for the values you provided. If you just access the view by VIEWPATH it will give you the result for the date of today.


Ampersand does not get urlencoded and breaks my GET parameters I am using views to create a dynamic url that contains some parameters. Unfortunately I am including the node title as a parameter and it just so happens that many of the titles contain &.

So my custom url in views looks something like this:
seminar?c=[field_seminar_cycle]&n=[field_seminar_num]&t=[title]

But it seems that when creating the view the ampersands inside the [title] don't get urlencoded. I am guessing that the drupal way of building a link is to split the url based on special chars and then urlencode the others parts before joining them all together.

Is there a way to urlencode the title field before adding it to the link? Can it only be done though templates or is there any workaround though views' gui?

I'd wager you could refactor a bit, and substitute the id for the title and avoid the problem altogether.

However, you can see similar problems being worked on throughout the Views issue queue. Like this one, for instance.


Drupal 8 Customize CKEditor Format Options Drupal 8.4.x

I am trying to add custom formats to the ckeditor dropdown.

Having the Geshi Filter module installed it would be nice to have the tags associated with the different languages available as a format option for users.

Following a reply here: https://drupal.stackexchange.com/a/244331/79805, I have success adding the "div" tag, but seem unable to add anything else like a "css" tag or even a "span" tag.

Is it possible to add custom tags to the format list?

This is the function running right now from user @rémy:

function ckeditor_add_format_tags_editor_js_settings_alter(array &$settings) {

    foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
        if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
            $settings['editor']['formats'][$text_format_id]['editorSettings']['format_tags'] .= ";div";
        }
    }

}

CKEditor's format drop down is intended for block-level elements only. So e.g. for headlines, divs, blockquotes, paragraphs and so on.

Inline-elements as spans, links (in CKEditor inline elements by default, even HTML5 specs state they can wrap block elements), i, b, strong, em and so on will have to use the styles drop down.

The css tag is neither block nor inline element, and you'd have to define it as custom block element first.

You can let CKEditor know about your block-level elements by extending the dtd setting, but this exceeds the scope of the Drupal Answers group, even Drupal 8 is using CKEditor by default. Please refer to the CKEditor docs for more information.

For your very special use case, I do have a suggestion:

In one of our projects, we have been using the GeSHi filter module in conjunction with the codesnippet module and added a text filter module codesnippet_geshifilter that "translates" codesnippet markup to GeSHi filter compatible markup.

The intention was to have JavaScript based syntax highlighting while editing the source code, but render pages with server-side generated GeSHi highlighting.

It works well for code blocks. There are some flaws with inline code however. These require tweaking the available CKEditor styles drop down.


Feeds Import Alter for Multiple Fields I am trying to setup a Feed Import from CSV.  There is an images field in the content type which can have unlimited values.  These images are in a folder and named in the following format:

[identifier_from_csv]_01_large.jpg
[identifier_from_csv]_02_large.jpg
[identifier_from_csv]_03_large.jpg

Each project has a variable number of images.  I would like to be able to read from the file system and import as many images it has located there.  I've tried to research into this and from what I can see the Feeds Tamper module I would still have to know how many images there are and have them all listed in a field.

How can I setup an import that would automatically read in as many images as there are located in the file import directory?  I'm assuming there is a hook I could use and loop through there checking the file system, I'm not sure where/how to implement that.

I ended up solving this myself.  My main question I guess was really about a feeds tamper plugin that can insert multiple values.  Turns out it's pretty easy, just return an array and I think set the 'multi' value on the plugin.  I ended up copying the "explode" plugin and modifying it for my needs.  Here is the result.  It's got some hardcoded values which I'm sure could be coded into the form settings.  I kept it simple for my purposes.

$plugin = array(
    'form' => 'my_feeds_tamper_image_import_form',
    'callback' => 'my_feeds_tamper_image_import_callback',
    'validate' => 'my_feeds_tamper_image_import_validate',
    'name' => 'My Image Import',
    'multi' => 'direct',
    'category' => 'List',
);

function my_feeds_tamper_image_import_form($importer, $element_key, $settings) {
    $form = array();
    return $form;
}

function my_feeds_tamper_image_import_validate(&$settings) {

}

function my_feeds_tamper_image_import_callback($result, $item_key, $element_key, &$field, $settings, $source) {
    $out = array();
    $index = 1;
    $fileExists = true;

    do {
        $filename = "public://import/" . $field . "_" . str_pad($index, 2, "0", STR_PAD_LEFT) . "_lg.jpg";

        if( file_exists($filename) ) {
            $out[] = $filename;
            $index++;
        }
        else {
            $fileExists = false;
        }

    } while($fileExists);

    $field = $out;
}


Upgrading from 7.22 to 7.28, htaccess file in /tmp I get this error :

My .htaccess file in that directory looks like this now (I copied it from the url):

# Turn off all options we don't need.
Deny All
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

I still get said error. Why?

Make sure your file system settings are set to /tmp or tmp, then...

In the tmp folder, select the htaccess and delete it from your FTP, then refresh your site cache.

Drupal will replace the missing .htaccess automatically.


How to add a CSS class to some certain pages depending on the path alias? I'm trying to add a CSS class to some certain pages for some certain menu styling depending on the current alias path. It works well with the following function but I'm wondering is there another way to split the current alias parts so I can use them as arguments? Here's my present function:

function mytheme_preprocess_html(&$vars) {

  $path = drupal_get_path_alias($_GET['q']);
  $aliases = explode('/', $path);

  if (isset($aliases[2]) && $aliases[2] === 'foo') {
    $vars['classes_array'][] = 'bar';
  }
}

You should be using Drupal's arg function:
https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7

Something like this should work:

function mytheme_preprocess_html(&$vars) {

    if (arg(2, drupal_get_path_alias()) == 'foo') {
        $vars['classes_array'][] = drupal_clean_css_identifier(arg(2, drupal_get_path_alias()));
    }
}

Added drupal_get_path_alias() as an arguement of arg() as suggested by @koivo


How to remove Upload picture lable from registration page? how to remove Upload picture lable from avatar image field.

Something similar to this should work. Use form id alter hook to remove the label from image field.

function yourmodule_form_user_register_alter(&$form, &$form_state) {

 // Search for the field you want to alter

 // unset the label using $form['search_image_field_name'] or remove the label using empty string for that form field.
}


How to display an image in a Views RSS feed I am trying to display an image in a Views RSS feed.

I have added the following fields to my View: field_image,
field_title, field_twitter (These fields come from my node).
I then set all fields to "Exclude from display".
I then create a new field in Views called "RSS Content".
I then place tokens for all the fields (from step 1) into "RSS Content".
Finally, I go to "Views >> Show >> Settings". In the drop down menu for "Description field", I select "RSS Content".

When I look at my RSS feed, the image field is displayed like this:

    <description>
&lt;img src=&quot;http://example.com/sites/files/nodes/content/images/intro/two-hearts-1312984-1280x960_0.jpg&quot; /&gt;
</description>

How do I get the image to display properly, instead of the image tags being escaped?

First add the Media RSS namespace to your views-view-rss.tpl.php

<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?> xmlns:media="http://search.yahoo.com/mrss/">

Then add the  tag to your views-view-row-rss.tpl.php

<media:content url="<?php print image_style_url('my_img_style_id', $node->field_image['und'][0]['uri']); ?>" type="image/jpeg" medium="image" height="800" width="600" lang="en" />

Lastly make the field data available to your theme's template

function mytheme_preprocess_views_view_row_rss(&$vars) {
  $view     = &$vars['view'];
  $options  = &$vars['options'];
  $item     = &$vars['row'];

  // Use the [id] of the returned results to determine the nid in [results]
  $result = &$vars['view']->result;
  $id   = &$vars['id'];
  $node   = node_load( $result[$id-1]->nid );
  $vars['node'] = $node;
}

Original article: https://blog.sam-thompson.info/images-in-drupal-rss-feed-without-additional-modules/


Changing the layout of user profile edit page I am working on a website based on Drupal Commons.
It uses Commons Profile Module to add extra fields to add user information.

I want to accomplish two tasks:

Change the layout of User Profile edit page i.e. : mysite/user/%user/edit.
Where do I make the changes. Should I create a new *.tpl.php file and if so, then where?
I want to fetch the User Information Fields added by the Commons Profile Module to the edit form.

Please provide a solution in which both these issues are taken care of.

I had to do this in the past and I went the module route.

Using Display Suite, Renderable Elements and Field Group I was able to fully change the layout of edit forms.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. Screencast

  Renderable Elements enables you to register any forms and manage the
  display through an UI. It will also make (additional) elements
  available of existing entities on the manage forms/display screens or
  you can for example register the contact form and rearrange the fields
  through Field UI. Screencast

  Field Group will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Edit: Also using Display Suite, you can add different views or blocks directly as fields to your node. So pulling fields from other entities shouldn't be a problem if you are good with views.


How to hide views page title I need to hide the page title in Views but still have it appear as the page title on the browser's window tab (for SEO). Could someone help me with that? I've looked around many times for answers but I haven't had any luck yet.

The CSS solution might not be the best for SEO purposes...
Another better alternative is to write in the page title field :

<No Title>
or : to leave it blank

And the title wont be displayed


Doing a simple checkbox in field API I'm trying to add a simple checkbox in a Drupal 8 Entity Form that displays like the old Form API:

$form['approved'] = [
  '#type' => 'checkbox',
  '#title' => t('Approved'),
  '#description' => t('Check this to indicate this person is approved for membership'),
];

Using D8 style field definitions, this should be something like

$fields['approved'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Approved'))
  ->setDescription(t('Volunteer is approved for trusted work.'))
  ->setSettings(array(
    'display_label' => TRUE,
  ))
  ->setDisplayOptions('view', array(
    'type' => 'unicode-yes-no',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'boolean_checkbox',
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

This doesn't quite work; I'm getting a checkbox with the label "On".

How do I fix this?  Also has anybody gathered the various parameters used for setDisplayOptions() in one place and documented how these map to the Form API and the Render API?  I've been looking at the sources in core/lib/Drupal/Core, and I'm not finding much.  And there isn't even a test for the boolean_checkbox widget, so no code to look at there either.

You can always just create a field in the UI and extract the settings from there. Or look at the defaultSettings() method in the plugin class, where you can find this:

/**
 * {@inheritdoc}
 */
public static function defaultSettings() {
  return array(
    'display_label' => FALSE,
  ) + parent::defaultSettings();
}

So, add 'settings' => ['display_label' => TRUE] to your form display definition and you have what you want.


How to show fields in different regions? I've tried the Display Suite module, which only comes with regions per display suite layout template (also the extra module did not change this) which basically just changes the body/ content region... making the themes regions available was not possible. It still would be a bit overkill for what I want anyways.

All I want to do is make a field from within any content type available to be put in any region. No blocks. No views.

Just as the display suite module offers a new column in the manage display tab "region" with a drop down to pick which region the field shall be put in.

How come there is no module like that?

Thanks!

Edit: I've read this thread but I want to do it without views and if possible without blocks.

As with anything in Drupal there are many ways of doing this. Display suite and Panels (as mentioned by Serpiente above) are great. However, if you are not already using them for your project, they are indeed overkill to get what you need.

You can use the CCK Blocks or Field as Block module. These essentially turn any field (you set) into a block to be placed in another region.

You can also use the Views module to create a block with a contextual filter based on the nid in the url and display whatever fields you choose.


Commerce: Unique single products + Custom line items, How to handle? I am building a shop with several types of custom cushions available. Each product (cushion shape) will have different options therefore i am using custom line items.

The issue is that to me it seems i need to create just as many different content types (product display) in order to reference the custom line item in the add to cart form of the Display?

There must be better way to do this?

Unfortunately there's not, you need a content type to match every line item type if you're dealing with different attribute fields.
That was the original intention of Commerce custom product but it's at the point of providing different product types, but the feature hasn't been developed yet.


Change the subtotal amount in commerce_email_order_items First, sorry for my poor English, and the faults you will probably found.

Globally, what I am trying to do , is to add the shipping amount into the 'base_price' component price, also labelled subtotal.

So far, it's working correctly on the site itself with the use of the hook hook_commerce_price_formatted_components_alter().
To give you an idea, here is the code that handle it.

function base_price_shipping_commerce_price_formatted_components_alter(&$components, $price, $entity) {
    // We modify $variables to "merge" base_price and shipping
if ( isset($components['base_price']) && !empty($components['base_price']) &&
    isset($components['flat_rate_expedition_internationale']) && !empty($components['flat_rate_expedition_internationale'])) {
    // We calculate the new price with included expedition
    $price_with_shipping_amount = $components['base_price']['price']['amount'] +
        $components['flat_rate_expedition_internationale']['price']['amount'];
    // We format this price with the used currency
    $price_with_shipping_formatted = commerce_currency_format($price_with_shipping_amount, $components['base_price']['price']['currency_code']);
    // We update the display of base_price component with the new price
    $components['base_price']['price']['amount'] = $price_with_shipping_amount;
    $components['base_price']['formatted_price'] = $price_with_shipping_formatted;
    // We unset the display of shipping
    //unset($components['flat_rate_expedition_internationale']);
}
}

Now the problem is to do the same thing with the token [commerce-order:commerce-email-order-items].
I know it's generated with commerce_email_order_items() and by commerce_email_prepare_table() specially.
But I don't get to understand how to make it work, or where to make the change.

Directly and overide the function commerce_email_prepare_table() ?
It will probably be around the ligne 174 in the commerce_email.module file :

$data = $wrapper->commerce_order_total->data->value();
 if (!empty($data['components'])) {

   foreach ($data['components'] as $key => &$component) {

     if ($data['components'][$key]['name'] == 'base_price') {
    $rows[] = array(
      'data' => array(
        ' ',
        array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
        array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
      )
    );
  }

Another possibility is to change the amount of the 'base_price' component, not on a formatted level (which just change it before display), but at the "root", for real. I don't know if I am clear enough.
But after days of research and try to understood the Price API, I still don't get it, and which hook or function to use :
http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21price%21commerce_price.module/7

Which way do you think is the best ?
Thank you for reading.
Pierre.

Well, after re-examining the code of the commerce_email.module, I had an epiphany, and finally get it.

Here is the code before my change (starting line 169) :

$data = $wrapper->commerce_order_total->data->value();
  if (!empty($data['components'])) {

foreach ($data['components'] as $key => &$component) {

  if ($data['components'][$key]['name'] == 'base_price') {
    $rows[] = array(
      'data' => array(
        ' ',
        array('data' => t('Subtotal:'), 'style' => array('font-weight: bold; text-align: right;')),
        array('data' => number_format(commerce_currency_amount_to_decimal($data['components'][$key]['price']['amount'], $currency_code), 2), 'style' => array('font-weight: bold; text-align: left;')),
      )
    );
  }

And now with my change :

$data = $wrapper->commerce_order_total->data->value();
 if (!empty($data['components'])) {
  foreach ($data['components'] as $key => &$component) {
         if ($data['components'][$key]['name'] == 'flat_rate_expedition_internationale' || $data['components'][$key]['name'] == 'flat_rate_expedition_outremerre' ) {
            $amount_expedition = $data['components'][$key]['price']['amount'];
          }

  }
  foreach ($data['components'] as $key => &$component) {
      if ($data['components'][$key]['name'] == 'base_price') {

          $amount_base_price = $data['components'][$key]['price']['amount'];
            if (isset($amount_expedition)) {
                $amount_base_price += $amount_expedition;
            }
          $rows[] = array(
              'data' => array(
                  ' ',
                  array('data' => t('Prix HT :'), 'style' => array('font-weight: bold; text-align: right; margin-top: 10px')),
                  array('data' => number_format(commerce_currency_amount_to_decimal($amount_base_price, $currency_code), 2), 'style' => array('font-weight: bold; text-align: right;')),
              )
          );
      }

It's not a great solution, and I will try to make a full module, to select dynamically the components to add to the base_price.
Until then, this will do the job.


Module to edit field data on multiple instances/nodes (in bulk) I've a need to allow my client to easily edit the price field for the projects (content type). In total there're about 1.5k nodes and he wants to change the price once and that it would be applied to all the 1.5k projects/nodes.

Is there a way to do it using some of the existing modules in an easy way, so that an amateur could make the change? Or can it be achieved by custom module, if so could you give some instructions in terms of how should it be done programatically?

I'm not a developer, but will pass it to my colleague, who's a developer. He tried to code a custom module, but it takes about 18min to update the field data for 1.5k nodes... So apparently something is not right.

Thanks.

For Drupal 7 you will need views bulk operations which packages this and other bulk operations.  For Drupal 8 you need Bulk Update Fields

Below the procedure is for Drupal 8 but very similar for Drupal 7

Install the module and modify the Admin content view found by going to admin/structure/views/view/content or perhaps you can use any view that you want.

add field and search for Node operations bulk form to add and make sure you enable

Selected actions: Bulk Update Fields to Another Value

With this when on the view page you can select 1 or more nodes and modify fields in bulk


A module to find linkable content I am looking for a module that finds related pages for the purpose of linking them internally. For example, we have two pages, both have the name "Kill Bill" in their content, but they are not linked. The module would put the similar content to attention so that the editor can link the two pages. Or something similar to this.

I could implement Solr but it's not the preferred option.

Thanks

You can achieve that using the Remove Duplicates module.

Don't bother about the name of the module. you can use it as following way.

This module helps the administrator to easily find out the nodes according to one of the node fields.

So you can easily find out the same content pages and like those.


How to add custom settings / attributes to a field I want to be able to add custom settings / attirbutes to field instances.

I can create a custom field with custom settings no probs, but is it possible to get rid of the custom field and just add the settings so that the settings are stored per instance?

For example:

I create a content type, let's call it vehicle. I add a field called wheels which is a basic textfield where you can specify the number of wheels. Now I would like to add a few settings to the wheels field such as brand, model, etc. These settings would be specific to the content type but if you re-used the field wheels on another content type the settings could have different values... now this is a bit contrived but you get the idea!

Any ideas on how this could be achieved? My current solution is to create a separate field called something like Wheels meta information with the settings but I would rather a cleaner solution.

Ok, this is done with third party settings in hook form alter:

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $entity = $form_state->getFormObject()->getEntity();

  $form['third_party_settings']['my_module']['my_field_setting'] = array(
    '#type' => 'textfield',
    '#title' => t('My custom field setting'),
    '#default_value' => $entity->getThirdPartySetting('my_module', 'my_field_setting'),
  );
}

...and that's it. So awesome.


Customize the output style of a view field I have a view block, where fields are added in the table.
I followed below steps to customize the output fields:

Navigate to the edit screen for a view (for example, admin/structure/views/view/MYVIEWNAME/edit).
In the Fields section, click a field. The Configure Field dialog box displays.
Click Style Settings.
Enabled the following options:
        Customize Field HTML
Specified the HTML element <div> to wrap around the item. and clicked on Create a CSS Class and specified a class name.
disabled the Add Default Classes option.
Clicked on Apply.

The problem is, the specified class name in step no. 5. got added to the corresponding <td> of the view table and not to the selected html element <div>

How to add class name for the specified HTML element <div> ?

For this case, don't use Style Settings. Instead, use Rewrite results.

Click on Replacement patterns, to get the Token of your field.

Then just wrap Token inside div tag.


How to list Content A nodes on Content B's page using Entity Reference fields and Views (with Paragraph field Bundles attached) I have Content A (Music Albums) with entity reference fields referencing Content B (Musician).

I want to display a view on Content B (Musician) page that displays every Album (Content A) they are 'tagged' on. Basically using entity reference fields in place of taxonomy (per StackExchange suggestion).

Content A (Album) has a View displaying various info such as album image, album name, record label etc... and an Entity Reference field  referencing Content B (Musician). When clicked it takes me to the node page of that Musician.

On the Musician's (Content B) page I want to have a View displaying all Albums (Content A) they appear on (tagged via entity reference field).

Finally, Getting the entity reference fields attached to a Paragraph Bundle to relate to Content B (Musician)

Simply under Advanced (far right), for Contextual Filter add your entity reference field. In my test, I called it "Made by" field_made_by.

Note: The view preview will be blank as the view edit page does not have an ID. Just place to your Musician page and it will show up then.

  However, when using paragraphs module to add node bundles is more
  complex because technically a paragraph bundle is it's own entity, so
  Content A references a Paragraph Bundle with an entity reference field
  within its bundle (LOL). It gets pretty complicating. Any help with
  that?

Then make a view of Paragraph and not of Content.

Then add relationship of Paragraph referenced from field_paragraph (paragraph field)

Then in contextual filter add field_made_by (entity reference field).


Views doesn't split content into seprates list items I need to produce a list of images with views 3 but these group items in only one li element...like this:

How can I force it to put items in is proper li element ?

thanks

EDIT: after tips from @LaurenG , this is the right obtained HTML Markup :)
Views 3 under D6 is a bit different of D7 but I found how to setup the display as I would.

now,I need to work on the JS code to run the slideshow.

Assuming all of these images are in a multi-value field:

Make sure your view is showing "Fields" instead of "Teaser" or some other display setting
Add your multi-value image field through the Fields section "Add" button
Configure the field by clicking on it. You should see a pop-up window with collapsible sections at the bottom - the top section is "Multiple Field Settings". Open that section. Turn on the setting "Display all values in the same row"; when you click that, it'll open the "Display Type" options, for which you'll pick either "Ordered list" or "Unordered list" (assuming unordered list, since you use  in the question's code).


How To Rescue Content from a Corrupt Database I have spent many weeks inputting content into a commerce system. The database is corrupt. (The website displays fine for an anonymous user, but if you log in you get a blank page. Backups/restore all yield same results) I have now set up a new version of the system, but would like to export/import content and content types from the old system to the new one. How can I do this? Which tables would I need to transfer?

The database isn't likely to be corrupt - unless you're coming up against a ridiculously unlikely scenario, it wouldn't work for any users at all if it was corrupt.

If the data was corrupt, you wouldn't be able to restore the backup, it would fail.

What you need to do is look into the server logs; you're currently seeing a WSOD (White Screen of Death), which is common in PHP applications.

Your server logs will contain details of the exact error your site is encountering, and you can use that information to decide on how to debug and fix it.


dkan resource not saving I have Drupal 7 using the DKAN module. When I edit a resource and try to save it, I'm getting a The URL is invalid error message.

Here is the url that is being edited from: http://hostname/?q=dataset/datasetnet/resource/e1f740cd-e80c-40d7-8d5d-e5a7221afe7c and then url change to http://hostname/?q=node/2051/edit.

So I checked the log and here is what I'm seeing the following errors:

Notice: Undefined index: filefield_dkan_remotefile in dkan_dataset_resource_node_form_validate() (line 536 of /dkan/dkan/profiles/dkan/modules/dkan/dkan_dataset/dkan_dataset.forms.inc).

Is there a reason why the resource is not saving?

Thank you,
Kevin

i'm not sure, but i would recommend asking in the DKAN issues found at Github where they actively develop their modules. The DKAN set of modules on github can be found at https://github.com/NuCivic/dkan


How to use nested select queries in Drupal 7 How can I write the following query in a Drupal-friendly way?

select max(cnt) from
(select COUNT(*) as cnt from Det a,
dbo.Mem b where a.no=b.no
group by b.no) X
go

Since you're going cross-database I think using db_select() could get quite complicated. I might be wrong though, it might just work.

Either way, you could always just run the query directly with db_query():

$sql = '
  select max(cnt) from
  (select COUNT(*) as cnt from Det a,
  dbo.Mem b where a.no=b.no
  group by b.no)';

$count = db_query($sql)->fetchField();


Tablefield output in No Results behaviour I have achieved to display the raw value of this tablefield in views - Global no results but not in the table format.

I have this in PHP-format in the Global - No results behaviour in views.

$view = views_get_current_view();
$node = node_load( $view->args[0] );
$table = $node->field_modal_parameters_tabel[und][0]['value'];
print $table;

This gives me this.

a:34:{s:8:"cell_0_0";s:1:"N";s:8:"cell_0_1";s:21:"nat. freq. meas. [Hz]";s:8:"cell_0_2";s:22:"&xij";s:8:"cell_0_3";s:1:"N";s:8:"cell_0_4";s:21:"nat. freq. calc. [Hz]";s:8:"cell_0_5";s:17:"damping calc. [%]";s:8:"cell_0_6";s:7:"MAC [-]";s:8:"cell_0_7"; ...

How can I display the table format?

Got the answer!!

<?php
$view = views_get_current_view();
$node = node_load( $view->args[0] );
$table_data = field_get_items('node', $node, 'field_modal_parameters_tabel');
$output = field_view_value('node', $node, 'field_modal_parameters_tabel', $table_data[0]);
print $output['#markup'];
?>


Custom error page: The path is either invalid or you do not have access to it I'm trying to add a custom page, by using admin/config/system/site-information

When I enter the field, as follows:

Default 404 (not found) page

http://mysite.com/errors/404.html

It shows the following error:

The path 'errors/404.html' is either invalid or you do not have access to it.

Though when I enter in my browser: http://mysite.com/errors/404.html it opens just fine.

So, what's wrong with Drupal, why it doesn't see it?

When you go to admin/config/system/site-information to enter the path in the field Default 404 (not found) page, you don't have to add .html just write errors/404 and it will work.


galleria Slideshow images does not display I have created an eva view, to display a group of gallery albums. Within my content type on manage displays am using a default galleria formatter and in my eva view I have a Grid of different image albums.
All I get is the album thumbnails. Tried to clear the cache but still.
I went through the galleria read me, and I believe I have done everything that they said one needs to do to get galleria working.

I am using Drupal 7 and have installed the followings:

Initially installed
Galleria Jquery plugin(libraries) 1.4.2
Galleria module (7.x-1.0-beta3)
but didn't work
I then added the following modules
Views Slideshow: 7.x-3.1
Views Slideshow: Galleria: 7.x-3.2

Am I missing something?

Thanks for browsing my question.
I got it right by simply reverting back to an old version of Galleria Jquery plugin. I used galleria 1.2.9 instead of 1.4.2 and all is well.

I am still puzzled though as to why the new version is not working.


"Your command line PHP installation is too old" But it's not? I was trying to install Drush version 7.x-5.9 when it gave me the following error (whenever I try to use the drush command):

Your command line PHP installation is too old. Drush requires at     [error]
least PHP 5.3.0. To suppress this check, set the environment variable
DRUSH_NO_MIN_PHP=1

My HostMonster Info:
Apache version  2.2.26
PHP version 5.4.24
MySQL version   5.5.35-log

I've reverted back to version 7.x-5.4 of Drush and the command line is working but I would like to use the newest version if possible.

The command line version of php (CLI) and the one used by your webserver (reported by hostmonster info) are not necessarily the same. Run php -v in a terminal to see which php command line version is installed.


Variables available on display suite php field I'm using Display Suite module to create custom fields.

I've to add a code field (php), that calls a function that has $nid as argument. I've added this field to node entity but I can't understand if there are variables available on this field.

Adding a php field I've a textare where I can add php code.ù
I've a custom functions that retuns html and require a nid as argument.

so in my custom field I should have something like:

<?php
print my_function($nid);
?>

The problem is that I don't know where find the $nid: $object? $node? $entity? $context?

This field is added on an node entity.

You can get access to the node via the $entity variable within the "Field code" text area.

This will only work for the Display Suite "Code Field". If you are using Display Suite 7.x-2.x, you'll have to enable the "Display Suite Format" module.

If anything is setup properly, you should see this help text below the "Field code" text area:

  You may post Display Suite code. You should include  tags when
  using PHP. The $entity object is available.


Where to start looking up if there's something wrong with cck field variables? in short: Something in my zen-based custom theme is keeping a couple of cck fields from being display on my page. Basically my question is where to get access to the variables that are supposed to contain the html for the cck fields (which are missing when I was looking them in firebug).
Below I explain why I think it's looking up the variables that might bring me closer to a solution

So I made this custom node type (events) with cck fields added. Also made some content using those fields. Added some css and it all displayed fine.
Later the taxonomy terms below the title and some metadata bugged me so I followed along with a 'theming cookbook' pdf book that taught me how to make a node-events.tpl.php and simply deleted php variables like $terms. This worked great.

Obviously this also means that all this time, the view permissions of those fields have been checked and also that the display options under 'display fields' have been set to standard all the time.
I also ruled out that the issue could be anything else than theme related as my cck fields do show up in a stock Drupal theme. The theme for my site is a zen-based custom theme.

So then even later, after I made a view for this node type and started adding css to that view I noticed at some point that my image field and two other fields are missing. It's hard to tell if they disappeared because of things that I did when creating the view and adding css (which would surprise me)

to test if the value of your CCK field is inside node content, I think that you can use  print_r($node); in your custom node.tpl.php (in your case node-events.tpl.php) file of your theme directory, to see the list of the CCK fields (or if you use Devel module, is best use dsm($node);)

For example, I have a CCK field called field_test_text, see this screenshot using dsm($node);

And this is the way to test the specific value of the test field:

  <div class="content clear-block">
    <?php print $content;
    dsm($node->field_test_text['0']['value']); //dsm way
    echo $node->field_test_text['0']['value']; //echo way
     ?>
  </div>

I hope information be useful.


A View which displays Posts assigned to a Parent which is followed by current user A little advice please:

Users "follow" a content type Parent by using the method in this question. There is a content type Posts which has an Entity Reference to the Parent it is assigned to.

How do I go about creating a View which shows all Posts which the current user has "followed"?

I guess this could be done with Views Field View but that seems a little over-kill. There must be a simpler way of doing this, just with Views out-the-box, surely?

Update

See my answer. Please, please, if anybody has a better solution let me know!

Use Views PHP.

In Views

Format

Content

Filter Criteria

Content: Published
Content: Type (=Post)
Global: PHP (see below for code)

Code for Global: PHP -

$flag = flag_get_flag('follow_parent');

$post_nid = $data->nid;

$post = node_load($post_nid);

$field_parent = field_get_items('node',$post,'field_parents');

$parents_followeds = array();

foreach ($field_parents as $field_parent) {
  $parent_nid = $field_parent['target_id'];
  $followed = $flag->is_flagged($parent_nid);
  $parent_followeds[] = $followed;
}

return in_array(TRUE, $parent_followeds) ? FALSE : TRUE;


Configure Modules from a Script I'm interested in created a sort of "deploy" script. I basically want it to take a fresh drupal install (plus my versioned work in sites/) and disable and enable modules as needed and then automatically configure the site.

The first part is easy with a simple script and drush. The second part is the part I'm not so sure of. I can manipulate the database directly (again, using drush) and run queries against it, but I wonder if that is a bad way to do it since the schema of modules can change when they are updated (though I think core will stay mostly the same in 7.x).

I'd like to be able to script things like the CSS/JS aggregation settings or the Facebook APP ID/Secret in fboauth. Is there any "safe" way to do this without worrying about module updates breaking the script?

Unfortunately, there is no "right" solution for Drupal 7; in Drupal 8, the configuration management initiative hopes to solve this problem.  There are a few things that you can look at to help you out.

Features: http://drupal.org/project/features:  Take database settings and write them to code, making a new module containing your settings.  Use "strongarm" module (http://drupal.org/project/strongarm) to be able to save items from the variables table in your features.  Once you have your features module, you can copy it to another site and run 'drush fr' to "revert" the feature (copy code back into the database).
Deploy: http://drupal.org/project/deploy: The counterpart of Features, it allows you to move content from one Drupal site to another.
drush generate-profile: http://drupal.org/node/1368242: Work in progress: given an existing site, creates a profile that will recreate that site.  Create your features first, then run generate-profile.  In its current state, it does a good job of creating your makefile and setting up the modules you need, but the template files that generate the profile code are not finished or working yet.  I am still working on this command, as time allows.


Exposed Views 2 filter for path alias I am surprised that I am not able to find an existing Views 2 filter for aliases (paths). Seems to be such a basic property to filter results by.

I know Views can filter by argument but I need it as an exposed filter.

Does anybody know of an existing module that does it -- or at least a snippet of code that would build such a filter?

Views Path Filter might be what you're looking for. It lets you filter nodes by paths in a views filter. I don't know how well it works with exposed filters though.


Circumventing Drupal's Cache for New Content We like to post updates to Facebook and Twitter when publishing new content. We are running into a problem, however, in that anonymous users will get the "Access Denied" page until the cache recycles to show them the new content.

Currently, we're caching pages for anonymous users for three minutes. How do we keep our cache, yet allow anonymous users to see new content immediately as it's published?

For what it's worth, we are not using Memcache, Varnish or anything outside of the standard Drupal page caching.

403 "Access Denied" on a cache miss seems odd to me. One thing to try is http://drupal.org/project/adbc as it makes the Dupal cache operate like one expects.


how do i store fields in one table via the install file? I am new to d7 and I am writing an install script.  This install script needs to create a content type (I've done that) and then create lots of fields that are used in this.

The problem I have found is that d7 automatically creates lots of tables for each field.  Considering I will have something like 60+ fields per content type, this isn't very practical.

How can I code into my .install file a way of making all these fields be in a single table e.g. |ID|value1|value2|value3|  instead of 3 tables for value1,2,3

Thank you.

Short answer: You can't.

As consumer of the Field API you don't have any control on the SQL schema when using the default field storage. The Field API however, allow usage of different field storage on a per field basis. It seems that the Per-Bundle Storage module aims to provide the feature you want. But it has no release, only code in its repository. Another solution is to switch field storage for your content type to a separated MongoDB database.


Is it possible to reference a field to a node, and also to a user? My question: Is it possible to reference a field to a node, and also to a user?

I want to keep track of scores scored by users while playing a boardgame. So, I'll need a reference between nodes (boardgame) and users. I'm using the "entity reference" for this.

With the module field_group and field_group_multiple, I can make rows with user field, score field, etc... But the problem here is: the score field is linked to the node, not to the user. (So if I want to make a view and get all scores scored by a player, this will be not possible.)

I found an answer. The modules entity_reference and field_collection are what I needed. field_collection makes a collection that has a reference to the node, and also to the user_reference. An awesome module!


node:url token not returning clean (alias) URL This is a follow-up question of: How to delay the execution of a rule for 5 minutes?

When not delaying the action, the node:url token does not return the alias URL, but the URL with the token ID: ...node/id. I assumed this is because this URL is simply not available yet. I have to use the clean URL, because otherwise a scraper would get a HTTP status code 302 and is unable to scrape the page correctly.

I'm using the Pathauto module to create the URL's automatically.

However, when using the sheduler, I'm still not getting the clean URL. These are my current settings:

The marked token in the screenshot should return the clean URL, but it returns the unclean /node/id one. I've already tried to change the token to [entity-fetched:url:path], but this seems to return an invalid URL (or no URL at all, is it possible to debug this?).

Why can't I get the clean URL using tokens in rules?

The weird thing is... if I edit a node instead of creating a new one, node:url does return the clean URL, but not when using the sheduler.

EDIT:

{ "rules_publish_to_fb" : {
    "LABEL" : "Publish to fb",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "fb_autopost_entity" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : {
              "event" : "event",
              "inspiration_theme" : "inspiration_theme",
              "news_item" : "news_item"
            }
          }
        }
      },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_facebook_message" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_facebook_published" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-facebook-message" ] } },
      { "data_is" : { "data" : [ "node:status" ], "value" : "1" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_facebook",
          "date" : "+2 minutes",
          "param_node" : [ "node" ]
        }
      }
}

And

{ "rules_facebook" : {
    "LABEL" : "facebook",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "fb_autopost_entity" ],
    "USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
    "ACTION SET" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "node:nid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "facebook_publication",
            "param_type" : "link",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "facebook_link" : "Facebook link" } }
        }
      },
      { "data_set" : {
          "data" : [ "facebook-link:field-facebook-message" ],
          "value" : "[node:field-facebook-message]"
        }
      },
      { "data_set" : {
          "data" : [ "facebook-link:field-facebook-link" ],
          "value" : "[entity_fetched:url]"
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "facebook-link" ], "pages" : "1247812435236072" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "drupal_message" : { "message" : "[entity_fetched:url]" } }
    ]
  }
}

Option 1 (a): Try another token

Check what result you get by using either of these tokens:

[site:current-page:url].
[node:node-path].
[node:node-url].

Option 1 (b): Pass the URL as an extra parameter

Inspired by the answer to the question "Send node path alias to user", you might be more lucky to get access to the correct value of your URL (or either of the tokens I suggested above) if you just pass that value to your Rules Component as an extra parameter (so on top of the "node" parm you already have). And of course use the value of that parameter in your Rules Component instead.

The reason why I think you may be more lucky, is that you already have that "node_is_of_type"-condition. So because of that, and similar to the answer in the above mentioned question, it should be available in your first rule in which you schedule the Rules Component.

Option 2: Perform Rules debugging

If Option 1 doesn't help, then I'd recommend you to do some further debugging of your actual rule, as detailed below (and in the order specified).

Basic debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Debugging using Rules settings

Something else that might help to find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Debugging using the Devel module

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Video tutorial about Rules debugging

Refer to the (great!) video "Debugging rules configuration" for way more details about the last 2 variations.


Comment not respecting line breaks (Drupal 7) All of my comments for all of my content types do not respect show line breaks.  I have tried to dig pretty deep into this issue but I now feel quite stuck.

This is what I discovered.

The problem is not related to the text formats. (I have verified that Convert line breaks into HTML is checked.)
The problem may have to do with safe_value. I used dsm() to show content of the $vars variable inside the hook_preprocess_field() implementation of the theme, which shows the value of the comment body has line breaks, but save_value doesn't.
The issue is not related to the format. With dsm() I have verified that the comment body is using  the Filtered HTML input format, which I believe is correct.

This is what dsm() outputs for the comment body.

When I found this problem it was because the results of the filter were being stripped by another filter.

Go to /admin/config/content/formats and check your filter processing order. The 'Convert line breaks into HTML' should be the last one.


Form API AJAX refreshes page I need to add some AJAX functionality to a node form. Using hook_form_alter I'm overriding form elements. In this particular case I need to add a callback on the 'language' element provided by the translation module (Core, Content Translation).

However, when selecting a different option in the 'language' listbox, the page refreshes. What could trigger this behaviour?

This is the code I'm using:

function foo_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bar_node_form') {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['language']['#ajax'] = array(
      'callback' => 'bar_form_callback',
      'wrapper' => 'bar-form-wrapper',
    );

    if (isset($form_state['values'])) {
      drupal_set_message('ajax callback');
    }
  }
}

function bar_form_callback($form, $form_state) {
  return $form;
}

What exactly are you trying to do? Is the page refreshing or the entire $form? What you're asking it to do is by attaching #ajax to the select is that when it changes a value resubmit the entire $form, which would probably include any submit handlers. Typically #ajax would be directed at a form element rather than the entire form.


Twig field collection theme get field id I am trying to get the field ID of of a field collection item being rendered in a field collection theme twig file: field-collection-item--field-name.html.twig.

I am able to render content using  {{content.field_name}} but I need a unique identifier to create an anchor link.
I can see an id is available using kint(item) but cant seem to figure out the proper syntax.

Any help would be greatly appreciated...

You can get The field collection item ID in field-collection-item.html.twig

{{ item['#field_collection_item'].id() }}

or you can get it from field-collection-item--field-name.html.twig, or other field template of field collection item.

{{ element['#items'].getEntity().id() }}

You can find these functions under Available Methods Tab when you printing out variables from twig template. You can use public methods.


Content creation screen: Add another field conditionally I'm trying to figure out how to do the following in D7:
I have a list field in a custom content type. The list contains 8 items. When creating content of this content type, the user can only select one item from this list. But there are two items from this list that I would like to have their own sub-lists. How would I have Drupal conditionally show another list if one of these items were selected? (This is all happening on the content creation screen).

Update
This is not a duplicate of the question you have referenced because this is regarding Drupal 7 content creation. The "Conditional Fields" module was built for Drupal 6 and is not fit for production, as per the module page, in Drupal 7 pages. I am looking for a stable, maintainable solution for a production website.

You may want to take a look at the Hierarchical Select module. It provides this kind of functionality for vocabularies.


Painfully slow, Devel Query logs show culprit I have been having a few problems with one of my clients site. Its a big site, theres a few thousand nodes, 10k users, and it holds large images galleries with 100+ images that are 500kb each.

At its slowest, the average page load is 45 seconds!! And the worst i when you are logged in.

After enabling devel query logs, this one stands out as the worst...

3923.69 ms  1  node_tag_new  P A
INSERT INTO history (uid, nid, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2)

Thats the first page load, the second is much much worse....

65594.921 ms  node_tag_new   P A
UPDATE history SET timestamp=:db_update_placeholder_0 WHERE ( (uid = :db_condition_placeholder_0) AND (nid = :db_condition_placeholder_1) )

What is the history table? Any idea why it is taking so long to run the query?

What is the history table?

This is a table for keeping track of what user has read what node. (To show a new/updated message next to it.)

  Any idea why its taking so long to run the query?

This could be anything, and might be at the server level (not related to Drupal).

First, check if SQL is slow outside Drupal (eg. PHPmyadmin). Run the same query, see what happens.

If SQL is still slow and you have ssh access to the server, try to run some disk speed checks using sudo hdparm -Tt /dev/sda and dd if=/dev/zero of=/tmp/output bs=8k count=10k; rm -f /tmp/output (assuming Linux). I had a slow site recently that was caused by a malfunctioning hard drive.


How to resend simplenews content for many times - Simplenews module I use drupal 7 and simplenews module.I want to send a simplenews for several times.by default simple news module support onetime send to user.but i want to send simplenews to user for several times by UI .
Is any way for resending support in simplenews module ?

Is any other module for edit contents before sending by mail and send it for several times to subscribers?

solution:
simplenews Status Reset module .


What is the recommended method for programmatically editing or inserting values into the field_data_* tables? I'm using Drupal 7.7

I'm working on a module to programmatically add users to an Organic Group.  I'm using og_group() and og_role_grant(), but the user is not given full access without also having their group_audience field set correctly.  So, my end goal is really to do just that.  I cannot find any OG functions that will perform that function, so I'm asking, generically, if there is any Drupal-approved method of writing data into that table.

I've tried using field_bundle_settings(), but I can't get that to work, and I'm pretty sure it won't ever work.

my code is below:

<?php

$settings = array(
    'group_audience' => array(
    'entity_id' => $user->uid,
    'group_audience_gid' => $gid,
    'group_audience_state' => '1',
  ),
);
field_bundle_settings("user", "user", $settings);

thanks

If you want to create users belonging to a group (able to publish content under the group, see group content), og_group() should do the trick; I'd check your implementation and make sure it's ok before going too far astray. I'm doing the exact same thing with the following code and it's correctly inserting the group_audience values into the field_data_group_audience table.

og_group($group_id, array('entity' => $account));

However, if you're totally stuck and want to try another route, you can always manually insert the data through db_insert().


How do I replace a string when altering the output of a view field? I have some text I'd like to alter in the custom output of a view field.  For example, if the output contains pancakes, I'd like to replace it with waffles.
The following code doesn't work.
{{ field_recipe_prep__value | replace({'pancakes': "waffles"}) }}

How do I replace a string when altering the output of a view field?

Remove the __value part.
{{ field_recipe_prep | replace({'pancakes': "waffles"}) }}


How to get total number of rows on a block of a view On hook_block_view_alter() I need to get a total number of rows that this block displays.

For example, I have a view with the following block:

On hook_block_view_alter() I do the appropriate checks in order to weed out unnecessary blocks and get the one shown in the figure above.

function mymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  if (!preg_match('~^views_block:taxonomy_tag_list~', $block->getPluginId())) {
    return;
  }

  $view = $block->getViewExecutable();
  // Gets the number of rows
  $totalRows = $view->get_total_rows;
}

But for some reason, $totalRows contains NULL.

Here is the object of the current view:

Why can't I get the total number of rows? Maybe I'm using the wrong hook?

Use a views_view_ hook, i.e. views_view_unformatted,  views_view_list  etc... I tried this with a PHP count for my views block and it worked great.

My function is:

function MYTHEME_preprocess_views_view_unformatted(&$vars) {
  $num_rows = $vars["rows"];
  $count = count($num_rows);
  echo '
This view has ' . $count . ' rows

';
}

This yielded the number of rows in the view.

Printed, I see:


Unable to render block in twig after updating Twig Tweak module I update the Twig Tweak module to version 8.x-2.x. After this update I can't render my disabled blocks anymore?

Before I used {{ drupal_block('myblockname') }} to render my block in the twig template.

Now I try to use {{ drupal_entity('block','myblockname', check_access=false) }}. But I don't see my blocks in the frontend?

It was a docker sync problem. Now with {{ drupal_entity('block','myblockname', check_access=false) }} the blocks are visible.


How to remove 'error' class from form field? I need to remove the error class from field after form submit. How to do that?

I found the function called _form_set_class but I suppose I can't overwrite it.

_form_set_class() is called from a bunch of different theme functions, including

theme_checkbox()
theme_fieldset()
theme_file()

(the rest are here)

You can override whichever of those functions you need to in your theme by renaming the function as (e.g.)

function MYTHEME_checkbox($vars) {

Then copy in the original code from the function, remove the call to _form_get_class(), and replace it with whatever makes sense for your use case.


Why are my translated Select List values not shown after switching language? I have a content type for Job Openings, which has many fields and some of them are drop-downs (select lists).

The issue is that when I switch the language (German) everything switches to the currently selected language but the data coming from select field stays in English.

I have been going over the internet and have not found anything. Any suggestions?

Notes:

All the fields are translated in the backend but they just doesn't show up (in German).
I have simple text_fields too and they are shown translated, but not the select list fields.

After you translated the select list options of your field(s), make sure that you ALSO change the Format of that selection list from Default to Default Tanslated

You can do so via "Manage Display", located at /admin/structure/types/manage/yourtype/display (whereas yourtype corresponds to your Job Openings content type). Similar to what is explained in this comment also ...


WSOD on deploy: failed to open stream: No such file or directory I am trying to deploy a site to a live server, but running into a "white screen of death". Enabling logs revealed that the zurb foundation starter theme was the source of my issues, so I disabled that and was able to use the site. I then switched it back on and went straight into white screen of death again.

Then I used drush to get a login url and accesed /admin where I could so the following list of errors:

https://gist.github.com/webconsult/a82eebc3d25480f674ed

I checked, and it seems these files and functions are all present. I'm not sure if the ownership settings are correct, though, but I am assuming the apache user is able to read and execute the fieles correctly since everything works if I switch away from the Zurb Foundation theme (i.e. Garland theme). Here is a sample of ownership and permission of the files in /includes:

-rw-r--r-- 1 admin admin  13816 Mar 19 18:30 actions.inc
-rw-r--r-- 1 admin admin  48742 Mar 19 18:30 ajax.inc
-rw-r--r-- 1 admin admin   1701 Mar 19 18:30 archiver.inc
-rw-r--r-- 1 admin admin  13664 Mar 19 18:30 authorize.inc
-rw-r--r-- 1 admin admin  17497 Mar 19 18:30 batch.inc
-rw-r--r-- 1 admin admin   2310 Mar 19 18:30 batch.queue.inc
-rw-r--r-- 1 admin admin 119919 Mar 19 18:30 bootstrap.inc

How can I fix this issue?

There is a file permissions overview on this page of how all file permissions should be setup. If you will scroll down to the bottom of the documentation page there is a shell script that you can install and run on an entire Drupal installation that will fix all file permission issues. That should fix any problems that OP was having.


Attachment of Taxonomy Term Description shows All descriptions on term page instead of only one I created a View page to display a sortable table of Category | Model | Brand | Price. Each product has it's own content types that has all of these fields entered. Category is a List, Model is the title field, Brand is a term reference, and price is an integer field.

I created a page view from the data of of this Product Content type and used contextual filters to display different views of tables at the /category and the /brand level. Because I had some trouble getting two contextual filters to work on the same Page view, I created a new page view [Brand] for the contextual filter for the Brands taxonomy terms. (see question and comments here: Can you display data dynamically from a textfield in the URL and Name of Views?)

Now I created an Attachment to attach to the Brand view. I created the attachment because I would like the Term Description to be above the Brand view that displays the Product Category / Model / Price for each Brand generated by the view. The trouble is that I am getting the description of every brand printed instead of just the brand currently being displayed on the page. Does anyone know what might be causing this issue? I feel like I need a specific filter for this to work.. I've tried different configurations that produce the same result.

Below are my screenshots:

http://i.stack.imgur.com/6gTcI.png --> The attachment

http://i.stack.imgur.com/S20sQ.png --> The page view for the taxonomy term

You need to add a contextual filter to the attachment view. This should be the taxonomy ID. And you have to set the Inherit contextual filters: to Yes


How use settings.local.php with Acquia Cloud I try to setup my .gitignore file. My local repo is a clone from my Drupal 8 distro from Acquia Cloud.

(I want to theme my template locally and then, step by step I want to push it to Dev on Acquia Cloud.)

So regarding handeling settings.php, whether or not to ignore settings.php and whether or not use settings.local.php:

If I look in my current settings.php is see this:

// On Acquia Cloud, this include file configures Drupal to use the correct
// database in each site environment (Dev, Stage, or Prod). To use this
// settings.php for development on your local workstation, set $db_url
// (Drupal 5 or 6) or $databases (Drupal 7 or 8) as described in comments above.

I am confused and don't know anymore how to setup my .gitignore file with all this information and whether or not use settings.local.php. Please can somebody advice my what I have to do exactly, so it's setup correctly from the beginning.

The default .gitignore file that ships with your Acquia Cloud git repository is fine as it is. See https://drupal.stackexchange.com/a/193251/23961

I also advised against adding settings.php to your .gitignore file here.

Using settings.local.php is optional. Details about the file are available in the file or the online Drupal documentation as described already here.


Term lineage in simple Hierarchical select module I'm working on a project using Drupal 7. I'm using simple Hierarchical select module.

How its possible to attach the parent lineage to the node? Is there any way to do so using simple Hierarchical select? because the SHS only attach the child term to the node
I tried to google it million times but couldn't find an answer

I tried the Hierarchical select module but its doesn't help because I'm using this field as exposed filter in a view and there are only two 'selection type' choices:

Autocomplete : Which is not what am not looking for
Drop down : Which combines the parent terms and children terms in one list and that is not what I want , I want the selection type to be Hierarchical select which is not provided

please help
thank you in advance

With views you can use SHS which will provide simple Hierarchical select as selection type in expose filter.

To attach the parent term to node, you need to use the combination of Display Suite, Panels and entity module with token.
You can use parent term's token in Display Suit of default layout or any you want to use.


Anonymous users skip comment approval but they shouldn't In my drupal 8.6.1 news blog anonymous users can skip comment approval althouth permissions are set to not skip. I rebuilt the permissions but nothing changed.

Also in comments page I see that some anonymous users are linked to an anonymous user account with id = 0 !

My site is not hacked and I can't understand what is going on.

Check this image!

Is there a chance that my drupal 8.6.1 has this unexpected behavior because is running on server with php 5.6?

Thanks in advance

On my side, the problem was the use of the cleantalk module.

In this module, in the configuration page: admin/config/content/cleantalk/settings

You must uncheck "Enable automoderation" if you do not want to override the "Skip comment approval" permission


Why do I get a blank page when I create a new node? It seems there are some problems with the content submission. When I select filtered HTML or full HTML, it shows a blank page after submitting a new node. I turned on the error messages, but I still get a blank page with no error message. When the input format is plain text, all works fine.

How do I resolve this issue?

The White Screen of Death (or WSOD) can be caused by a lot of different things.  There is an article about them http://drupal.org/node/158043

Without more information, especially error messages or logs, all answers will be guesses.

Follow the steps in the article above, in order and one by one, to track down your problem.  The first step is making sure you can see errors by adding:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

to you index.php or settings.php.  Once you do this, you should see what is happening and be able to address it.

That said, the two biggest culprits of WSOD are errors in custom code and hitting the PHP memory limit.


What is the value returned by theme_get_registry, and why is it not NULL? I was going through Drupal code, and in the theme.inc file I found something that I couldn't understand. On theme(), I see the following code:

if (!isset($hooks)) {
  init_theme();
  $hooks = theme_get_registry();
}

theme_get_registry() is defined as follows:

function theme_get_registry($registry = NULL) {

  static $theme_registry = NULL;
  if (isset($registry)) {
    $theme_registry = $registry;
  }
  return $theme_registry;
}

I found the function is calling without any parameter, and the default parameter is NULL, but when I use print_r($registry) in the first line of the function theme_get_registry(), I get the values popped out; I assume the value should be NULL because it is not passing any value, and default value is NULL, from where $registry got values in the first line.

The value returned from theme_get_registry() is initialized by _theme_set_registry(), which is called by _theme_load_registry(), which is called by _init_theme(), called by init_theme().

function _theme_set_registry($registry) {
  // Pass through for setting of static variable.
  return theme_get_registry($registry);
}

init_theme() is called from theme(), right before calling theme_get_registry().

  $args = func_get_args();
  $hook = array_shift($args);

  static $hooks = NULL;
  if (!isset($hooks)) {
    init_theme();
    $hooks = theme_get_registry();
  }

The value used by theme_get_registry() ($theme_registry) is a static value; this means that the value theme_get_registry() gets from _theme_set_registry() is then returned all the times theme_get_registry() is called. NULL is the default value for $theme_registry, until $theme_registry = $registry is executed, and the calling function uses a value different from the default one.

To notice that the declaration of a static variable is different from the declaration of other local variables used by a function.

If I declare a variable as static $registry = NULL it doesn't mean the variable is always set to NULL. The constant value used in the declaration is the value assigned to the variable when it is initialized; the second time the function is called, its static variables are not initialized anymore, but they retain the value they had in the previous call of the function.
As reported in Variable scope:

function test() {
  $a = 0;
  echo $a;
  $a++;
}

  This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

function test() {
  static $a = 0;
  echo $a;
  $a++;
}

  Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.


adding panel to select field in content type I created a content type for a new block. One of the fields in this needs to pull in category information from a magento site. I have code to get all of the categories and display them in a drop-down working in a panel template.
The only step I am missing is know how to access this as a field in my new content type. I have read some articles about using something called hooks for this process but I'm not fully sure about how they work.
Is a hook the best method and if so what exactly does it involve programmatically?

As mentioned in one of the comments I used the hook_form_alter but instead of pulling in the panel I just created another function to get the information and used that as the options for my select.

  function gacms_magecp_content_type_edit_form($form, &$form_state) {

   $conf = $form_state['conf'];
   $categories = gacms_magecp_categories();

    $form['magecp'] = array(
     '#type' => 'select',
     '#options' => $categories,
     '#title' => t('Mage Category Product'),
     '#default_value' => isset($conf['magecp'])?$conf['magecp']:'',
     '#format' => isset($conf['format'])?$conf['format']:'full_html',
    );

    return $form;
  }

   function gacms_magecp_categories(){
    db_set_active('magento');

    $result = db_query("SELECT entity_id, name FROM catalog_category_flat_store_1");
        while ($row = $result->fetchAssoc()) {
           $content[$row['entity_id']]= $row['name'];
        }
        db_set_active();
        return $content;
    }


How do you allow users to create own menus? The idea is that a user should be able to create a menu to structure his uploaded content. How would you go about making this possible without giving the user access to edit other users menus?

Cheers,

Menu Admin Per Menu Module comes to solve this purpose!!

  The Drupal 7 Menu Admin Per Menu module is a simple module that allows
  you to grant permissions for users to administer specific Drupal menus
  based on their role.

  This module for instance would allow you to allow one role to modify
  the Main menu, while not allowing the role to modify a separate menu
  on your Drupal 7 website.

Watch this Screencast to learn about it : How to allow a specific role to administer the user menu on a Drupal site without giving them access to modify the Main menu


How can I add a new field from config inside hook_update_N? I have to add taxonomy by php code. Taxonomy has to got 2 fields. I added new function to test_taxonomy.install, and it seems to work:
function taxonomy_update_8805() {

    $config_path = 'modules/feature/test_taxonomy/config/update/';
    $source = new FileStorage($config_path);

    \Drupal::entityManager()->getStorage('taxonomy_vocabulary')
        ->create($source->read('taxonomy.vocabulary.regulation'))
        ->save();
}

Added new vocabulary to taxonomy.
Content of file:
langcode: pl
status: true
dependencies:
  module:
    - test_remote_vocabulary
third_party_settings:
  test_remote_vocabulary:
    is_remote: 0
name: 'Test'
vid: regulation
description: 'Test desc'
hierarchy: 0
weight: 0

The problematic part is when i try to add fields to the vocabulary.
I created 2 files
field.storage.taxonomy_term.field_regulation_test.yml
langcode: pl
status: true
dependencies:
  module:
    - taxonomy
    - text
id: taxonomy_term.regulation.test
field_name: test_field
entity_type: taxonomy_term
type: text_long
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

field.field.taxonomy_term.field_regulation_test.yml
langcode: pl
status: true
dependencies:
  config:
    - field.storage.taxonomy_term.field_regulation_test
    - taxonomy.vocabulary.regulation
id: taxonomy_term.regulation.test
field_name: test_content
entity_type: taxonomy_term
bundle: regulation
label: TEST
description: 'Tekst test'
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: text_long

But i am not sure how can i load them in update_xxx function.
EDIT:
I tried
    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.storage.taxonomy_term.field_regulation_abo'))
        ->save();

    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.field.taxonomy_term.field_regulation_abo'))
        ->save();

but i'm getting Missing bundle for entity type taxonomy_term while trying to update module

Yes, you can't create content before the relying config has been imported. That's a classic Drupal 8 paradox which has just recently been solved by a new hook: hook_deploy_NAME(&$sandbox).
Update to the latest Drush and from now on run drush deploy as part of your deployment routine, which replaces the old drush updb && drush cim routine. Then create a new file in your module: MYMODULE.deploy.php. In there implement MYMODULE_deploy_NAME(&$sandbox) where NAME can be any unique name (or an incrementing number as well). And use this hook to create the terms, same as in the hook_update_N(&$sandbox) in your question.
drush deploy will ensure that this hook will be picked up at the very last in the deployment routine, after the relying config has been created from configuration import.


How to override the widget of an exposed form filter? I have a view with a single filter criteria (let's call it category) exposed to the user. The user can also select multiple categories in for this view (standard view stuff).
The category selection filter is rendered to the user in a big <select> for element. For aesthetic reasons, this is undesirable.
What I'm trying to do is override the display of the widget that renders out the <select> element. I've copied my /sites/all/modules/view/themes/views-exposed-form.php.tpl to my theme's folder, however, the widget itself (which contains the <select> form control I want to change to something else) is simply rendered by $widget->widget;
How can I change how the widget renders the multiple categories selection filter in the view?
Edit, for more info and clarity: This question deals with styling a widget, which is not quite what I want to do. I want to change the markup that renders the widget.
Another edit (after answering my own question): Turns out widget is not quite the correct Drupal terminology to use here for the exposed form filter.

Ok, so after spending a day digging around the net, it seems that there are two ways to do this.

First off, for clarification, the exposed filter from the view is not a widget, at least in the Drupal sense of the word. In the traditional Drupal sense of the word, a widget is something used on an edit form or add form. Hooks like hook_field_widget_alter() and it's brethren operate on these widgets.

Just because the views-exposed-form.php.tpl has $widget as a variable, THAT DOES NOT MAKE IT A WIDGET!!!

Now that that confusion is out of the way, there are two ways to change the exposed filter.

Add a custom module and use hook_form_alter to change things about the exposed filter form. I got as far as creating a custom module (called bypass) and creating a hook to display some simple debugging info:

function bypass_form_alter(&$form, &$form_state, $form_id){
    dsm($form_id);
    dsm($form);
}

when I discovered the Better Exposed Filters module.

Use the Better Exposed Filters module to display the filters as checkboxes, radio buttons, etc. and style those.

Option 2 is what I'm doing now.  Hope this helps someone :)


Why can't I output it? stdClass Object(
  [nid] => 98
  .......
  [title] => hello world!
  [body] =>
  ........
  [field_img] => Array(
    [0] => Array(
      [fid] => 200
      [list] => 1
      [data] => Array(
        [alt] =>
        [title] =>
      )

      [uid] => 1
      [filename] => coupon.jpg
      [filepath] => sites/default/files/coupon_0.jpg
      [filemime] => image/jpeg
      [filesize] => 4434
      [status] => 1
      [timestamp] => 1302080050
      [nid] => 98
      [view] =>  **the image**
      ......
    )
  )
)

Supposing the object is $test,  echo $test->field_img[0]["timestamp"] in views-view-fields.tpl.php outputs 1302080050, but echo $test->field_img[0]["nid"] and echo $test->field_img[0]["view"] don't output anything; I can't print 98 and the image. print_r($test->field_img[0]) doesn't print the node ID and view? Why?

In Views template files you have access to the following objects:

$row
$fields['field_my_field_value']->row
$fields['field_my_file_value']->content

You do not have access to multiple image objects in your case. You should call an external function to retrieve data for each item.

$arg = (object) array(
  'type' => $fields['type']->raw,
  'vid' => $fields['vid']->raw,
);
$files = filefield_get_node_files($arg);

foreach ($files as $file) {
  print theme('imagecache', 'preview_body', $file['filepath']);
}


multiple selection widget I am using Drupal 8 and I cannot find where the multiple selection checkbox for my taxomomy field is.

And the result is radio buttons.

You have selected field cardinality to one . So its not reflecting checkbox.
Please follow the below steps you can achieve what you asked

Go to Structure > Content Type.
Select the {{Custom Content Type}} . Click on Manage Fields.
Edit the taxonomy Entity Reference field.Click on Field Settings Beside Edit Tab
Change Allowed number of values from Limited to Unlimited


Difference between Media and Asset module Today I saw a "new" module: Asset.

It looks interesting but I don't understand the difference between this module and the Media module, in the 7-2.x version.

Could someone help me?

Looking at this issue in the media module issue queue, the main technical difference (apart from UI) would be that the Asset module creates its own entity while Media uses the core managed_files API. In other words: Asset is 'an island' and other modules must specifically support Asset module. Integration with media module is easier because it uses core infrastructure.

There actually is a request to merge parts of Asset & Media code.

I took the module for a quick spin, it looks pretty easy but less flexible then the media module. However, I always found the media module configuration very complicated (file styles) because of its flexibility probably.


No Search form for custom theme I am creating my first theme.  I don't see the "Search form" block under structure>block for my theme.  It is present for other themes.  I am not sure what I am doing wrong.  Should I put something the the .info file to enable it?
NB: I am working with Drupal 7.

It turned out that there was nothing wrong with my theme.  I installed the theme in a new installation of drupal and the search block was available.


Sortable table: secondary sort I have a view (Drupal 6 / Views 2, but I think this may apply to other versions as well) displayed as a sortable table. I can add fixed sort criteria as you can with all views, but once the table is sorted by the visitor on a certain table, those sort criteria are ignored.

In the style options there is a box called "Override normal sorting if click sorting is used", which doesn't make sense to me. It seems to effectively disable click sorting, leaving the end user with a clickable but not working table headers.

Is there a way to keep the fixed sort criteria and use them as secondary criteria?

The initial sorting that you have specified in views is only used on the first page view. When you click on the header to change the sort the query is altered to use the drupal table sort routines instead. Unfortunately there is no support in the built in table sort code to allow multiple column sort, nor the ability to define a default of descending instead of ascending column. An alternative if your table is displaying all results is to add some Javascript that performs table sorts on the HTML and not provide sorting on the columns in Views. A google.com search for "javascript table sort" will give many results, this one looks to be quite robust: http://tablesorter.com/docs/


Drush Error: no database record could be found after failed attempt of sql-sync I was pushing our latest version of the site from our development environment to our live site (located on the same server). But unfortunately our web server ran into memory issues which prevented the move. We opened up access to more space but now SQL-sync refuse to function.

I assumed that we had issues with the database being corrupt so I replaced the database with our backup. But this did not help.

The development environment seem to work really well but I am very poor with Drush/SQL so I got a hard time understanding the error messages I get when testing the alias and site config. The Dev site work well while the live site is down and I would appreciate any advice on likely sources of the error.

The Dev alias that work well

sigvard@server1:~$ drush @mysite.dev status
 Drupal version                :  7.26
 Site URI                      :  dev.mysite.org
 Database driver               :  mysql
 Database hostname             :  localhost
 Database username             :  mysite_dev
 Database name                 :  website_mysite_dev
 Database                      :  Connected
 Drupal bootstrap              :  Successful
 Drupal user                   :  Anonymous
 Default theme                 :  mysite
 Administration theme          :  seven
 PHP configuration             :  /etc/php5/cli/php.ini
 Drush version                 :  4.5
 Drush configuration           :
 Drush alias files             :  /usr/share/drush/includes/../aliases/mysite.
                                  aliases.drushrc.php
                                  /home/sigvard/.drush/aliases.drushrc.php
 Drupal root                   :  /var/www/mysite_dev
 Site path                     :  sites/default
 File directory path           :  sites/default/files
 Private file directory path   :

Alias of the live site

sigvard@server1:~$ drush @mysite.live status
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).
 Drupal version         :  7.26
 Site URI               :  mysite.org
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /etc/php5/cli/php.ini
 Drush version          :  4.5
 Drush configuration    :
 Drush alias files      :  /usr/share/drush/includes/../aliases/mysite.aliases
                           .drushrc.php /home/sigvard/.drush/aliases.drushrc.php
 Drupal root            :  /var/www/mysite
 Site path              :  sites/default
 File directory path    :  sites/default/files

sql-conf of the dev site

sigvard@server1:~$ drush @mysite.dev sql-conf
Array
(
    [database] => website_mysite_dev
    [username] => mysite_dev
    [host] => localhost
    [port] =>
    [driver] => mysql
    [prefix] =>
)

sql-conf attempt on the live site

sigvard@server1:~$ drush @mysite.live sql-conf
include_once(/var/www/mysite/sites/default/settings.php): failed to [warning]
open stream: Permission denied in drupal_settings_initialize() (line
717 of /var/www/mysite/includes/bootstrap.inc).
include_once(): Failed opening                                       [warning]
'/var/www/mysite/sites/default/settings.php' for inclusion
(include_path='.:/usr/share/php:/usr/share/pear') in
drupal_settings_initialize() (line 717 of
/var/www/mysite/includes/bootstrap.inc).

I wonder if it's a file system permission on your live site. Are you sure /var/www/mysite/sites/default/settings.php on the live site is readable by your web server?

(Also, unrelated to this but Drush 4.5 is getting pretty old so if possible you might want to update it.)


Form API placeholder attribute rendered as "- Select -" In a custom Drupal 8 module, I have a couple of Form API fields of '#type' => 'select':
<?
    $form['form-right']['field_role'] = [
      '#type' => 'select',
      '#title' => $this->t('Role'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Role Foo'),
        'bar' => $this->t('Role Bar'),
        'baz' => $this->t('Role Baz'),
        'quux' => $this->t('Role Quux'),
        'plugh' => $this->t('Role Plugh'),
        'xyzzy' => $this->t('Role Xyzzy'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Role'),
      ],
    ];

    $form['form-right']['field_contact_reason'] = [
      '#type' => 'select',
      '#title' => $this->t('Contact Reason'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Contact Reason Foo'),
        'bar' => $this->t('Contact Reason Bar'),
        'baz' => $this->t('Contact Reason Baz'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Contact Reason'),
      ],
    ];

Before a value is selected, the dropdown select picklists display the string '- Select -':

The client would like them to display the value in the placeholder attribute instead.
Have I done something wrong?

According to the documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Select.php/class/Select

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for
a required field and "- None -" for an optional field.


Batch API to process millions of records I need to run Batch API on a huge dataset. Specifically I have a custom table with a lot of rows which I need to iterate over. The batch process works fine using small numbers. When using the full set I run out of memory before it even starts because I am loading a very large array of IDs to pass in to the batch function. Think of a 5 million item array. What is a good way to handle this? Break it into smaller chunks somehow to then pass in to Batch API? Increase the memory limit to an (ungodly) amount?

Add a column for 'processed'. Each time you run the batch process select rows with a limit of 100 unprocessed rows for you batch process and then mark each row as processed.

You could run this on cron or something or run a nested batch.


Correct way to alter markup as html within theme_preprocess_container? On my node edit form I've got a field widget that needs some information added to it. Before my alterations, the kint dump of $variables['children'] looks like:

However, after manually setting $variables['children'], the dump looks like:

Before alteration, html renders correctly. However, afterward it is all just rendered as a string with the HTML displaying on the page.

I've tried using the create() method instead that's shown as available under:

...but it doesn't do anything at all.

I've also instead tried changing $variables['element']['display']['#markup'], but that doesn't have any visible effect.

You can't modify a markup object, but you can use the create() method on a new markup object to replace the old one.

$variables['children'] = \Drupal\Core\Render\Markup::create('
Manually set
');

By the way, you are modifying a twig debug message which won't be there in a production environment.


all nodes page not found Drupal 7.26 multi-site , one of my sites is playing up.
Error started with no login page until I realised all nodes except home were not found.
So I tried putting in code in index.php to see errors but none showed up. Then I dropped the database and reinstalled settings to start with basic drupal install but after importing sql and again drush updating database still pages cannot be found excepting home page. Then went to ?q=user to login as admin and could see all the pages but clicking on any one of them would throw page not found error.

update: this has morphed into new question but was able to regain pages by removing clean-urls so will grant answer and ask new question.

It could be because you have enabled clean url but its not working may be because of .htaccess file missing. Just check if there a .htaccess file in your sites first folder. if not copy one from other drupal site. or what you could do is go to yoursite/?q=admin/config/search/clean-urls this page and uncheck enable clean url and save


Custom module not indexing in search I'm using drupal search module to search/find/filter content in my CUSTOM MODULE and it's not returning any results when I search for a word listed in content of my custom module content type. It return results only when i search for a users and others content type.

Any body knows what can i do to fix this? Do I have to implement any hook to index the content of my custom module?

PS:

1) My custom module it's based in the drupal core blog module

2) I was using Custom Search module, but i've disabled it

3) I've tried the search api module and views exposed filter (Search Terms) and nothing

Thank you

This is a shot in the dark, but I would do the following.  This assumes you are on Drupal 7.

On, admin/structure/types/manage/page/display, open Custom Settings and select Search Index.  Save.  Then click on the Search Index tab and configure the view mode for all of the fields that you want to search in.

On admin/config/search/settings, make sure that you have Node selected.

On admin/config/search/custom_search/content, double check that you have selected the content types that you want to search (or leave that fieldset empty).  Also check that you aren't excluding any types that you actually want to search.

If your site isn't that big, I would dump the search index and rebuild id.  I normally do this from drush:

drush search-reindex
drush search-index

Then, open your MySQL tool of choice, and look for a few keywords that you know you should have hits on:

SELECT
    *
FROM
    search_index
WHERE
    word = 'foo'

If all of that works, then you shouldbe getting search results.  If not, you need to find what is interfering with the indexing, which could be specific to your system.