How do I reproduce this SQL with Drupal 7's query builder? SELECT * FROM mytable
WHERE ('myfield1' = 'someval1' AND 'myfield2' = 'someval1')
   OR ('myfield1' = 'someval2' AND 'myfield2' = 'someval2')
   OR ('myfield1' = 'someval3' AND 'myfield2' = 'someval3')

I'm trying to do this with a foreach() loop:

foreach($mywords as $w)
{
  $myquery
    ->condition('myfield1', $w)
    ->condition('myfield2', $w);
}

Each iteration of the loop, however, should add the next set of conditions.

You need to do something like this:

$query = db_select('mytable', t)->fields('t');
$condition = db_or();
foreach($mywords as $w {
  $condition->condition(db_and()->condition('myfield1', $w)->condition('myfield2', $w));
}
$result = $query->condition($condition)->execute();

This is not tested but should work.

For reference, see db_or and db_and


Updating node field value using custom module validation I currently have a custom module which calls a submit custom validation function. I am trying to update a value after the validation is run. Basically, if a value is present, update a field to say "Yes".

function sitefuncs_form_alter(&$form, &$form_state, $form_id){

if( $form_id == 'stage_2_node_form') {
   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';
}

} // end hook_form_alter()

function sitefuncs_custom_submit($form, &$form_state) {

        $banned = array(
        'better cures',
        'better nhs',
        'because it',
        'so what'
        );

  if (in_array($form_state['values']['field_stage_two_question_one']['und'][0]['value'], $banned)) { // if a banned word is the value of the input

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "No"; // set the value of the text input to No

} else {

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "Yes";

$messages = drupal_get_messages('status');
drupal_set_message(t('Your changes have been saved.'));

}

}

If anyone has any idea why the $form_state isn't updating the fields after I save the node, any help would be great!

I worked out that I was using

   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';

When it should have been

   $form['actions']['submit']['#validate'][] = 'sitefuncs_custom_submit';

Then all my data saved using

$form_state['values']['field_stage_complete_text']['und'][0]['value']['#value'] = 'No'; // set value to No


Connecting to a remote database in D8 I have the following params in settings.php to connect to an external database .

$databases['d8243']['default'] = array (
  'database' => 'drupal8',
  'username' => 'root',
  'password' => '123123',
  'prefix' => '',
  'host' => '192.168.1.243',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

And am using the following code to access some data from the db .

\Drupal\Core\Database\Database::setActiveConnection('d8243');
$query = "Select * from node__field_target_config_controller";
$result = db_query($query);
$obj = $result->fetchObject();
echo json_encode($obj);
exit;

My current server and the external db server are in a same network .

But am geting the following error :

  exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access
  denied for user 'root'@'192.168.1.245'      [error] (using password:
  YES)' in
  /var/www-drupal/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:149

Is there a different method to connect to remote db in D8 ? or how to do it ?

When i checked d6/d7 versions have an option to specify remote db like

$db_url = 'mysql://username:password@quranschools.org/databasename';

how to do this in D8 ?

You can use like:

$other_database = array(
  'database' => 'drupal8',
  'username' => 'root', // assuming this is necessary
  'password' => '123123', // assuming this is necessary
  'host' => '192.168.1.243', // assumes localhost
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql', // replace with your database driver
);
// replace 'YourDatabaseKey' with something that's unique to your module
Database::addConnectionInfo('d8243', 'default', $other_database);
db_set_active('d8243');
// execute queries here
db_set_active()

You can access your other database like above. For reference check this link.


Can I install Drupal Commerce as a site in a multi-site architecture, preferably using Commerce Kickstart? Commerce Kickstart comes bundled with the latest version of Drupal and modules necessary for it to operate.

I already have a Drupal install where various sites make up a multi site architecture. Can I use Commerce Kickstart to install a store as one of those sites in that architecture? Note, this would be stand alone. I don't want the default install to be Commerce where there would be an attempt at a multi store setup, I just want one of the sites to be a Drupal Commerce site.

The CK project pages says, "Who should use Commerce Kickstart? Anyone who wants to skip weeks of configuration to build a commerce site on the Drupal Commerce framework."

Certainly I would like to avoid weeks of configuration and setup.

Is this possible? And if so, what's the best workflow to get it installed and the demo store setup?

If this is not possible, please indicate as much, and let me know if it's possible to install Drupal Commerce as a site in a Drupal multi site architecture nonetheless.  If this is the direction I need to go, what would be the folder structure under sites/store.mysite.com? Would I simply follow the directions on the Drupal Commerce project page as if it were an independent installation?

Thanks!

After much research, I've found out the following:

Can Commerce Kickstart be added to a multi-site installation?

The answer is No.

As Clive pointed out, CK ships with patches to Drupal core, so it's definitely not unmodified.  Additionally, CK will break if one tries to migrate an already existing, stand alone installation to be one of the sites in an existing multi site setup. CK depends on the installation profile to be present to continue to function correctly. Finally, Bojanz, a contributor to the project, points out, CK is a distribution and has to stand alone.

Can Drupal Commerce be added to a multi site installation?

The answer is Yes.

In that same answer above, Bojanz also points out that Drupal Commerce can be added to a multi site architecture. The caveat is that it has to be built out a la cart with modules as needed that make up the Commerce Kickstart distribution.


How to prevent applications from uncovering the technologies used on the website Here is a super hard question, probably for the most experienced people:

Can we prevent applications from uncovering the technologies we are using.

We all know that making sure to keep the core and contributed modules up to date is one of the most important aspect of web development. But meanwhile hiding information about the used technologies will another layer of the security.

Looking in the https://drupal.stackexchange.com/ and Google I can see the last time people talked about this topic was 2013, I think this is the time to ask this question again with hope that someone now have a solution for this.

Making all the Drupalisms disappear is hard work and most definitely not worth your while, as stated above by Clive. In addition, you'd also have to edit/obfuscate many of your http headers.

At that point, if it were me visiting your site all the SSL and Trustee certs could not make up for trust lost and I'd leave. Plus, I might tell my nerd friends what a suspicious weird site you run and turn them off too.

My advice: Don't break what makes the web work, and secure your site. You can and should stop nginx and PHP from advertising their version numbers, and you should delete Drupal's .txt files.


How to replace teaser/content for anonymous users I'm kind of new to Drupal so please bear with me. My question is, is it possible to replace the teaser/content for anonymous users? I have some restricted content but I don't want it to be removed and hidden from anon users, just show something that says they should be logged in to view the content/teaser. I've searched for hours and everything that comes up hides the content completely. I've seen a module that kind of does this thing (restricted content module) but it's only available on d6. I'm using d7.

Thanks in advance!

You can separate teaser from body as a new field, and use module "Field permissions" or similar modules.You can control access for that field.

Another way is custom module which use hook_node_view or hook_node_grants_alter to control if user can access node.


Custom views query - pager dosn't work I am trying to modify view query, basically I build my custom query and assigned it to:

$view->build_info['query'] = $query;
$view->build_info['count_query'] = $query;

everything has been done in hook_views_pre_execute. I tried to do the same in hook_views_query_alter but I wasn't able to construct more complex where clause.

Everything works fine apart from a pager. I noticed that I get pager but main query is not modified with LIMIT option so when I click on particular number of pager my result has not being updated. Below is a query which I need:

SELECT DISTINCT
  dat.field_date_and_time_value AS field_date_and_time_value,
  n.created AS created,
  n.nid AS nid FROM node n
LEFT OUTER JOIN og_membership pb
ON n.nid = pb.etid
AND pb.entity_type = :entity_type
LEFT OUTER JOIN field_data_field_date_and_time dat
ON n.nid = dat.entity_id
AND (dat.entity_type = :entity_type AND dat.deleted = :deleted)
LEFT OUTER JOIN field_data_field_og_public_to pt
ON n.nid = pt.entity_id
AND (pt.entity_type = :entity_type AND pt.deleted = :deleted) WHERE
(n.type = :db_condition_placeholder_0)
AND
(n.status = :db_condition_placeholder_1)
AND
(dat.field_date_and_time_value >= NOW())
AND
(
    (pb.gid = :db_condition_placeholder_2)
    OR
    (pt.field_og_public_to_target_id = :db_condition_placeholder_3)
    OR
    (
        (pt.field_og_public_to_target_id = :db_condition_placeholder_4)
        AND
        (pb.gid IS NULL )
    )
)
ORDER BY dat.field_date_and_time_value ASC, n.created DESC

I created it like that:

$query = db_select('node', 'n');
$query->distinct();
$query->fields('dat', array('field_date_and_time_value'));
$query->fields('n', array('created', 'nid'));
$query->leftJoin('og_membership', 'pb', 'n.nid = pb.etid AND pb.entity_type = :entity_type', array(':entity_type' => 'node'));
$query->leftJoin('field_data_field_date_and_time', 'dat', 'n.nid = dat.entity_id AND (dat.entity_type = :entity_type AND dat.deleted = :deleted)', array(':entity_type' => 'node', ':deleted' => '0'));
$query->leftJoin('field_data_field_og_public_to', 'pt', 'n.nid = pt.entity_id AND (pt.entity_type = :entity_type AND pt.deleted = :deleted)', array(':entity_type' => 'node', ':deleted' => '0'));

$query->condition('n.type', $view->argument['type']->argument);
$query->condition('n.status', $view->filter['status']->value);
$query->where('dat.field_date_and_time_value >= NOW()');
$subcondition = db_or()
->condition('pb.gid', $view->argument['gid']->argument)
->condition('pt.field_og_public_to_target_id', $view->argument['gid']->argument)
->condition(db_and()->condition('pt.field_og_public_to_target_id', $view->argument['gid']->argument)->isNull('pb.gid'));
$query->condition($subcondition);

$query->orderBy('dat.field_date_and_time_value', 'ASC');
$query->orderBy('n.created', 'DESC');

Any idea why pager doesn't work?

Ok, I resolved the issue with the hook_views_query_alter using add_where_expression method. It allows you to create complex where conditions. Below is example

// Delete current where conditions created by view and replace it by custom ones.
unset($query->where);
$query->add_where_expression(0,'node.type = :node_type', array(':node_type' => $node_type));
$query->add_where_expression(0,'node.status = :node_status', array(':node_status' => $node_status));
$query->add_where_expression(0,"(CASE node.type WHEN 'event' THEN field_data_field_date_and_time.field_date_and_time_value WHEN 'training_course' THEN field_data_field_date_and_time.field_date_and_time_value ELSE NOW() END) >= NOW()");

$or_conditions = array();

$or_conditions[] = '(og_membership.gid = :public_by_gid)';
$or_conditions[] = '(field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid)';
$or_conditions[] = '((field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid) AND (og_membership.gid IS NULL))';

$or_condition = implode(' OR ', $or_conditions);

$query->add_where_expression(0, $or_condition, array(':public_by_gid' => $public_by_gid, ':public_to_gid' => $public_to_gid));

I hope it was useful for someone.


Easy theming of admin-side forms? I need to provide a backend user with a fieldset to enter technical data, such as value (in an editfield) and unit (selected from a dropbox). Instead of the default row-based layout such as in:

Value: [editfield]
Unit: {dropbox|values}

I would like to provide:

Parameter name: [value editfield] {unit|list}

While I know I could set up a suggestion template for that, does anyone know of the easiest way to re-position the fields? Display Suite?

Artur

Try the Arrange Fields module.

  This module lets you drag-and-drop the fields of any CCK content type, Webform, or almost any other form in Drupal into the positions you would like for editing. This makes it super simple to have forms with inline fields, which you can change at any point.


Dynamic ordering of views based on argument I'm sure this is possible, I'm just looking for some advice on the best way to approach it.

Here's the situation:

We have some English content. If the user is in Australia, we want to show them all content, with Australian tagged content sticky at the top. If the user is from another English speaking country, we will just show them all content in normal reverse chronological order.

At present, we are tagging content with Locations using locations.module. I have some code in hook_init which identifies the user's country, which is stored in their session.

I figure using an argument to locations.module's views argument support is the best way to do this, but we can happily use another solution like taxonomy if that is more appropriate.

Any ideas on how best to configure a view like this?

I ended up using this code to get the desired functionality:

function mymodule_views_query_alter(&$view, &$query) {
  // in my case I'm pulling info from the user object to decide the sort,
  // but obviously you could check anything here. Use arg($x) to read URL arguments.
  global $user;
  if ($user->country == 'AU') {
    // Note in this case NULL is above AU, so descending order it is.
    $query->orderby = array_merge(array('location_country DESC'), $query->orderby);
  }
}

I'd love to hear any other thoughts on good ways to do this, particuarly some guidance with adding sort objects to the view using hook_views_pre_execute or similar.


How do I deploy/manage similar sites from an unique profile, without dumps? I do not like the "cloning website" solutions which implies dumping a database and importing this dump in another environment. This does not look like a real world way of deploying several instances of the same website (staging/prod/dev/etc).

With D7 we usually used custom profiles and used drush to install websites from these profiles (and maybe using features for later site synchronisations). This provided us with fresh installations, no test content, but sharing important settings. Common content synchronisation would be done with migrate, for example.

I tried to manage several D8 instances sharing the same install profiles. Where the final goal would be to share and sync site configurations. And every installation has a different site UUID.
I have no success in enforcing the system.site uuid config variable at install time (of course I can alter the value later, but it seems to me that this is too late, and all objects are already created with different UUIDs, which makes the first synchronisation a nightmare, where some default contents must be deleted, or default language crashing the sync because it cannot be removed, etc.).

To enforce this UUID I tried using a generated settings.php file with a $config['system.site']['uuid'] value inside, big fail (the setting was completely ignored, even after site installation).

I've also looked at configuration installer profile, which I do not completely understand, especially the way to mix this solution with another install profile.

So the question is, what is the best way of deploying fresh sites from an install profile:

without "cloning websites" and manipulating SQL dumps at site creation (like in what are cloned sites question ).
with a fresh clean install (without developers content garbage), using the exported configuration and code only
which can manage both install configuration defaults and later synchronisations

Features can help bypassing the UUID problem. It's still buggy, which prevents us from fully automating the process, but we can at least shift and maintain configuration manually.

Features still creates modules, it exports the configuration into the config/install directory of the given features module. This will be picked up when you install the feature, and you can continue to update your site config (similarly to what the old drush features-revert did) as your features export changes.

You can also import configuration directly via drush, make sure to use the --partial flag, to avoid overriding configuration not in the config folder. Using --source you can also define a custom configuration folder location, so you can do something like drush cim --partial --source=docroot/modules/features/myfeature/config/install.


Fetch images across the internet with File API How can I use the FileAPI to fetch an image from another website via URL, and bring it into Drupal? Here is what I tried:

foreach ($data['photos'] as $item) {
            $photo = file_get_contents($item['url']);

            $filename = $entity->field_id['und'][0]['value'] . '-' . $x . '.jpg';

            $file = file_save_data($photo, 'public://' . $filename, FILE_EXISTS_REPLACE);

            if (is_object($file) && file_exists($file->uri)) {
                $file->status = 1;
                $file = file_save($file);
                drupal_write_record('file_usage', $file);
                $entity->field_entity_image['und'][] = (array) $file;
                $x++;
            } else {
                // error
            }
        }

It doesn't quite work. The first time around it grabs some of the photos, then the second time around, it should remove any photos in the system and resave them (even if none changed), I have no way to tell if the remote file is new or not.

You might want to try just leaving the remote files as remote and have something like http://drupal.org/project/remote_stream_wrapper? There's an open issue in the module to add a field widget for image and file fields to support just a simple URL entry for a file.


Passing variables that contain HTML through the t() function - ! placeholder has been removed In Drupal 8, it appears that using the ! (exclamation mark) placeholder with the t() function has been removed.

I have a variable that contains HTML:

John Hancock (@JohnH)

I want to keep this HTML, as it will be styled specifically wherever it appears on the site.

In Drupal 7, I was able to do this:

t('Your name is !name', array('!name' => $name));

In which $name contains the HTML shown above. However, in Drupal 8, this doesn't work since the exclamation mark pass-through placeholder has been removed.

I tried this:

t('Your name is :name', array(':name' => $name));

But the HTML is still escaped.

The @ mark also escapes the HTML.

Does anyone know how HTML can be passed through the t() function in D8?

UPDATE:

According to No Sssweat's comment, it seems that my the ! mark does seem to work in t(). So here is my actual code:

drupal_set_message(
  $this->t(
    "@amount has been transferred to !account",
    array(
      '@amount' => '¥' . $form_state->getValue('amount'),
      '!account' => $this->accountService->formatAccountName($account)
    )
  )
);

And I get this error stack:

User error: Invalid placeholder (!account) in string: @amount has been transferred to !account in Drupal\Component\Render\FormattableMarkup::placeholderFormat() (line 235 of core/lib/Drupal/Component/Render/FormattableMarkup.php).

Drupal\Component\Render\FormattableMarkup::placeholderFormat('@amount has been transferred to !user', Array) (Line: 204)
Drupal\Core\StringTranslation\TranslatableMarkup->render() (Line: 15)
Drupal\Core\StringTranslation\TranslatableMarkup->__toString() (Line: 451)
drupal_set_message(Object) (Line: 128)

The user error is what made me think the ! mark is not allowed, but I must have misdiagnosed it. Does anyone know what is happening here?

It appears that any arguments passed to t() function are escaped unless they implement MarkupInterface. So that you need to represent the name as an object.

use Drupal\Component\Render\FormattableMarkup;

$formatted_name = new FormattableMarkup(
  '
    @first_name
    @second_name
    (@user_name)
   ',
  [
    '@first_name' => 'John',
    '@second_name' => 'Hancock',
    '@user_name' => '@JohnH',
  ]
);

drupal_set_message(t('Your name is @name', ['@name' => $formatted_name]));


Extra "mystery" markup being printed to page I have a strange thing happening. If you see this page:

http://morningsidecenter-teachablemoment.org/teachable-moment

you will see a pretty much broken super fish nav (that until earlier tonight was working.) If you inspect the element you will find numerous empty  being printed to the page...

I went through and undid all the work i had done, but to no avail. Has anyone ever encountered this sort of thing? I've combed over my .tpl files to see if there is anything strange going on, but I cannot see anything (though it is late). Also, when I am logged in the error does not present itself, nor does it on interior pages for that section; click on any item in the sub menu, and you will see the nav is not broken, and no extra markup in the form of empty  tags...

thoroughly flummoxed...

If I view source on the page you can see there is a unclosed anchor tag in this chunk:

Posted in Classroom Ideas & Resources

Is this a hard-coded chunk of html in a view? Looks like you have mixed around the closing


preprocess_field() not working - what am I doing wrong? I am trying to use mytheme_preprocess_field() to alter how a field is displayed. Here is the code I added to my theme's template.php:

function creative_responsive_theme_preprocess_field(&$vars) {
$element = &$vars['element'];
if ($element['#field_name'] == 'field_myfield') {
   $element['#items'][0]=[];
   $element['#items'][0]['value'] = 'replaced value';
   $element['#items'][0]['format'] = 'filtered_html';
   $element['#items'][0]['safe_value'] ='';
   $element['#items'][0]['#markup'] = 'replaced value';
   return;
 }
}

I confirmed that the code is being executed, but the rendering of the page does not reflect what I have done in the code. The field is being displayed as usual. I am using display suite. Not sure if that effects anything, but searching online, I see no indication that above should not work. And I added the #markup part because I read that is truly what one has to do...

Ideas?

regards

I think it was the # in front of items that was messing things up. I have this working now as

function creative_responsive_theme_preprocess_field(&$variables) {
    if (user_is_logged_in()) {  return $variables;}
//if (in_array($variables['element']['#field_name'], array('field_audio_fast_', 'field_audio_slow_'))) {
    if (($variables['element']['#field_name'] == 'field_audio_fast_') OR ($variables['element']['#field_name'] == 'field_audio_slow_')){
        $variables['items'][0]=[];
        $variables['items'][0]['value'] = ' ';
        $variables['items'][0]['format'] = 'full_html';
        $variables['items'][0]['safe_value'] ='';
        $variables['items'][0]['#markup'] = ' ';
        return $variables;
    }
}

At first  $variables['items'][0]=[]; was producing a bunch of warnings about invalid arguments to core functions regarding children and parents and rendering. Then I cleared drupal cache. The thing is, the field I am replacing is an audio file field. So I think there must be a cleaner way to do this than above. Let me know if you have suggestions!


Display Youtube videos in a gallery of thumbnails with a primary player I'd like to be able to display a gallery of youtube video thumbnails underneath a primary Youtube video "player" area. When a thumbnail is clicked, that video would play in the main player area without the user being taken to any other page. Is there a way I can accomplish this with existing modules and/or Views?

Thanks!

I have make something like this using views slideshow.

Added youtube thumbnail in the views
Added youtube video in the views
Add slideshow as style format of the view
Set youtube thumbnail in pager of the slideshow

Its working for me.


Why is 'render element' sometime 'element' and sometime 'elements'? I notice in Drupal source code, in core modules hook_theme(), some places are 'render element' => 'element' and some places are 'render element' => 'elements' (plural). Why? Even the render element purpose is to display a single object (e.g. node canonical), not a list of objects.

The problem is it results in different key in $variables in template_preprocess_hook(). For instance, I have a custom entity and if I use _entity_view in entity canonical route, the $variables has 'elements'. But if I manually use this entity theme in a page, the $variables has 'element'. I'm so confused.

Because it wasn't standardized.

The safe approach is to check the info array for the render element key.

There is actually an issue with the field groups module that ignores everything but form & elements.


How do I access the paragraph value? In 1 node. I'm using multiple paragraph type & within that I have fields.

Paragraph 1 -> field_title, field_time
Paragraph 2 -> field_test

How to access Node's Paragraph 2 -> field_test value?

Need to add below code in your theme file

themename.theme

/**
 * Implements hook_preprocess_node().
 */
function theme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  switch ($node->getType()) {
    case 'article':
      $my_paragraph = null;
      foreach ($node->get('field_content') as $paragraph) {
        if ($paragraph->entity->getType() == 'my_paragraph') { // Change to your paragraph type
          $my_paragraph = $paragraph->entity;
        }
      }

      if (!empty($my_paragraph)) {
        $variable['test'] = $my_paragraph->field_test->value;
      }

      break;
  }
}


Noob question about private files and Content Access This is almost certainly a really stupid question, but the Drupal 7 site we're building has an image gallery that users can upload content to. Unauthenticated users should not be able to see these images, but some other rôles should be able to see all the images uploaded by other users. The way we first built it, images all show up from a directory below the webroot, so anyone can see the image, if they know the URL.

I thought Private files would be my solution, so I followed the instructions there, setting up a folder in our filesystem (above the webroot, so you can only get there via Drupal) and changing the field settings within the appropriate content type to use Private files as the Upload destination and then went to set a bunch of Custom permissions, so that the appropriate users have "View anyone's value for field Image" (and so on) but that Anonymous users don't.

Then I cleared all the caches and went to upload a new image. If I go to the node page and right click to get the image URL, though, pasting that into an Anonymous Browser Mode window still shows me the image.

So I figured maybe I just needed something more fine-grained or that I'd implemented it wrong.

So I enabled the Content Access module and went back to the appropriate Content type and set the Access Control settings so that only the appropriate rôles can "View any gallery_image content" (and so on). Clearing the caches, uploading another new image, I can still grab the URL and see it from a new Anonymous Browser Mode window.

Now the Private files thing seems to be doing the right thing — the image URL is now /system/files/styles/image_thumbnail/private/gallery/images/filename.jpg and the files are appearing in the right part of the filesytem, but Drupal doesn't seem to be respecting the access control — or even just requiring that you log in.

Presumably I've done something wrong somewhere, as it seems like I'm implementing the right thing and I've just made a mistake somewhere. So is there an obvious step I'm missing?

Update: The hosting environment is RedHat Linux and we don't allow .htaccess files (we're developing the site, a third-party is responsible for security, so they would rather everything go into the httpd.conf instead). This is part of why I deliberately close a directory above the webroot, so that a .htaccess file would not be necessary. I do notice, though, that if I try to access /system/files/styles/image_thumbnail/private/gallery/images/ in a browser, I get a Drupal 403 message, not the apache one.

I believe that this issue was fixed in SA-CORE-2012-002 - Drupal core multiple vulnerabilities instead of being posted to a public site like this. In the future something like this should be reported to the security team. And, if upgrading Drupal core doesn't fix your bug let's discuss more details by having you submit a new Core security issue where we can figure out what's going on in private and then, if appropriate, release a patch that fixes the bug.


Min/Max Facet slider not working I am working on Search API. I am using Search API module, Facet API, Search API ranges, Pretty Paths modules to add facet filters.

All the filters working fine like select list, checkbox but Min/Max slider not working. When I am moving the slider, it gives 0 results to me.

How can I solve this problem ?

I got the answer. Pretty paths module creates the problem for this. I disables the Pretty Path module and flush the cache.

Now Min/Max slider working fine.


Dreadful Google CSE error We have several sites on a multisite structure, and almost all of them use Google CSE. However, some of these websites display the error "Refused to display 'http://www.google.com/cse?cx=...' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. This behaviour happens only for a couple of sites. I have compared Google CSE settings, and they are identical. How can I fix this issue?

UPDATE: I've compared directory sizes from both sites and they were different, so I've tried removing the module from the site that doesn't work, and copying one from a site that does work; but no dice :S

Doing a quick search on Google I found this answer to a similar question: https://stackoverflow.com/questions/7905169/when-did-google-search-start-sending-x-frame-options-sameorigin

I hope it helps.

Best regards,
David.


How to setup view to filter based on second URL parameter? We have a view, myview, that is added to the https://www.adomain.com/some-page/ page. It has an exposed filter, Topic that a person can use to filter the user where Ajax = Enabled so that it loads the results without refreshing the page.

The view is added to a landing page (content type = basic) and at the bottom of the page. It is meant to return nodes where topic tag value is equal to what is supplied from the url.

Taxonomy term values (topic):

IoT
Cloud
Cloud Security

How to setup view to filter based on second URL parameter?

Expected behavior:

Display all items when https://www.adomain.com/some-page/ is loaded.
Display all items where topic = Cloud Security when https://www.adomain.com/some-page/cloud-security is loaded
Display all items where topic = Cloud when https://www.adomain.com/some-page/cloud is loaded

Current Behavior:

Displays all items when loading https://www.adomain.com/some-page/
Displays no items when loading https://www.adomain.com/some-page/cloud

What we have tried using block display type:

Create view using block display type with a contextual filter Content: topic
When filter value is not available = Display all results for the specified field
When the filter value is available or a default is provided is set to Specify Validation Criteria = enabled, Validator = Taxonomy Term Name, Vocabulary = topic, and Action to take if filter value does not validate = Display all results for the specified field

What we tried using Page display type:

add path /some-path (without %)
Add relationship, field_topic: taxonomy term and require relationship = true
Add contextual filter: Name from Taxonomy term (field_topic) with the following settings below.

Contextual filter settings:

When the filter value is not in the URL

Display all results for the specified field

When the filter value is in the url or a default is provided

Specify validation criteria = Validator = Taxonomy term name
Vocabulary = Topic
Transform dashes in URL to spaces in term name filter values = true
Action to take if filter value does not validate = Display a summary
Case = Lower case
Case in path = lower case
More = Transform spaces to dashes in url = enabled

Content Views don't have access to Taxonomy term name information out of the box, you only have term ID available. So even if you add the Taxonomy term field as the contextual filter and set the Validator = Taxonomy Term Name you're not telling it what to use, you're basically making a mistake trying to use that validator.

You can test this if you enter the term ID into the Preview instead of the name, or set the Action to take if filter value does not validate to Display a Summary and see what you get as output ;)

Add term name info through Relationship

To introduce the term name information into your content views you have to:

add a Relationship to the term: Taxonomy term referenced from field_topic. Require it if you only want to list nodes that have a topic assigned.

Now you will see a new Category of fields when adding Contextual filters: Taxonomy term
Add the Contextual filter Name from Taxonomy term Category, it will use the Relationship from previous step by default, and configure it:
When filter value is not available
Display all results for the specified field
When the filter value is available or a default is provided
 Specify validation criteria
Taxonomy term name
[Case settings, other relevant config as you see fit]

You will now see all results when visiting the main path, and if you visit the path with topic name appended the list will be filtered to show only nodes with that topic.

In case you have terms with the same name accross vocabularies

There is a bug that kicks in sometimes  when using term name as the Validator, if you have different terms with the same term name: TermName views argument_validator is not working as expected.

The patch from that issue is working, as reported by the question author usernameabc, so it can be used until a new version is released that includes it.


Translation of the OG's User Roles I have a view which contains the relationship "OG membership: OG Roles from membership", and the only thing I need is to translate the retrieved values from this relationship.

What is your recommendation?

This is an open issue which is worked on here:

https://www.drupal.org/node/1473262


how to display the uploaded zip file content in drupal? i created a cck file field and i uploaded zip file in that content type. Now i want to display the content of zip files after uploading the zip files. i don't know how to implement it?. can you tell me how to implement it?

thanks in advance.

It will not be very hard to accomplish. Don't let anyone tell you otherwise :D

What you need to do (if you have some experience with PHP and creating a very simple Drupal module) is download the PCLzip module which basically integrates the pclzip library into Drupal. There is no submodule for listing zip contents at the moment but it is very simple to make one if you keep in mind that there is a specific method in the library, the ListContent method.

You can see examples of how the methods of the library are used at the related projects that do use the pclzip module like PCLzip Folder or PCLzip Content Files. If you study their code, you will be able to achieve your goal very easily (and hopefully contribute your code back to the community).

Don't listen to advice that say: "extract the contents of the zip file first" since:

There is no need to extract files out of the zip file, you just need to see them
It's never a good idea to add extra complexity and write custom code that will be useful to nobody but you (and after a while so much custom code will be useless to you too)

Keep it simple: use the work of other people and expand it.

Edit: Let me give you an example so that you can understand how easy it is. If you check the pclzip module you will find a function that looks like this:

function pclzip_build_archive($filename) {
  // get the temp file
  global $pclzip_temp_file;
  $pclzip_temp_file = tempnam(file_directory_temp(), $filename);
  // build the archive
  require_once('pclzip/pclzip.lib.php');
  return new PclZip($pclzip_temp_file);
}

The line:

return new PclZip($pclzip_temp_file);

is the one that uses the PclZip method to create a new archive. All you need to do is create a new function, similar to that one, in your custom module, that will use the listContent method to list the contents of the zip file. It's that simple.

Notice, that there is one extra step after retrieving the contents of the zip file, and this is: "displaying them". Since the method of the pclzip library gives you back an array, it should be simple enough to display it (you can choose how you want to do it).

I have tested the following:

Installed the pclzip module
Made sure that the library is in the appropriate directory (according to pclzip instructions)
Added the following code in the pclzip.module file:

function pclzip_nodeapi(&$node, $op) {

  $cckZip = $node->field_zipfile;
  $zipPath = $cckZip[0]['filepath'];
  $zipView = $cckZip[0]['view'];

  if (isset($zipPath)) {
    require_once('pclzip/pclzip.lib.php');
    $zip = new PclZip("$zipPath");

    if (($list = $zip->listContent()) == 0) {
      die("Error : ".$zip->errorInfo(true));
    }

    $zipView .= "
";

    for ($i=0; $i<sizeof($list); $i++) {
      $zipView .= $list[$i]['filename'] . "
";
    }

    $zipView .= "
";

    switch ($op) {
      case "view":
        $node->content['body']['#value'] .= $zipView;
    }
  }
}

Notice that:

field_zipfile is the name of the cck field that I used to upload the zip file
I have edited the pclzip module directly (which is not a very good idea). You should probably do the changes in your own module, but I just wanted to test the solution very quickly
You should decide where the filenames will be printed. I have just added them at the end of the node's content without any specific formatting. you can add classes and specific tags to the filenames in order to theme them if you want.


Does turning off features modules affect what the features modules does? I have a site that uses the media_vimeo module and I need to turn it off to install another module, but I can't turn it off as its currently being used by a bunch of feature modules. Would turning off these features modules affect the site or it doesnt matter as these features modules has already imported the needed changes to the site?

FWIW I've successfully uninstalled modules required by a feature before, but I had to remove the dependency from the feature's info file first and then disabled and removed the module. I've seen several Features where the creator unwittingly auto-added all sorts of modules and dependencies to the feature, so just because a module is listed as a dependency doesn't necessarily mean that it is really needed. As this tutorial points out, we should "Build natural dependencies, prevent arbitrary dependencies." and it's so true because as these arbitrary dependencies creep in, a site's features become more difficult to manage.


how to change the colorbox image size? I have a content type named gallery and under this, I have created
the gallery content which is belong to that content type and added the
multiple images but the problem is when I click the thumbnail image
color box window opened but small images opened.

Create a new image style of any size you want to open the image in colobox.
Now browse to manage display of your content type.
Select the formate 'Colorbox' for image field.
Add newly created image style for Colorbox image style, please follow below screenshot.


Help with contextual filter and entity reference fields I have a content type with an entity reference field that allows users to assign multiple other nodes to be referenced from the current node.

I am trying to create a view that will list the related nodes for the current page.

What Relationship/s and contextual filters must be set to achieve such a thing?

I have read a number of other posts asking similar questions, though most seem to be in reference to Drupal 7 and their suggestions either do not work, or appear to not exist in Drupal 8.

I can get a list which shows all the other nodes that reference the current node by setting a contextual filter to: Content:field_related_pages and setting the default value to Content ID from URL this, however, is the exact opposite of what I want...

I have tried creating a relationship based on the Entity Reference field, however there are two options I can see:

Content referenced from field_related_pages
Content using field_related_pages

I have also tried using a contextual filter of: Content: ID with the default value set to Content ID from URL

I feel like I have attempted every conceivable combination of the above and none seems to work. Can someone please put me out of my misery and incompetence and please how to get a contextual filter to show a list of nodes related to the current via a entity reference field?

Apparently I had the following selected under the "more" tab in the contextual filter:

Exclude If selected, the numbers entered for the filter will be excluded rather than limiting the view.

Which lead to all kinds of odd behaviour...

If it is of use to anyone else, the correct answer appears to be:

Content using field_related_pages with the relationship required.
The contextual filter set to Content: ID with  with the ```default value set to Content ID from URL`` and
Relationship dropdown set to the field_related_pages


Panels block title translation I use blocks in a panel with Drupal 8. With view generated blocks there are no problems: The block titles are translated accordingly to the view settings. With custom blocks, it appears to be problematic to get the block title translated. I hoped that these titles would be translatable via the user interface translation but they are not; plus, in the panel settings, I can set the block title, but I cannot translate it.

How can I translate block titles (and maybe block content) of custom blocks in a panel, with Drupal 8?

You can override the block.html.twig template and handle the translation of the title directly on the template:

    {{ label|t }}

You may need to confirm the title structure (if is #markup or plain text/string)


How to redirect a menu item to the anchor? I have created menu with sub-menus. The menu block is placed on the specific page.

Drupal menu path allows only allows normal path to be given to menus(like node/nid and pagepath).
I want to give path like node/256#myblock.

I do not want to go with contributed modules(void menu or any other) as this is for the single link in my site.

Modules are how you extend Drupal's functionality; there's very little point saying you want to achieve something without a module, as if one exists, you're just going to end up copy/pasting its code into your own module/theme anyway to get the same effect.

Drupal core has no functionality to link to an anchor, so you need to install a module which does, or copy the code from one to your own.

Whichever of those methods you decide to use, Special Menu Items has the functionality you require (you can either install
and use it as normal, or pick the relevant bits of code out into your own module/theme).


Quick-edit button in Drupal Commerce I'm using Drupal 7 and Commerce Kickstart 2.0-rc1.
I can't find a way to remove the possibility for a user role to use the "Quick Edit" button in admin/commerce/manage-products . I tried using hook_permission() but, despite the permission is taken into account, the button is still here and still works.

Is there a clean way to remove this action from the drop-down list ?

Thanks.

The whole "Products Listing" requires the "super permission" (a permission that grants all kinds of access, including the ability to quick edit) "administer products." I have filed a feature request in the Commerce Kickstart Issue queue that requests the quick edit button have a more granular permission.

http://drupal.org/node/1883280

Josh


How to programmatically determine if the cron is running Is there any way programatically to determine when the cron is running (and if possible, what tasks are being run)? I've explored some options online that are bound to drupal_cron_run(), but no examples on how to listen for this method being used, as it is intended to start the cron.

In Drupal 7:

To determine if the current page request is a request for cron:
in other words, "is my code being called during cron"?

If you're running cron through cron.php, this is probably sufficient:

return strpos($_SERVER['REQUEST_URI'], 'cron.php') !== 0;

A more reliable way to determine a cron would be through introspection (e.g. debug_backtrace()), but that would entail a much greater degree of overhead.

To determine if any cron request is still running, across all Drupal threads and pageloads: in other words, "is any process running cron anywhere?" * Note that this method will fail if cron is stuck.

Drupal will programmatically set a variable called cron_semaphore while the cron is running. This variable is deleted once cron has completed. You can check for the presence of this variable to determine whether cron is currently active or not:

if (variable_get('cron_semaphore', FALSE)) {
  // cron is running
}

You can see the specific use of cron_semaphore in the documentation of drupal_cron_run().

The 'tasks being ran' will be implementations of hook_cron, which you can find using:

foreach (module_implements('cron') as $module) {
  $function = $module . '_cron';

  drupal_set_message($function . '() is being ran');
}


How do I discover property names? When doing a custom D7 to D8 migration, i sometimes need to migrate a specific value such as 'fid' (for example file ID of an images) into the

'field_image/target_id'

property. How do I find out which property i can use for D8 fields? By property i mean the target_id part. For example for uid field? The devel module does not seem to be helpful here, or I may be wrong.

You can use the EntityFieldManager. This is an example how to get the properties for the field uid of the entity node:

$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');
$properties = $fields['uid']->getPropertyDefinitions();

From the command line you can use this in a drush php-eval command:

drush ev "var_dump(\Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node')['uid']->getPropertyDefinitions())"


Add property to existing field type I have troubles adding a simple additional properties (like alt or title) to the image field type.

In the .module file I defined an alternative class for the image field.

function image_video_link_field_info_alter(&$info) {
  // Change the default widget for fields of type 'image'.
  if (isset($info['image'])) {
    $info['image']['class'] = '\Drupal\image_video_link\LinkedImageItem';
    #$info['image']['column_groups']['videolink'] = ['label' => t('Link to a video.')];
  }
}

I extended the ImageItem class with some additional properties.

/**
 * @file
 * Contains \Drupal\image_video_link\LinkedImageItem.
 */

namespace Drupal\image_video_link;

use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Extends the default PathItem implementation to generate aliases.
 */
class LinkedImageItem extends ImageItem {
  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    $settings = parent::defaultStorageSettings();
    $settings['default_image']['videolink'] = '';
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    $settings = parent::defaultFieldSettings();
    $settings['default_image']['videolink'] = '';
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
    $schema['columns']['videolink'] = [
      'description' => "Link to a video.",
      'type' => 'varchar',
      'length' => 512,
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['videolink'] = DataDefinition::create('string')
      ->setLabel(t('Videolink'))
      ->setDescription(t("Link to a video on Vimeo."));

    return $properties;
  }
}

I believe I have to update the database in the .install file as I am getting the following error.

  Undefined property: stdClass::$field_gallery_videolink

How do I do that? Is my method even valid?

I know this is a older issue but I found it when trying to do the same. Still for this exactly case maybe answer from xxx would be also helpful.

After it took me a while to figure out how to do it I wanted to share this example. Only thing needs to change is the first few lines.

/**
 * Add new property to all fields of type XXX.
 */
function XXX_update_80YY() {
  $field_type = 'XXX';
  $new_properties = array(
    'PROPERTY_NAME' => array(
      'description' => 'PROPERTY DESCRIPTION',
      'type' => 'varchar',
      'length' => 255,
    ),
  );

  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
  $field_manager = \Drupal::service('entity_field.manager');
  /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
  $entity_type_manager = \Drupal::service('entity_type.manager');
  $field_map = $field_manager->getFieldMapByFieldType($field_type);
  $schema = Database::getConnection()->schema();
  foreach ($field_map as $entity_type_id => $fields) {
    $field_manager->clearCachedFieldDefinitions();
    $storage_definitions = $field_manager->getFieldStorageDefinitions($entity_type_id);

    $storage = $entity_type_manager->getStorage($entity_type_id);
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage->getTableMapping();

    foreach ($fields as $field_name => $field) {
      $storage_definition = $storage_definitions[$field_name];
      if (!empty($storage_definition)) {
        $column_names = $table_mapping->getColumnNames($field_name);
        $table_names = [ $table_mapping->getFieldTableName($field_name) ];

        if ($storage_definition->isRevisionable()) {
          $table_names[] = $table_mapping->getDedicatedRevisionTableName($storage_definition);
        }

        foreach ($table_names as $table_name) {
          foreach ($new_properties as $property_name => $property_spec) {
            if (!$schema->fieldExists($table_name, $column_names[$property_name])) {
              $schema->addField($table_name, $column_names[$property_name], $property_spec);
            }
          }
        }
        $definition_update_manager->updateFieldStorageDefinition($storage_definition);
      }
    }
  }
}


Have module .install create a table in a non-default DB I have constructed a module that, using the .install file, creates a table on a database different than the default.  The module installs fine and functions fine – just a hello world example in the controller. However, when I uninstall the module I get: “The website encountered an unexpected error. Please try again later.” and the reports log there is:
DatabaseExceptionWrapper: SQLSTATE[42S02]...

Here is the .install file code:

function hello_world_schema()
{
    db_set_active('notTheDefaultDB');
    $schema['create_table'] = array(
      'fields' => array(
        'id' => array('type' => 'serial', 'not null' => TRUE,),
        'name' => array('type' => 'varchar', 'length' => 40, 'not null' => TRUE,),
        'last_name' => array('type' => 'varchar', 'length' => 40, 'not null' => TRUE,),
        'message' => array('type' => 'varchar', 'length' => 250, 'not null' => TRUE,),
        'boogie' => array('type' => 'varchar', 'length' => 20, 'not null' => TRUE,),
      ),
      'primary key' => array('id'),);
    return $schema;
}

I do realize that I'm tell hook_schema to switch to notTheDefaultDB and don’t switch it back – if it is switched before the return statement the table is created in the default.

As I said, the module seems to function as intended, but blows up when uninstalled.

Is there a way to write the module so it doesn’t blow up on uninstall or perhaps an entirely different way to do what I’m after?

To my mind, the entire purpose of hook_schema is to build the Drupal schema. If you need/want to create tables outside of Drupal, it seems like just using PDO in a hook_install() and hook_uninstall() implementation might be the way to go. Can you explain your use case a little bit more?

All that said, I don't see an obvious reason for your code to fail.


Need to save node twice to get wanted result I have made 2 custom tokens that I use to determine the URL alias in the Pathauto pattern. They work fine too, but since my custom tokens rely on certain (taxonomy) fields in the node, they always get the "old" field value when the user changes them. The url alias isn't correct until the second time I save the node. Thus I need to "presave" the node immediately when the user changes the field value, so that the new token value is taken into consideration when saving the node... How can I do that?

Since the change is done on the client side I would need to use Ajax to call node_save or hook_node_presave directly when the field value is changed?

Any help is appreciated :-)

EDITED: I have realized that I probably need to write a JS script that uses ajax to call a php function that saves the node when the field is changed. So the question now is if that is wise to do when the user is in the editing mode… ?

Edited again:

I finally worked it out. I skipped the JS solution and opted for using field_attach_presave('node', $node) and field_attach_update('node', $node) in the function hook_node_presave. Doing so permits to save 2 specific fields programmatically just before the node is saved definitely by the user. And Pathauto can use those 2 fields as tokens for my URLs. It works too :-). There are many reasons for this non straight-forward solution, a bit to lengthy to explain here (migration is involved among other tings). But I am happy with this solution. Thanks for the input though!

Happy you solved it without walking around it via AJAX, I think it was a good call. I am still gonna pick up on this thread though, simply out of stubbornness, please bear with me. :-)

So, your hook_node_presave entry point is fine and in all practical aspects you probably will not need to read further down. However, your tokens should have been available from the very beginning to Pathauto. The problem was - following your code from this revision - the use of the menu_get_object() function. I assume the following caused the problem:

You created and saved a new node with your migration code
Your hook_tokens implementation was called from the Pathauto module during node_save
menu_get_object was called and returned nothing
New node was created with the wrong URL path

The reason menu_get_object returned nothing is because the new node was not yet available via Drupal's routing. This is expected since all new nodes need to be properly saved once to get a route like node/NID ). This also explains why your code worked properly for a - now - existing node, with a registered route.

Your code would actually have worked fine if you had used the $data parameter, you could have picked your node object from there like this:

// $node = menu_get_object();
$node = $data['node'];

I tried this quickly in my sandbox and I could both reproduce the original problem and also solve it.

Conclusion: Your code, if you still want to use it, and get rid of the additional hook_node_presave implementation, should work fine if you apply the above change.

Cheers!


How do I preserve custom files in my Drupal configuration across minor core upgrades? When I do a minor upgrade of the core, my custom .htaccess and robots.txt are overwritten.

How do I prevent that?

You can build a site totally with git to help manage this process. The process is basically

Git clone into your DOCROOT:

git clone --branch 7.x http://git.drupal.org/project/drupal.git /var/www/mysite/docroot

Rename the remote:

git remote rename origin drupal

Checkout the latest tag, and make a site branch for your site:

git checkout 7.26
git branch -b mysite

Now, you can build your site and customize robots.txt and .htaccess to your needs.

When there is a core update, you can:

git fetch drupal

and then use the normal git methods for merging your changes in, eg:

git merge 7.27

or you can preview what will happen, check for conflicts, etc.

If you do this, you need to make sure you don't do a plain:

drush pm-update drupal

as this will then mess things up. I do not think that drush pm-update --lock=drupal works to prevent this.


Update database with data from dev site? I've made changes to 12 nodes on a site that already has about 4000 nodes.  I'd like to be able to push these changes to the database without affecting any other data (and without having to redo all the changes by hand).

Problem is, this is a live site, so if I try to simply import the updated database I'll lose some data.  What is the best method for doing a partial update?
-JB

Jordan.

Unfortunately, this is not something that Drupal does very well.

You can try using the Deploy module, but in my experience as a professional developer, I have never met anybody who has found a good way to export nodes in a way that is thorough, consistent, and safe.

More specifically, Deploy may not support all field types, and sometimes field definitions are hard to find, and can be inconsistent (for example, taxonomy terms are exported as TIDs, which change if the term is deleted and then added again).

Sorry for the bad news.


How can I specify background color and image for a block or node? My web page consists of vertically aligned blocks. Each of these blocks/nodes may have  a custom background color or image. I am entering the background color/image within the specific block. How can i then apply these CSS attributes on that specific block? I would like to simply render the block as

[...]

I played with block template but was not able to persuade the color or image attribute to appear where i needed them, both the values were wrapped in the useless

markup.

You can do it with this module:
https://www.drupal.org/project/bg_image_formatter

Just upload image as background field and set the class in the field settings for which element you want to display image as bgd.
It works with Views as well. So, for example, you can use Views conditional module and create a block and test if bdg field is empty and then create different styles with bgd color in that case.


How can I show the flag field using Twig? I created a twig template for my node.

If I want to show the body field, I use {{ content.field_body }}. Similarly, how can I show the flag field?

I found it.

Flag machine name: bookmark

Then we can use {{ content.flag_bookmark }} in node.html.twig to show bookmark flag .


Use theme template with specific Views I have a D8 subtheme of Bootstrap and on the homepage I have 2 Views (2 carousel views).
I turned on twig debugging so I could see which template file(s) is (are) being used, and where it starts and ends.  When I used this before it included a listing of sample alternate filenames for that specific content (e.g. paragraph--about-us-page--full.html.twig), which was a big help.
For each of the views on the homepage, they are shown using views-view.html.twig and views-view-field.html.twig whether from the module template, bootstrap template or my copy of the files into my theme.
Is there a way to set up a template file for each of the views individually?
View Machine Names:

homepage_slider
homepage_loans

They only reside on the front page.  I have tried renaming files to see if I can see it being used in the Twig debugging and frequently clear the cache.
It could be a Page, View, Block, etc. template, but then how do I reference the parts of the View to control the display of the fields.
Thank you.

I think what you're looking for is in this section: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions#s-views
Specifically,

views-view-field.html.twig based patterns are postfixed with the
view's field id (as in replacement patterns) to display a single field
in a view:

views-view-field--[viewid]--[view-display-id]--[fieldid].html.twig
views-view-field--[viewid]--page--[fieldid].html.twig
views-view-field--block--[fieldid].html.twig
views-view-field--[fieldid].html.twig
views-view-field.html.twig


Kernel Test: Programmatically create a vocabulary and add a field to it I want to add a taxonomy term and add field to it. My current code looks this way:

<?php

namespace Drupal\Tests\permissions_by_term\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Tests the ERR composite relationship upgrade path.
 *
 * @group permissions_by_term
 */
class SelectTermTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = array('taxonomy', 'text');

  /**
   * List of taxonomy term names by language.
   *
   * @var array
   */
  public $termNames = [];

  /**
   * The vocabulary used for creating terms.
   *
   * @var \Drupal\taxonomy\VocabularyInterface
   */
  protected $vocabulary;

  function setUp() {
    parent::setUp();

    $this->installEntitySchema('taxonomy_term');

    // Create a vocabulary.
    $this->vocabulary = Vocabulary::create([
      'name' => 'Views testing tags',
      'vid' => 'views_testing_tags',
    ]);
    $this->vocabulary->save();

    // Add a translatable field to the vocabulary.
    $field = FieldStorageConfig::create(array(
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'type' => 'text',
    ));
    $field->save();
    FieldConfig::create([
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'label' => 'Foo',
      'bundle' => 'views_testing_tags',
    ])->save();
  }

  public function testSomething() {
  }

}

If I run the test by the following command:

  vendor/bin/phpunit -c modules/permissions_by_term
  modules/permissions_by_term/tests/src/Kernel/SelectTermTest.php

I'm getting the following output:

  PHPUnit 4.8.11 by Sebastian Bergmann and contributors.

  E

  Time: 882 ms, Memory: 6.00Mb

  There was 1 error:

  1)
  Drupal\Tests\permissions_by_term\Kernel\SelectTermTest::testSomething
  Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The
  Drupal\field\Entity\FieldStorageConfig class does not correspond to an
  entity type.

  /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityTypeRepository.php:98
  /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityManager.php:375
  /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/Entity.php:509
  /home/peter/Websites/pbt-d8/modules/permissions_by_term/tests/src/Kernel/SelectTermTest.php:49

  FAILURES! Tests: 1, Assertions: 1, Errors: 1.

I do not understand this part:

  Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The
  Drupal\field\Entity\FieldStorageConfig class does not correspond to an
  entity type.

As an example I have used the Drupal core taxonomy test from

  core/modules/taxonomy/src/Tests/Views/TaxonomyFieldFilterTest.php

This test does what I want to do, but is not a Kernel test. It is a Simpletest, since it inherits from WebTestBase. If I use WebTestBase, it works. But the test is much slower then. Do you know what's missing in my code for running it as a Kernel Test?

You need to enable the field module so its entity types are present. Kernel test base does not enable required modules so the FieldConfig and FieldStorageConfig entity types don't exist until you enable the field module. Put it in the $modules property with 'taxonomy' and 'text'.


Adding a background image to the header I'm trying to display a photo as background image for a Drupal 7.7 website.

After reading a doc on subthemes, I have created a directory called "pasture" in the same directory where "bartik" resides (i.e. in ~/public_html/drupal/themes/pasture).

I have created the pasture.info file.

name = pasture
base theme = Bartik
stylesheets[all][] = pasture.css
files[] = pasture.jpg
core = 7.x

I have created the pasture.css file.

#header {
        background:url(/drupal/themes/pasture/pasture.jpg) top left no-repeat;
}

I have saved a public domain image as pasture.jpg. The image is the following one.

Unfortunately, my site appears completely broken, after I activate that theme, and I see numerous warnings:

  Notice: Undefined index: Bartik in method drupal_theme_initialize() (line 98 inf file /usr/www/users/simplex/drupal/includes/theme.inc).
  Notice: Trying to get property of non-object in method phptemplate_init() (line 12 in file /usr/www/users/simplex/drupal/themes/engines/phptemplate/phptemplate.engine).

I cannot comment, but some remarks

remove the files[] = pasture.jpg line, it isn't needed
you may enable your base theme, but it isn't necessary
put your own themes (modules) under /sites/all/themes or /sites/default/themes, don not put them inside /themes (/modules), if this directory doesn't exist, just create them

Question, does your site works when using the Bartik theme?


How to use replacement pattern in css? Is it possible to use tokens such as [view_node] in css ?
I want to display links only for a particular content type.

Thanks !

Assuming your view uses Show: fields.

Add type as a field, check mark the hide from view box.

Click on your field, in REWRITE RESULTS, checkmark rewrite outlput of field

In there, put
[field_name]

Then in CSS

.all-links { display: none; }
.all-links.article { display: block !important; }

Another solution, is to use Views Conditional

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

Then just do a simple condition if type is x, then [field_name]


How exactly does a View Preview differ from what is rendered on a page/block? There are a number of questions relating to this issue. I'm interested in a general explanation so I can troubleshoot why my complex (contextual filters, relationships, etc) view preview would be working as expected while the view block shows different results.

What exactly is being run for the preview compared to the normal display of the view? What happens 'after' the preview, or are these different paths/processes/methods/hooks altogether?

If aggregation is enabled and query settings distinct and/or pure distinct as well with flags relationships, I experienced differences in what the preview was showing and what showed in the actual block/page version. The solution for me was disabling the distinct option.


Display current node rank from votes (voting api) in view As in Title. I am struggling by programming but with no luck. Mechanism of voting api is too complicated for me. How can I display current node rank (order number) by votes?

My view now:

Sort critera:
(Vote results) Vote results: Function desc

Relationships
Node: Vote results

When displaying all results it's have order number thanks to view php field module.

Display position in rank of current, single node is hell for me. Custom sql query doesn't work at all.

I am using voting api and rate module.

Please help.

EDIT

Since I am using +1/-1 I try to:

Sum +1 Votes
Sum -1 Votes
Subtract sum of -1 votes from sum of +1

Code:

$plus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = 1 GROUP BY content_id ORDER BY sum DESC, nid ASC");
                                         $minus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = -1 GROUP BY content_id ORDER BY sum DESC, nid ASC");

                     $pluses = array();
                                         $minuses = array();

                     while ( $row = db_fetch_object($plus_rates) ) {

                                            $pluses[$row->nid] = $row->sum;

                     }

                                         $plus_rates = NULL;

                                         while ( $row = db_fetch_object( $minus_rates ) ) {

                                            $minuses[$row->nid] = $row->sum;

                                         }

                                         $minus_rates = NULL;

                                         $keys = array_keys($minuses);

                                         foreach($keys as $k) {

                                                if (array_key_exists($k, $pluses)) {

                                                        $pluses[$k] = $pluses[$k] - $minuses[$k];

                                                }

                                         }

                                         arsort($pluses, SORT_NUMERIC);

                                         firep($pluses, 'pluses');

$pluses is sorted DESC but order is totally different from my view display:

Sort cirteria: (Vote results) Vote results: Function desc)
Relationship Node: Vote results, Aggregation function: total score

EDIT 2

I try to query votingapi_cache directly but still order is totally different than in views:

  SELECT value, content_id FROM votingapi_cache WHERE value_type =
  'points' AND tag = 'vote' AND FUNCTION = 'sum' ORDER BY value DESC
  LIMIT 0 , 30

Check the comments on this question: Problem visualizing the rating value inside a view

It sounds like you probably haven't set an aggregate function on the Node: Vote Results relationship. You cab definitely display the total votes in a View without writing any of your own code.


Add css file to the Admin Theme of the Commerce Kickstart distribution? I'm trying to add a css file to the Admin Theme (for Backend) of the Commerce Kickstart distribution.

I tried this in a custom module, but not working, the css file is not loaded at all.

drupal_add_css(drupal_get_path('theme', 'commerce_kickstart_admin') . 'css/overrides.css', array('group' => CSS_THEME, 'type' => 'file'));

I created the css file at:

profiles/commerce_kickstart/themes/commerce_kickstart_admin/css/overrides.css

Also, is there any way to put the css file in other location? like:

  site/all/themes/mytheme/css/overrides.css

I would strongly suggest to create a subtheme for additional CSS. That's what subthemes are for, after all, and it's less work than to make a module. Simply use info file and it's stylesheets[all][] entry.

If you have time, you can investigate how AdaptiveTheme allows GUI editing of CSS, and implement this in your custom theme. AT is open-source after all, so it would be legal to copy-paste this functionality. It will make your life easier for future:


Tokens available in views I am trying to change the output in my view; the problem is that I cannot access the [URL] token to rewrite to this is my link.

It seems I can only access the [title] token. Do you have any idea?

The tokens available when rewritting the output of a field correspond to the values of the other fields you have selected in the view. They must also be above the field you are rewritting in the field order.

In order to get the URL, you should add a node path (or link to node) above your current field and mark it as "hide from display".

The token will now be available!

PS - If you want to link to the node's url, you can always just select the option to display the field as a link to its node.


How can I get major version updates with drush pm-update? I often check for updates to my modules using drush pm-update.  However, this check does not check for succeeding major versions.  For example, if I am using Mollom 1.1, drush pm-update will not alert me that there is a 2.3 version available as well.  Is there a way to tell drush to give me all possible updates, including major versions?

You can explicitly ask Drush to tell you all of the available releases for a specific project using the pm-releases command:

$ drush pm-releases mollom
------- RELEASES FOR 'MOLLOM' PROJECT -------
 Release         Date         Status
 7.x-2.x-dev     2012-Dec-19  Development
 7.x-2.3         2012-Oct-22  Supported, Recommended
 7.x-1.x-dev     2011-Dec-20  Development
 7.x-1.1         2011-Jul-09  Supported, Installed

However, what you want to do -- to have pm-update(code) automatically notify you when there is a newer major release -- is not supported.  I have opened a feature request in the Drush issue queue for you:  http://drupal.org/node/1880970

UPDATE:

Regarding kiamlaluno's comment, you can force the update using pm-download:

$ drush dl mollom-7.x-2.3
$ drush updatedb

I think that it would be more difficult to write a script to check for updates with pm-releases than it would be to enhance pm-updatecode to show this information.  If you'd like to help out, please post a patch at the issue I linked to above.


How to replace allowed_values for a select field by external definition? I created a custom content entity, called member, with some fields of which one, called status, is a list appearing in form as a select:

$fields['status'] = BaseFieldDefinition::create('list_integer')
  ->setLabel(t('Statut'))
  ->setRequired(TRUE)
  ->setSettings(array(
    'allowed_values' => array(
      0 => 'Ancien',
      1 => 'Actif',
      2 => 'Non renouvelée',
      3 => 'Renouvelée',
      4 => 'En attente',
    ),
  ))
  ->setDefaultValue(4)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'weight' => 7,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'options_select',
    'weight' => 7,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I'd like to put the definition of the allowed values 'somewhere else' (meaning not directly in the definition of the member entity).
I know I could create another content entity (e.g. possible_status) that I would reference this way:

$fields['status'] = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'possible_status)')

But it seems a bit 'rich' to handle a couple of values...
Is there another way to store the values 'outside' the code defining the member entity?
An include file, a text file, a JSON file I could import?
What would be the best practice for that?

[EDIT]
I changed for this:

$fields['status'] = BaseFieldDefinition::create('list_integer')
  ->setLabel(t('Statut'))
  ->setRequired(TRUE)
  ->setSettings(['allowed_values_function' => 'association_allowed_values_function'])
  ->setDefaultValue(4)

with this in my module:

function association_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {

  if ($definition['entity_type'] == 'member' && $definition'field_name' == 'status') {
    $values = [
      0 => 'Ancien',
      1 => 'Actif',
      2 => 'Non renouvelée',
      3 => 'Renouvelée',
      4 => 'En attente',
    ];
  }
  return $values;
}

and it works!

Now, I'd like to move association_allowed_values_function to an include file.   And I don't know how...

Instead of allowed_values you can add a callback to set the allowed values:

  ->setSettings(['allowed_values_function' => 'callback_allowed_values_function'])

The callback:

function callback_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {
  if (isset($entity) && ($entity->bundle() == 'not_a_programmer')) {
    $values = [
      1 => 'One',
      2 => 'Two',
    ];
  }
  else {
    $values = [
      'Group 1' => [
        0 => 'Zero',
        1 => 'One',
      ],
      'Group 2' => [
        2 => 'Two',
      ],
    ];
  }

  return $values;
}

You can get the allowed values from a text file or put the callback in an include file.

For more information see options.api.php

A different approach might be to store the allowed values in config, for which there is a bundle specific base field override, see How to easily alter an entity's base field definition per bundle. Then you can manage the allowed values list in a yaml file of an exported config.


List field: translated values are not translated In my Drupal 8 project I have some list fields. For example maybe a field "project type" with the following key|values, coming from the original language German:

1 -> öffentliches Projekt
2 -> privates Projekt

Which I translated in the field's settings:

1 -> public project
2 -> private project

The field is NOT set to be translatable because the value should not be changed in a translation: the project type is in all languages the same! But now when I go to the node edit page, when I view the node or when I add this field as exposed filter to views I always see the German values of the field no matter what is set as the current language of the page. When I change the field to be translatable the value of the list field can be changed in English translation -> so it can come that a project is "public" in German and "private" in English what is not the desired result.

How do I get the translated values of a list field to be used in form element and node view when the list field itself should not be translatable?

Ok, it seems that it was just a weird cache thing. I cleared the cache several times after changing these translations. Now the translated values of the select list appear without setting the field to be translatable.


How could I allow content editors to send email to a selected bunch of users? I have a content editor that wants to be able to send emails on a regular basis to a selected bunch of users. Could I create a view of all site users and use Views Bulk Operations for this?

If your content editors need to be able to select the group they are contacting  you can use Views Send. You can also use Rules (and probably Views Rules to ease the process of writing the rule some) particullarly if the editors are not going to be editing the message (if they are sending a notice about content updates or something similar).


Services Views not exposing thumbnail image url I am trying to create a view which will be exposed as a service via Services Views module. I have only defined Default display for this view and added the following field to the list of Fields -

Node: Nid Nid
Node: Type Type
Node: Title Title
Profile: Author Info: Full Name Author Name
Node: Post date Post date
Node: Teaser Teaser
Node: Promoted to front page Promoted to front page
Node: Last edited by Last edited by
Node: Updated date Updated date
Content: Thumbnail URL to file

All the fields are appearing nicely when I request it (using this url: http://localhost/app/rest/views/articlelist?args[0]=1), but the last field, which is the url to thumbnail file isn't appearing there.

A sample response from the above url is as follows -

<item>
<nid>22</nid>
<type>Article</type>
<title>UK soldier killed in Afghanistan</title>
<author_name>Demo Journalist</author_name>
<post_date>Jul 1 2012 - 4:08pm</post_date>
<teaser>
<p>&nbsp;ret rre tre tretre trtretre tre t re t&nbsp;ret rre tre tretre trtretre tre t re t&nbsp;ret rre tre tretre trtretre tre t re t&nbsp;ret rre tre tretre trtretre tre t re t&nbsp;ret rre tre tretre trtretre tre t re t&nbsp;ret rre tre tretre trtretre tre t re t</p>
</teaser>
<promoted_to_front_page>Yes</promoted_to_front_page>
<last_edited_by>admin</last_edited_by>
<updated_date>Jan 2 2013 - 3:56pm</updated_date>
</item>

What do I need to do to display the related thumbnail url?

Edit

Here is the query that is being executed (obtained from preview) -

SELECT node.nid AS nid, node.language AS node_language, node.type AS node_type,
       node.title AS node_title,
       profile_values_profile_full_name.value AS profile_values_profile_full_name_value,
       profile_values_profile_full_name.uid AS profile_values_profile_full_name_uid,
       node.created AS node_created, node.promote AS node_promote,
       node.changed AS node_changed,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_fid AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_fid,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_list AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_list,
       files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_data AS files_node_data_field_thumbnail_image_node_data_field_thumbnail_image_field_thumbnail_image_data,
       node_data_field_analysis_box.field_analysis_box_value AS node_data_field_analysis_box_field_analysis_box_value,
       node.vid AS node_vid
FROM node node  LEFT JOIN content_type_article node_data_field_thumbnail_image
ON node.vid = node_data_field_thumbnail_image.vid
LEFT JOIN files files_node_data_field_thumbnail_image
ON node_data_field_thumbnail_image.field_thumbnail_image_fid = files_node_data_field_thumbnail_image.fid
INNER JOIN term_node term_node
ON node.vid = term_node.vid
INNER JOIN users users
ON node.uid = users.uid
LEFT JOIN profile_values profile_values_profile_full_name
ON users.uid = profile_values_profile_full_name.uid AND
    profile_values_profile_full_name.fid = '1'
LEFT JOIN content_type_article files_node_data_field_thumbnail_image_node_data_field_thumbnail_image
ON files_node_data_field_thumbnail_image.fid = files_node_data_field_thumbnail_image_node_data_field_thumbnail_image.field_thumbnail_image_fid
LEFT JOIN content_type_article node_data_field_analysis_box
ON node.vid = node_data_field_analysis_box.vid
WHERE (node.status <> 0) AND (term_node.tid IN (1, 2))
ORDER BY node_changed DESC, node_created DESC

It's a bit unclear what you have in your view, but here are some suggestions:

Make sure you have Formatter set to "Image URL", and the "Image Style" set to the specific style (ie thumbnail)
Ensure that you actually have some data for your filter. "No Results Behavior" may have "Hide if empty", which would omit this field in your response if it's not set.
Enable showing the query and results for the view to at least check that the return data contains the value that you expect (admin/structure/views/settings -> [] show performance statistics)
Check that your contextual filter is not obfuscating something - remove the args[0]=1
Ensure that the normal Page response for the view displays a value for the thumbnail field, by going to the "path" that you've defined for the view.


How to disable access to file page (view display mode = full)? I want to disable access to the view display page of file by url like file/fid.

What's the good way for this? I have tried to use the hook_node_view() but it not called for the files.

I have finally used the RABBIT HOLE module, it contains a sub-module for managing file_entity! :)


How to use a views contextual filter OR? After browsing the net and SE for a while it appears to me there is no good solution to combine 2 contextual filters with OR (rather than the default AND).

This post mentions a PHP hack and this post has some links to an issue stating a recent change in views 7.x-3.1.
It also mentiones using hook_views_query_alter(&$view, &$query) to modify the view.

Does anyone have a working example or a better solution?

Try the patch in this issue : Pull filter value from an argument

It allows you to pass the value from the contextual filter to the "normal filter". There you can do your advanced conditions.


How to list node parent's children Sorry if this is a repeated question, tried many suggested options but no result.

There is business model of 1 to N relationship "parent and children".

I am working on a project where i have a content type building as parent and apartment as child. within a building there could be  N number of apartment and every apartment has it is own contents. something similar to attached screenshots

Parent :

Children :

-Building #1
 --Apartment #1
 --Apartment #1
 --Apartment #1
 --Apartment #1

I guess there are few modules which could help "Reference module, Entityreference, Views and  Taxonomy"

To list all nodes of the parent, i.e. siblings.

// Node ID to to search by
$nid = 1;

// Load Node
$node = node_load($nid);

// Get Node's Content Type
$type = $node->type;

// Search for siblings
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $type)
  ->propertyCondition('status', TRUE); // Get only active nodes
$result = $query->execute();

// Load Sibling Nids
$nids = array();
if (isset($result['node'])) {
  foreach ($result['node'] as $node) {
    $nids[] = $node->nid;
  }
}

// Load Sibling Nodes
$nodes = node_load_multiple($nids);

Building relationships

In regards to structuring a 3 tier relationship, I personally use Entity API and simply reference Nodes to Terms. In cases where I need to create a relationship between Nodes only, I've used an Entity Reference module, or now, I just create a module, which attaches a field with an option to enter a referencing node.

You may also want to check out a Relation module, which has a more complex use to it.


Edit profile2 tab in view profile2 rendered with views I have a profile created using profile2 module. I want this profile to be rendered as a separate page and I have done so using views. The profile can be viewed in a url: www.example.com/application/authors/username.

I want to provide to the owner of the profile a tab on the page for editing it.

This should be simple using hook_menu, but it doesn't seem to work for me.

function MY_MODULE_menu() {
  $items['application/authors/%author/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile2', 1),
    'access callback' => 'MY_MODULE_access_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

Is the above code correct? Do I need to register the view as a parent tab?

Profile2 provides a submodule Profile2 pages which does exactly that: allows the ability to render the profile separately and includes an Edit tab.


How to create a module to insert some analytics code in the footer of website pages? I want to create a module for Drupal 7, with a simple scope. It's just to insert the analytics code in the footer of website pages and with an option to exclude some pages if required.

I just need a module configuration page with 1 text field to enter the Analytics ID. And a text area below it, just like in blocks configuration page, which allows you to show the block on specific pages.

After this info is saved, the code should be inserted in the footer of each page, with that Analytics ID.

Can anybody tell me what hooks I will need to implement this functionality?

These two links should get you started:

https://www.drupal.org/node/206761

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_page_alter/7


How to move every node to its own subdomain with Drupal? I have a content site that was affected by Google Panda, and recently it was suggested that it is advised by Google that moving content to subdomains might work.

Does anyone have a working solution to move aliased nodes to their subdomains so
mysite.com/subfolder/my-great-content
moved to
my-great-content.mysite.com ?

I found this but seems to be abandoned:
http://drupal.org/project/subdomain

Also this which is very advanced:
http://www.easymodrewrite.com/example-subdomains

Or is multisite the way to go? I notice drupalgardens.com has subdomains for user pages.

Also found another method that uses the PURL module for Open Atrium, described here: https://community.openatrium.com/documentation-en/node/708
I guess this could be combined somehow with a wildcard subdomain setup? I notice it even has a subordomain module
http://drupal.org/project/subordomain

Here is a general solution
https://stackoverflow.com/questions/1943356/creating-subdomains-programmatically

A couple years later... I have a similar requirement.

The Subdomain Field module works well for me. https://drupal.org/project/subdomain_field

Has clear installation instructions: edit your settings.php, update your virtual host, add a wildcard DNS record. Then simply install the module and add a "Subdomain Field" field type to any content types that you want.

Now when I edit /node/2 and change the subdomain, I have subdomain.example.com displaying the contents of node 2. Perfect!

Note that it requires the Entity API module, but that is currently not listed as a "requirement"


How to add two products in one click In my Drupal Commerce site, I have a product type - an attribute which refers to another product type (via reference product).

The display is:

Type 1

Product 1-1 x

Product 1-2 x

Product 1-3 x

Add to Cart

Type 2

Product 2-1 x

Product 2-2 x

x produces 2-3

Add to Cart

I would like only one "add  to cart" button to be visible, and that clicking it should add  two products which were selected at the same time.

How can this be accomplished?

I would do this with rules:

Event

After adding a product to the cart

Action

Add a product to the cart

Parameter: User: [site:current-user],
Product SKU: [other product
sku] Provides variables: Added product line item
(product_add_line_item)


Drupal Local and Dev Database I have a Drupal Environment that deploys to GitHub as well as my server. The only issue is I have local database credentials and server database credentials. For now when I do my merge/push, I have to manually change the settings file to make sure I don't connect to the server db and make local changes.

Is there a way to connect to a local database when appropriate and a server database any other time. I tried to use a different connection in the settings.local.php file, but it didn't seem to work.

in your settings.php, uncomment

# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

so it looks like this:

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

then in the same directory edit the settings.local.php to have your local settings.

Then add settings.local.php to your .gitignore file

That way, you can keep local settings that differ from the settings on dev.

So your dev server would have it's own unique settings.local.php file that differs from your local settings.local.php file.

If you need to check your database settings, you can add this at the bottom of settings.php

dump($databases); die();

You should see your correct settings (you can do this on both your local and your dev site to verify, then remove the dump command once you have verified.


What is the true impact of Panels Everywhere on theming and layout duties? From an answer on another question:

  If you have chosen Precision because it is minimalist, then you might
  want to consider adding the 'Panels Everywhere' module. This module
  works very well with Panels (same authors) and allows you to bypass
  the Drupal Theming process altogether. This greatly simplified my
  styling work.

Does this mean regions and blocks are completely ignored with Panels Everywhere (PE) in favor of panels only?
If so, does it mean one has to recreate some layout for standard pages such as node edition and publishing for example? I have an editor user profile to create specific content. Do I loose all the layout of existing Drupal screens the user could access?
After enabling PE, what configuration is expected regarding layout and theming (CSS) on standard pages delivered by Drupal?

Fact is, when trying PE with the Precision theme, I lost layout on all standard pages, but I want to know if this is a configuration issue or not.

From my own findings:

Yes. In fact, one can set a site template which (more or less) replaces the concept of regions.
No, one should set a site template and not forget to have a Page Content pane.
None, except for the site template itself. Eventually, some can be set on the Page Content too.


Can't update hook_theme after clearing the cache I have a hook_theme instance in my template.php which outputs various components in my theme. I want to add an extra argument to one of the templates but no matter what I do it doesn't update. I have cleared the cache (using drush and not), removed the theme array, cleared cache and added back in. I have even truncated all the cache tables - but somehow it's still picking up the old function. Is there something stupid I have missed?

template.php

function MYTHEME_theme() {
  return array(

    'featured_blocks' => array(
      'arguments' => array(
        'blocks' => NULL,
        'image_format' => 'test!',
      ),
      'template' => 'featured-blocks',
      'path' => drupal_get_path('theme', 'MYTHEME') . '/templates/other'
    ),

  );
}

featured-blocks.tpl.php

<?php

printr($blocks); // blocks are all here
print $image_format; // this is undefined!!!

Calling the hook theme

<?php print theme('featured_blocks', array(
            'blocks' => $wrap->field_my_blocks,
            'image_format' => 'this is a test'
          )) ?>

After doing a bit more reading I restarted my MAMP server and switched themes, then back again. I'm not sure which did it but it's working now...


Get paragraph field in a specific text format I have a landing page with a list of paragraphs. I'm trying to render the main body paragraph field as a summary to use in a metatag in the header.
$basic_content_block->get('field_content')->first()->getValue();
Returns:
[
    'value' => "
Some rich text here. "basic_html"
]

How can I return this field as a teaser view, or more appropriately, a summary of just the text?

$basic_content_block->get('field_content')->summary;

I believe that should do it.