Clearing cache failed to add the new CSS properties For Drupal 7, I'm using

Cache pages for anonymous users
Compress cached pages.
Aggregate and compress CSS files.
Aggregate JavaScript files.

The problem is when I update the CSS code for one of my CSS file, the code doesn't show in my page.

I have tried to Clear all cache and even run cron, but the new CSS code doesn't get added to the cached and minified version of my CSS.

The only workaround is just to disable "Aggregate and compress CSS files."

Any thought on this will be helpful.

Your Drupal is not able to write inside DRUPAL_ROOT/sites/*/files/css directory. That's why aggregated CSS files are not renewed. Consult your sysadmin to correct permissions and allow Drupal full write access inside DRUPAL_ROOT/sites/*/files and all subdirectories, that should solve it.


Sharing content with domain access? I setup a site with domain access. It has 2 subsites.
I want to publish content from the main site to the subsites. This is already working good with send to affiliates. But I want some local admins on the subsites to have the permission to decide if they want to use the content or not. Is it even possible with domain access or is it just one way from top to bottom ?

One solution I did recently in a similar situation was just create a views xml feed of the content I want to feed to my subsites. From there my subsites would have the feed_import module and have to fetch the articles every 10 minutes. Once fetched it will be unpublished but can only be viewed by certain roles for screening.

Now as for the left over imported nodes I would use node_purge to delete nodes that are X days old. Obviously this solution wouldn't be ideal for sites with sensitive data as the xml feed is exposed.


Altering database tables belonging to core modules Using D6's date_api.module module, I noticed that the .install uses db_add_field() to add a "timezone_name" column to the {users} table, and hook_schema_alter() to declare that change.

I was surprised to see a module alter a core module's table, and would have instead expected date_api to create a {date_user_timezone_names} table with "uid" and "timezone_name" fields (and subsequently a hook_user($op='load') to add a timezone_name property to the user object).

The advantages of simply adding a column to another module's table are obvious to me. I'm interested in hearing what the disadvantages are. Are there any gotchas that one should be aware of?

Yes, I'm not sure altering core tables is a good idea.

I don't see any problem with it, as long as you just add fields.

But I remember having seen some code here and there that cycles through all the fields in a table, so even this might cause problems.

It's a bit personal and question of belief, but as far as I can, I try to make my code as something that can work with core's code and structure. I've seen too many devs going in implementation hell with decisions like that.

Also, having to alter what's already been designed by big teams and/or big guys like core devs is very often due to a bad analysis of the use case.

My general advice for anybody who's lower than core dev level (including me, of course) would be : don't do it.


Show content type form to block I've created one content type named Newsletter. And I want to display that content type form to block. I've tried with this code but failure. Your suggestions will be appreciated.

$my_module_form = drupal_get_form('blog-node-form');
$my_module_form = drupal_render($my_module_form);

Using contrib modules will certainly help for this. There are at least two I can think of:

Form Block (https://www.drupal.org/project/formblock)
Advanced From Block (https://www.drupal.org/project/afb)

To answer your question, however, you need to instantiate a new (or existing) node object to set as your form_state (Assuming the machine readable name of your content type is "newsletter").

global $user;
$node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'newsletter', 'language' => LANGUAGE_NONE);
$form_state['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('newsletter_node_form', $form_state);

If you want the form to edit an existing node, the you can replace the $node = (object) part with a node_load([nid]) function.


How do I re-create a built-in view? I duplicated a view before making changes, but it didn't save and I'd changed most of the view settings before I realised I was working on the original.
How can I recreate the standard taxonomy view?
I am using Drupal 9, if that makes a difference.

Export your current config using drush cex -y
Copy/paste the /web/core/modules/taxonomy/config/optional/views.view.taxonomy_term.yml into your config directory (usually /config)
Import the config using drush cim -y


How to alter existing page of a node that is Organic Group and add Two links above i am using Drupal 7 with og support and also the og corresponding modules (og, entityreference, services_menu) inside DrupalGap.

As can be seen from the picture i want to add some links(drawed in red color) on top of the display of an Organic Group. I want the subscribe/unsubscribe button AND the navigation buttons above.

Create a Custom DrupalGap Block
Place it above the title block within the region configuration of the settings.js file
Use a List Widget and some CSS to render your buttons above the title


Using symlinks / multisite to display one drupal site at two domains Does it create any problems for me to use symlinks to display the same drupal site at more than one domain? It appears to work, but I'm not sure if bugs might appear in the future due to scripts being misinterpreted as XSS attacks or something.
Example
I own two domains, sweet-bro.com and hellajeff.net . They're hosted on the same account, such that people who go to sweet-bro.com see the files in ~/sweet-bro/html and people who go to hellajeff.net see the files in ~/hellajeff/html
There's a drupal 7 site at http://sweet-bro.com/drupal and I want visitors to see the same site if they go to http://hellajeff.net/ruse . So, first I make a symlink in the html directory:
ln -s ~/sweet-bro/html/drupal  ~/hellajeff/html/ruse

Then I make a symlink in the sites directory:
ln -s ~/sweet-bro/html/drupal/sites/default  ~/sweet-bro/html/drupal/sites/hellajeff.net.ruse

This is what I've done and it seems to be working. Is there any reason not to do it this way?

I don't think it's going to cause any problems, but it seems you just make things complicated for no reason. So, that would be a reason not do it that way :)

Just point both domaines to ~/sweet-bro/html and get rid of the symlink in /sites/.

Both domains will be showing the same site, as long as you don't use a .htaccess rule to redirect to one or the other.


How to display node when view contains only 1 item? I have a custom view which displays all nodes of a specific content-type off the main menu.  You can click on any of the teaser headers and see the individual node data.

I have been asked to display this drill down-detailed view if there is only 1 item in the main view rather than forcing the user to click through another layer to get to the detail view.

Any thoughts on how to hook into this and which hook to call to override the defined view and jump directly to the node view?

My approach is to count the views result first. If the result is only one I will get the node id and load it using entity_load_single and render according to whatever you want.

Pseudo code:

function hook_name_or_callback() {
  // Get the view.
  $view = views_get_view($view_name);
  // Based on $view you can get the views result.
  if (result_is_one) {
    $node = entity_load_single('node', NID);
    $node_view = node_view($node);
    return drupal_render($node_view);
  }
  else {
    // Just display the view.
  }
}

P.S: Haven't test this code and might not work for you.

See these:

https://api.drupal.org/api/views/views.module/function/views_get_view/7.x-3.x
http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.module/function/entity_load_single/7


Allowing users to create calculated views I am using Views 3 and I was able to do some math on the fields using the "Views Custom Field" module that was recommended to me.

It works perfectly and does exactly what I want it to do, but my problem is that I need to grant access to users to create views and calculations on them.  Views custom field is not really a math only field, it's basically allowing them to execute PHP code directly on my site, which I suspect is dangerous.

Also, another requirement is that they are not directly modifying the actual data, but creating a view for themselves(or to share) that derived from this data. That means the view they create must somehow be connected to their ID and not modify the master data.

I don't know if it is the best approach, but I was thinking of using something like phpexcel and exposing the tables so they can link to certain data; it seems complicated for me and even more complicated for the users.

How would you approach this?

You are right, you shouldn't allow people to change php code on your site.

I would allow a lot of customization to the data that is returned via views filters.

You can return the data in a table format and allow this table to be exported to excel or csv (there are views modules for both of these). Then people can create whatever they want.

There are a few js libraries which can give you spreadsheet like functionality in the browser with an HTML table, that may be an option too.


Changes in test version applied in live version as well On a D6 multisite setup, under the sites folder, there are a bunch of sites. Two of which are the sites testsite.domainname.com and domainname.com.
They have the folder structure I put at the bottom of this post.

So the problem is that changes made in the test version also seem applied to the live version, obviously with very
undesired results for the end users.
I checked the settings.php file to see if the same database would be connected to but the
data in both files are for different databases.

Changes applied to the test server that unintendedly have an effect on the live site
are not only limited to changes in the domain_custom.module file.
I noticed that changes made on the testsite in the page.tpl.php did the same thing;

testsite.domain.com
-modules
--domainname_custom
--nice_menus
-themes
--custom_theme
-settings.php

domain.com
-modules
--domainname_custom
--nice_menus
-themes
--custom_theme
-settings.php

Of course i have to ask the obvious here, did you check out multi-site install


View page doesn't output but views_embed_view with same arguments does? I have a view with a page display. A simple view with a few content types to display, and a contextual filter for taxonomy.

If I enter an argument in the views preview, it works as expected. Displays "no results found" for gibberish, and properly filtered nodes for taxonomy terms that exist.

If I put a views_embed_view in the page template with a hard-coded argument, it also displays as expected.

<?php print views_embed_view('explore', 'explore', 'About-Us'); ?>

My problem is that if I go to the page path www.site.com/explore/About-Us I get nothing. No errors, no "No results" dialog, no results. The content array is completely empty.

I've done dozens of views pages, with arguments and without, and never had this problem. Does anyone have any ideas?

I knew the answer would be stupid.

I had registered the path I was using for my view's page in a module a couple months ago and forgot. ><


How to theme table row to link particular column data? I have created a list of table records in admin section using the following code.

class userDownloadedFiles extends ControllerBase{ public function userList() {
$header = array(

  array('data' => $this->t('Username'), 'field' => 'name', 'sort' => 'asc'),
  array('data' => $this->t('Email'), 'field' => 'mail', 'sort' => 'asc'),
);

$db = \Drupal::database();
$query = $db->select('users','u');
$query->innerJoin('users_field_data','ufd','u.uid=ufd.uid');
$query->fields('ufd', array('name','mail'));
$table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')
                    ->orderByHeader($header);
// Limit the rows to 20 for each page.
$pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')
                    ->limit(20);
$result = $pager->execute();

// Populate the rows.
$rows = array();
foreach($result as $row) {
  //Get URL to user profile
  $profile_url = \Drupal::service('path.alias_manager')->getAliasByPath('/user/'.$row->uid);

  $rows[] = array('data' => array(
    'name' => "$row->name",
    'mail' => $row->mail,
  ));
}

// The table description.
$build = array(
  '#markup' => t('List of users who have downloaded model drawing or requested an account for downloading one.')
);

// Generate the table.
$build['user_info_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#empty' =>t('There are no records yet.'),
  '#rows' => $rows,
);

// Finally add the pager.
$build['pager'] = array(
  '#type' => 'pager'
);
return $build;  }}

But the a tag used in username column is displayed as it is not appearing as link. This is how it appearing

Please guide me how to make it likable and how would I do it for other columns too.

You can try using the render element syntax for a Link element, like this:

$rows[] = array(
  'name' => array(
    '#title' => $row->name,
    '#type' => 'link',
    '#url' => $profile_url
  ),
  'mail' => array(
    '#title' => $row->mail,
    '#type' => 'link',
    '#url' => 'mailto:' .  $row->mail,
  ),
);

That way you can stick to a more consistent coding style, i.e. render arrays for presentation.


Display blockquote of text in article post, while showing original Can anyone provide an idea for how I can add a block quote in an article post where that text is also in the body of the message?

What I mean by this, is that right now when one of our users wants to create a blockquote, they use the CKeditor WYSIWYG module and choose 'blockquote'. What this does is highlight that specific text as a blockquote. What I am more looking for is the ability of the writer to choose what they would like to have as a blockquote and also see that same text again where it belongs in the article.  Please see the image below for what I mean.

Ideally it would be great to have certain text highlighted that it is a blockquote. Then have that blockquote be right next to the original.

Update: I just talked with our themer and maybe the best solution is to highlight any text that we want blockquoted and include it in there twice. Then we can style the text with CSS that has the blockquote tag. But if there is a better way, then great!

You can style the block quote using the blockquote {} tag in CSS.

For example, something similar to the image you uploaded...

blockquote {
float:left;
margin:20px;
font-size:1.2em;
color:red;
}

However, your client would need to enter the piece of text twice.


Block inside another block I'm using jquery countdown timer, I want to but it in the main page content block. How do I put a block inside another block?

From the url /admin/structure/block you can set Blocks to Regions on your site.
You simply drag and drop the block(s) to the given Region of your page and Save the block ordering on that page. In this screenshot I have 3 blocks in the main content area for my theme:

You can then go into each block with the configure link and set that block to show only on certain page(s) for instance, or only for certain Roles of the site.

This is the simplest means using Core drupal and no 3rd party modules.

If you want to eventually look into other means of doing this look into the Context module, or Panels.


How can I use xx time ago in Drupal 8 comments? I use Drupal 8 and want the date of comments just show "xx time ago".

I added this code to mytheme.theme, but it does not work:

function mytheme_preprocess_comment(&$variables) {
/** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
$date_formatter = \Drupal::service('date.formatter');

$variables['foo'] = $date_formatter->formatDiff(REQUEST_TIME - 12345, REQUEST_TIME, [
'granularity' => 3,
'return_as_object' => TRUE,   ]); }

And I use {{ foo }} but that does not show "time ago" either. Other things I tried (and which didn't work either):

{{ created|date_modify }}
{{ created|time_deff }}
{{ created }}

Any help/hints about how I can do this?

Note: using the same logic as in my previous question (How can I use 'xx time ago' as date format?) and using MYTHEME_preprocess_comment instead (as suggested by Neograph734) does not seem to work for comments.

Have a look at what is mentioned on "Formatting the way the date/time is displayed in Drupal 8". Here is a quote from it:

  You can change the date format for comment using template_preprocess_comment(). For example, normally in comments the comment created time is displayed like Thu, 12/17/2015 - 23:04. We can change the format to look like 3 weeks 5 Days ago.

And this is the sample code mentioned below it:

/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}

I haven't tested this code (yet), but it looks pretty close to what you're asking for ...


How to access Views administration in Commerce Kickstart 7.x-2.9 I can't seem to get into the Views administration panel from any place in Commerce Kickstart 7.x-2.9.  There is no menu entry even with Administration menu installed.  Trying to configure via the link for Views on the modules admin page simply sends the page to the Administration menu with no "Views" option.  Likewise directly entering siteurl/admin/views goes to the same place.

I guess the Views access is overridden by the Kickstart configuration.

Does anyone know a way around this?

If you have not made any changes and are logged in as admin then the menu link should be under Site Settings -> Visual and Layout -> Views


Custom text between webform elements Is is possible to insert user-editable text as a form component?

I would need some custom text between the "email" and "name" fields. How do I achieve this?

Assuming you are talking about the Webform module, you can create an element with type of "markup".  There are a few options for this, including input format.  If you have everything configured properly, you can use a WYSIWYG editor on the fields, too.

If you are using the Form API, then you can use #type = "markup"; to put pretty much whatever HTML you want in your custom form.


How can I include a dropdown in menu_local_tasks tabs? I am trying to include a Bootstrap style dropdown in the local_tasks tabs on a section of my website. I thought I might be able to accomplish this with the 'theme callback' option of 'HOOK_MENU', but it doesn't run the custom callback. Any ideas on a good way to accomplish this?
Menu:
    $items['module/submenu/tab'] = array(
    'title' => 'Title',
    'page callback' => 'mymodule_menu_callback',
    'access arguments' => array('access content'),
    'theme callback' => 'mymodule_menu_local_task_dropdown',
    'type' => MENU_LOCAL_TASK,
);

Callback:
function mymodule_menu_local_task_dropdown($variables) {
 $link = $variables['element']['#link'];
 $link_text = $link['title'];
 $classes = array();

 if (!empty($variables['element']['#active'])) {
 // Add text to indicate active tab for non-visual users.
 $active = '' . t('(active tab)') . '';

 // If the link does not contain HTML already, check_plain() it now.
 // After we set 'html'=TRUE the link will not be sanitized by l().
 if (empty($link['localized_options']['html'])) {
  $link['title'] = check_plain($link['title']);
 }
 $link['localized_options']['html'] = TRUE;
 $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));

 $classes[] = 'active';
}

$classes[] = 'dropdown';

//haven't written this part yet
$dropdown = 'build dropdown';

return '
' . l($link_text, $link['href'], $link['localized_options']) . $dropdown . "
\n";
}

What I'm looking for:

For the drop-down menu you need include drop-down JavaScript in the "page callback". See drupal_add_library() function.

And I recommend for you pay attention to "CTools module".

"Drop-Down Menu" Code from CTools module:

  // Show examples of ctools javascript widgets
  $output .= '
' . t('CTools Javascript Widgets') . '
';

  // Create a drop down menu
  $links = array();
  $links[] = array(
    'title' => t('Link 1'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 2'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 3'),
    'href' => $_GET['q'],
  );

  $output .= '
' . t('Drop Down Menu') . '
';
  $output .= theme('ctools_dropdown', array('title' => t('Click to Drop Down'), 'links' => $links));


LDAP Configuration with Synology DSM We have Synology DSM (Disk Station Manager) Installed in our office, and my Drupal 7 site is hosted on it. I want to use Directory Users to use Drupal with same credentials using LDAP.

I installed the LDAP required modules, but I am still having trouble configuring and connecting.

Did anyone work with LDAP with Drupal?

We have successfully integrated Drupal with DSM using LDAP project: https://www.drupal.org/project/ldap

Basicall DSM is running OpenLDAP which is supported by the project. Be sure to enable php-ldap extension.

The ldap module distribution comes with a set of submodules that you enable to configure LDAP authentication and authorisation:

ldap_servers - define LDAP server
ldap_user - Sync users (User entity fields to LDAP attributes) with LDAP
ldap_authentication - Allows user to authenticate with their LDAP username/password
ldap_authorization - Give Drupal users roles based on LDAP group.

It also provides a comprehensive GUI to visually configure everything. Also integrates with 'devel' to debug.

HTH


Publish node link to social media on content creation I'm looking for a way to publish the node link to social media (Facebook, Twitter and Linkedin) on the creation of the node.

So what I would like is a little checkbox saying: publish to facebook on the node edit page.
Does anyone know a module that could help me achieve this?
Thanks !

Take a look at the twitter module:
https://drupal.org/project/twitter

You should be able to then use twitter to send that story to Facebook by hooking up your twitter account to your Facebook account. I'm not sure if the same is possible with linked in though.


How to make fields available to users in Drupal 7? I want users to participate in creating some content. I allowed them (people/permissions)  to create own content on particular content type. The question is: how to provide them access to fields of content type, that are available to me as administrator? In other words, I can put content in fields through my admin panel, but how to make users possible to meet that fields, how to make fields  public?
Thanks in advance!

Give "Create content" permission to the user type who can create content at your instance.

There is the Field Permission module which lets you specify permissions for each field in a entity. You can set permission for each field by help of this module.


How do I get all children's taxonomy term IDs? How do I get all children's taxonomy term IDs in Drupal 8?

$tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid); uses the taxonomy term name, not the taxonomy term IDs.

What happens if the taxonomy term names are equal?

You are close, but you want to pass some additional parameters to that method.

$vid = 'my_vocab_machine_name';
$parent_tid = 87; // the parent term id
$depth = 1; // 1 to get only immediate children, NULL to load entire tree
$load_entities = FALSE; // True will return loaded entities rather than ids
$child_tids = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $parent_tid, $depth, $load_entities);

See the api documentation for more info.


Can we create a feature for the changes in webform by using feature module? I am unable to create a feature for the changes in webform on development site to be used on production site by using feature module.Is it possible ?

Features does not give you the power to import/export the webform created.

You could use the Webform Share module.

For more details you could read the README.txt file of this module.


How can I create dynamic options based on the existing bundles from hook_drush_command()? I want to create dynamic options based on the entity types (returned by entity_get_info() function) inside the hook_drush_command(). There's no bootstrapped Drupal available at all, so the db_query() entity_get_info() functions aren't available. How can hook_drush_command() get site information?

(The module is inside the ~/.drush/mymodule directory.)

This should work. Drush bootstraps Drupal before discovering module commands, so the first step is to make sure your commands are defined in a drush.services.yml file as usual.

From there, you should be able to define dynamic options using hook options. Since Drush bootstraps Drupal prior to discovering module commands, you should find that the Drupal site is always bootstrapped when your hook is called. You can inject the services you need through your drush.services.yml file.

EDIT When I read through the comments I thought that you said this was working when you were using hook_drush_command, so I answered as if you were asking how to convert and do the same thing in Drush 9. I don't remember the internals of the convoluted Drush 8 bootstrap very well, but I'm not sure this is possible in Drush 8.


How to display content for specific user I created a content type Report. One of the fields name is MyUser and field type is EntityReference. For this field, widget type is SelectList and Target type is User.

I added two contents: Content1 and Content2. I selected UserA for the MyUser field in Content1 and I selected UserB for the MyUser field in content 2.

Now, I created a page view to select the content for the logged in user. If userA logged in, he should see only content1 and if userB logged in, he should see only content2. I thought I needed to add a filter criteria/relationship in view.

How to add the filter criteria/relationship to meet the above requirements?

Add an explicit relationship to the user, and mark it as required. After that you will be able to add a new filter criterion to your view: User: Current.


Creating Number fields (integer and decimal) manually in code for custom forms I need to manually render a number field in Drupal 7 on a custom form. I have created the following field definition:

$form['num_seats'] = array(
  '#type' => 'textfield',
      '#title' => t('Number of Seats'),
      '#required' => TRUE,
      '#number_type' => 'decimal',
      '#field_name' => 'num_seats',
      '#element_validate' => array ('number_field_widget_validate'),
      '#field_parents' => array(),
      '#language' => $language->language,
      '#field_prefix' => '$',
      '#size' => 14,
      '#maxlength' => 12,
      '#default_value' => $location ? $location['num_seats'] : $node->field_workshop_num_seats[$node->language][0]['value'],
);

However submitting the form produces an error of the form:
"preg_replace() [function.preg-replace]: Compilation failed: range out of order in character class at offset 14 in number_field_widget_validate() (line 391 "

If I use 'integer' instead of 'decimal' for 'number_type', it works fine.
I checked Number module's code and could see this is bcause of regex not being created correctly from field definition.

So my question is how can I manually render Fields outside of regular Drupal entity_type context (i.e. outside node/user etc. forms) in a custom form whose submission gets stored to a custom table.

After some googling and a bit of thought of how I've used stuff in the past. You're confusing a FAPI element with a Field Widget. They are not the same thing, this has been discussed before on Drupal.StackExchange. And is fully answered there in terms of why they are different.

I think your easiest solution is to create your own #element_validate function and not rely on the validate function provided directly by number_field_widget_validate -- but I would copy its guts essentially and create your own validate function from it. The preg_replace is failing because your FAPI element is not a Widget and has no $field['settings']. That's what I think is going on.


What is the execution sequence of functions while rendering a form? I have a form in my website with id: sample_test_custom_form. I have used hook_form_alter in a custom module  to alter this form. I also have a preprocess function (mytheme_preprocess_sample_test_custom_form) to do a little preprocessing.

However the alter function and the preprocess function are a little dependent on each other.

So I ask, what is the execution sequence of these function? Which of them is executed first?

Here's a diagram of the form build workflow in Drupal 7

More info: https://drupal.org/node/165104


Add a class to a image for a specific view I need add a class to a image for one specific views.
I tried:

theme_preprocess_field() but it doesn't work
theme_preprocess_image() but it's for all the images
I tried what suggested in Override image template for field image_formatter own, but it is too complex to simply add a CSS class
This answer is the more accepted but I like other ways

Is it possible to override a field/image template file for a specific view?

If your view is outputting fields (& not a teaser) you can easily do it in the views UI.

Edit your view
Click on the image field
STYLE SETTINGS > Customize field HTML > Create a CSS class
Save

Now your image field should have a class:


Forms display label elements as placeholder Do you have any solution for this?

I know I can hide labels via template.php but how to add placeholders to some inputs?

SOLUTION 1:

There is a function through which you can add placeholder to every text field based on its title.

function MYMODULE_auto_placeholders(&$element) {
  if ($element['#type'] == 'textfield') {
    $element['#attributes']['placeholder'] = $element['#title'];
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

Now in your form_alter() function just call this function;

MYMODULE_auto_placeholders($form);

SOLUTION 2:

To add placeholder to inputs of individual from you can use hook_form_alter .

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'id_of_form') {
    $form['your_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

SOLUTION 3:

There is also a module to add placeholder to form input.

Placaeholder:

  This project adds an extra FAPI attribute called '#placeholder' to textfield field elements. Often textfields should have some text in them like "Enter your text here" until the user clicks on (or tabs to) the element in question. At that point, the text should disappear and the user can enter his or her desired input.


Replace textfield value on ajax callback 1) Am i missing something here? it's not replacing the textfield value.
2) Also how do i replace if i have a multiple textfield and multiple button in a form.

<?php
    function test($form, &$form_state) {
      if (isset($form_state['values']['your_name'])) {
        $name_value = $form_state['values']['your_name'];
      }
      else {
        $name_value = "";
      }

      $form = array();
      $form['your_name'] = array(
        '#title' => t('Your or your company name'),
        '#type' => 'textfield',
        '#value' => $name_value,
        '#prefix' => '
',
        '#suffix' => '
',
      );
      $form['load_settings'] = array(
        '#type' => 'button',
        '#value' => t('Load my settings'),
        '#ajax' => array(
          'wrapper' => 'subscribers-name',
          'callback' => 'simplenews_mod_load_subscriptions_ajax',
          'method' => 'replace',
        )
      );
      return $form;
    }

    function simplenews_mod_load_subscriptions_ajax($form, &$form_state) {
      $form_state['values']['your_name'] = "loaded value";
      return $form['your_name'];
    }

function test($form, &$form_state) {
  $form['your_name'] = array(
    '#title' => t('Your or your company name'),
    '#type' => 'textfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (isset($form_state['values']['your_name'])) {
    $form['your_name']['#value'] = 'if';
  }
  else {
    $form['your_name']['#value'] = 'else';
  }
  $form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#submit' => 'simplenews_mod_load_subscriptions',
    '#ajax' => array(
      'wrapper' => 'subscribers-name',
      'callback' => 'simplenews_mod_load_subscriptions_ajax',
      'method' => 'replace',
    )
  );
  return $form;
}

function simplenews_mod_load_subscriptions_ajax($form, &$form_state) {
  return $form['your_name'];
}


Alter Add to Cart form POST data provided by #action I am going to be phasing out Drupal Commerce on our website in favor of a new custom built application that is hosted at another URL. Without completely rebuilding everything I am trying to override the Add to Cart form to redirect with POST data to the new app.

Using $form['#action'] I can redirect properly and dumping out shows something like this:

array(7) {
    ["quantity"]=>
    string(1) "2"
    ["product_id"]=>
    string(4) "8566"
    ["form_build_id"]=>
    string(48) "form--90fc5Yp9qgp4CVFJlq03jfEZyYBkAhDX-j7E5g9oBQ"
    ["form_token"]=>
    string(43) "T08Fl1dNHuI4BCZ4JuLNwxbw6gUTOfnodbc1zcQMR4E"
    ["form_id"]=>
    string(35) "commerce_cart_add_to_cart_form_8566"
    ["field_are_you_a_product"]=>
    array(1) {
        [0]=>
        array(1) {
            ["field_are_you_a_"]=>
            array(1) {
                ["und"]=>
                string(3) "yes"
            }
        }
    }
    ["op"]=>
        string(11) "Add to cart"

This is helpful but the product_id is useless as I need more info, like the SKU or a custom ID field I have on the product level. I can't seem to get this to provide me with the product info I need.

I initially tried using a custom submit handler instead but that didn't work. drupal_http_request isn't right as it just sends post data, does actually redirect with post data like action does.

So since setting the action works great, how would I alter this form to send more information during that step within hook_form_alter?

You can add other fields to your form as hiden, in the hook_form_alter for example add SKU field as hidden.

  $form['sky'] = [
    '#type'  => 'hidden',
    '#value' => YOUR_VALUE,
  ];

Hidden fields will submitted like others.


For settings.php $conf, how can I tell what a variable in Drupal 7 is named in Drupal 8? This article explains that using $conf in settings.php works differently in Drupal 8 compared to Drupal 7:

  The settings.php file could contain environment level overrides. Just
  remember how we disabled email sending on development servers in
  Drupal 7:

  $conf['mail_system']['default-system'] = 'DevelMailLog';

  That’s how it will look in Drupal 8:

  $config['system.mail']['interface']['default'] = 'devel_mail_log';

In Drupal 7, I used $conf to set different Google Analytics accounts per site environment like this:

  if (PANTHEON_ENVIRONMENT == 'dev') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-X';
  }
  else if (PANTHEON_ENVIRONMENT == 'test') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Y';
  }
  else if (PANTHEON_ENVIRONMENT == 'live') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Z';
  }

How can I determine what $conf['googleanalytics_account'] was renamed to in Drupal 8?

Unless the module's documentation tells you the name directly, you'll have to look for it manually.

You can search with drush:

drush config-list (cli)     List config names

Choose one of the names and display its whole content:

drush config-get (cget)     Display a config value, or a whole configuration object.

If you are using a lot of modules, that list may grow fast so you can narrow it down by inspecting the module to get an idea of how its data is structured.

Drupal 8 modules can ship with documentation in a .yml file in their config/install directory, which may include default values for configuration. It seems unlikely there would be a hardcoded default value for the equivalent of the googleanalytics_account variable, but you would at least be able to find the code fetching its value, something like this: \Drupal::config('googleanalytics.account');. *

There's also the new State API, meant to store information which could be different depending on the environment (dev vs production), or any other information you would not want to synchronize with different instances of the same system, like the last time automated jobs ran. If the module uses that, look instead for lines like this: \Drupal::state()->get('googleanalytics_account'). *

Once you've found what you think may be the correct key name, you can retrieve its current value using drush:

drush state-get key

The names used here are quick guesses based on the Drupal 7 names, the real code may use entirely different names.


How to show registration page in another language, maintaining its natural behaviour? I need to show my registration page in another language, keeping this separate from his natural behaviour. In particular this page must be showed in English on the page of the site it owns to, but i need to show it in Italian on another site into an iframe. Now, common sense tells me i need a page

 www.example.com/user

and a

 www.example.com/it/user

and i tried to achieve this by "admin/config/regional/language/configure" and the option "Determine the language from the URL (Path prefix or domain)." and all works fine, but, for some reason, as i activate this option, ALL my site pages get a "/en/" in their url, breaking a lot of things into the site (that is extremely complex). There's a way to achieve this behaviour for the registration page only? (be able to call a page www.example.com/it/user to show registration in italian and having www.example.com/user and all other pages in the site work without any changes?)

Navigate to /admin/config/regional/language within your site, and verify these things (and correct where appropriate):

Use "English" as your default language
use the "Edit" link for "English" on that page, which will bring you to "/admin/config/regional/language/edit/en". On that page, make sure the value for "Path prefix language code" is "blank".


db_query variable substitution I'm trying to substitute a variable in a db_query but keep on getting this error:

Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, string given

It's a single item string that I'm trying to insert:

$primary_key = db_query("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'mydatabase') AND (`TABLE_NAME` = '%s') AND (`COLUMN_KEY` = 'PRI')",$mytable)->fetchAll(PDO::FETCH_ASSOC);

I've tried wrapping the variable in an array but then I get no results. How do I substitute my variable here?

Drupal 7 doesn't use the '%' place holders.  Try this:

$primary_key = db_query("SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'mydatabase') AND (`TABLE_NAME` = :tbl_name) AND (`COLUMN_KEY` = 'PRI')", array(':tbl_name' => $mytable));


Filter by content type and shared taxonomy terms I want to classify my content within the following categories:

Technology
International Politics
Education
Religion
Sports

They are shared among my content types (e.g. news, page).
I want to create listing pages filtering by category, something like "news/international-politics" (notice the clean URL).

What is the best way to achieve this?

I've kind of done it with a shared taxonomy and a view per content type with an argument, but then I can't use the taxonomy links and have to build them by hand (cleaning the taxonomy name), but it's not a very clean solution.

To create the view

Create a view with appropriate fields/whatever.
Add the first argument Node: Type.
Add the second argument Taxonomy: Term.
For the second argument select Transform spaces to dashes in URL.

To create the listing page
Option 1
Bite the bullet and create the page in code. You just need to iterate over the content types and terms, creating the links as you go.
Option 2
Create a normal view that lists the taxonomy terms. Use link rewriting in the view to output a link that's contains the term name and content type, and is easily identifiable. Eg. custom_term_list/news/International Politics. Use custom_url_rewrite_outbound() to translate this to /news/international-politics. Gotta be careful not to slow the site down here.
Option 3
Use a terms as nodes paradigm. (I think this would work.) Create a content type for which each node will refer to a term. This can be done with taxonomy_node, nat (Node Auto Term), or even content_taxonomy (and maybe others for all I know). Add a computed_field that calculates the name of the term with spaces turned to dashes (or whatever). Then it would be easy to make the listing. If you want the node term to be created automatically when a term's created, then you'll need to use one of the first two modules mentioned.
Those are the only approaches I can think of to create listing pages. I think I'd just go for the first one.


Why is items list lagging? I'm exploring Drupal 8 Twig system.
After I altered menu.html.twig I tried to print out menu items list, but when I load the page after appending {{ dump( items ) }} it all stucks, page is not loading, Apache process is at 15% CPU. Why is this happening? Can I somehow print out all item's content?

I'm afraid twig's dump() is a resource killer. You can follow this issue on drupal.org for more information and alternatives: Twig dump crashes site/server with out of memory.

My advice would be to use Devel's kint() function, and you might want to track Symfony's Ladybug which is under development for inclusing in Drupal 8.3.


Load block programmatically, result: <drupal-render-placeholder I want to load a block programmatically:

$block = \Drupal::entityManager()->getStorage('block')->load('contextualcart');
$block = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
$blockMarkup = \Drupal::service('renderer')->render($block);

But the result is:

<drupal-render-placeholder callback="Drupal\block\BlockViewBuilder::lazyBuilder" arguments="0=velocontextualcart&amp;1=full&amp;2" token="5IaX-v_M8zGkro6F9hTE93zRfIj9p4nHeLFv8Ja6ZW0"></drupal-render-placeholder>

This is fine, because I have to insert a block in AJAX.

What happened? How do I fix it?

When calling ->render() it is rendering a structured array tree assuming that it is part of a whole page which will then do placeholder replacements later.

Use renderRoot() if you are the last instance and e.g. return this directly as an AJAX or JsonResponse.


How to set images path on libraries JS file in Drupal 8? I would like your kind help to point the correct path of images from JS.
I'm trying to change a DIV background using CSS and JS. Quite simple, right?
Well, not for me in Drupal 8.

My div loads the background defined in the CSS (my_module.libraries.yml)
The JS also works for changing positions of the layers (or DIVs, sorry, I'm from the Netscape times, old school).
But it doesn't work for setting the background because cannot find the images.
That means that there is no problems regarding routing neither configuration of the module.

So, the question is: How can I set the path for the CSS images in the JS libraries?

Here goes some codes:

My_module.libraries.yml

box-simulador:
  version: 1.x
  css:
    theme:
      css/box-simulador.css: {}
  js:
    js/box-simulador.js: {}

Excert from the CSS file

#SimHolder {
    background: url(img/pillow.png) left top no-repeat; /* << WORKS FINE! */

Excert from the JS file

function setTowel() {
 document.getElementById('SimHolder').style.backgroundImage='url(img/towel.png)'; // DOESNT WORK :(
 document.getElementById('textHolder').style.top='30%'; // IT WORKS!

I'm sure the answer would be quite simple ;)
Thanks in advance!

Weel, I found s solution, quite simple: just use {{directory}} on the template. ;)


Drupal 8 & Solr 8.1: No search results, error: "The datasource with ID '' could not be retrieved for index..." I have Drupal 8.7.1, Solr 8.1.
My Solr Server is running and my content is indexed.

But I have no results (with a query or without) in my view, and an error:
Drupal\search_api\SearchApiException: The datasource with ID '' could not be retrieved for index 'Solr search index'. in Drupal\search_api\Entity\Index->getDatasource() (line 365 of C:\Users\Oksana\Documents\sites\drupal2\modules\search_api\src\Entity\Index.php).

The function that produces this error in the indicated file is:

 /**
   * {@inheritdoc}
   */
  public function getDatasource($datasource_id) {
    $datasources = $this->getDatasources();

    if (empty($datasources[$datasource_id])) {
      $index_label = $this->label();
      throw new SearchApiException("The datasource with ID '$datasource_id' could not be retrieved for index '$index_label'.");
    }

    return $datasources[$datasource_id];
  }

As I understand, the Search API module receives no results from Solr.

If I type http://localhost:8983/solr/first_solr_core/select?indent=on&q= in browser, I get:

{
  "responseHeader":{
    "status":0,
    "QTime":1,
    "params":{
      "q":"",
      "indent":"on"}},
  "response":{"numFound":0,"start":0,"docs":[]
  }}

Which means, as I understood, that Solr has no results.

How can I find where is the problem (what happens with results after contents are indexed, and where results disappear)?

Thank you

Possible problem: "Search API Solr" module 8.x-2.7 does not support Solr 8.

Solution:

Remove "Search API Solr" module 8.x-2.7 using 'composer remove drupal/search_api_solr'
Install "Search API Solr" module 8.x-3.1 using 'composer require drupal/search_api_solr'
Find Solr modules in Drupal BO ("Extend" > "List") and click "Install" button
Add Solr Server in Drupal BO. I used solr path "/".
Download the configs zip folder from Drupal BO, copy files from the folder to the conf directory of the Solr core. (See details in INSTALL.md file in the module directory).
Restart solr server.
In Drupal BO in my Index configs select the name of my Solr server.
Go to the Index in Drupal BO. Click to run the index of content.
Go to my previously confiured view. See search results and search!


Search box result => node add (searched string = node title) What I want to achieve is quite simple, when performing a search trough the search block , instead of receiving the message "your search yielded no results" when the searched string is not in the DB I would like to have the possibility to add it as a node (question box "do you want to add yes or no?) , so the searched text would be the new node title.

This is probably because of not indexing the content after adding it. You can re-index the site by visiting http://<your-site-url>/admin/config/search/settings and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.


How does the Drupal session system work? I would like to implement the familiar "Remember me" functionality on user login forms, i.e. if a registered user leaves the browser without hitting the log out link, (s)he will still be logged in when visiting the website afterwards. A quick search leads to the Remember me module, whose description states:

  (...) the default Drupal behaviour is to remember your session for the extent of 3 weeks and 2 days. (...) Can you imagine the colossal risk this places on users accessing your service from public terminals or shared workstations, with no means to their disposal of securing themselves against this threat.

If the first sentence is true, it seems that I do not need the module to accomplish my need. Indeed, I can safely exit Firefox without loosing my session for "a while" (I do not know the exact time interval). However, other users on my website complain that they are immediately logged out after closing their browser.

So now I want to know the ins and the outs of the matter. Are sessions handeled differently for different browsers and, if yes, why? Does Drupal remember sessions for the extent of 3 weeks and 2 days and, if yes, why was this long time interval chosen? Is not using a module like Remember me indeed a risk?

Drupal has a pluggable session handler, however it generally uses a cookie + database session model by default.

The sessions table in the database stores the session details for the users. The session id is stored and matched from a browser cookie.

The settings for session duration can be found in settings.php, in particular:

/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

You can adjust those settings to affect the session lifetime. Indeed, the "remember me" module uses the session.cookie_lifetime setting to apply its functionality.


Drush on windows - back up goes missing I am new to drupal and drush, so please do not close this if it's naive.

My setup:

Windows 7
Xampp 1.8.3 (PHP 5.5.6/Apache 2.4.7/PHP 5.5.6)
Drupal 7.26
Drush 6.3-dev

Intention:

Back up my site and restore on a separate machine using drush
    archive-dump and drush archive-restore

Action: I went into the folder where I have installed drupal and issued the command drush archive-dump

Result:

Archive saved to                                                            [ok]

C:\Users\srihari.sahu/drush-backups/archive-dump/20140206101025/drup
al.20140206_101027.tar.gz
C:\Users\srihari.sahu/drush-backups/archive-dump/20140206101025/drup
al.20140206_101027.tar.gz

When I go in the folder C:\Users\srihari.sahu\drush-backups\archive-dump\20140206101025\ I don't see anything. The folder is blank.

What am I missing?

This is a known issue for drush in Windows, along with several others regarding sql operations and rsync. The best solution I know so far is described in:

https://drupal.org/node/1393672


Redirect to /user upon login I can't figure out why users are redirected to http://example.org/user (the domain is just an example) when they log in. I don't see a rule anywhere. I have written rules to redirect somewhere else upon login, and the rules do not work. I suspect the Logintoboggan or the Drupal Commerce, but I can't find any settings that would cause this. I don't have any other redirect modules installed.

Why are user redirected to their user profile after they log in?

The redirect is specified in the login form forst_state array under the redirect key, that's why. You can change that by altering the user login form.


How to remove a term programmatically from entity reference field using entity browser on translation form? I have a content type "Articles", this is a multi-language site, by default the content is created in English, and then translated into Spanish. On new article in English, I set a title and a term for the "Category terms" field, this field is an "Entity Reference", and I'm using "Entity Browser" to show terms from a view (they are a lot of terms), when I create a translation from English to Spanish I need to remove any term related to "Category terms" field. I have tried a couple of ways, but this is not working for this field.

Here is the hook code that I'm using.

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Form state object double check.
  if (is_object($form_state) && method_exists($form_state, 'getStorage')) {

    $form_storage = $form_state->getStorage();

    // Temporal condition to avoid unexpected results while developing
    if ($form_id == 'node_articles_form') {

      // Check if form is a translation.
      if (isset($form_storage['content_translation'])) {

        // Hard coded test to override title - This works.
        $form['title']['widget'][0]['value']['#default_value'] = 'Forced title text translation';

        // Hard coded test to override Meta Search Terms - This doesn't work. Is not applyed
        $form['field_category_terms']['widget']['entity_browser']['#default_value'] = [];

        // Removing completely the field - This is not a solution, only for test.
        // unset($form['field_category_terms']);

        // Removing data from "Callback Object"
        $build_info = $form_state->getBuildInfo();
        // Getting the entity
        $entity = $build_info['callback_object']->getEntity();
        // Removing terms from entity
        $entity->field_category_terms = [];
        // Setting the entity
        $build_info['callback_object']->setEntity($entity);
        // setting a modified callback object to the $form_state
        $form_state->setBuildInfo($build_info);

        // Removing target_id default value.
        unset($form['field_category_terms']['widget']['target_id']['#default_value']);
      }
    }
  }
}

To remove them from the user interface, you would have to empty the items array of 'current'

$form['field_category_terms']['widget']['current']['items'] = [];

This would however only hide them in the user interface, to actually remove them you also have to NULL target_id

$form['field_category_terms']['widget']['target_id']['#default_value'] = '';

If the users are allowed to add new terms during the translation, you'd also need to make sure the emptying of the terms only are done initially, because if not, they would always appear empty since Entity Browser uses AJAX and change the form when you add a new term. Something like:

  if (!$form_state->isProcessingInput()) {
    $form['field_category_terms']['widget']['target_id']['#default_value'] = '';
    $form['field_category_terms']['widget']['current']['items'] = [];
  }


Image styles are not getting created Our image styles are not getting created on one of the Drupal 7 sites in a multi-site installation. They are created for at least one of the other sites that uses the same Drupal 7 core.

Symptoms: Upon uploading an image to a node, the image preview does not get displayed (depending on the browser, a broken image placeholder may display). The image is not created in the file system either. I have verified file system ACLs. Both sites use the same .htaccess.

As per image style (imagecache) images are not being created, changing the theme and reverting back fixed the problem. Very strange - it would be nice to know what the cause was!


How to get user id of order from order entity metadata wrapper I am implementing hook_commerce_cart_line_item_refresh(). It will be receiving line item and entity metadata wrapper for the commerce order.

How can I get user id of order from its metadata wrapper without loading user object like this

$uid = $order_wrapper->owner->value()->uid

With above line it will be loading user object. I would like to avoid loading user object and simply take uid directly.

Following line does not work:

$uid = $order_wrapper->uid;

Or should I think of loading order object? As it might be already in static cache.

Thanks

It's the same as any property on a metadata wrapper:

$uid = $order_wrapper->uid->value();

  Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with

$order = $order_wrapper->value();


Import an Image Folder into one Image Field I've searched a lot for my problem, but I haven't found an answer yet.

I want to achieve, that if somebody uploads a whole folder of images per FTP, it should be possible to select the folder during the creation of a new node and add them into one image field.

It must be somehow like the file_attach module of drupal 6.
But for Drupal 7 and for whole directories instead of single files.
Does anybody has a guess or solution for me?

It will most likely involve implementing the Drupal File API in combination with the Field API in your custom module. I can't write a full implementation for you here because honestly it would take at least an hour to do it correctly, and still my example could miss your use case. But if you have a good handle of PHP and Drupal, you should be able to do it with the two APIs I mentioned above.


How to set to Webform's fields a 'Number of values' setting like in default content types? Yeah, so in content type fields like Article or any other when you add a field it has an option 'Number of values' and if you select Unlimited it adds a button 'Add another item' when creating a content.

So I was thinking is it possible to do that with Webform module's forms? Let's say a user is filling in the form, let's say he fills in his phone number into Phone number field and then maybe he has a another phone number, so he could click 'Add another item' and that would open up a second field of a Phone Number field.

To be exact, I need that Unlimited option to work on Webform fieldset fields. So if I have a fieldset of three fields, I can click 'add another item' and it opens up a 2nd fieldset.

Webform Addmore

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields. The approach was proposed by Bartezz, and code originally
  implemented by span and kranklin 1. This module adds a checkbox
  setting to webform fieldset components to select which should have Add
  more functionality, as well as an advanced setting to override the
  button label per Webform.


How can I show contextual links on my node's full content view mode? I need to be able to display my contextual links in the node full content view mode. How can I achieve this? Maybe something in my node.tpl?

if you want to show contextual link on a node view
try out this code on your custom module file.

function mymodulename_node_view_alter(&$build) {
  $node = $build['#node'];
  if (!empty($node->nid)) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }
}


block to display nodes using entityQuery with pager I am trying to figure out how to create a block that displays recent content using a pager that can fetch the next set of nodes
here is what I have so far
/modules/example_module/example_module.info.yml

name: Example Module block with pager
description: 'Example Module block with pager'
core: 8.x
type: module
dependencies:
- node
- block
type: module

/modules/example_module/src/Plugin/Block/ExampleModuleBlock.php

<?php
namespace Drupal\example_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Display all instances for 'ExampleModuleBlock' block plugin.
 *
 * @Block(
 *   id = "example_module_block",
 *   admin_label = @Translation("Example Module"),
 *   category = @Translation("Example Module"),
 * )
 */
class ExampleModuleBlock extends BlockBase {
  public function build() {
    $output = example_module_get_content();
    $out = [
      '#markup' => $output,
      ],
    ];
    return $out;
  }
}

and /modules/example_module/example_module.module

<?php

function example_module_get_content(){
  $out = "";
  $nids = example_module_query();
  foreach($nids as $nid){
    $node = \Drupal\node\Entity\Node::load($nid);
    $out .= "<div>" . $node->getTitle() . "</div>";
  }
  return $out;
}

function example_module_query() {
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->sort('created', 'DESC')
    ->pager(10);
  $nids = $query->execute();
  return $nids;
}

which creates a block that can be placed on a theme and displays the latest/recent 10 nodes on the drupal site.

Well I can probably devise a way to query the database and figure out a way to create a custom pager and probably use $current_path = \Drupal::service('path.current')->getPath(); to get the pager PAGE but I was wondering if there is an obvious way that could greatly help and I don't have to reinvent the wheel

what is the deal with pagers are they of any help here ?

The first step is to include a pager in the query $query->pager(10), which you have already done. Then you need a render element pager:

  $build['result'] => $out;
  $build['pager'] = [
    '#type' => 'pager',
  ];
  return $build;

If you have multiple pagers on the site, which is probably the case for a block placed on different pages, you have to connect query and pager with a pager id:

  $element = '123';

  $query->pager(10, $element);

  $build['pager'] = [
    '#type' => 'pager',
    '#element' => $element,
  ];


Link to send private message to current user in the node (author of the content)? Is it possible to create a link to send private message to CURRENT USER in the node (to the author of the node content to be more precise). I'm using the Privatemsg module.
I was trying to do this with the Display suite dynamic fields, but I am not able.

I found that the Privatemsg module comes with an option to "Display link on the selected content types. So, I have the "contact current member link" right in the content type, but it shows only for logged in users.

Is there any configuration or hook that I can implement to show the same link to anonymous user?

This is the code that shows the link.

function privatemsg_node_view($node, $view_mode) {
  $types = array_filter(variable_get('privatemsg_link_node_types', array()));
  $url = privatemsg_get_link(user_load($node->uid));
  if (in_array($node->type, $types) && !empty($url) && ($view_mode == 'full' || (variable_get('privatemsg_display_on_teaser', 1) && $view_mode == 'teaser'))) {
    $node->content['links']['#links']['privatemsg_link'] = array(
      'title' => t('Contact member'),
      'href' => $url . '/' . t('Message regarding @node', array('@node' => $node->title)),
      'query' => drupal_get_destination(),
      'attributes' => array('class' => 'button radius privatemsg-send-link privatemsg-send-link-node'),
    );
  }
}

To make it clearer, I don't want anonymous user to send messages. What I want is just a link to log in for anonymous users. Expressing it with pseudo-code...

global $user;

if (isset($user->roles[1])) {
  // Do not show button to Anonymous user and show something else or a button to log in (THE CODE FOR LOG IN)
  echo "something else";
}
else {
  // Show button to logged in user (the code of "Send author a message" button)
}

I did it with a Display suite custom code field. With it I am able to use some PHP code.

global $user;
// If the user is anonymous (role=1) show this; otherwise show nothing.
if (isset($user->roles[1])) {
  print l(t('Contact member'), 'user/login', array('attributes' => array('class' => array('radius', 'button'))));
}

So, when the user is logged-in, this code above will be replaced with the contact member link (Send author a message).


Translation mess up with fields which are not translatable used in views Example set up:

Content type news with fields

Body (translatable)
date (another date field beside node published date - translatable)
type of news (list field - not translatable, the news should be of the same type in every language)

View with filters:

Published: yes
Content type: news
Content language: currently activated interface language
field "type of news" -> exposed to the user

Default language in the project is German.

When I go to the view in German and choose a type of news in the exposed filter there is no problem - the expected news are listed. The problem appears when I enter the page in English and I choose a type of news -> no results are found although the same nodes are translated into English.

I found out that this is due to the fact that the "type of news" values in the fields table are saved with the language id of the original node which is 'de' but the full view query expects the field value to have a language code 'en' (like the currently activated language has).

See this query and especially the INNER JOIN:

SELECT node__field_date.field_date_value AS node__field_date_field_date_value, node_field_data.nid AS nid, node_field_data.langcode AS node_field_data_langcode
FROM
{node_field_data} node_field_data
INNER JOIN {node__field_news_typ} node__field_news_typ ON node_field_data.nid = node__field_news_typ.entity_id AND (node__field_news_typ.deleted = '0' AND node__field_news_typ.langcode = node_field_data.langcode)
LEFT JOIN {node__field_date} node__field_date ON node_field_data.nid = node__field_date.entity_id AND (node__field_date.deleted = '0' AND node__field_date.langcode = node_field_data.langcode)
WHERE (( (node__field_news_typ.field_news_typ_value = 'press') )AND(( (node_field_data.langcode IN  ('en')) AND (node_field_data.status = '1') AND (node_field_data.type IN  ('news')) )))
ORDER BY node__field_date_field_date_value DESC
LIMIT 10 OFFSET 0

You may see that the inner join expects the langcode field in node__field_news_typ to be the same value as node_field_data.langcode which is 'en' when I enter the view in English. But looking into the table of node__field_news_typ I do not find one entry with 'en' as the field is not set to be translatable and all the nodes are originally written in German.

Maybe I did not get some basics of the multilanguage architecture in Drupal 8 but I find it a little bit strange that fields which are not translatable filter out nodes in views where a filter is set to "current active language". Is there not UNDEFINED_LANGUAGE ('und') anymore? Why do fields get a fix languagecode when they are not translatable? How can I avoid this behavior?

It seems to me that there is no other way as setting the field to translatable although I want to assure that translated nodes have the same value?!

This is known core bug, see https://www.drupal.org/node/2451657. The patch there should work well.


Printing current node workflow state name as the page body classes I have a workflow system in my site using workflow module, and I need to print the node current state name as body class.

I did the same with user current role in template.php with this snippet:

function sattari_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

I'd really appreciate your help.

I think once you get the node object in your preprocess function then you will be able to add the class. Body classes are only applied in template_preprocess_html so you can do the following,

function sattari_preprocess_html(&$vars) {
  // If on an individual node page, add the node type to body classes.
  if ($node = menu_get_object()) {
    // debug($node);
    // Change as per your node object values added by workflow module.
    $variables['classes_array'][] = drupal_html_class('node-status-' . $node->status);
  }
}

For more reference have a look at template_preprocess_html


create module that load index.php I have a php code written in index.php that contain a form with method post.

It also read from an external database and fill a table.
To load this form I created a .module file with 2 functions _menu and _block, but I am not able to load the form (index.php)
I need to load the form and to open it in the main content of the drupal page
i used :

header("location
drupal_goto(
$external_link

but nothing is going right and it open in new blank page not in the main content like i want.

please it is urgent
any help

The Drupal way

In Drupal we create similar form like this:

Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info with this in it:

name = form_test
description = form_test
core = 7.x
package = Own
Create a file sites/all/modules/own/form_test/form_test.module

(start it with <?php tag, but don't add ending ?> tag)

Write these functions in your module:

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

An explanation

form_test_menu
creates a menu item in your navigation menu so we can have a place where to show our custom form. You can think that menu address referring to a page yoursite/formtest.

title

Title of the page.

page callback

Calls a function drupal_get_form which returns a render array for drupal_render().

page arguments

Here we pass our custom render array (which form_test_form returns) as an argument for drupal_get_form.

access callback

We define it TRUE so that everyone can access this page.

(Rendering means turning a structured array into HTML.)

function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

An explanation

So we use render arrays to describe a form in drupal.

When you use a function to return a render array for drupal_get_form, there are two default parameters that are in use:

$form   Holds the form array items we define inside the function when this function is called again.

&$form_submit   This parameter holds various data items like the values you pass when you submit the form.

(Ampersand & means that this is a reference to a variable, so if we change this variable in this function, changes will show in the parent function too.)

Form items are added as arrays to the $form variable. Hash (#) sign refers to an attribute of the item.

Enable the module in admin/modules

Flush the caches

Form can be seen in yoursite/formtest, but it doesn't do anything yet.

OR
more links are :

Drupal 7 - How to Make a Simple Module with a Form and Menu Link

Ten Step-by-Step Code Samples for Learning Form API


Rewriting output of View I have a View of taxonomies. I want to rewrite the output of each field (name) as this:

[name]

so when I click on the taxonomy, it will prompt an alert with the term name.

I try to rewrite through the Views GUI to no avail.
I even tried with views_pre_renderbut because there is no #markup property, the rewriting is not HTML but plain text.
I did the trick with views_pre_render and other kind of content, but not in taxonomy. And is it really impossible to achieve that in the GUI ? Surely I am missing something very very basic here.

You can do this through theming.

For that you can create a new views-view-field--VIEW_NAME--FIELD_NAME.tpl.php file and write the HTML output for the field.

Dont't forget to clear your cache after adding the file or you can do 'Rescan template files' inside your view.


Clone a node programmatically I am modifying the node content on hook_form_alter() as follows.

  $node = \Drupal\node\Entity\Node::load($nid);
  if ($node) {
    $node->field_p_frontip = $availableip[0];
    $node->save();
  }

I need to clone the node and save it in the  hook_form_alter() submission. How could I do this?

UPDATE

In D6 the node was cloned using the function clone_node_save which uses the node id to clone as clone_node_save($nid,false);, what is the corresponding function in D8 ??

In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.


How do I add a node add link ( for a different content type ) in the node add form (drupal 7) I'm overriding the node add / edit form using panels. One of the fields that I have added is using the auto complete widget (it is a node reference field). I also want to add a link underneath the autocomplete field to add a new node (one of the referenced nodes). I'm wondering if there is a way to add this link.

If it's not possible within panels, perhaps it is possible someone can give me an idea of how to add this sort of link to node add form using templates.

The module your are looking for is References dialog.

Also, you can use contextual administration. It's a more general approach, that won't put the link exactly where you want, but is much more flexible on the other hand. It allows you to use the same rule set as Panels, such as "Selection rule: Node type", for example to node/add/[other-type]. Fits like a glove together with Panels.


Why does entity_metadata_wrapper does not preserve node's custom URL while updating other fields? I am programmatically loading a node of custom content type (i.e. staff) using entity_metadata_wrapper and add a reference to a collection of other nodes and then save the node.

The custom nodes (i.e. of type staff) has a custom a URL, set when the node was created (they are all created manually but, subject to being updated programmatically on regular basis). I also have pathauto module enabled but, I don't need it for this specific scenario.

entity_metadata_wrapper does load the node, assign the references and magically resets the node's custom URL to automatic. Any idea about this behaviour? Is there any way to preserve the custom URL?

Here is the code that loads the node, establish reference and saves the node :

      $node = node_load($staff_drupal_id);
      $wrapper = entity_metadata_wrapper('node', $node);
      $wrapper->field_staff_selected_publication->set($publication_ids);
      $wrapper->save();

In case someone else face the same issue, I come across the following

  Pathauto uses the following logic (listed by priority) to determine if
  the Pathauto checkbox should be checked when editing a node:

  If the node is a new node, it defaults to having an automatic alias.
  If the node is not a new node: If the node does not currently have an
  alias, it assumes that the node was manually un-aliased, so it will
  default to not have an automatic alias. If the node's current alias
  matches the alias that Pathauto would generate based on the pattern,
  then it will default to checked. Otherwise, the checkbox will default
  to be unchecked. If you are using the Pathauto persistent state
  module, then once you save a node, the checkbox will remain checked or
  unchecked regardless of the logic above until you check or uncheck it
  later.

  If you have content you've created before installing Pathauto that you
  would like to ensure that the checkbox is checked whenever you edit
  them, then you should use the 'Update URL alias' bulk action on your
  content listing admin page (admin/content/node).

  If you are saving changes to nodes automatically using node_save, you
  need to specify $node->path['pathauto'] = FALSE; in Drupal 7 or
  $node->pathauto_perform_alias = FALSE; in Drupal 6 (see
  http://drupal.org/node/1179988) in order to stop pathauto overwriting
  any custom paths you might already have for the node.

In Drupal 6

$node->path['pathauto'] = FALSE;

in Drupal 7

$node->pathauto_perform_alias = FALSE;


Is Filter Contains all words working well? I have a View and a filter, with "Contains all words". I see that the SQL contains the expression

'%word1%' AND '%word2%',

but this is making that if I write "angular", just when I start writing the "a", also words which have the character a and not necessarily start with a will appear, for example "matter".

Shouldn't the placeholder % be only in one place, this way:

LIKE ( 'word1%' AND ' word2%' ) AND (' word1%' OR 'word2%')  ... [other combinations]

I am hurrying on the suggestion, but that way, it will look for a beggining of string as one of the two (or more) words, and the other words must have an empty space before them if they are not at the beginning.

Change your Operator to Starts with and Apply.

If you need use a specific filter you can alter your view query with this hook:

function YOUR_MODULE_views_query_alter(&$view, &$query)
{
    if($view->name == 'NAME') {

    //here modify your query

    }

}


7 - Mapping multiple LDAP groups to single Drupal roles using Boolean operators I'm attempting to set up fairly complex permissions in D7 based on LDAP group membership, and it would help greatly if there were a way to use Boolean operators to perform the role mapping.

Some context:

There are multiple, similar departments: each has a pool of employees, and each has a manager.
LDAP groups map to departments as well as roles. The manager of the Finance department belongs to two groups: one that designates the group Finance_dept, another that designates the group Managers.
Managers should have R/W access to parts of the site that correspond only to their respective departments; employees should only have R access.

What I've tried (and ruled out):

I have the LDAP module configured to provision Drupal roles based on LDAP group membership--that piece works well for one-to-one mappings; e.g.:

Finance_dept|finance
Managers|managers

I've tried various iterations of LDAP search filters, to no effect:

Finance_dept & Managers|finance_managers
(&(Finance_dept)(Managers))|finance_managers

Has anyone gotten this to work?

Until I can find (or someone else posts) a better way to do this, my interim solution is:

Set up LDAP group -> Drupal role provisioning as normal.
Use the Rules module to assign/revoke another role programmatically on events User has logged in, and Before saving a user account.

Example (referring to my question above):

LDAP Provisioning:

Finance_dept|finance
Managers|managers

Create roles manually:

financemanagers

Rules:

Finance_dept + Managers = FinanceManagers

Events: User has logged in, Before saving a user account
Elements: User has role(s): finance, managers
Actions: Add user role: financemanagers

Removed from either Finance or Managers

Events: User has logged in, Before saving a user account
Elements:

NOT User has role(s): finance
OR
NOT User has role(s): managers

Actions: Remove user role: financemanagers

Works for now, but it won't scale well beyond a handful of role combinations.


Views: show nodes that share taxonomy term with user I have a content type requests with the taxonomy field categories.  I have added categories to my user's profile as well.

I need to create a view that displays all the requests that have category terms the user has selected in their profile.  How do I go about this?

Create a view showing requests.
Add a contextual filter for Field: Category.
When the filter value is NOT in the URL choose "Provide default value" of type PHP.
In the "PHP contextual filter code" write:

global $user;
$account = user_load($user->uid);
return $account->field_category['und'][0]['tid']; // this line may need changing based on your category field name


node aliased path as views contextual filter I want to have a view which would output a node title and use a contextual filter the aliased path of a node

/nodefilter?url=/category/path-to-article

I see there no php contextual filters in drupal 8 anymore do I have to write a custom contextual filter or is there another solution ? Any help will be greatly appreciated

First I have created a view that uses contextual filter content ID to filter the results by "node id" and can be called like this

/nodefilter/[NID]

After I made sure the view was working I modified the content ID contextual filter adding default query paramenter named url under WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value

then in a custom module used the views api hook_views_pre_view as follows

use Drupal\views\ViewExecutable;
function MODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if($view->id() == 'view_machine_name'){
    $url = \Drupal::request()->query->get('url');
    $path = \Drupal::service('path.alias_manager')->getPathByAlias($url);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
      //$node = \Drupal\node\Entity\Node::load($matches[1]);
      //$nid = $matches[1];
      $args[0] = $matches[1];
    }
  }
}

Now the view works with NID or the url parameter

/nodefilter/[NID]
/nodefilter/?url=/category/path-to-article


Do translated taxonomy terms have different tid's? As per title; or are they translated in the same way user interface elements are handled?
Im using Drupal 7 btw.

No if you choose to localize your terms. Edit your vocabulary and tick this option: "Localize. Terms are common for all languages, but their name and description may be localized."


How to set URL alias automatically for a content type WITHOUT using Pathauto? Which hook to implement? Pathauto can do the job easily for all content types, but in my case I only have one content type URL that needs to be customized, and I would prefer to not install Pathauto and Token.

Can anyone advise me how to do?

/**
 * Implements hook_node_insert()
 */
 function mymodule_node_insert($node) {
   if ($node->type == 'mytype') {
     $node->path['alias'] = 'mytype/' . $node->nid;
   }
 }

Additionally, you may add this code to hook_node_update()


How Drupal handles nodes 404 requests? I'm curious about how Drupal 8 handles nodes 404 requests. I think there might be a route of 404 and then an internal check - if node id doesn't exists, it simply calls 404 route path.

If this scenario is right, how can I achieve the same for custom entity?

I have a content entity type, but want a 404 redirection if someone access wrong entity id directly similar to any node page which doesn't exists.

Ah, seeing that this is a follow-up to How to check if entity id exists or valid?, I think I know what the problem is.

If you ensure upcasting through the route, then Drupal throws a not found exception automatically and shows the 404 page.

So, you need to define your route as /entityform/{your_entity_type_id} and in the controller, type hint the argument YourEntityTypeId $your_entity_type_id. Then Drupal automatically loads the object, gives it to you and returns a 404 page if not found.


get path of uploaded picture for custom parallax effect i created a custom block where i can upload an image. i overwrite the custom block with a template:

  {{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}
  {% block content %}

          {{content.field_parallax_bilder }}  <----- (1)

  <----- (2)

  {% endblock %}

i want to get the path of the image (1) and include it in my data-image-src parameter (2). is there an easier way then write a block_preprocess?

You'll have to set a $src var from the corresponding preprocess hook.

function myModuleOrTheme_preprocess_block(&$variables){

if(isset($variables['elements']['content']['field_parralaxBgImage']))
//or any other way to test if you are in the right block

   //Get the Image id :
   $imgListItems = $variables['elements']['content']['field_testimages']['#items'];
   $imgId = $imgListItems->getValue()[0]['target_id'];
   //load the entity :
   $image = \Drupal\file\Entity\File::load($imageId);

  // now you can simply return the original image's url :
  $variables['parralaxBgSrc'] = image->url();

  //or return a styled image's url (croped or resized) with a image style configured in the BO
  $imageStyle = \Drupal\image\Entity\ImageStyle::load('imageStyle_id');
  $variables['parralaxBgSrc'] = $imageStyle->buildUrl($image->getFileUri());

}

After that, you'll be able to use it in your twig tpl :

 <div class="parallax-window" data-parallax="scroll" data-image-src="{{$parralaxBgSrc}}">

(Dont forgot to flush your cache after adding the hook)

Et voila! :)


View Filter based on condition I have a View that is using the Table format to show all users who have uploaded content under a particular node. This view will be visible to anyone in the Authenticated User role. Users in Administrator role (about 4 users) also contribute to this, but I don't want their details to be visible to anyone else in the table. This is not intended to be an exposed filter.

So basically, if the current logged in user is in the Authenticated User role, then he should not see the admins.

If the current logged in user is in the Administrator role, then he should see everyone.

Possible? Thank you

by the sounds of it, you're looking for Views Conditional module:

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

 Equal To
 Not Equal To
 Greater Than
 Less Than
 Empty
 Not Empty

  Views conditional allows you to output text based on the result of the condition.


Accessing Drupal database for read purposes I'm interested in analyzing various aspects of the content in our Drupal site involving node meta data such as type, name, creation date, etc. I know I can create views to show some informaiton and I know I can dump out the database and analyze it separately, but I'd really like to query the database live (for read purposes only) from a remote machine so that I can use the software of my choice to do the analysis, reporting, etc.

Does Drupal have a remotely accessible API that I can use query its database?

(Note: I suspect the "db-api" tag is inappropriate for this question, but I couldn't figure out anything else to use.)

If you want easily importable data, consider using Views data export:

  This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML

You can import CSV or XML to pretty much any data analysis tool you may need.


Sending mail to an adress specified in a node creation form with an CCK email field with Rules I'm using a node creation form open to anonymous users to register volunteers for an event, and I want to redirect them to a thank you page, and send them an email when they register.

I'm using Rules to detect the submission of a volunteer node, and trigger a redirect to the thank you page, but I cannot figure out how to send a mail to the address specified in the form submitted.

As long as you have the Rules module and the Token module installed, it should be a pretty straightforward.

1) Create a rule that responds to the event "After saving new content"

2) Add an action to that rule "Send a mail to an arbitrary mail address" (from the System section)

3) Use a token for the Recipient field. As long as there is a CCK field for the email address, there will be a token provided for it. It will be listed in "Token replacement patterns."


How do I fetch the values of an entity's field? How to query all the values of a particular field. I used Drupal\Core\Database\Connection object to fetch the values as below:

$connection = \Drupal::database();
$result = $connection->select('node__body', 'n')
  ->fields('n', array('body_value'))
  ->execute()->fetchCol();

Is there any Drupal 8 API specifically for this?  I need to fetch all values of the field and fetch the field values for a particular node bundle.

In Drupal 7, you would use the EntityFieldQuery class. In Drupal 8, there is an equivalent service.

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('changed', REQUEST_TIME, '<')
    ->condition('title', 'cat', 'CONTAINS')
    ->condition('field_tags.entity.name', 'cats');

$nids = $query->execute();

In your case, instead of field_tag.entity.name, you need body.body_value. See EntityFieldQuery has been rewritten.
If you just need to get all the node IDs, remove all the condition() lines, and then use entity_load_multiple('node', $nids) to load the full node objects.

In this way, your code is not making assumptions about the tables used to contain the node data. Plus, it can be easily extended to filter the nodes basing on some criteria (node properties, content of fields...).


Views 2 Drupal 6 Filter Result if none of the fields have a value What I need seems pretty straightforward but I cannot seem to accomplish it.

I have a view, a content pane to be precise, fetching specific fields of the node that it's parent panel overrides.

What I need, is for the view to return 0 results (and thus be hidden completely) if NONE of the fields are populated. If even one fields is populated I want it to display, but if NONE of the fields in question have a value I need the content pane to dissapear completely. I understand I have to do it with filtering and the NOT NULL option but I cannot understand how since in 2.x-6.x there is no AND/OR capability of what I can see.

Any help?

Module Views Or allows me to add OR clauses to my filters and get the job done. Here is an excerpt about it from the module's project page:

  ... allows Views to combine filters or arguments with OR and fields with COALESCE.


Protect user login page with Basic Auth Is it possible to make Drupal more secure by making LOGIN page private? I would like to make /user/login page private with Basic Auth so an user and password are needed before I get in that page.

Or is there another ways to make the login more safe? Goal is to prevent hackers to get in. Also if there's some module that helps on this it would be nice.

From your question

  Is there another ways to make the login more safe?

Yes,try one of the following modules

Login Security

  Login Security module improves the security options in the login operation of a Drupal site. By default, Drupal introduces only basic access control denying IP access to the full content of the site.

Secure Login

  Secure Login module enables the user login and other forms to be submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in clear text. Secure Login module locks down not just the user/login page but also any page containing the user login block (or other forms that you configure to be secured).


Migrate: Create term(s) if they do not yet exist Question similar to this question here, but this time, I am not doing a separate migration later.

I want to create taxonomy terms if they do not exist while processing a record. Does entity_lookup do this in the same way migration_lookup does for stubbing? In this case, I won't be doing another migration to fill in a stub, but surely there must be a way to create a term and keep going.

I don't see anything in entity_lookups plugin indicating it will create if not found.

Wow, ok, getting better at parsing the docs/code for migrate plus. I found it as soon as I posted. The entity_generate plugin will do this behavior.

  field_paper_jel_codes:
    plugin: entity_generate
    source: jel_codes

Now I have a system full of taxonomy.


printing drupal field in comment.tpl.php I have disabled user pictures, and created a field in users instead because i feel i have more control of the user pictures, i.e. i can organize them on webhotel with tokens, and choose a certain picture style etc.

Now i want to use the field in the comment.tpl.php of the theme, so i printed following code <?php echo render($content['field_profilbillede']); ?> where the <?php print $picture ?> usually appear .. but nothing happends at all .. what did i do wrong?

Ps. i got the code from another post on stackoverflow.com so yes i have already searched for related posts.

Thanks

I'm not positive about this, but maybe try removing the $content portion and rendering the field directly?

<?php echo render($field_profilbillede); ?>


Webform Protected Downloads Module This module is able to send emails to subscribers. User has to click a download link (included in an email) and will be redirected to a download page. After that he/she need to click the link to open the file. Lastly, save the files to their computer.

Here is my question: Is there any way to click the download link from his/her email and download the files immediately?

More Info: I think Email Download Module is what I need, however it is only use for drupal 6.

I have never used that module before but by reading its home page I found this

When a user submits a webform with protected files he will be sent an
email with a link to the downloads page. The link contains an
individual hash code that will be checked upon page load to verify the
access. If verification fails access will be denied. If it succeeds
the user will see the default private upload file listing with all
protected files that are attached to the webform.

Now based on your question you want to add a link direct to the protected files by the module, bypassing (if that is possible) the access verification, to violate the module's functionality. Why you want to do that ? I think that this is not a good idea even if possible. Probably you are looking for another module or I am missing something.


Access currently logged in User profile from search index view? I have a Product Display listing of indexed nodes that show a "List Price" I want to do math on them (if I can get the multipliers I can do the math) in the view to show a users "Cost" and "Selling Price" the multipliers that I need are on the users Profile however I can't seem to find a way to access the current UID/ users profile fields in this type of view.

a) is this even possible to do?
b) can someone explain to me how I can do it?

Thanks in advance t anyone who can help

I am assuming you are using views module to create this listing. In that case, this is certainly possible.

But first, I am not sure what you mean by current user. Is this the user who created the particular product? Or is it the currently logged in user?

If the user is the creator of the product node, just add a
relationship to the user using Relationships section in the View.
And then all the user profile fields will be accessible to you in
the Fields section. Easy.
If you're talking about the logged in user, then you can use views_php module. Install views_php and then add a PHP field to your view. In that field's output, write your php code which fetches that particular value. For example, the following code will give you the uid of the user. You can similarly extract more fields from his profile.

global $user;
echo $user->uid;

You can inspect this $user object using dsm(), which is provided by devel module to inspect where your field lies in this object.

One important thing, write the above code in the output section of the views_php field, and INCLUDE php tags.


How to print taxonomy term field in node.html.twig? In Drupal 7 we use following snippet to print taxonomy term field in node.tpl.php

$term = taxonomy_term_load($node->field_example['und'][0]['tid']);

$result = field_view_field('taxonomy_term',$term,'field_desired_field');

echo render($result);

In Drupal 8 how we can print taxonomy term field in node.html.twig?

To get the field value from a field in a taxonomy term that is referenced in the node:

{{ node.field_example.entity.field_desired_field.value }}

If you want to render a formatted output, use either the ui to configure a custom view mode or use the module Twig Tweak:

{% set tid = node.field_example.target_id %}
{% if tid %}
  {{ drupal_field('field_desired_field', 'taxonomy_term', tid) }}
{% endif %}


Access .html file only if logged in How do you restrict a .html file/page with drupal so that only logged in users can access it?

Basically I have this .html file I need to put up, I don't care whether or not it's a content-page or just simply a file - but I need only those who are logged in to be able to access it.

I've tried simply pasting the html-code in content-creator (read; /?q=node/add/page), but that crashed my site and I had to manually remove the node from the database to get it working again - so that's not an option.

The Drupal way of doing this is to pull out the content from your HTML file; you don't need to paste the entire contents into the node body, that will break your site's theme.

Once you've created the node with the content you've pulled out of the HTML file, you can use the Content Access module to restrict viewing of the node to only authenticated users.


Drupal 7 Views bulk operations based on terms I want to do bulk operations based on terms instead of node id. For example, I have a term called "XXXX", I have selected this term for 10 contents. So, in manage views I want to display only the term name, if when user selecting that term and do publish/unpublish, that 10 contents should be publish/unpublish.

Is it possible with Rules? Can anyone please guide me?

Thanks in advance.

I use admin_views
to do that and more.

After enabling it, you'll find Views -> Administration: Nodes, Edit that view.

Under Filter criteria you will find a default "(term) Taxonomy term: Vocabulary (exposed)".
Add your "(term) Taxonomy term: Name (exposed)" and use the other as referene to get your settings correct.

Pending on how many terms you have, this dropdown can get messy, so you could refine your filter settings to only show some terms in the filter.