Remove an item from $form_state in an ajax callback I'm using this form api example: AjaxAddMore. I want to add a "remove button" for each indiviaul element, in order to remove an item but not the latest. Thouse are my changes:

...
  $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#attributes' => array('class'=>array('container-inline')),
    ];

    for ($i = 0; $i < $num_names; $i++) {

      $form['names_fieldset']['fields'][$i] = [
        '#type' => 'fieldset',
        '#name' => 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['ids'] = [
        '#type' => 'textfield',
        '#title' => $this->t('ID'),
        '#default_value' => $i,
        '#name' => 'id_'.$i
      ];

      $form['names_fieldset']['fields'][$i]['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name')
      ];

      $form['names_fieldset']['fields'][$i]['remove'] = [
        '#type' => 'submit',
        '#name' => 'remove_'.$i,
        '#value' => $this->t('Remove this'),
        '#submit' => ['::removethisCallback'],
        '#ajax' => [
          'callback' => '::addmoreCallback',
          'wrapper' => 'names-fieldset-wrapper',
        ],
      ];
    }
....

It works good and I can add several records. But I can't remove an item other than the latest one. This is my callback function where I've tried to unset the item I want to remove:

public function removethisCallback(array &$form, FormStateInterface $form_state) {
    $button_clicked = $form_state->getTriggeringElement()['#name'];
    $id = substr($button_clicked,7);
    $values = $form_state->getValue(['names_fieldset']);
    unset($values[$id]);
    $form_state->setValues(['names_fieldset'], array_values($values));

    $name_field = $form_state->get('num_names');
    if ($name_field > 1) {
        $remove_button = $name_field - 1;
        $form_state->set('num_names', $remove_button);
    }
    $form_state->setRebuild();
}

But It doesn't work. How could I remove or update an item from $form_state?

$form_state->setValues(['names_fieldset'], array_values($values));

setValues(array $values) only has 1 parameter

For 2 params, you need to use setValue($key, $value) without the "s"

$form_state->setValue('name', array_values($values));

Alternatively, you could do

$values = $form_state->getValues();
$values['name'] = array_values($values);
$form_state->setValues($values);


template_preprocess_comment() overrides template.php I try to override this function in my template.php in Drupal 7; I copied the function found on template_preprocess_comment().

The first line contains function themename_preprocess_comment($variables).

It contains the following code, which doesn't work.

$variables['submitted'] = t('!username on !datetime', array('!username' => $variables['author'], '!datetime' => $variables['created']));

I clear the cache, I override theme_textarea($variables) and it works.

You need to pass the variable by reference like this using &

function themename_preprocess_comment(&$variables) {


How do i check the duplicate entry in the table? I have created a custom form as below. And the  user has to fill all the fields for the submission(I am storing all the fields after submission).

Question is how do i check if the email address has already been entered ?

One way of doing that is using the hook_form_alter and add the custom validation function, and in that custom validation you can check if the enterd email already exists in the database than set error, somewhat like below:

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form id of your form.
  if ($form_id === 'YOUR_FORM_ID_WHICH_YOU_WANT_TO_EDIT') {
    $form['#validate'][] = 'check_email_address_exists';
  }
}

function check_email_address_exists(&$form, &$form_state) {
  // Get the value of email field. if you are under than use: "dpm($form_state['values'])"
  $email_entered = $form_state['values']['EMAIL_FIELD_NAME'];

  // Generate the query somewhat like below, For Example I am using users table's "uid".
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->condition('u.mail', $email_entered);

  // This will return the count of the fields found.
  $row_count = $query->countQuery()->execute()->fetchField();

  if (isset($row_count) && ($row_count > 0)) {
    form_set_error('EMAIL_ADDRESS_FIELD_NAME', t('This email already exists, please try with another email  address!'));
  }
}

In order it to work you have to change the values as per you requirement, and don't forget to modify the db_select query as per your requirement, and last CLEAR THE CACHE after implementing the same.


How Can I Create a Front Page Based on Blocks? I am building a front page that comprises a number of Views-based blocks.  How can I create a front page that has no actual "content" (besides these blocks) without getting a "Page not found error"?

The best I have been able to do is create a Views page and set a filter that will never return a result e.g. nid < 0.  I set the path to the front page and the title to none.  This seems like unnecessary overhead.

Surely, there must be a better way?

If it was me, I would create a custom page-front.tpl.  I'd omit the $content region and probably create a few custom regions for the homepage.  I can then place my blocks into the regions.

D6 create page-front.tpl.php
D7 create page--front.tpl.php

Cheers.


What are some specific reasons NOT to share a users database table between sites? I'm building a site for a client, and surprise! Turns out they're using a shared users table between multiple Drupal 7 sites (completely different code bases, different config, etc). I'm only supposed to be working on the one new site, but obviously this new wrinkle has me considering how these other sites will mess me up.

In my heart of hearts I know this is a terrible, very bad, no good idea. I don't want to launch a new site with this timebomb lurking under the hood. But I can only think of one scenario where things go hideously wrong. Deleting users could lead to major complications.

Other than that, what are specific scenarios that you have faced, or that you could think of arising when sharing a users table between Drupal sites?

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

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

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

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


Theme Preprocess Conditional Field Display Looking for a way to preprocess two fields. I am trying to hide Field 1 from display if Field 2 has value.

If Field 1 has value and Field 2 has value display Field 2 only.
If Field 1 has value and Field 2 has NO value display Field 1.

This should only apply to content type USER POSTS. And I am using Display Suite to arrange the fields if that makes a difference.

What would be the preprocess hook to place on mytheme.theme?

Any help is greatly appreciated.

Can you hide it with CSS? In which case you could do something simple like:

<?php

/**
 * Implements template_preprocess_hook().
 *
 * Adapt logic, field names etc to suit your needs.
 */
function MYTHEME_preprocess_page(&$variables) {

  if (empty($variables['node']->get('my_field_2')->value)) {
    $variables['page_classes']['#plain_text'] .= ' field_two--display-none';
  }

}

/* CSS */
.field_two--display-none { display: none; }

Not super elegant but would do the trick.

Your other option is to use the conditional fields module.


Loading js file for all browsers except IE I have a requirement to add a js file only for IE (6, 7, 8) browsers. The following script works fine and sometime it doesn't. I cleared the cache several times but has no difference.I don't know where I am going wrong . Is there anything to do with drupal_add_js for IE?

function mymodule_init() {
  if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external');
  }
}

// The code modified to true for all browsers it works for all browsers but not in IE
function mymodule_init() {
  if(1)) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external'); // loading in all browsers except IE
  }
}

As you may be suspected, the original condition is wrong.  Here's a related post on how someone was able to find a better condition for checking the user agent for IE:

https://stackoverflow.com/questions/5302302/php-if-internet-explorer-6-7-8-or-9

summary: use this instead:

if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])){}


Main page colorbox and facebook like box In my CakePHP site when user is first entered to my site, I check for a cookie. And if I can't find the cookie, after document load from my js file, I show Facebook like box to my visitors. I show a "div" that in invisible in my page.

I can't imagine how can I implement this in my Drupal 7 site.
Should i put the invisible div into one of my node. If so, how can I load it from main node that includes only links to inner nodes?

I would be very happy if you can write the steps or show an example of this issue.

You can use the hook_boot() to set/unset the visitor's cookie.
You can then use hook_init() to check the value of the cookie and execute some javascript to construct your div. Your javascript can be inserted in the page during hook_init() through drupal_add_js().


How do I override a RenderElement? There is a Drupal 8 RenderElement called HtmlTag, which controls how HtmlTags are rendered. I would like to override this so that I can change its default behaviour.

I could write a class that extends HtmlTag and override what I need, but then how would Drupal core and the theme system know to use my new class?

Alternatively, maybe I should be using hook_theme_registry_alter() to tell Drupal 8 to use my new class?

I'm not really sure of the best way of achieving this and there don't seem to be any examples of this being done.

Using hook_element_info_alter() would be one option, not sure it's the best.

The existing class sets 2 pre render callbacks, which you can override in your own class:

function MYMODULE_element_info_alter(array &$types) {
  $types['html_tag']['#pre_render'] = [
    [\Drupal\mymodule\HtmlTag::class, 'preRenderConditionalComments'],
    [\Drupal\mymodule\HtmlTag::class, 'preRenderHtmlTag'],
  ];
}

...

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\HtmlTag as CoreHtmlTag;

class HtmlTag extends CoreHtmlTag {

  public function preRenderHtmlTag($element) {
    // ...
  }

  public function preRenderConditionalComments($element) {
    // ...
  }

}


entity reference view in a view I have 2 content types: location and maintenance.

I would like a view that shows all the locations with a search box at the top so the user can search the right location; when users click on a location, they are redirected to the location details and the maintenance nodes listed under the location details.

So the workflow is like this:

Search the location
Click on the location
See a view with location and maintenance nodes

I have already installed entity reference and made references from maintenance to locations, but I just can't get the view settings right; a list of all the locations is what I am getting, so far.

Your existing view listing all locations is fine for now (assuming a path like "/locations"). Create another display in that view (or a complete different view if you want). This second display/view should first get a relationship to the (location) entity referenced by the field "location". Then the view should have a contextual filter on a node id using that relationship; argument should be in the URL, e.g. by using something like "/locations/%/maintenance" as path.

So if you have two locations (nids: 1 + 2) and 4 maintenance nodes (nids: 3-6), you should see all locations at "/locations" and all maintenance for the first location at "/locations/1/maintenance". Now you just need to link from the first view to the second one by using the correct path "/locations/[nid]/maintenance" and it should be the way you want it. You can take it a step further by displaying all locations along with the maintenance on a single page. You'll need an additional module (if not yet installed): views_field_view.

If that is installed, you can proceed to the next step and include the maintenance view in the location view. Add two new fields, first of type "Content: Nid" and second of type "Global: View". For the latter field choose the maintenance view in the dropdown and enter "!nid" in the argument textbox. By doing this, the current nid of the location is send as an argument to the maintenance view and thus only displaying maintenance nodes that are connected to that current location.


What's the best practice for field API prefixes? (To prefix or not to prefix, that is the question) I'm implementing a giant list of fields, instances, bundles, et cetera in a custom site specific module.

In progress, I see that the core Tags vocabulary has a field_ machine name prefix, and none of my custom vocabularies have this prefix. I've known that creating fields through the Drupal GUI also prefixes fields with field_.

In my previous experience working with prefixed fields, this has always seemed too verbose.

Is prefixing Field API fields with _field a best practice for a reason I haven't come across yet?

I prefix my custom fields always with the name of my module, which, I think, is a good practice, so that I know which module provides this field. And also I think this is the same reason Drupal Field UI adds the field_ prefix since the fields are created by the Field module in this case.


How can I put a time-delayed lock on a node? I'm using Drupal 7, and would like to add a time-delayed lock to a specific node type: when a node of that type is created, the creator of the node has fifteen minutes to edit that node. The node then locks and its state changes in workflow.module.

What's the best way to achieve this result?

http://drupal.org/project/user_alert is a good module combined with "Job scheduler" or a trigger module for timing should be Fine. but you may have to get creative with the setup. also try http://drupal.org/project/notifications


How to make the submit button not appear on form unless an option is selected from radios? I have a form with three form elements:

'#type' => 'radios' element having two options (Yes or No),
'#type' => 'submit' &
'#type' => 'checkbox'

When the user lands on the form page, he should only see the radios element first and can see the checkbox & submit elements only if he selects an option from radios element.

Is there a Drupal way to do this using the Form API?

You can use #states attribute in form api to hide submit button and check box

For Example

$form['email_canceled']['settings'] = array(
    '#type' => 'container',
    '#states' => array(

      // Hide the settings when the cancel notify checkbox is disabled.

      'invisible' => array(

       ':input[name="email_canceled_toggle"]' => array('checked' => FALSE),
      ),
    ),
  );


is there any possible conflict for fields with the same machine name? i am trying to debug a paragraph not displaying fields and i am having

  /admin/reports/fields

a same machine name for a field in 3 different paragraphs

field_call_to_action_ref    paragraph   Entity reference revisions (module : entity_reference_revisions)

    Bloc compositeParagraphe standardElement d'accordéon

Machine names for fields must be unique per entity type.

The means that with nodes, fields must be unique across all content types. So you can't create two fields with the same machine name on different content types, as both content types are nodes, and machine names must be unique for the entity type. (Edit - you can however re-use the same field on multiple content types, but it will be the same field, not two fields with the same machine name).

You can have a field_image on a node, and field_image on a taxonomy term. Here, the machine name is the same, but unique to each entity type, so there is no problem.


how generate chart from Views Aggretation Plus I created a table from webform submission data (group and compress) using Views Aggregator Plus

I would like to generate a pie chart from this table (industry as the label and turnover as the values).

Any hints to generate the pie chart would be appreciated.

Now I can do that,

(a) Exclude the Company field
(b) In the VAP setting, disable the summary sum in the footer
(b) Then use highcharttable module to create the pie chart.


array_keys() expects parameter 1 to be array, null given in drupal_schema_fields_sql()? i have developed a custom module which will calculate the employee salary . I have created the hook_schema() like this

This is mymodule.install file with two entities

function payroll_schema() {
$schema['payroll'] = array(
  'description' => 'A detail payroll structure for an employee',
  'fields' => array(
    'payroll_id' => array(
      'description' => 'payroll id',//this is my primary key.
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'paid_days' => array(
      'description' => 'Working days of an employee',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  ...
  ...
  'primary_key' => array('payroll_id'),
);
$schema['payroll_item'] = array(
  'description' => 'Details of payroll items',
  'fields' => array(
    'item_id' => array(
      'description' => 'item_id',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'payroll_items_id' => array(
      'description' => 'Payroll id', //foreign key
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    ...
    ...

  ),
  'primary key' => array('item_id'),
  'foreign keys' => array(
    'payroll_items_id' => array(
      'table' => 'payroll',
      'columns' => array('payroll_items_id' => 'payroll_id'),
    ),
   ),
);
}

Here is the mymodule.module file with hook_entity_info()

function payroll_entity_info() {
  $return['payroll'] = array(
    'label' => t('Payroll'),
    'entity class' => 'Payroll',
    'controller class' => 'PayrollController',
    'base table' => 'payroll',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'payroll_id',
      'label' => 'Payroll id',
    ),
    'module' => 'payroll',
    'view modes' => array(
    'full' => array(
       'label' => t('Full content'),
       'custom settings' => FALSE,
       ),
    ),
  );
  $return['payroll_item'] = array(
    'label' => t('Payroll Item'),
    'entity class' => 'PayrollItem',
    'controller class' => 'PayrollItemController',
    'base table' => 'payroll_item',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'item_id',
      'label' => 'Item id',
    ),
    'module' => 'payroll',
    'view modes' => array(
    'full' => array(
      'label' => t('Full content'),
      'custom settings' => FALSE,
      ),
    ),
  );
  return $return;
}

Here is the entity_load ()

function payroll_load($id) {
  $payrolls = entity_load('payroll', array($id));
  return reset($payrolls);
}

And here is my mymodule.controller.inc

class PayrollController extends DrupalDefaultEntityController {
  public function __construct($payroll) {
  parent::__construct('payroll');
  }
  public function create() {
  $payrolls = new StdClass();
  return $payrolls;
  }
}
class PayrollItemController extends DrupalDefaultEntityController {
  public function __construct($payroll_items) {
  parent::__construct('payroll_item');
  }
  public function create() {
  $payroll_items = new StdClass();
  return $payroll_items;
  }
}

When i am trying to install a module it gives a error as:

  Warning: array_keys() expects parameter 1 to be array, null given in
  drupal_schema_fields_sql()  (line 6969 of
  mylocation/includes/common.inc).

Can you tell me where i may made any mistake ??

You've forgotten to return anything from your implementation of hook_schema().

Just add return $schema; to the end of the function, and re-install your module.


Convenient way to copy & paste links to uploaded file attachments when editing Drupal 7 content? In Drupal 6, when enabled, the upload module presents a handy list of all the files attached to a Page node.  The list includes the file URL in plain text for convenient copy & paste into the Page node body.  E.g.

Drupal 7 replaced the upload module functionality with file fields in core.  The listing provided by this functionality does not display the file URL.  E.g.

How can I conveniently copy and paste the file URL using this Drupal 7 method?

Note: Right-click + Copy file location is not convenient because you end up with extra overlay related information on your URL.  Furthermore, you also always get the full URL instead of just the parts you want (i.e. relative link).

IMCE will let users browse to it and insert links to the files inside a text area if that's what you're going for. You could also programmatically alter the form and provide a copy to clipboard link next to the file in the listing.


Applying image style to authors pictures in comments without preprocess function Is there anyway I could apply an image style to the user picture in comments without using a preprocess function (YOURTHEME_preprocess_user_picture?)

The reason I ask this is because the preprocess function scales and crops the user pictures and I can no longer use the uncropped version (the original) in Views for example.

Any and all help on this is greatly appreciated.

Thank you. :)

You should be able to do it through straight css, or look into a module that will allow you to customize image styles for different applications.

.comment .user-picture

.comment .user-picture img


Drupal 7 Contextual Filter on URL Alias I have a view which shows a list of articles, located at:

  mypage.com/articles

Each article is linked to its main sub page view, like this:

  mypage.com/articles/name-of-my-artile-yay

The URL path is created with autopath & URL aliases.

In views, how do I create a contextual filter to show only the selected sub page view?

I have this as my path in views:

  articles/%

but don't know where to go from here. I tried title and making it lowercase and replacing spaces with a hyphen, but that won't always work and the URL aliases change the URL such that it removes words like:

  a, an, as, at, before, but, by

And if a page title is:

  This is my page title - with this

The URL alias becomes:

  my-page-title

Therefore it won't be able to match in my contextual filter using the page title.

What am I missing?

I think the simpliest way is to use Panels, and override the Node page. Add a variant and put your view in it, and send the node's nid argument to it, using node:nid contextual argument.

(install page manager)
Enable node view page (node/%node)
Add a variant, set a validation criteria selecting your concerned node type
Use simple one-column display
Add your view in your column
It asks for an argument, send the node:nid, (or entity_id, or whatever)
In your view, use node:nid contextual filter

All is done.


One taxonomy term in multiple vocabularies Is there is a way to refer to one term in more than one vocabulary?

e.g. i have 2 vocabularies ... Properties for sale and Properties for rent

Properties for sale:
-Apartment
-House
-Land
Properties for rent:
-Apartment
-summer house
-Room

So, how can i have the term (Apartment) in both vocabulary

Well you could combine them in a single vocabulary and then your term can have two parents:

Properties
-Properties for sale
--Apartment
--House
--Land
-Properties for rent
--Apartment
--summer house
--Room


Client-side validation module, fields required only if certain values in other fields are set We've built a form using WebForms and are using the Client Side Validation module for AJAX/jQuery validation.

One field on the form needs to only be mandatory if a certain country is selected in the drop down.

We've got as far as being able to customise the styling (the jQuery side of things) to hide/show the required field notice, but we can't seem to dynamically alter the validation rules that the module is working to.

How can we achieve this?

You can always create a custom rule for Client Side Validation, check clientside_validation.api.js for instructions, but you'll need some coding experience, otherwise feel free to open a feature request and we'll see what we can do.


Drupal Commerce: How to perform a complex calculation of order's final cost (VATs & discounts)? Here's is what I want to accomplish:

There are 2 taxes in my country: 6.5% & 23%. Every product has to be matched with 1 of these 2 VATs (I'm currently using a taxonomy vocabulary holding these 2 VAT values instead of using commerce tax module)
A discount should always be available, based on total order's amount, excluding tax e.g. an order's total (with no tax included in base prices) of €0,01-€50,00 awards the customer with a discount to the order's total (including tax) of -5%, from €50,01 to €80,00 gives a discount of -8% etc etc

What I want to accomplish:
- Customer adds products to cart (product prices are displayed excluding tax, ie w/o components) and heads to checkout. According to order's total (addition of products' base prices w/o tax), the appropriate discount will be applied.
- Final Price = (Products' base prices + their appropriate taxes)*Pre-calculated Discount + Shipping Cost

Example:
Shopping cart includes:
- Product 1: €20 base price (6.5% VAT)
- Product 2: €25 base price (23% VAT)
Checkout Process:

Discount pre-calculation: Total base price is €20 + €25 = €45. As a result, the customer should be awarded with a -5% discount (see available discount rates above).
Order's total including products' VATs = (€20 + €20*0.065) + (€25 + €25*0.23) = €21.30 + €30.75 = €52.05
The pre-calculated -5% discount from step 1 is applied: €52.05 - €52.05*0.05 = €49.45 and that's what the customer has to pay for the products in his/her cart.
Order's weight is calculated and a shipping flat rate is applied (I have this functionality already working). As a result, the shipping cost is added to €49.45 and we finally get the sum that the customer will have to pay using one of available payment methods.*

I would appreciate your suggestions on how to make this happen.

Tricky parts:

different products can have different VAT (23% or 6.5%).
The discount has to be calculated by adding all products' base prices (NOT including tax) and THEN applied to line item (including tax) prices.
It would also be nice if VATs & discount were displayed to customer in order's review.

You can achieve what you're looking for using some module and disabling others. This explanation is based on Drupal Commerce (7.x).

Uninstall standard Commerce Tax module since it leads to weird results with different VAT if you aren't a Rules master as exposed in this issue on drupal.org.
Install Commerce European Union VAT (commerce_eu_vat) choosing the right country: the module has a good written API and you can adapt it for extra-EU countries easily. Now you can assign product by product the right VAT and even assign a default VAT by product type via "manage fields" on product variations administration.

Install Discount (commerce_discount) module. You can set discount per product and per order (your case). Create a new discount, e.g. "My funny discount".
Now you can create your per-order discount. Every time you create a new discount it appears on both Discount page and on Pricing rules. Since VAT is sometimes applied before Discount (in my case it was) then you have to change the Rule weight for your new discount. Go to the Pricing rules administration page, search for "My funny discount" > edit > Settings > Weight and give it a negative weight to apply the discount before the VAT. Note: when you override the discount you cannot save it anymore since you've changed the parent Rule. Just revert the rule to make it editable again and then reapply the weight trick.

Now you have to hide unwanted components from your price on display: to do this install Commerce price by components (commerce_price_components). On your product type > Manage display you can change your price field widget from "Formatted amount" to "Price by components" and check only Discount and Base price, excluding VAT and other components.

Here the result on checkout:

Hope this helps.


All pages showing "Access Denied" if not logged in I am on MAMP, able to login and try to figure things out. (First time developing in Drupal). I am using Drupal 7, with Project Kickstart distribution. https://drupal.org/project/project_kickstart

This is meant to be a public site in the end - any idea what I should be checking to see why anonymous user cannot view content? I checked node_access and there is an entry for GID 0. There is also a user 0.

When you are logged in as admin, go to /admin/people/permissions and make sure that anonymous users are given View published content permissions.

If you are new to Drupal, you should probably stay away from the database tables for now.


How to import/add translated strings having inline styles? I've imported a .po file having Spanish translations. The import was successful but some translation strings were skipped because they contain disallowed HTML.

From UI, I found that some translations were not translated. So I tried them adding those via the translate admin interface (Administration » Configuration » Regional and language » Translate interface)

I could see the original text having inline style like following.

But when I tried to add a Spanish (Latin American) Translation and hit 'Save translations' getting the following error.

  The submitted string contains disallowed HTML:Hola

I've enabled Translatable all HTML text formats under multilingual settings  (Administration » Configuration » Regional and language » Multilingual settings)

It's working when I remove inline style add translation   like the following. So I guess it's not supporting inline styles and classes.

 Hola

What could be the problem? I found a function in function locale_string_is_safe($string) under includes/locale.inc file. Do I need to do any tweaks with that?

Any suggestions would be much appreciated.

Yes your guess is correct,locale_string_is_safe  "Check that a string is safe to be added or imported as a translation." if you want to ignore your job you should patch it for a while ,
change it to

function locale_string_is_safe($string) {
  return TRUE:
}

after your job  revert it.


hook_taxonomy_term_update(), where does it get invoked in drupal's core code? I looked after a module_invoke_all('taxonomy_term_update') in the taxonomy module (and more in the entire Drupal core) but I didn't find anything.

Where does that hook get invoked in the code?

It's invoked from taxonomy_term_save().

The reason you can't find it is because the hook gets invoked via an interpolated string, depending on the current operation (insert or update):

module_invoke_all("taxonomy_term_$op", $term);


Conditionally unpublish a nodes more than latest 20 I want to show the latest updated 20 nodes and unpublish rest of the nodes more than 20 for particular content types.

Here is my code I Have done for a single node

public function unpublishednode() {
   $all_content_types = NodeType::loadMultiple();
    foreach ($all_content_types as $machine_name => $content_type) {
      if($machine_name == 'events') {
        $node = Node::load(389);
        $node->setPublished(FALSE);
        $node->save();

      }
    }
}

You need an entity query to get the nodes filtered by the content type, sorted by the changed or created date and starting with the 21th node:

  $query = \Drupal::entityQuery('node');
  $nids = $query
    ->condition('type', $type)
    ->sort('changed', 'DESC')
    ->range(20, PHP_INT_MAX)
    ->execute();
  $nodes = Node::loadMultiple($nids);

You could also add a condition for published nodes, so that you don't load nodes that don't need to be unpublished:

    ->condition('status', NodeInterface::PUBLISHED)


How to remove default 'search' text form search form I can't seem to figure out how to get rid of the default text "search" on my search form (located here: http://dev.mysourcewise.com/media-center)

I can confirm the following works in Chrome's console:

jQuery("#edit-search-block-form--2").val("");

However, when I try adding it using Drupal.behaviors or even with the following code in my theme's template.php file, it doesn't work (even though I can confirm the javascript is loaded in the footer):

  drupal_add_js('jQuery(document).ready(function () { jQuery("#edit-search-block-form--2").val("");',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 1000)
 );

I have tried other methods as well, and nothing is working except entering the the above in the browser console.

The Search text in input is created by jQuery from any where. When I search through the JavaScript files, I find the following file:

file : /sites/default/modules/hg/sw_tweaks/js/sw_tweaks.js

The code

//Search Bar @ Top of Home Page
    $(function () {
      $('#edit-search-block-form--2').val("search");
    });
    jQuery('#edit-search-block-form--2').click(function () {
      jQuery('#edit-search-block-form--2').val('');
    });

Try to remove this code.
I hope this helps you or help you finding the problem.


How to fetch fields related to node in view templates? Hi I am trying to do similar in Drupal 8 :

Can we write php conditions in view field templates?

Is that possible to fetch fields related to node such as terms, comments count and comment form link, revisions, voting count and voting widget and edit link in one field template. If I create template file of title field like How can we override view field template in drupal 8  and need to fetch other fields related to node in that same template, But we should not add other fields in view itself but fetch other fields related to node in preprocess or by some other method.

Please suggest, I am trying but not able to conclude exact approach.

File made template based on above which is in action for title field everywhere :

  views-view-field--title.html.twig

Is that possible to fetch other fields related to node in this template without adding fields in view ?

Thanks!

In my opinion it's better to write a template preprocess for your view in yourtheme.theme file. hook_preprocess_views_view()

function yourtheme_preprocess_views_view(array &$variables) {
  if($variables['view']->id() == "your_view_id") {
    if (isset($variables['rows'][0]['#rows'])) {
      $nodeValues = [];
      foreach ($variables['rows'][0]['#rows'] as $value) {
        $nodeValue['taxonomyValues'] = $value['#row']->_entity->field_taxonomy->entity;
          :
          :
        $nodeValues[] = $nodeValue;
      }
      $variables['node_values'] = $nodeValues;
    }
  }
}

Above, is a sample code for fetching a taxonomy reference field. Fetch required fields and pass it in your own variable to views-view.html.twig file

To further give template suggestion for views-view.html.twig use

function yourtheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables)

In your views-view.html.twig

{% for value in node_values %}
   {{value.taxonomyValues}}
{% endfor %}


Clean up rdf mappings and vocabularies In the past I have imported automatically some vocabularies using rdfx/evoc and put some rdf mappings using rdfx ui. The module also made automatic rdf mappings with taxonomy terms and various fields that does not let me delete.

Now I need to clean up the mappings and reach astate of rdf mappings as it would be a fresh install.

RDF UI and other modules do not provide the possibility of deleting mappings.

What tables/fields I have to delete/alter from the database, so to clean up, without damaging the rest of the site?
How I can bring rdf_mapping, mapping BLOB to defaults?

You are more likely to get an answer in the RDF Extensions issue queue on drupa.org. see this comment as an answer to your question: http://drupal.org/node/1296820#comment-5068706


Help with themeing the Admin Theme I'm working on a D7 site at the moment and need a bit of help with the admin themes.

I've got 2 levels of admin for the site. Super user and a lower level admin that can only edit content they created. The lower level does not have access to the administration theme so their pages and admin forms are showing up in the site's content.

My question is: Is there a way of theming these pages through a template? Does it just use the basic node.tpl.php file? I can style the page in the CSS but I don't think this is going to be enough.

Thanks

Admin pages are not nodes, so you would need to use the page template rather than the node template. You can copy your theme's page.tpl.php file and rename it to page--admin.tpl.php to create a template just for all admin pages.  If you need these changes to extend for node edit pages, then you would need to also create a page--node--edit.tpl.php file.

Another option is the ThemeKey module; it allows you to specify which theme to display based on path (i.e. you could change it for all admin/* paths) and/or based on user role (change theme for super users and low-level admins). You could choose a contributed admin theme to display on these conditions, or create a sub-theme of your front-end theme to display.


Rewriting a link field to link to 2 different places depending on what's given I have a content type which contains a website field of type "link." I am creating a view that should have the title which links to the content for each piece of content, unless a link is provided in the website field - then the title should link there.

This is what I am currently trying:

title field is hidden
website field results rewritten so that [title] is the text and it is outputted as a link to [field_website-url].
website field no results are set to go to: [title]

However, this method is not working. It works when there is actually a website URL specified in the website field, but for all others, clicking on the titles links to ".com/link].

Any help figuring this out would be greatly appreciated!

The problem lies in trying to use the 'link to original content' in 'no results'.

Try putting the fields in this order with these formats:

Title - just plain text
Link to content - raw URL
Website field - raw URL

Then set Rewrite Results to [title]

And set No Results Behaviour to [title]

Note you'll have to find the right token for the links in the Replacement Patterns section that shows up when you tick 'Rewrite the output of this field'

Don't use 'Output this field as a link' or the link will apply to the No Results Behaviour as well, I think.


How to inject an object into a service? I need to do a couple of things:

Inject guzzle's httpclient into class A
Inject class A into my service

What I've tried so far:

services:
  my_module.field_fetcher:
    class: Drupal\my_module\ClassB
    arguments: ['@my_module.obj', '@logger.factory', '@config.factory']

  my_module.obj:
    class: Drupal\my_module\ClassA
    arguments: ['@http.client']

parameters:
  my_module.http_client.config:
    base_uri: 'http://myurl.com/'

services:
  my_module.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%my_module.http_client.config%']

  my_module.obj:
    class: Drupal\my_module\ClassA
    arguments: ['@my_module.http_client']

  my_module.field_fetcher:
    class: Drupal\my_module\ClassB
    arguments: ['@my_module.obj', '@logger.factory', '@config.factory']

Simple versions of classes A and B look like this:
ClassA:
<?php

namespace Drupal\my_module;

use GuzzleHttp\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class A {

  /**
   * @var \GuzzleHttp\ClientInterface
   */
  private $httpClient;

  public function __construct(ClientInterface $httpClient) {
    $this->httpClient = $httpClient;
  }
}

ClassB:
<?php

namespace Drupal\my_module;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;
use Drupal\Core\Logger\LoggerChannelFactory;

class B implements BInterface {

  /**
   * @var \Drupal\my_module\A
   */
  private $a;

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  private $logger;

  public function __construct(A $a, LoggerChannelFactory $logger, ConfigFactoryInterface $config) {
    $this->a = $a;
    $this->logger = $logger;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      A::create($container),
      $container->get('my_module.obj'),
      $container->get('logger.factory')->get('my_module'),
      $container->get('config.factory')
    );
  }
}

No matter what I try, I keep running into the same issue of drupal error logs telling me that "argument 1 passed to Drupal\my_module\ClassB::__construct() must be an instance of Drupal\my_module\ClassA, string given"
Edit: Updated classes A and B to reflect changes suggested.

For this my_module.services.yml file:
services:
  my_module.obj:
    class: Drupal\my_module\ClassA
    arguments: ['@http.client']

You can discard the create() method from your A class, because you declared it as a service for which the arguments get resolved by the services YAML file parameters ie. '@http_client':
class A implements AInterface {

  /**
   * @var \GuzzleHttp\ClientInterface
   */
  private $httpClient;

  /**
   * @param \GuzzleHttp\ClientInterface $http_client
   *   A Guzzle client object.
   */
  public function __construct(ClientInterface $http_client) {
    $this->httpClient = $http_client;
  }

argument 1 passed to Drupal\my_module\ClassB::__construct() must be an instance of Drupal\my_module\ClassA, string given

Fix this by correcting your B class create() method to pass your service A name being 'my_module.obj', which would then in turn correctly pass an instance to the constructor of class B:
class B implements ContainerInjectionInterface {

  /**
   * @var \Drupal\my_module\AInterface
   */
  private $a;

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  private $logger;

  /**
   * @param \Drupal\my_module\AInterface
   *   Your module A class.
   */
  public function __construct(AInterface $a, LoggerChannelFactory $logger, ConfigFactoryInterface $config) {
    $this->a = $a;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_module.obj'),
      $container->get('logger.factory')->get('my_module'),
      $container->get('config.factory')
    );
  }


Drupal mail problem - Greylisting in action I'm not sure how to solve this one and even not sure if it's a drupal issue or misconfiguration.

I'm running a Drupal site (7.22) and have huge problems with the sending mails. Most of the mails can't be delivered and I (the admin) get immediately a Mail Delivery System message:

  This is the mail system at host OUR_MAIL_HOST.

  I'm sorry to have to inform you that your message could not be
  delivered to one or more recipients. It's attached below.

  For further assistance, please send mail to postmaster.

  If you do so, please include this problem report. You can delete your
  own text from the attached returned message.

              The mail system

  : host
  USER_MAIL_HOST said: 450 4.7.1
  : Client host rejected: Policy
  Rejection-    Greylisting in action; Please try again later. (in reply
  to RCPT TO    command) Reporting-MTA: dns; OUR_MAIL_HOST
  X-Postfix-Queue-ID: D8047189CE9 X-Postfix-Sender: rfc822;
  admin@mail Arrival-Date: Wed, 26 Feb 2014 08:22:24 +0100
  (CET)

  Final-Recipient: rfc822; user@mail
  Action: failed Status: 4.7.1 Remote-MTA: dns;
  USER_MAIL_HOST Diagnostic-Code: smtp; 450 4.7.1
  < OUR_MAIL_HOST[OUR_MAIL_HOST_IP]>: Client host    rejected: Policy
  Rejection- Greylisting in action; Please try again later.

  The original mail content...

So to get a mail through this greylisting-filter requires sending the mail again, but I don't know whether it should be done via Drupal or via the mail server? The admins of the mail server told me to send the mail again, but this means, I have to tell Drupal to send each mail twice if it gets greylisted. This sounds pretty odd to me and I'm sure there is a clean solution. So any ideas? I'm sure I'm not the only one with such a problem.

In your setup PHP mail() sends mail, but it's your mailserver who gets "false rejection" notification - possibly a different machine, and even if the same machine, it's totally separate system. PHP mail() never receives anything, so it can't resend. And your mailserver never sent it, so it can't resend, either.

Simplest way to fix it is to use SMTP module

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

PHPmailer module

  The main differences to the SMTP module are:

  Integration with Mime Mail module
  Improved bulk-mail performance through SMTP keep-alive connections (if supported by the mail server)
  Built-in e-mail rerouting option (useful during site building and development)

or similar solutions, there are a few more.

That way your Drupal will only need to send mail once, and your outgoing mail server will take care about graylists - most of them are configured in a way that works with graylist receiving servers out of the box.


How to create a new entity with default values if not passed? Hello everyone how are you?
I created a new configEntity called Modal with 3 fields:

Label
Body
Auto Open

To create a new Modal I'm using this code:
$modal = \Drupal::entityTypeManager()->getStorage('modal')->create();

$modal->setLabel('Modal Title');
$modal->setBody('Modal Content');
$modal->setAutoOpen(TRUE);
$modal->save();

OK! It works!
But now I don't want to pass "auto-open" and I this value with TRUE as default. Like this:
$modal = \Drupal::entityTypeManager()->getStorage('modal')->create();

$modal->setLabel('Modal Title');
$modal->setBody('Modal Content');
$modal->save();

Note that there is no "Auto-Open" and it inserts a new Modal with "auto-open" = FALSE
My goal is; if you don't pass "auto-open" this field is filled with TRUE by default.
Do you know how can we do this?
Thank you so much, everyone

For entities in general, set default values by adding preCreate() to your entity class:
  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'auto_open' => TRUE,
    ];
  }

In this specific case, define a class property with the same name as the field, which defaults to TRUE:
  /**
   * Auto Open.
   *
   * @var bool
   */
  protected $auto_open = TRUE;


simplenews-newsletter-body.tpl.php won't be overridden My newsletter is almost ready, where it not that the node title ends up in the sent testmail as well. So I figured if I would just override the simplenews-newsletter-body.tpl.php
I followed the guidelines from this page.

In my simplenews configuration I just checked just the generic content type that simplenews generated. In that same configuration page, I chose 'newsletter' as the taxonomy term attached to it. This makes the filename simplenews-newsletter-body--newsletter.tpl.php

The idea to just delete the following line from the copied file:

<?php print $title ?>

The tutorial I mentioned says to paste in into the custom theme folder directly. I was assuming not in the templates folder. I tried both though while flushing cashes at least twice after each try. Still getting the darn title in my test mail.

UPDATE: I discovered that the filename needs to be the term ID of the simplenews newsletter, being a number. I looked up the tid and changed the tpl filename accordingly - in my case making it simplenews-newsletter-body--110.tpl.php. Of course the needed flushing of cashes. Didn't help either.

The file may need to go in the admin theme folder, if you're using admin theme/sections, and not in the regular theme folder. Worth a shot.


Statistic count not working with API call There isn't much info around it, but when I'm using Statistic module to get the views per node it's only working when I'm visiting the page of the specific node. When I'm using an API call to a specific node, the statistic module doesn't increase with 1...

Is there a way to solve this?

Node views are only counted when node_view() is invoked (i.e. when the node is actually viewed).

When retrieving a node via services you're not, conceptually, "viewing" it, so you shouldn't expect the view count to increase.

In order to get your desired workflow, you'll probably need to implement a custom services resource which updates the statistics manually when a node object is requested. See How to create a custom resource with Services-3.x for more info.


How to execute the code at certain time without relying on Cron I have a custom entity with a timestamp field which can be populated by the user.

At these specific "times" I have to "react" and update(execute some code) on some other entities related to this time.

First thing coming to mind is to implement it as a Cron job but, I'm not satisfied with this solution as I need to execute the code at a very specific time(any minute) while I don't want to set up the Cron(even a specific Cron job) to run every minute as it's sound quite overwhelming.

Are very any other ways to smartly manage a code execution based on specific(not hardcoded interval) time?

Running cron every minute is perfectly acceptable. But if you really want a different solution you could (for example) create a Drush command to do what you want and then call that every minute with something like Jenkins or RunDeck. If you really need this command to run at the exact times users specify and only at those times, then you could write code to publish out the time (and other contextually relevant info) to some external system which is constantly running with some Daemon.

This solution will work but it is:

a) hard because there is a lot of custom work to do
b) tricky because you have to worry about publishing, but you also have to worry about updates and deletes in case your users ever make changes to the time or the contextually relevant data
c) unnecessary since frequent cron runs sounds like it can solve your problem.


Is it necessary to cache data generated by menu_tree_all_data and menu_tree_output called in preprocess_page In hook_preprocess_page in my template.php I'm using this code:

// Get the entire main menu tree
$main_menu_tree = menu_tree_all_data('main-menu');
// Add the rendered output to the $mobile_menu variable
$mobile_menu = menu_tree_output($main_menu_tree);

To generate the entire menu tree of main menu

Thinking that preprocess_page is executed on every page (please confirm this if it's true) I cached the above code in this way:

$cid = 'ctm_mobile_menu:' . $vars['language']->language;
$mobile_menu = &drupal_static(__FUNCTION__);
if (!isset($mobile_menu)) {
  if ($cache = cache_get($cid)) {
    $mobile_menu = $cache->data;
  }
  else {
    // Get the entire main menu tree
    $main_menu_tree = menu_tree_all_data('main-menu');
    // Add the rendered output to the $mobile_menu variable
    $mobile_menu = menu_tree_output($main_menu_tree);
    cache_set($cid, $mobile_menu, 'cache');
  }
}

But my doubt now is: is caching effectively necessary here? or menu_tree_all_data and menu_tree_output already does caching by itself?

My concern is that I'm caching already cached data and this can generate bad loops.. I don't know please help me

No need to cache menu_tree_all_data() as it is already cached; which leaves menu_tree_output(). This function looks fairly light; but it really depends on how many items are in $main_menu_tree. Note that it's not 100% safe to cache menu_tree_output() the way you're currently using it as it uses menu_get_item(). If you were to use the tab_root_href key as part of the cid then that would probably work. If this code only gets called once (my guess as it's in hook_preprocess_page()) then the static cache will not help. The important questions are how fast is your cache backend, how many items are in $main_menu_tree, and how often does this code get called. Knowing that will tell you what's better.

Questions like this can be answered with some help from microtime(). Example below:

// Get current menu item.
$router_item = menu_get_item();
$menu_name = 'main-menu';
// Get the cache ID.
$cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'] . ':' . $menu_name;

// Try core static cache.
$menu_output = &drupal_static('menu_tree', array());
if (!empty($menu_output) && !empty($menu_output[$menu_name])) {
  $mobile_menu = $menu_output[$menu_name];
}
else {
  // Try cache backend
  if ($cache = cache_get($cid) && !empty($cache->data)) {
    $mobile_menu = $cache->data;
  }
  else {
    // Get the rendered output for the $menu_name variable.
    $mobile_menu = menu_tree($menu_name);
    // Save to the cache bin.
    cache_set($cid, $mobile_menu, 'cache');
  }
}

$time_start = microtime(true);
    // Get the entire main menu tree.
    $main_menu_tree = menu_tree_all_data('main-menu');
    // Add the rendered output to the $mobile_menu variable
    $mobile_menu = menu_tree_output($main_menu_tree);
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did non-cached in $time seconds\n";

$time_start = microtime(true);
    // Get current menu item.
    $router_item = menu_get_item();
    // Get the cache ID.
    $cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'];

    // Try cache backend
    if ($cache = cache_get($cid)) {
      $mobile_menu = $cache->data;
    }
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did cached in $time seconds\n";


Views to show all child terms without showing parent Vocabulary has 5 parents, each containing 10 child.

Through views I want to display all child terms in a block, but to hide/skip showing parent terms in result.

Creating view that displays both parents and child was easy, but this I cant figure out.

You can add a relationship with your parent term. After that you can set a filter with your parent term and filter all terms, which have a parent term id (parent taxonomy term: term id(not null)).


Add custom link when using field_get_field I have an image field on a taxonomy term. I am retrieving it via field_view_field and render it afterwards to display it. But I would like to give it a custom link. How to do this?
Do I need to make a new image formatter, with a link as configuration property? Or is there another solution to add the link before the render?

Thanks!

Problem with that module is that you have to define a token or fixed link. I am writing code that create a link on the fly, that can change in time.

For example: displaying the image of a taxonomy term, with a link to the last added node having this term.

The easiest solution:
$image = render(field_view_field(……));
$output = l($image, $link, array('html' => TRUE));I

When I tried this earlier it wasn't working, because by default the HTML option is set to false, displaying HTML code instead of rendered HTML code.


How to query for parent theme(s)? Drupal lets you sub-theme a theme, basically like inheritance.  How can I print out a list of all themes that a drupal site is 'using'.  For example: actual theme -> parent theme 1 -> base theme

This is how Display Suite does it:

// Get layouts defined in the default theme and base theme (if applicable).
$theme = variable_get('theme_default');
$themes = list_themes();

$base_theme = array();
$ancestor = $theme;
while ($ancestor && isset($themes[$ancestor]->base_theme)) {
  $ancestor = $themes[$ancestor]->base_theme;
  $base_theme[] = $themes[$ancestor];
}


how to include one drush make.yml file in another? With the INI-style drush .make files I could say includes[common] = "common.make" in say, drupal_master.make but I can't see a way of breaking my make.yml files into smaller reusable chunks.
I've tried

imports:
  - common.make.yml

(like Symfony uses elsewhere) as well as other guesses and I can't see any examples or documentation on "including" YAML drush make sub-files.

Can it be done?

Edit: I do see that you were using the wrong keyword, it should be includes and not imports.

It looks like you have the correct syntax above I believe. We use something like the code below in our make process, there are three different core makes that we call that one in, local, development, and build (we wanted to get updated versions in local and more stable ones in dev and build, just so we can update when appropriate.). It works pretty well but see the code below for an example. Thanks!

api: 2
core: X.x

defaults:
  projects:
    subdir: "contrib"

includes:
  - drupal.make.yml
  - libraries.make.yml
  - modules.make.yml
  - themes.make.yml
  - custom.make.yml

Here is the link for the Drush documentation for the make files, I didn't notice that they had swapped over to YML in the make docs or I would have started with this probably: Drush Docs - Make.


After "?" redirect, the url is cut, why? I am using the Anonymous Redirect module to redirect example.com to example.com/login.

But when I refer a link like
example.com/525?some=node/227 and log in, the url will be cut to example.com/525

I don't know why the url is cut after "?" or "&".

Any solutions for this one?

Even though I haven't ever used the Anonymous Redirect module, I wouldn't be surprised if your "issue" is caused by the fact that this module does not support what you're trying to do.

However, as a possible alternative (as per your "Any solutions for this one?"), you may want to use the Rules module to perform the redirect you want to do. For an example of how to do so, refer to my answer to "How to redirect an anonymous user to the login form after a 403 error?" (the "option 2" part of it. Not sure what exact "Rules event" would fit in your case, but it'll be probably something related to a specific "path" in your site.

Not sure if it would fit your needs here also, but maybe you want to add the "Rules URL argument" module also to this. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.


Record admin changes in log? Is there a way of recording changes made to a Drupal site in a log?

Im working as part of a team and some members are off site. We're running into issues where changes are made to the path pattern of nodes by other members, and it would be really useful to be able to check what changes have been made recently. Even better would be to know which admin user made the changes. Thanks

In Drupal 8 configuration is also stored in files, so you can commit it to git and have a full log. As far as I know there is no mechanism to record all actions of users in any version of Drupal.

If you insist, you can implement hook_form_submit() for every form and add additional save function to record who, when and what, but it will be hard to use log created this way.

Other approach is to use Features - let them develop their parts on their copies and just send you packages with working pieces.


Form and Table on same page I got a Form and a Table displayed on the same page. The weird thing is that when the form is submitted and the page are reloaded (after doing a database SELECT) with $_POST values, the table is not showing....why?

Here is the code (suppose $tabb2 have correct table data):

<?php

function collabinc_menu($may_cache) {
  $items = array();
  $items['admin/reporting/report_details2'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details2',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function say_report_details2($values = array()) {
  $output = "";

  if (isset ($_POST['search'])) {
     $output = theme("table", $tabb2);
  }

  $build['content'] = array(
    'this_does_not_matter_too_much2' => drupal_get_form("report_details_form"),
    'this_does_not_matter_too_much1' => array('#markup' => $output,),);

  return $build;
}

Please note that both Form and Table are working, and displayed correctly at the same time when not putting the "if (isset ($_POST['search']))" condition. Also note that the condition is fully working and checked.

Thanks!

You can use the Table theme. Example :-

$form['data_field'] = array(
'#type' => 'textfield',
'#title' => t('Search!'),
'#id'   => 'search',
'#maxlength' => 1024,
'#description' => t('Search by using tags and free text'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

$form['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('Empty Rows')
);
}
return $form.


Render a field contained inside of another field I am using Drupal Paragraphs module that lets you create "bundles" of fields inside other fields. (It does this using entities). Each bundle has it's own tpl.php file.

In addition, you can nest "sub-bundles" inside the "main-bundles" for complex layouts.

I have created a "main-bundle" called field_panels_content.

Inside this is another "subbundle" which holds a field_body_text. The "main-bundle" can hold an unlimited number of "sub-bundles".

In my theme, I need to access the all field_body_text fields from the multiple  "subbundle" from the tpl.php file that is for the "main-bundle".

I have used devel_themer and found I can get to the field_body_text fields like this:

<?php print render($content['field_panels_content'][0]['entity']['paragraphs_item'][9]['field_body_text']); ?>
<?php print render($content['field_panels_content'][2]['entity']['paragraphs_item'][10]['field_body_text']); ?>
<?php print render($content['field_panels_content'][2]['entity']['paragraphs_item'][12]['field_body_text']); ?>

As you can see this does not make for efficient theming as I would need to know the second array value in order to print it out (e.g. [9][10][12]).

Is there away I can use a loop or some other PHP function to get to the second array value automatically without knowing it?

This second array value changes with each new piece of content (e.g. If I add a new subbundle it will have a value of [13]. The reason the numbers jump from [10] to [12] is because I deleted the subbundle that was [11].

Update

Here are some more steps I have tried (from this page):

Here is an example loop:

<?php
foreach ( $content['field_panels_content'] as $wrapper) {
  foreach ( $wrapper['entity']['paragraphs_item'] as $item ) {
    if ( !empty($item['field_body_text']) ) {
      print render($item['field_body_text']);
    }
  }
}
?>

It produces the following results:
    Cannot use object of type ParagraphsItemEntity as array in foreach ( $wrapper['entity']['paragraphs_item'] as $item ) {

Here is a reworked version:

<?php
foreach ( $content['field_panels_content'] as $wrapper) {
  foreach ( $wrapper['entity'].paragraphs_item as $item ) {
    if ( !empty($item.field_body_text) ) {
      print render($item.field_body_text);
    }
  }
}
?>

Error message: Fatal error: Cannot use object of type ParagraphsItemEntity as array in line "foreach ( $wrapper['entity'].paragraphs_item as $item ) {"

Editing the code so only field_body_text is in square brackets (e.g. $item['field_body_text']), produces this error message:
Fatal error: Cannot use object of type ParagraphsItemEntity as array

Editing the code so only paragraphs_item is in square brackets (e.g. $wrapper['entity']['paragraphs_item']), produces this error message:
Fatal error: Only variables can be passed by reference in line  print render($item.field_body_text);

If I use print instead of render, I get this error message:
Fatal error: Cannot use object of type ParagraphsItemEntity as array

Other Notes

The following code works perfectly:

<?php print render($content['field_panels_content'][0]['entity']['paragraphs_item'][9]['field_body_text']); ?>
<?php print render($content['field_panels_content'][1]['entity']['paragraphs_item'][10]['field_body_text']); ?>

So surely it should be a simple case to refactor the code into a loop to get the desired result.

Please note

I don't want to use other modules.

I will be printing out all the field_body_text separately at the top of the tpl file.
I'll then display the whole paragraph (with the field_body_text still in it) in the normal way.

I think the issue here is that each of those paragraph groupings contain various elements that are array keys. For example, if you dpm up to $content['field_paragraph'], you may see values that look like this:

I think the issue is, due to your loops, your trying to render/loop through things that aren't objects. To get around this, you might want to try checkin if the key is numeric before proceeding on.

Something along the lines like this:

<?php
    foreach($content['field_paragraph'] as $key=>$array){
  if (is_int($key)) {
    foreach ( $array['entity']['paragraphs_item'] as $key2=>$item ) {
    if ( is_int($key2) ) {
      print render($item['field_body']);
    }
  }
  }
}

?>

Note the is_int($key), that's what you need to get the errors to go away. Note my code has my own field names in it, so you'll just need to switch yours in.


Leaflet - Possible to go straight to node instead of popup on click? I'm using the leaflet module in drupal and would like the user to go directly to the node instead of a popup when clicking upon a marker or polygon. Is there a way to do this?

The easier way is to use the IP Geolocation Views & Maps module, which works a treat! Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).


How to sort/delete comments by a particular user? I have a relentless human spammer that is extraordinarily difficult to keep away. Spam filters are unhelpful as he does not use a set of frequently used words. Rather, his insults are more "subtle" to be captured by any regext.  Each time I block him, he comes back with a new username but soon the new user reveals his spammy nature. So I need to go through the list of comment to finds the one by him and delete them one by one. On the other hand, I don't want to disable comments auto-approval just because of one bad apple.

It is painful especially when you need to do it a couple of times a day! so I wish there was an easier way to sort and then delete comments of a particular user, and not involved direct querying the database?

Using Views Bulk Operations, you can create a view for all the comments written by a user, which allows you to delete all the comments written by a user without the limitation of deleting them in groups of 50 at time. When you click on the button to select the comments shown in the pager's page, you are asked if you want to select all the comments; in that way you can delete all the comments with a single click. As the view can be set to use batch operations, it is able to delete a great number of comments without any timeout.

You can create a view that is shown in the user profile page (as done on Drupal.org), or you can create a view that replaces the page shown in admin/content/comment. Being a view, you can filter the comments listed using different criteria, such as the content type of the node for which the comments have been created, the author of the comment, the author of the node to which the comment is attached, etc.

Views Bulk Operation doesn't come with a custom view to show the comments made from a user; it comes with a view that can be used to replace the page shown at admin/content/node. Using that view as example, you can easily build the view you need for the comments.


Location subfields problem to render in teaser template node I have tried render only two array´s parameters. Street and postal code but don´t display anything this code.

<?php print render($content['field_mapa']['und'][0]['street']); ?>and <?php print render($content['field_mapa']['und'][0]['city']); ?>

However with this code print all parameters.

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

I don´t understand where is the problem with this field.

The location field module wrap fields inside #location so try with :

<?php print render($content['field_mapa'][0]['#location']['street']); ?>

and

<?php print render($content['field_mapa'][0]['#location']['city']); ?>


How to insert content type fields directly into Views I am wanting to place a view into my sidebar like yahoo answers Yahoo Answers TOP Right Sidebar. The block would display the actual fields (to be filled out) from the content type, once submitted it would create the content.

Is there a specific module for this or can it be done directly with views somehow?

Thanks!

You should use webform module for it. You can display the form to users which the users can fill and submit. You can review the form submissions by going to content/webforms link.
You can display the webform as a block. You cannot display a content type to be filled in by the user, as only admins can create contents by default.
You can download webform from this Link


How to insert the title of the page as a class in page title block? I am new to Drupal 8 theming and I've been long time trying the following:

I want to add classes to page-title in the template, page-title.html.twig. Two new classes:

1.- 'page_title'

2.- The real title of the page

The code I'm using is,:

{{ title_prefix }}

{%
set classes = [
'page-title',
title|clean_class
]
%}

{% if title %}

{{ title }}

{% endif %}

{{ title_suffix }}

it renders:

FORMACIÓN: CURSOS Y  TALLERES

The string 'page-title' is working well but the variable title provoke an error:

  Notice: Array to string conversion in
  Drupal\Component\Utility\Html::getClass() (line 72 of
  core\lib\Drupal\Component\Utility\Html.php).

And print the class, array.

Any help?

Seems title is a render array. You probably have to use title.value instead. But I'd recommend to simply preprocess that and leave the templates untouched.

You can implement hook_preprocess_hook and then use TitleResolver::getTitle and Html::cleanCssIdentifier to do what you want from inside your theme's *.theme file or from within a custom module's *.module file:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  // This won't work properly with Twig debugging enabled.
  // $title = $variables['title'];

  // Here is a safer method to get the current title.
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['title_attributes']['class'][] = 'page-title';
  $variables['title_attributes']['class'][] = strtolower($css_title);
}

You can use nearly the exact same snippet to add that CSS class to the <body> tag:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_html(&$variables) {

  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['attributes']['class'][] = strtolower($css_title);
}


Distribute configuration to several sites There should be several sites, starting with something like a similar distribution, but over time, each site might get some individual modules. Yet, I'd like to keep the site updated with new versions and new configurations over time as well.

So I can't use the full import/export of configuration management, since this would delete my individual additions on some sites, if I understood it correctly. And I need to be very careful with single exports, since those don't care about dependencies.
Configuration Packager has been merged into Features, so it seems as I need to use features anyway.

So what do I put into a configuration? And what into a feature?
And how would I distribute the preconfigured stuff to all sites? Use a feature server like in Drupal 7? (If the Github process is setup and I've got a dev and several production sites, how do I push configuration and feature updates to production?)

So .. found more details on it.

With
drush config-list | grep news  I can get all configurations that are named with news. Those can be exported into a Module / YAML file and moved to another installation, or rather copied and enabled.

More information on that: http://nuvole.org/blog/2014/jul/15/packaging-and-reusing-configuration-drupal-8

So that would make Features in D8 quite unnecessary - depending on the use case, very good.

It might be reasonable to use config-merge but I'm not sure about:
If I'd do a Full Export, I'd only be able to use this on Cloned sites (like Staging/Live). But in my case I'd do an initial clone or a profile and would only like to pass on functionality (like features) and that might not work with config-merge?


How to set a default image on a Drupal 7 Media field I have a non-required field_thumbnail that is of type "Multimedia asset", and the widget type is "Media file selector".  However on the field's settings page there is no option to specify a default value.  I've also perused the Administrative section seeking configuration in the Image styles, and File styles, but neither permit a default image to be used.

What would be the recommended way to get a default image, when a user does not select any media object for the given node?

Whenever I need to do this I just use a plain old Image field and use the Media File Selector as the widget. That way you can specify a default image for the field and still use the nice popup media browser.

So far I haven't found any benefits to using a Multimedia Asset field type over an Image field type in this situation, but that's not to say there aren't any or won't be any in the future.

EDIT

At the code level the following might help you get started:

// Implement hook_field_info_alter to add a setting for the multimedia field type
function MYMODULE_field_info_alter(&$info) {
  $info['media']['settings'] = array(
    'default_asset' => NULL
  );
}

// Implement hook_field_settings_form on behalf of the media module
function media_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];
  $form['default_asset'] = array(
    '#type' => 'media',
    '#title' => 'Default Multimedia Asset',
    '#description' => 'The default asset to use when none is selected',
    '#default_value' => $settings['default_asset']
  );

  return $form;
}

That will add a default multimedia asset picker to the field settings. Then you just need to work out how to inject that default value into the field display when it's otherwise empty. I would guess at the use of something like hook_field_prepare_view() for this.

Note that there's no way to restrict the type of the default multimedia asset as those types are set at a per instance level, not at the field level. If you want to do it at the instance level much of the same code above will help but you'll have to extend it further to restrict the type of media based on the checkboxes on the instance form.


What's the difference between access arguments and access callback? What's the difference between access arguments and access callback?

Suppose I set the access callback to 'user_access', and array('custom permission') is the value for the access arguments.

What does that mean? How do they affect each other?

"Access callback" is the function that is called to verify the user has access to the page. As special case, it could be the value TRUE, and in that case all users would have access to it; in other words, the access permission would be bypassed.

In the case you are using a function name for the "access callback" value (by default, it's "user_access"), then you can also use "access arguments", which is an array containing the arguments passed to the access callback function.
As with other menu callbacks, the arguments must be a string, or a number; in the case it's a number, the value will be replaced with a value taken from the menu path. If you want to avoid this replacement, instead of a number you need to use a string; for example, using "1" as one for the arguments passed to the access callback would avoid the automatic replacement.

These are some example of menu callback declarations used from Drupal core modules. (The examples are from Drupal 7 code, but for what I want to point out, that doesn't make any difference.)

This is an example where the access callback is user_access().

  $items['file/progress'] = array(
    'page callback' => 'file_ajax_progress',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

This is an example where the access callback is not a function name.

  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
  );

In this case, the access callback is user_view_access() to which is passed, not the number 1, but a value taken from the menu path (which in this case is "user/%user"); this is a particular case, as the function will get the value returned by user_load().

  $items['user/%user'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

Suppose the previous menu were defined as follows, and invoked with a path like "user/hello."

  $items['user/%'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view_page',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    // By assigning a different menu name, this item (and all registered child
    // paths) are no longer considered as children of 'user'. When accessing the
    // user account pages, the preferred menu link that is used to build the
    // active trail (breadcrumb) will be found in this menu (unless there is
    // more specific link), so the link to 'user' will not be in the breadcrumb.
    'menu_name' => 'navigation',
  );

In this case, the access callback would have received as argument the value taken from the path (0 means "user," and 1 means the part after "user" and the slash); in this case, that value is "hello."

To better understand these wildcard arguments, see Wildcard Loader Arguments. The documentation page is tagged Drupal 6, but what reported is still valid for Drupal 7.


Displaying and selecting data from a database in a module I have a database table (gpx_api) with the following fields:

runID   userID  score   distance    pace    speed   gpx_path    missionID   startTime   duration

I want to display all of these fields from within a module.

I have searched a lot on stack and I got until here:

   $query = db_select('gpx_api', 'run')
     ->fields('run')
     ->condition('runID', $firstparameter, '=')
     ->execute()
     ->fetchAssoc();

Do I only select the row where runID = $firstparameter like this?

This should only return one result. Now how can I display the fields one by one?

$query->distance

will not work.

I also tried

foreach($query as $result2){
 $result .="DISTANCE";
$result .= $result2->distance;
  }

This strangely enough gave a lot of results and errors.

I am sure there is a very simple way, but I am not familiar with the drupal API.

--Update

a var_dump of query gives me:

array(10) { ["runID"]=> string(1) "2" ["userID"]=> string(1) "1" ["score"]=> string(2) "10" ["distance"]=> string(3) "200" ["pace"]=> string(1) "7" ["speed"]=> string(1) "8" ["gpx_path"]=> string(0) "" ["missionID"]=> NULL ["startTime"]=> NULL ["duration"]=> NULL }

so it is just about displaying the array. Shouldn't $query->distance  work then? Yet if I try it, I get this error:

Notice: Trying to get property of non-object in epicrun_mymenu_page_callback() (line 62 of /home/suneesto/public_html/addons/epicrunapp.com/sites/all/modules/epicrun/epicrun.module).

Basic php error, it's $query['distance']


Show content of custom content type in a block based on taxonomy term In D8 I have created two custom content types:

Store
Store products

It's not an e-commerce, I just need two custom types to show all the stores on one of the subpages and the products that each store has.

Because there are 24 stores, I would hate to create 24 custom types of a store products, so I also added a taxonomy term field to a Store product.

Now, I would want to show the Store products in a Block, depending on the taxonomy term.

For example:
I created Store A, which has products A1, A2, A3. If I go to the page of Store A, there should be a block that shows those products.

If I would go to Store B, the same block would show products of Store B.

I tried following this answer and added a contextual filter, but no luck so far:
Display content based on URL

What I did:

Created a View Block for Store Products
Added a contextual filter to the block (Has taxonomry term -> taxonomy term ID from URL)
Also added another contextual filter node:id
Added the block under blocks to render on the page Store

What you're trying to do already come out of the box in "Taxonomy term" content views.

If you have tagged your Store product nodes with taxonomy terms these nodes will appear on the related term pages. You don't need a separate Block, the term pages will show a list of nodes tagged with that term.

You don't even need the Store content type if its whole purpose is to provide categorization. The "Store" Taxonomy Vocabulary is all you need.

Can you try and see if that is enough for you?

In your Contextual configuration you should use the option "Load default filter from term page", and not "Load default filter from node page" because the information is taken from the taxonomy term page, you're not showing a block on a node page.

Why do you need the second Contextual for NID? This is usually used when you want to exclude the current node from the list (Under More > Exclude), but you're not on a node page so there is nothing to comare the NID to. Remove that second Contextual, you don't need it.


Is it possible to use tokens in a menu link in Drupal8? I need to add an option to "User account Menu" that shows the current user name. It is possible to do this using tokens or some other method?

Thanks!

No, you cannot use tokens in menus out of the box.

Here are some options:

Use Views to create the link.  This won't give you a menu, but you can make a block in Views and use that as a menu.  You may have to hard-code the rest of your "menu" in the views block, which isn't ideal but if you can't code that may be your best option for now.
Code the menu link.  See the routes documentation.
Watch the progress of the Menu Token module.  This module does what you want but it doesn't have a stable release for Drupal 8 yet.  I haven't used the D8 version so I don't know how well it works at the moment.


Delete any path alias by language We are running Drupal 8.8.5. I can see duplicate aliases when I look at /admin/config/search/path.

Unfortunately, there are many duplicate aliases on our website with 6000 URLs. The /node/1 node has three translations: en, es, and zh-hans.  /node/1 also has a second entry for es containing a duplicate path alias which I would like to delete.

I need to find a way to programmatically delete path aliases. If I have Create, Read, Update and Delete (CRUD) operations on the path/alias/langcode, I can create a solution to eliminate the duplicates.

The following code obtains the alias data associated with the node whose ID is equal to 1 and dumps the Path, Alias and LangCode.

$alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1');
var_dump($alias->getPath());
var_dump($alias->getAlias());
var_dump($alias->language()->getId());

The base language of the website is English, and the last var_dump() yields en.  So far so good.

How can I gain access to the alias data for these two languages?  I know the following works.

$alias_es = \Drupal::service('path_alias.manager')->getAliasByPath('/node/1','es');

I need to delete the duplicate Spanish path alias to accomplish my goal, so I need to figure out how to use entities which have a delete() method.  You might think the following code should work.

$alias_es = $alias->getTranslation('es');

It returns:

  InvalidArgumentException: Invalid translation language (es) specified.

I also tried $alias->getTranslationLanguages(), which returns an array with only one element (['en'] => object(Drupal\Core\Language\Language)).

It appears that our original $alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1'); only has one language translation which is English.

How can I gain access to the path aliases for es and zh-hans?

How can I gain access to the path aliases for es and zh-hans?

To get all path alias by language for instance es:

$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path' => '/node/' . $nid,
  'langcode' => 'en'
]);

  I need to delete the duplicate Spanish path alias

$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path'     => '/node/' . $nid,
  'langcode' => 'es',
]);

// Get the actual associated spanish path alias to your node.
$spanish_associated_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid, 'es');
foreach ($alias_objects as $alias_object) {
  // If its not the actual alias delete it.
  if ($alias_object->get('alias')->value !== $spanish_associated_alias ){
    $alias_object->delete();
  }
}


Print module on a Views page? Is it possible to have a print/pdf link (using the print module) displayed on a views page?

I've got it displaying in a basic page type, but view is not a content type, so how do I select the option?

For Drupal 7 go to admin/config/user-interface/print, and add that page's (page created by view) path to the the list of system (non-content) pages in the Advanced Link Options tab.

This will show the link on that page. For Drupal 6 the path is admin/settings/print.


Have Database Update ignore prefix for multisite with shared database I currently have a multisite with a single database. Each instance has a different prefix for their tables, except for one with no prefix which is considered to be the main instance. Now there is a custom table I made that contains custom data. That table is meant to be shared across all instances. In a function I'm updating a field like so

$database = \Drupal::database();
$database->update('custom_table')->condition('id', $my_id, '=')->fields(['full_name' => $fullname, 'address' => $address])->execute();

This works on my main site. Unfortunately in the other multisite instances that's using the same function, this is causing an error. In the error I have

  Base table or view not found: 1146 Table
  'database.myprefix_custom_table' doesn't exist

I realize that it's trying to prepend the prefix for the table. But it's a table that every site is meant to share. I don't want a prefix to be used.

I noticed that the update method can use options as a parameter https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Connection.php/function/Connection%3A%3Aupdate/8.2.x

But I'm not sure if I can tell it not to use a prefix in the options I can supply.

I understand that I can just use the query method instead of using the update method (I think) but I would like to know:
Is it possible to force the update method for the connection object to not use the database prefix?

UPDATE: This was suggested as a duplicate:
How to identify multi-site programmatically?
But that isn't related to my problem.

In that example it's identifying what site it's on, but it's not performing anything with a database. I know how I can check what site it's on. That's not a problem. I need to call an actual database method and get rid of the prefix it's automatically applying.

In my code

$database->update('custom_table')->condition('id', $my_id, '=')->fields(['full_name' => $fullname, 'address' => $address])->execute();

I'm not even supplying the prefix. It's automatically applying it without my knowledge if it's being run on another site.

Looking at the comments in settings.php, you may well be able to do something like this:

$databases['default']['default'] = [
  'database' => 'db_name',
  'username' => 'root',
  'password' => 'root',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => [
    'default' => 'shared_',
    'custom_table' => '',
  ],
];

I haven't tried it, but in theory that should set the prefix for all tables to shared_, except for the custom one, which would have no prefix.


Could a controller return binary data? This is my javascript request:

var XHR = new XMLHttpRequest();
XHR.responseType = 'blob';
XHR.addEventListener('readystatechange', function() {
    if (XHR.readyState == 4) {
        if (XHR.status == 200) {
            var blob = new Blob([XHR.response], {type: "application/mp3"});
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = 'Myfile.mp3';
            a.click();
            window.URL.revokeObjectURL(url);
        } else {
            document.getElementById(regidrs).innerHTML = "Error: " + XHR.responseText;
        }
    }
});

var FD  = new FormData();
FD.append('uuid', uuid);
XHR.open('POST', '/fetch');
XHR.send(FD);

This is my module routing:

my_module/my_module.routing.yml

my_module.content:
  path: '/fetch'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

And my controller:

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\drupal_set_message;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Defines HelloController class.
 */
class MyController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function content() {
     ...
        $response= file_get_contents(....);
        $file = file_save_data($response, "public://myaudiofile.mp3", FILE_EXISTS_REPLACE);
     ...
     return [
      '#type' => 'markup',
      '#markup' => $response,
    ];
  }

}

But file_get_contents returns a mp3 file, and I need to pass this mp3 to the javascript httpresponse in order to donwload it.
Saving $response to a file, I have checked the file is ok.

How can I do it?

With the BinaryFileResponse class, you can return the content of a file in the response. The FileDownloadController class is an example of controller returning the content of a file. It's the controller for /system/files/{scheme}, /system/files/{filepath}, and /system/temporary.
See its FileDownloadController::download() method.

public function download(Request $request, $scheme = 'private') {
  $target = $request->query
    ->get('file');

  // Merge remaining path arguments into relative file path.
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {

    // Let other modules provide headers and controls access to the file.
    $headers = $this
      ->moduleHandler()
      ->invokeAll('file_download', [
      $uri,
    ]);
    foreach ($headers as $result) {
      if ($result == -1) {
        throw new AccessDeniedHttpException();
      }
    }
    if (count($headers)) {

      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
      // sets response as not cacheable if the Cache-Control header is not
      // already modified. We pass in FALSE for non-private schemes for the
      // $public parameter to make sure we don't change the headers.
      return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
    }
    throw new AccessDeniedHttpException();
  }
  throw new NotFoundHttpException();
}

The ExportForm class is another example of how to return a file, even if it's a form class. What changes is how the response is used, but how the BinaryFileResponse class is used is still relevant for a controller.
The relevant code is the following one, in ExportForm::submitForm().

$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);