Show menu links for anonymous users only I need to show the user register link as a menu item in the account menu. I am able to add the link in the menu via links.menu.yml.

The menu links shows up for anonymous users as well as authenticated users but not for admin user role.

How can I hide the menu item for logged in users irrespective of user role?

Tried all the options to hide the menu item from authenticated users irrespective of the role, but admin always sees it. Did that using CSS and Menu Link Attributed module. Using the module I added a class to the menu link and then using the body class user-logged-in hid the menu item for logged in user.

I am still open to any other alternative and a better solution.


How can I have profile edit pages displayed in admin theme? Drupal 8- How to use admin theme for user profile edit page while editing the profile by an administrator.

Example: when admin takes the URL: www.mysite/profile/{id}/edit (This is the URL you get when admin edit a user profile from user profile list.) I need to show the edit form in admin theme

I am using below profile module

version: '8.x-1.0-rc6'

core: '8.x'

project: 'profile'

The profile form is already designated as an admin route, so you just need to change the permissions for relevant roles so they can view that theme.

The specific permission you're looking for is:

  View the administration theme


View | So taxonomy terms plus some links associated with current taxonomy page I have made a view that show taxonomy terms. What i want is show Taxonomy terms plus some content with.
ex.
I have Auto Manufactures like

Auto>
     Audi[taxonomy term :taxonomy/term/1]
     Renault[taxonomy term :taxonomy/term/2]
     Mazda[taxonomy term :taxonomy/term/3]
     [AllNon][content node/1 has field taxonomy ->selected:auto]

How i can make a view that shows taxonomy terms and include some content links.
The content links is pages that use a taxonomy field.

If I understand the question correctly:

create a view (table) of the content type that contains the taxonomy terms
add fields as appropriate
add a  Content: Link   field that links to the actual content
under Table Settings, Group by the taxonomy term

This will however, create multiple rows of the each taxonomy term (one for each node in which it is used).

If your intent was to create one row for each taxonomy term with multiple links (one for each node using that term), I don't believe you can do that in Views.


Should one avoid lots of use statements in a custom modules .module file? Should one avoid lots of use statements in a custom modules .module file?  Or does it not matter?  To quanity "lots", let's say, using 7 to 10 "use" statements.

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\Component\Utility\Html;
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

I suppose for organizing code, it may be more elegant to create a service to hold custom functionality, rather than to put it directly in a custom module's .module file, but are there any performance implications for many use statements in a .module file?

The use statements alone are definitely not going to be a performance concern. I doubt that we're even talking about nanoseconds here. So that really doesn't matter. I'm guessing that this is resolved at compile time anyway.

Especially in a .module file, use statements usually grow, the more code you have, the more use statements, as a .module file is often doing many different things, implementing various hooks and so on.

If you want to optimize something, look at your actual code, forget about the use statements. Some hooks can be moved into include files, especially those that are only needed when rebuilding caches, like hook_views_data().  Other things can be done in services. But also here, the argument is most likely not going to be runtime performance, parsing code is really, really fast. It's your performance in understand the code, finding bugs, writing  test and so on. Optimize for that.


Can I remove/hide the "Provide a Menu Link" checkbox when creating new content type? I am creating a site where authenticated users (not too computer savvy) will be entering in data to the content types we create and the "Provide a Menu Link" may cause them too much trouble.  Is there a way to remove or hide this option when I create my custom content types?

In drupal 7, go to edit your content type and in the tabs at the bottom there should be 'menu settings'. If none of the checkboxes under 'Available menus' are checked, then the option of creating a menu item is not displayed when creating content of that type.


Issue with drupal_add_css, can do it by nid but not by alias I am using the drupal_add_css function in my template.php file (Drupal 6) and this code works:

if (arg(0)=="node"&&arg(1)=="74" ) {
drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
  }

However if I use this code, it does not work.

if (arg(0)=="web-portfolio") {
drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
  }

I am wondering what I am doing wrong. (note "mythemename" is used in place of my actual theme name here and the actual aliased path is example.com/web-portfolio

arg() doesn't work with path as far as I know. I'm sure there are better aproaches to doing this, but I found a bit of a hack.

if(strstr($_SERVER['REQUEST_URI'], "web-portfolio")) {
  drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
}

I wouldn't use this however its not really the Drupal way. You are adding CSS for a slider, I guess that slide is made with views. You could just make your drupal_add_css call from the views template. That way you'll have it even if you change the path.


Foolproof way to prevent email sends from local/dev server We have had a number of occasions when a new new developer starts working on a project, and when they have it installed the cron runs and sends out a load of emails to users. If the database is fairly old this could send out a lot of unwanted mails. What is the best way to prevent this?

We are currently using Reroute Email which works fine, but obviously this is needs to be enabled. We have set up the settings.php to override the config to enable this, but as it's not included in the GIT repo a new developer might not include this when setting up their local version.

Is there any way to lock this down so it can't happen?

You can sanitize the database so that the emails are not "live" before you provide the database to new developer(s).

drush sql-sanitize is one way to do this.

On my site, I have dev/staging/live servers.  When the live/test database is cloned to dev, a script is called that automatically changes all email addresses to uid@mysite.com.  And then all developers pull the database from the dev server.  This way, it is impossible to accidentally spam users.

I think the only "foolproof" way to prevent accidentally emailing users is to never give the developer the users' emails in the first place.


Inquiring about finding mentors in the drupal community Recently, I've noticed that drupal.org has added user profile fields for areas such as adding drupal ID's for attributing thanks to some mentors.

I was curious as to see if there currently is a means or process of seeking or finding a drupal mentor online or through drupal.org? I would ask people in person but i really don't know that many drupalers at the current moment.

Would the best place to look be the forums on Drupal.org? Or just persistent begging on IRC? I would eventually like to mentor others myself once i feel comfortable

Welcome to Drupal! There are established core-office-hours for folks looking for mentorship (and looking to mentor); Your best best is to start there and outline your skill set. Someone will be more than happy to help. See http://drupal.org/core-office-hours - So you don't have to beg in IRC. Just show up at the appropriate time. :)


How to detect if a user is in a specific directory/accessing a specific path? For example I need to know if a user is in this directory http://example.com/directory; the value should return true if the use is on any of the following pages:

http://example.com/directory/cars
http://example.com/directory/homes
http://example.com/directory/homes/howtosell
http://example.com/directory/food/seafood
http://example.com/directory/food/seafood/fish

For example I need to know if a user is in this directory http://example.com/directory

If "directory" is a filesystem directory, then it's not possible for a Drupal function to know when a user is visiting that directory, for the simple fact Drupal is not invoked to serve the content of a directory. One of the Rewrite directives present in the .htaccess file that comes with Drupal is the following one:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

If "directory" is the path for which a module defines a menu callback, and there isn't a directory with that name, then it is possible for a function to return TRUE when the user is visiting a specific path.

function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if ($dir == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

This function doesn't consider the path aliases. If http://example.com/path-alias is the path alias for http://example.com/real-path, $_GET['q'] will contain real-path when the user visits http://example.com/path-alias; the same is true for arg(), which will return an array containing real-path.
If the function needs to consider also the path aliases, then it needs to be rewritten as:

function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if (drupal_get_normal_path($dir) == $path) {
      return TRUE;
    }
  }

  return FALSE;
}


Sorting Views result rows based on an array of node IDs I have a View of song nodes, and each node has a programmatically calculated total number of points associated with it. (For background: song nodes are referenced in a custom field_chart_items field on a chart node, hence the $chartHistory node query seen in the hook below. The custom field includes a numeric Position that's entered on the chart node, and a numeric Points total that's hidden from view and calculated based on Position in a chart_field_entity_presave() hook.) I'm trying to sort the View's results by points, with highest points totals listed first.
In a views_pre_render() hook, I calculate the points total for each row and place it into an array, $songAndPoints, that contains the song's nid and points total. The array is sorted so that the song with the highest points total comes first – therefore, the order of the nids in the array is the order in which I want my results to appear.
Can I programmatically reorder the $view->result array based on the array of nids I'm getting? My attempt below, using a uasort() callback, doesn't work, but I'm not sure if or how I can do what I'm looking for (or if, perhaps, it needs to happen in a different hook).
<?php
/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(&$view) {
  if ($view->current_display === 'DISPLAYID'
    && $view->id() === 'VIEWID') {
      $entity_type_manager = \Drupal::entityTypeManager();
      $node_storage = $entity_type_manager->getStorage('node');

      foreach ($view->result as $key => $song) {
        $node_type = 'chart';
        $songNID = $song->nid;

        $chartHistory = $node_storage->getQuery()
          ->condition('type', $node_type)
          ->condition('field_chart_items', $songNID, 'IN')
          ->condition('status', 1)
          ->execute();

        if ($chartHistory) {
          foreach ($chartHistory as $chartNID) {
            // ...
            // Various calculations to get points total, $songPoints, for each song.
            // ...
          }
          $songAndPoints[$key] = ['points' => $songPoints, 'nid' => $songNID];

          // Sort based on point values.
          arsort($songAndPoints);

        } else {
          $songAndPoints[] = ['points' => 0, 'nid' => $songNID];
        }
      }

      kint($songAndPoints); // Array with original row number as key and two values, points and NID, sorted with highest points first. This is how I want to sort the results.

      uasort($view->result, "MODULE_sort_by_points_total");
  }
}

/**
 * Custom uasort() callback to sort view results by points totals.
 */
function MODULE_sort_by_points_total($left, $right) {
    $order = ['704', '712', '707', '713', '711', '709', '708', '883', '882', '715', '714', '710', '705']; // TEMPORARY: Hardcoded list of node IDs in order; should be replaced by something like array_column($songAndPoints, 'nid'), but hardcoded values don't work either.

    $flipped = array_flip($order);
    $leftPos = $flipped[$left]->nid;
    $rightPos = $flipped[$right]->nid;
    return $leftPos >= $rightPos;
    // via https://stackoverflow.com/questions/17324708/php-array-multisort-not-sorting-my-multidimensional-array-as-expected/17325584#17325584
}

I got my answer via the Drupal Slack, but reposting it here for anyone who might come across this later, since that's not publicly searchable. It was more of a PHP issue than anything Drupal-specific.
Within the uasort() callback, the $left and $right arguments are objects of the ResultRow class, with nid available from them, so switching $leftPos and $rightPos to $flipped[$left->nid] and $flipped[$right->nid], respectively, gets me access to the results' nids.
/**
 * Custom uasort() callback to sort view results by points totals.
 */
function MODULE_sort_by_points_total($left, $right) {
    $order = ['704', '712', '707', '713', '711', '709', '708', '883', '882', '715', '714', '710', '705'];

    $flipped = array_flip($order);
    $leftPos = $flipped[$left->nid];
    $rightPos = $flipped[$right->nid];
    return $leftPos >= $rightPos;
}

Continuing on, I figured out that switching it to an anonymous function was what I needed to pass $songAndPoints to the uasort() function, as follows, instead of separating it:
$sortByPointsTotal = function($left, $right) use ($songAndPoints) {
    $order = array_column($songAndPoints, 'nid');

    $flipped = array_flip($order);
    $leftPos = $flipped[$left->nid];
    $rightPos = $flipped[$right->nid];
    return $leftPos >= $rightPos;
};

uasort($view->result, $sortByPointsTotal);


Upload a drupal site to the server to test I have finished the drupal website on my localhost. I want to upload everything to the server, but only to test before officially launching it. Is there a way that I can keep my current non-drupal website running normally, but also upload this drupal site and test it at the same time?

If I create a new directory on the root, say '/drupal_test, and put everything there for now, will that be a problem when I copy everything to the root later? Or is there any standard drupal way to do it?

Thanks!

I suggest you instead use any other unused domain. In that case robots.txt, .httaccess will work normally. And also there is risk of Googlebot indexing this content.

Just add "Disallow:/" in the robots.txt as a first rule.


How to get media entity field value in twig? Sometimes it is necessary to get the actual value of a field (not the formatted/rendered one), e.g. to check a boolean for true or false.

If I want to get a field value of a node or paragraph inside twig templates (node.html.twig / paragraph.html.twig) I can use node.field_my_boolean.value respectively paragraph.field_my_boolean.value.

How do I accomplish this in a media twig template? I've already tried media.field_my_boolean.value but it does not work.

Right now, the Media module does not pass its object in the variables like Paragraphs and Node does. This is why media.field_my_boolean.value does nothing.

You can correct this in your theme by implementing theme_preprocess_media, which adds the media object to the variables:

/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  $variables['media'] = $variables['elements']['#media'];
}

You can then access media. in your twig template and any connected fields on it just like Paragraph or Node.


How do I disable a module? I am trying to disable modules in Drupal 8, and I found some solution like Drupal console, but I am not sure how to use it with XAMPP.

I am unable to understand how I can disable a Drupal 8 module. With Drupal 7, that was possible directly from the user interface, but in Drupal 8 the checkboxes shown before the module name are disabled.

How do I disable a module in Drupal 8?

In Drupal 8, you cannot anymore disable modules: You can just install or uninstall them. Uninstalling a module has the same effect it had on Drupal 7 and previous versions: It removes the database tables the module installed.

On /admin/modules, Drupal shows you which modules are not installed, and which modules are installed. You can click the checkbox shown for the modules that aren't installed; clicking on Install at the bottom of the page will install them.

For installed modules, clicking on the checkbox shown before the module name doesn't have any effect. In fact, the checkbox is disabled.

To uninstall a module from the user interface, you just go to /admin/modules/uninstall (or click on the Uninstall tab visible on /admin/modules).

Select the modules you want to uninstall, and click on the Uninstall button shown on the bottom of the page.

Keep in mind that Drupal can still not being able to uninstall a module for various reasons, for example because the module implements an entity and you created those entities on the site.

You could also use Drupal Console for uninstalling a module, but you would need to install it (on the server). After you install it, and open a terminal window on the Drupal root directory of the site, with drupal module:uninstall <module_name> you would uninstall the <module_name> module.

From the user interface it's easier. It's the only possible way, if you are working on a remote site for which the provider doesn't allow you to use an SSH shell.


Adding form placeholders to text input fields Is there a way to convert a regular form and add placeholders with a module, or should this be done with a form template or with jQuery?

That's an HTML5 placeholder, you can just add it as an attribute to any element and HTML5 enabled browsers will react accordingly:

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

A short recursive function like this might be handy if you want to automatically add placeholders for every textfield in a form (based on the field's title in this example):

function MYMODULE_auto_placeholders(&$element) {
  if ( isset($element['#type']) && $element['#type'] == 'textfield') {
    // set placeholder
    $element['#attributes']['placeholder'] = $element['#title'];
    // hide label
    $element['#title_display'] = 'invisible';
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

Then in your form alter function just call

MYMODULE_auto_placeholders($form);

That method will work for pretty much every textfield on a form, with the exception of those that are added in #process functions (like the alt and title textfields of an image field for example).


Add Nested  List into $form I have something like this. How can I make $upload_items be a nested
 list under Upload examples

Something like

 Upload Ex

 YAY

What I have now

$upload_items = array(
  'PDF',
  'Video',
  'PNG, GIF, JPG, JPEG',
);
 $step_items = array(
    'Upload Examples',
    implode('

',$upload_items),
    'Describe The Project',
    'Assign Tags',
    'School/Company',
  );
 $form['step_list'] = array(
    '#prefix' => '

',
    '#markup' => implode('

', $step_items),
    '#suffix' => '

',
   );

Also, what is an easy way to add ids to these

Using #markup is ok, you want to use theme_item_list to easily build your list and add html attributes to it:
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_item_list/7


Drupal + Solr, how to boost search results with updated date? I'm trying to boost search results to give more relevancy to newly updated / created content. What I have tried is to use the following:

/**
 * Implementation of hook search_api_solr_query_alter
 */
function mml_search_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  // Boost by changed date. Fresher to top.
  $call_args['params']['freshness'] = 'recip(abs(ms(NOW/HOUR,ds_changed)),3.16e-11,10,1)';
}

But it doesn't seem to have any effect.

Any help would be appreciated.

Here is screenshot of solr admin side of the "field" Im trying to boost http://monosnap.com/image/A3c6WOGi71z0Smeke8tYgBbnoeNkyK

This module may be a solution https://www.drupal.org/project/search_api_sorts

Otherwise using you method above - According to this post http://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results

then you need to add an extra []

$call_args['params']['freshness'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),3.16e-11,10,1)';

However after testing I still can get the result I want.

For example the value 3.16e-11,10 ; as far as I understand it means a year of milliseconds that gives a score of 10 inside that time span. and then decrease after.

For testing I used

call_args['params']['qf'][] = 'recip(abs(ms(NOW/HOUR,ds_changed)),86400000,21,1)';

which should give Posts added/changed on the day a score of 21 and then decreases daily.

Testing with 3 identical listings.  And only title set at a boost rate over 1.  I cannot get the articles to listing in date. order. Have i missed something obvious.


Proper way to access data in a custom table I have a module for which I've created a custom table in the database. I want to access various data in the table.

Since normally accessing content types is done via the abstraction layer provided by Drupal itself I'm wondering what would be the most "drupal" way to access the data in my table.

I assume I could simply use Database::connection class and function, but it seems a tad brutal(so to speak).

Would it make sense to create a repository or am I just overthinking this and should just go ahead and use the Database class and be done with it.

If this question was about D7, you could start from what's suggested in the Developers Guide that comes with the Forena module (disclosure: I'm a co-maintainer of the D7 version). Here is a quote from its introduction:
Forena implements custom hooks to allow the report engine to be extended in many ways. Forena does use OOP methodologies, but also leverages the observer pattern so prevalent in Drupal.

There is then a common pattern that is used to extend Forena:

Implement a custom php class that lives in your module directory. You may extend any of the Forena classes, or write your own from scratch.
Implement the expected registration methods in your class (e.g. templates, formats).
In your module implement a hook (e.g. mymodule_forena_controls) that tells Forena the location of your class definition file.

These days, Forena has a dev version for D8 also, for which it's current status can be summarized like so (from it's release notes):

Basic rendering of reports and document types are complete, however the GUI version of the report writer has not yet been ported. Sufficed to say, this version can be used by Drupal 8 report writers who are comfortable writing .frx files and sql elements by hand.

Some more details to help you digest these release notes:

"SQL elements" refers to Data Blocks and the Data Sources they relate to, as explained in the Data Guide.
The ".FRX files" are the actual specifications of how you want you report to look like, as explained in the FRX Reporting Reference.
The "GUI version of the report writer" is what is explained in the WYSIWYG Reporting Guide.


add a search bar on a page and limit it to search only under post titles? I wand to add a search bar on a page called "dictionary" and want to limit it to post titles. I mean it should search only texts in posts tiles not the whole posts contents. Please explain me clearly step by step how to do it.

Regards
Ismail

Use custom_search module.

By this module you can create customize search form that searching on custome content type and custome fields on content type.


How do I create product variants? I have a product (for example, "Desk") which has two attributes (size and life). Size has the values small, medium, and large. Life has the values 7 years and 10 years.

The price is different for each variation. How can I change the price for each variation?

You would need to use the Ubercart Attributes module, which is included in the Ubercart core module. From the Ubercart user guide:

  Products are not created equally, and in some cases the customer gets
  to decide the type of product they want. For example, your store may
  sell t-shirts, and the customer may find a design they like but need
  to get it in a certain size. In a situation like this, you will need
  to take advantage of the product attribute system in Ubercart. It lets
  you define attributes (like size), give them options (like small,
  medium, and large), and enable attributes and options on a per-product
  basis. For an example, check out the Ubercart Beanie on the Livetest.

The module allows you to set different prices per attribute and it is not very difficult to setup really.

Having said that, I prefer the Drupal Commerce way of handling product variations.


Path (alias) does not work after migration, nor Content view I'm using the migrate (7.x-2.x-dev) module to import a node(s) from static HTMLs to Drupal 7, and I want to set the path the same as the original directory/filename.  I have defined in my migration class as follows,

$this->addFieldMapping('path', 'filename');
$this->addFieldMapping('pathauto')->defaultValue(0);

and it seems to be working - when I open the imported node in the edit mode, I see the correct path in the path field, and the Generate automatic URL alias checkbox is unchecked.

However, the path is not working.  Say, when the path is set to be info/legacy.html, and the node is 21,

http://localhost/node/21

is fine, whereas

http://localhost/info/legacy.html

returns 404 (Page not found).

In fact, the node is not listed in the Content page /admin/content either.  I found the node number (21 in this case) by browsing directly the SQL database (the entry of the node in the database looks no different from other nodes).

Everything else looks fine, I mean, all the fields related to the node are imported as I intend.  But the above-mentioned 2 points are weird...

Why is it so, and how can I achieve the above?  Any idea?

Actually, I have just found out it was due to the i18n setting of the node and site.  The language of the node was set to be ja (Japanese), correctly.  Probably because of that,

http://localhost/info/legacy.html

does not work (HTTP 404), but

http://localhost/ja/info/legacy.html

does display the node imported.

Similarly, the Content manager does not display the node in the default-language mode (English) /admin/content, however it does display the newly imported node in Japanese /ja/admin/content.  I should note I allow all the URL (Path prefix), Session, User, Browser in the language configuration (/admin/config/regional/language/configure) in my environment.

My browser's HTTP request, when I test, is

"Accept-language": ja

So, I expected when I opened

http://localhost/info/legacy.html

it would open the node in Japanese, following the browser's request, as opposed to 404, but it does not, apparently.

Hmm, I guess it is likely my understanding of the i18n handling in Drupal is not sufficient.  Anyway, I think this can be solved with the redirection module in Drupal, after investigating and finding out how to set it up during migration.  I didn't want the default URI to be something like node/21, but if it is ja/info/legacy.html, I am fine with it, as long as the redirection works.

[Edit: 2014-10-06]
I have figured out why.  In my i18n setting of Drupal, URI-path-prefix is checked and is given the highest priority, where English is default with its language-code for path-prefix being undefined.  Hence,

http://localhost/info/legacy.html

is the English version of the content, which does not exist.  When I define the language-code of English (en) for path-prefix, then the access to the URI brings up the Japanese version, if my browser's preferred language is Japanese (and the i18n of the site is configured to accept the browser's preferred language at the lowest priority), because the URI is not any more specific for the English version.

Another note is the redirection module works only when redirecting to a node URI [or path without the language-code prefix (added on 2014-10-11)].  The redirection to, for example,
/ja/info/legacy.html
does not work well, as it can bring up the path of

http://localhost/ja/ja/info/legacy.html

in some cases.

[Edit: 2014-10-11]
The whole point (and much more) is covered and summarised in the document published at drupal.org:  https://www.drupal.org/node/2354755


Background Images Paths are Changed when CSS Aggregation is On I have a Drupal 7 site with and Adaptives Themes subtheme enabled and set as default. I was recreating the Drupal 6 site in Drupal 7 on a subdomain and have recently transferred it over. My site has worked any problems until I turned on the aggregator for the CSS and JS files.

When my CSS files are compressed, the background images paths are not only absolute, background-image: url(images/relative_to_CSS_file.png) => background-image: url(/subdomain/sites/all/themes/theme_name/css/images/relative_to_CSS_file.png), it adds the subdomain in the path. Instead, I would like to just remove the subdomain.

I have flushed the caches a few times, but this problem persists. How do I update these files?

Thank you @jessehs from Drupal.org.

His solution, which worked for me, is the following:

  Long story short, the problem was that Adaptive Theme appears to be
  doing a "pre-caching caching" of the compiled CSS files in the
  sites/default/files/adaptivetheme/ directory.

  The way to get the aggregated files to actually build is to clear all
  caches and immediately save the theme's settings form at
  /admin/appearance/settings/[themename], then do another cache clear,
  just for good measure.

Also included at the source is a helper module that will flush these files when you flush the cache.

Source: https://www.drupal.org/node/1995938


drupal_mail() strips all html tags from emails So as the title explains, when sending an HTML email with drupal_mail(), email comes with no HTML tags.

    $module = 'module';
    $key = 'contact_message';
    $language = language_default();
    $params = array();
    $email = 'sender@email.com';
    $from = variable_get('site_mail', 'admin@example.com');
    $send = TRUE;
    $message = drupal_mail($module, $key, $email, $language, $params, $from, $send);
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8';
    $message['subject'] = 'Test';
    $message['body'] = array();
    $message['body'][] = 'Testing anchor in mail';
    $system = drupal_mail_system($module, $key);
    $message = $system->format($message);
    $message['result'] = $system->mail($message);

And when recieving the email, and viewing the source:

Message-Id: <201305090722.r497MLAV005654@test.server>
X-Authentication-Warning: testserver : www-data set sender to sender@email.com using -f
To: from@email.com
Subject: Test
X-PHP-Originating-Script: 1000:system.mail.inc
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 8Bit
X-Mailer: Drupal
Sender: sender@email.com
From: from@email.com

Testing anchor in mail [1]

[1] #

So you can see that any HTML tags were stripped.
And it doesn't matter what HTML tags I put in body.

I thought it might be related to Text Fomats, but I have "Filtered HTML" and "Full HTML" active filters with any permissions.

The thing confused me were the Ubercart invoices. At first they were sent with HTML, and then at some point it stopped. They were received plain text.
After digging a bit @develkar answer, I've found this in one of ubercart updates:

/**
 * Installs HTML Mail System for Ubercart.
 */
function uc_store_update_7004() {
  // Set mail handler for all Ubercart modules
  variable_set('mail_system',
    array_merge(
      variable_get('mail_system', array('default-system' => 'DefaultMailSystem')),
      array(
        'uc_cart'  => 'UbercartMailSystem',
        'uc_order' => 'UbercartMailSystem',
        'uc_file'  => 'UbercartMailSystem',
        'uc_roles' => 'UbercartMailSystem',
        'uc_stock' => 'UbercartMailSystem',
        'uc_store' => 'UbercartMailSystem',
      )
    )
  );
}

I guess that at some point, one of installed modules (I suspect SMTP module) overridden this variable, and that's why emails were coming plain text.
After running this update manually again, Ubercat invoices are HTML again.

For the rest of emails, I'll have to install some modules as suggested in other answers.

Thanx.

drupal_mail(), by default sends a mail as plain text.

If you print out the array $message['headers'], you will get something like:

array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  );

As you can see, the Content-Type in the mail header is text/plain; charset=UTF-8; format=flowed; delsp=yes. You can try by modifying this header in hook_mail_alter(), you could use one of the modules which allows you to send the mail as HTML, like HTML Mail, or Mime Mail.

Edit:

Following the comments by @Ayesh and @alechko and after looking into the APIs, I found out that the headers are not the only reason for sending the mail as plain text. Because drupal_mail() internally makes a call to drupal_mail_system(), which returns an object that implements the MailSystemInterface interface. The format() method implemented by drupal_mail_system() is responsible for stripping out the HTML from the emails. So, even if the headers of the mail show the formats to be HTML, the mails would be sent as plain text only. So, I guess one could not send an HTML mail using drupal_mail(). You should look for some other alternative (module) mentioned above.


How can I change a file before save in programmatically? I want to upload an audio file on Drupal, trim it, and save it in sites/default/files/audio/. I know how I trim the audio file; I only want to set my audio-trim-library in Drupal when the file is uploaded, and not when saved.

How can I do it?

My best guess is to use hook_field_presave() to alter it before it gets saved, for example:

function hook_file_presave($file) {
  // Change the file timestamp to an hour prior.
  $file->timestamp -= 3600;
}

See also: How do I change the uploaded file name after the node has been saved?


Show field from a join table on Views Let's consider a views on an entity named :"Person" .
"Person" has a field named "id" (the primary key)
"PersonTag" has a field named "person_id" (this field is referencing the id of "PersonTag" entity.

My issue is that I want to display in this views the fields of "PersonTag".
First idea was to try to implement a join with Person using hook_views_query_alter() . That was the main purpose of this question.
Well now I'm having the join on my query, but  can't figure out how to display the fields (of the join table) in my views.

So after some searches, I realised that I should use hook_views_data() as it explained in this question.

In documentation of hook_views_data() it's mentionned that:

  To provide views data for an entity, instead of implementing this
  hook, create a class implementing
  \Drupal\views\EntityViewsDataInterface and reference this in the
  "views" annotation in the entity class.

Since I'm having this class already created, I tried to implement my join in there.
Here are the code implemented:

 class PersonViewsData extends EntityViewsData implements       EntityViewsDataInterface {

/**
 * {@inheritdoc}
 */
public function getViewsData() {
$data = parent::getViewsData();

$data['person']['table']['base'] = array(
  'field' => 'id',
  'title' => $this->t('Person'),
  'help' => $this->t('The Person ID.'),
);

 $data['person']['table']['join'] = array(

'person_tag' => array(
  'left_field' => 'person_id',
  'field' => 'id',
  ),
);

$data['person']['id'] = array(
'title' => t('Example '),
'help' => t('Example'),
'relationship' => array(
  // Views name of the table to join to for the relationship.
  'base' => 'person_tag_field_data',
  // Database field name in the other table to join on.
  'base field' => 'person_id',
  // ID of relationship handler plugin to use.
  'id' => 'standard',
  // Default label for relationship in the UI.
  'label' => t('Example '),
 ),
 );
return $data;
 }
 }

This code doesn't work, I don't see any field appearing in my view.

Would help me to figure out the solution?

The solution is pretty simple.
Here is the code:

 class PersonViewsData extends EntityViewsData implements EntityViewsDataInterface {

  /**
   * {@inheritdoc}
   */
   public function getViewsData() {
   $data = parent::getViewsData();

   $data['person']['table']['base'] = array(
   'field' => 'id',
   'title' => $this->t('Person'),
    'help' => $this->t('The Person ID.'),
   );

 $data['person']['id'] = array(
'title' => t('Medecin tag test'),
'help' => t('Medecin tag test '),
'relationship' => array(
   // Views name of the table to join to for the relationship.
  'base' => 'person_tag_field_data',
  // Database field name in the other table to join on.
  'base field' => 'person_id',

  'id' => 'standard',
  // Default label for relationship in the UI.
  'label' => t('Test field'),
   ),
 );

 return $data;
 }
  }

Then you go in UI of the view:  Advanced-> Relation -> add a new relation.
You can see your new relationship there. After selecting it, go to "Add field ", you can then, find you new field that you can add to your view.

NB: There is no need to use hook_views_query_alter as mentionned in the question above.


How to check the Webform submission values in a twig template I have an Webform with an option element, (option_one), with 6 options.

Below this are 2 option elements with 5 and 2 options.

These 2 option elements have a conditional statement to display if the correct option is selected on the, (option_one), option element.

Added email handlers to the form for the site admin and the submitter.

Using the default email format, all display as per the Webforms default email output, with the correct option element hidden as per the coditional statements.

Goal

Build my own twig template to enable me to theme the email using inline styles.

Below is the code used to check for the selected options.

UPDATE

Question simplified:

How to compare a Webform token with a given value in a twig 'if' statement?

{% if webform_token('[webform_submission:values:airports_to_radio]', webform_submission, [], options) == Heathrow %}

Don't want or need to go and build a submit handler via hook_form_alter()

{% if webform_token('[webform_submission:values:airports_to_radio]') == 'Heathrow' %}

{{ webform_token('[webform_submission:values:heathrow_terminals_to]', webform_submission) }}

{% endif %}

{% if webform_token('[webform_submission:values:airports_to_radio]') == 'Gatwick' %}

{{ webform_token('[webform_submission:values:gatwick_terminals_to]', webform_submission) }}

{% endif %}

This works to a point. Both sections of the twig template do not display, so i assume that the syntax is correct, but not using the correct comparison.

Any help to get the correct syntax for the {{ if }} statement would be great, or any links to information on the web would also be great.

Webform source code below.

airports:
  '#type': fieldset
  '#title': Airports
  airports_to_radios:
    '#type': radios_other
    '#title': Airports
    '#options':
      Heathrow: Heathrow
      Gatwick: Gatwick
      Stansted: Stansted
      Southend: Southend
      'London City': 'London City'
      Luton: Luton
    '#options_display': buttons
    '#other__option_label': Hotel
    '#other__title': Hotel
    '#other__placeholder': Hotel
  heathrow_terminals_to:
    '#type': radios
    '#title': 'Heathrow Terminals'
    '#options':
      'Terminal One': 'Terminal One'
      'Terminal Two': 'Terminal Two'
      'Terminal Three': 'Terminal Three'
      'Terminal Four': 'Terminal Four'
      'Terminal Five': 'Terminal Five'
    '#options_display': buttons
    '#states':
      visible:
        ':input[name="airports_to_radios[radios]"]':
          value: Heathrow
  gatwick_terminals_to:
    '#type': radios
    '#title': 'Gatwick Terminals'
    '#options':
      'South Terminal': 'South Terminal'
      'North Terminal': 'North Terminal'
    '#options_display': buttons
    '#states':
      visible:
        ':input[name="airports_to_radios[radios]"]':
          value: Gatwick
  customer_email:
    '#type': email
    '#title': 'Customer Email'
    '#default_value': test@localhost

Adding :raw to your webform submissions value has worked for me.
{% if webform_token('[webform_submission:values:airports_to_radio:raw]') == 'Heathrow' %}


Make CKEDITOR Caption Required Using Drupal 8 Ckeditor Core plugins -> drupalimage/drupalimagecaption how do I make an image caption required? The checkbox shown should always be clicked.

The CKEditor image dialog is a form, so you can change it via Drupal Form API with hook_form_alter:

/**
 * Implements hook_form_alter().
 */
function MyModule_form_alter(&$form, $form_state, $form_id) {
  // Check if the form is editor_image_dialog.
  if ($form_id == 'editor_image_dialog') {
    // Make caption required.
    $form['caption']['#required'] = TRUE;
    // Change default_value to true.
    $form['caption']['#default_value'] = TRUE;
  }
}


How to get nodes from Google Search? I'm using CSE in my drupal website and due to some technique restrictions i couldn't use Solr search.

My news portal gives a " RELATED CONTENT " block to each article using tags similarity but i'm not very satisfied with the result.

I wonder if there's a way to integrate Google Search (like solr module does) to return back (in a view) a list of similar nodes by searching the title for example.

What you're describing is a content recommendation system. This isn't what Google CSE is built for and implementing the way you describe would likely result in poor results.

You're better off implementing one of Drupal's existing recommendation modules or some other 3rd party recommendation service (e.g. OutBrain).

Some of Drupal's recommendation modules include:

Recommender API: Broad API that ties into other Drupal entities.
Similar By Terms: Use similar taxonomy terms to find related content.
Similar Entries: Uses MySQL full text searching to find related content.


theme_username($object) in Drupal 7? In my author_pane template, I get my user´s names trimmed as it was back then in Drupal 6.
So I went to the api page (as I did in my D6 installation) and I see that the code that used to work in Drupal 6 isn´t there anymore in Drupal 7.

This was the code I´m looking for:

function theme_username($object) {

  if ($object->uid && $object->name) {
    // Shorten the name when it is too long or it will break many tables.
    if (drupal_strlen($object->name) > 20) {
      $name = drupal_substr($object->name, 0, 15) . '...';
    }
    else {
      $name = $object->name;
    }

How may I ensure in D7 that my username´s names aren´t being trimmered at 20 character´s length?

That code has been moved in template_preprocess_username(), which is called before the theme function.

// Set the name to a formatted name that is safe for printing and
// that won't break tables by being too long. Keep an unshortened,
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = format_username($account);
if (drupal_strlen($name) > 20) {
  $name = drupal_substr($name, 0, 15) . '...';
}

If you need to use the full-length name, you should use $variables['name_raw'] in your implementation of theme_username(), remembering that the value has not been passed to any sanitization function.


White screen after deleting a module I have a white screen "The website encountered an unexpected error.". The
"update.php" is not working.

I deleted a module that still was installed (big mistake).
I moved the module back into the folder. But has the white screen.
The watchdog table in SQL says that the used module is still missing.

Is there a chance to fix this?

Maybe in SQL? (I use Sequel Pro in place of myPHPadmin).
Installing Drush seems to be complicated. I'm no programmer but a little experienced in coding with Drupal.

I looked many links online, but did not found the right solution.
Thank you.

If you deleted and returned a module to its original place, then all it takes for the website to start working normally again is to get cache refreshed, which will bootstrap it.

You can do it by:

Running the update.php file. Make sure to set $settings['update_free_access'] = TRUE; on the settings.php file.
Using drush. Installing drush is not as complicated as it might sound. Just follow instructions on http://docs.drush.org/en/master/install.
By clearing cache tables directly in the database. Just use some kind of user interface for the database like, for example, phpMyAdmin, open the website's database and truncate all the tables starting with cache.
If none of the above methods works, then try to uninstall and re-install the module or manually remove all database references to the fields which were created by the module.


How to load custom block via code? I created a new custom block type from /admin/structure/block/block-content/types  having  x and y fields with field types image and textfield respectively.  Then created a block with the same block type  and uploaded image in x and some text in y.  Here  my problem is: how to load this block via code?

More than that how to get values of these block fields x and y  by loading the block?

I tried these:

$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityManager()->getViewBuilder('block_content')->view($block);

but it didn't work.

Place the block in the disabled section at admin/structure/block, this creates a block instance with your block_content type, give it a nice easy machine name to remember.

By placing it in the disabled section, it won't show up, until you load it programatically.

Then using your machine name:

$machine_name = 'myblock';

$block = \Drupal::entityTypeManager()
  ->getStorage('block')
  ->load($machine_name);
if (!empty($block)) {
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  $pre_render = $block_content;
}

If you really want to get the rendered fields, you can do:

$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->build($pre_render);

But it is more standard practice to use Drupal's formatters and such and perhaps a custom template, rather than building the block and extracting elements from the rendered render array.


Reset frontpage after changing it to user I wanted my drupal site content to only be accessed by users who login.
I have a front-page which works fine:   "mysite.com/"
I want users to be re-directed to:
"mysite.com/user"  or   "mysite.com/?q=user"

So, I went into the Admin > Site Configuration > and changed the front page to be /user

Unfortunately, my home page is exactly the same, no change there, and now I can't access the login to get back in as an Admin.

So, there are two questions:

1) How do I go into the database to reset this setting by hand, or is there a php file I have to go into?

2) Once I get my home page back, and the /?q=user page working again, how can I force users to that page to login before anything that happens.

This is Drupal 7 ... I remember Drupal 5 and 6 being so much easier to manage.

I am also using the MD Apline theme if that matters ....

Thanks for any help!
                               Tom

That's a pickle. This should get you out of it:

drush vset site_frontpage node

Or if you don't have access to drush (why would you use drupal without drush?) you can run this sql:

DELETE FROM variable WHERE name = 'site_frontpage'


How to return a View's content in search results? We have a page display of a view that contains two or more nodes, but when searching for a keyword that would pertain to those nodes, only links to the individual nodes are returned.  What we really want is just the link to the page display of the view to be returned, but it doesn't show up in the results list.

I'm looking into caching the View and index the cached content through a custom module, but i was wondering if anyone has come across this situation and can share their solution?

edited: made some clarifications.

There is the Search by Page module that allows this (and much more). Some details from its project page:

This module is an enhancement to the core Drupal search module, which adds a new tab to the core Search page or can also be used in stand-alone mode. The differences between Search by Page and the existing tabs in the core Search module lie in what is indexed for searching and how it is indexed:

Search by Page indexes the content of your pages as rendered by your theme (Search indexes the default rendering you would have from an unmodified theme)
Search by Page allows you to omit content from indexing (such as "database table" node types that should never be viewed as stand-alone content)
Search by Page allows you to index non-Node pages, including user profiles, file attachments, and Views
Search by Page is language-aware, so it only shows you results in the current language.
Search by Page has multiple search "environments", so you can have different search pages/blocks to search different things.

Maybe you can use that or look how they index the views pages.


DD-Block resizes images I'm developing a website in Drupal 6, and I've employed Dynamic Display Block for a slideshow that displays in a panel.

Unfortunately, even though the images show in the slideshow, they are not rendered in their full size as I described in the configuration page of the Dynamic Display Block settings.

I used firebug, and I realised that a class called ddblock-processed has been added which is the cause of the issue i'm facing, as it has different dimensions compared to the one I specified.

I've tried overriding that effect in the style sheet - css, but to no avail.

Someone should kindly help me hack this stuff under the hood.

Thank you.

ddblock-processed class is added to your div when the Javascript event is attached to it by Drupal. This is normal behavior, but it shouldn't be too hard to override the style with CSS.

To show you a simple example of CSS overrides (even though this is considered an inefficient selector, it doesn't matter too much in cases such as yours):

If on the original style, the CSS is declared as follows:

.ddblock-processed {
  width: 100px;
}

You can easily override it in your own stylesheet by including the "parent" element in the CSS selector. So if ddblock-processed div's parent is a div with an ID of myregion then doing this will override it:

div.ddblock-processed {
  width: 200px;
}

/* OR */

#myregion .ddblock-processed {
  width: 200px;
}

/* OR */

body .ddblock-processed {
  width: 200px;
}

/* OR */

div .ddblock-processed {
  width: 200px;
}

This is called CSS specificity if you want to read up about it.


Adding conditional css to view or display type Hi i have created a view that displays recently viewed items. This displays the 'teaser' display mode of a custom content type. This content type has a field 'favorite'.

What i want is to add a css class to the outer div (on the teaser div or de col-... generated by the view). But only if it is a 'favorite'.

I have created the view in the Drupal backend I could probably do in a custom module. I just want to check if it is possible without any programming.

You could try this but may depend on your 'favourite' field output

If you click on "Format > settings" when editing your view you'll see a "Row class" field. In there you can put the replacement pattern for your favourite field.

So if its populated it will add the field value as a class to the view-row div. And you can use this to know if the field has content

If that's not going to work because the field content isn't suitable as a class then you could preprocess the node view and add a class yourself in the attributes array


Full archive configuration export doesn't work When I go to /admin/config/development/configuration/full/export and want to export the full archive, the site loads for a while and then just goes completely blank and the URL bar shows /admin/config/development/configuration/full/export-download.

There is no error in the server log files and no entry in the Drupal reports.

In the sync directory sites\default\files\config_[...]\sync there is no file except for the .htaccess.

And when I try drush cex or drush cex sync this error occurs:

PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in C:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\lib\Drush\Command\DrushInputAdapter.php on line 27

I've tried everything with the settings.local.php enabled and disabled. But the export just doesn't work. What can I do?

Firstly, What is the version of drush?

I advise that you use the console bundle(add it via composer:  "drupal/console": "~1.0")

and then execute this command

drupal config:export  --directory="modules/custom/import_export_config/config/install/"


Can I call drupal_goto in form #submit handler? I've a node type Person and want to attach a new submit handler.
Will it be fine if I call drupal_goto to another URL from within this new submit handler?

What I want to do is to ask for some confirmation message and then save the node using drupal_execute.

In the submit handler I'll save $form_values in session using key form #build_id
and then in it I'll redirect it to another url with this build_it in the url as GET parameter. In the redirected form url I'll be doing some checks on the node data( if same title node already present etc) and asking for confirmation. If yes then I'll create/save the node myself using drupal_execute.

Will it work this way?

Can you call drupal_goto in a submit handler: Yes
Should you call drupal_goto in a submit handler: No

Why?

The reason is that potentially other submit handlers might need to be called in order for things to work properly. If you call drupal_goto you would stop the execution flow and make it impossible for the other submit handlers to do their thing.

What you should do instead is to use $form_state['redirect'], which when set will be the url that is redirected to when the submission process is completed.

In your specific use case, however it could work since you don't want the node to be saved, but stopping the process in this way could give you strange bugs/side effects.

But you really should't be doing it this way.

Instead you should attach a validate handler to the node form. If the validation fails the node is not saved and you can display any message to the user via drupal_set_messsage or form_set_error. You could save in $form_state that the message has been displayed to the user and allow him to save the node anyway if he resubmits the form. This is what the validate handlers are built for, after all.


Drupal Views Date Views - Today in History (month, day) I am using Drupal 7, Views, Date Views, and Date module.
My database uses a field named "release date" which contains the date that specific items were released (Month/Day/Year)
I would like to customize my view to show only content with today's date (historically) basically showing all items that were released on this Month/Day in a block so that every day new content is displayed.
Can someone lead me in the right direction to accomplish this? Thanks

Add to your view a contextual filter: add your date field and select "Provide default value: current date". Then, in Granularity (in the same field settings, lower), set the granularity to a "Day" so that only content that was marked for that day is displayed.


Admin Menu at bottom of screen My admin menu keeps randomly showing up at the bottom of the page. Any ideas why?

EDIT: I've continued to pay attention to the behavior.. and it appears to only happen when there is a "message" displayed at the top (in the green box).

Drupal core 7.16 with Omgea 7x-3.1 theme and loads of modules. Just experienced the similar behavior where admin menu was locked at bottom of the page. Read through this, decided to not touch Skinr and instead:

Home » Administration » Configuration » Administration

Turn of the "Adjust top margin", save, clear cache, turn on "Adjust top margin" AND "Keep menu at top of page" - this solved the problem in my case.


Elysia cron module does not execute cron job automatically I have installed the elysia cron module and setup the cron job. My module has a cron function test_cron() which inserts some data into a table.

This function lists in the elysia cron status page. I have setup the the default scheduled rule to */1 * * * * to run the cron after every minute.

When I click on the run infront of the test_cron() the cron runs and some data inserts into the database.

But this the manual method, I want to execute the cron after every minute therefore I defined the scheduled time for the test_cron(),  but it does not executed automatically after every minute.

What should I do? Is there any other configuration which I should do to run the cron automatically?

As I mentioned before Elysia Cron can only schedule the cron jobs not control it when to run.
If system crontabs are set to run every minute elysia cron module can control it from there on.
Check out the drupal page for that module.

  Elysia Cron
  However to get the full potential out of elysia cron and have the full
  control over you tasks a further step is needed: you need to configure
  the system crontab to execute drupal cron every minute.


Sort criteria in views: how to add custom one I have added a "node title" field.  I want to add this sort criteria to the node: the number of times the node  has been viewed by visitors in a week, descending.
If I want to add a sort criteria with PHP code and a SQL query to insert in Views module, how should I do?

ps:i have overwritten a field. i want to query the database and using the query to Sort Criteria**how to add the custom one

First, make sure you have Drupal's Statistics module enabled and collecting page view statistics.

In Drupal 6, you need to enable Count content views under admin/reports/settings. This will count total node views and give you total day count. Unfortunately, it does not give you a weekly view count by default.

This will give you a sort criteria for Node statistics: Total views and Node statistics: Views today.

Upon closer inspection of the day count for node views, this value is reset to 0 every 24 hours by statistics_cron. This value would prove more useful as a sort criteria if it was the most recent 24 hour's node views. So, the Node statistics: Total views would be your best bet.

NOTE: See Statistics Granularity module for week, month and year.


How to clone a node without translations I have a site with multiple language. Assume I have a node (nid = 1) with origin languages is en and translate to es. And I clone this node with code:

$node = Node::load(1);
$nodeDuplicate = $node->createDuplicate();
$nodeDuplicate->save();

And I have a new node (nid = 2), and the new node have two content translate en, es same the node id 1.

But I don't want clone all content translate. I only want to clone one language es or en. So how can do that?

A suggestion : use ->removeTranslation() to get rid of the languages you don't want to be cloned.

Example to get rid of 'es language' so that we clone only the english version :

$langcodetoremove = 'es';
$node = \Drupal\node\Entity\Node::load(1);
$node->removeTranslation($langcodetoremove);
$nodeDuplicate = $node->createDuplicate();
$nodeDuplicate->save();

hope this helps


How do I set the creation time of a node during a migration using the Migrate module? I am building a migration and it is important that each new node has the same creation time stamp as the cosponsoring data in the old system.   How do I set the creation time of a node during a migration using the Migrate module?  I am assuming that it is set by a specific call to addFieldMapping()

I've been using prepareRow in my class to solve this kind of problem .

First of all I add a new Source Field to the MigrateSourceSQL

$source_fields = array(
  'created' => t('the created date'),

then in prepareRow I added the php for the timestamp and attached it to the row.

$row->changed = $nowtimestamp;

And then assign with addFieldMapping

$this->addFieldMapping('field_created_date', 'changed' );

This seems to work fine for me.


Can you dynamically request a (cached &) scaled image via imagecache in css? Is there a way to request a scaled image via imagecache by adding width/height parameters or a preset-reference to the image url within css? For example:

Obviously, to scale down an image in css, you can do the following:

HTML:

<figure id="logo"></figure>

CSS:

#logo {
  background: url('path/to/image.jpg') no-repeat;
  width: 50%;
  height: 50%
}

This will still load the full sized image and scale it down on the client side. I am wondering if something like the following is possible within CSS, so you dynamically request a scaled image via imagecache:

#logo {
  background: url('path/to/image.jpg?width=50px&height=50px') no-repeat;
}

or

#logo {
  background: url('path/to/image.jpg?preset=existingimgpreset') no-repeat;
}

Which will scale down the image on the server side and hopefully will return a cached version of it when possible.

The URLs imagecache produces are pretty reliable, and contain the name of the preset. Looking at the code in imagecache_create_url() you could build up a path in your CSS that looks something like this:

/sites/default/files/imagecache/preset-name/path/to/image.jpg

Assuming that your files are stored at /sites/default/files


Decryption failed because the HMAC could not be validated while decrypt I am using the Encrypt module to encrypt some of user object data.

I can encrypt data, but while decrypt it, I get the following error:

  Decryption failed because the HMAC could not be validated

encrypt('name') // It works.
decrypt('some encrypted data') // It throws the above error.

How can I decrypt data using that module?

I have found below solution. I have un-serialized encrypted data. Found below details.

Used above input to decrypt function.

$options = array();
$method = 'mcrypt_aes_cbc';
$key_provider = 'drupal_variable';
$config = array('provider_settings' => array('method' => 'variable_contents')); // I have updated method name later.
decrypt('encrypted_text', $options, $method, $key_provider, $config); // It works now :)


How to remove title field from content edit page? i want remove field title in any content type on drupal 7. i use module display suite and hidden title but when i add new content that "title is required .......................................... ". thank you for help.

i want remove title field in any content type.

You want to either:

Remove the title field completely using the Fields UI. See this documentation page on the Fields UI. If you really don't want a title then just remove the field from the content type.
Use the Automatic Nodetitle module to create a title from a Token and hide the title in Edit Forms.
If not a Node, use the Automatic Entity Label module to create a title and then hide it from users in the Edit forms.

In general most content types need a title. Titles are the Names we give content to find them using Search forms and pages.


admin/commerce/orders/{orderId}/payments/add "You are not authorized to access this page." When I try to add a new payment to an order (either created by a customer or via the backend) I always encounter the "You are not authorized to access this page." error.

My user has the administrator role.

I'm running core 8.6.7 and commerce 2.11.0

To solve this issue, I needed to add one payment method that is not "Offsite"

the error message is just very misleading.


How to translate a warning message? There is a code
define('SPAMBOT_DEFAULT_BLOCKED_MESSAGE', 'Your email address or username or IP address is blacklisted.');
How to make the phrase 'Your email address or username or IP address is blacklisted.' translatable? (with t).

Depending on how often it appears, you can call t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE) every time you invoke the constant in your code. For instance:

<?php

define('SPAMBOT_DEFAULT_BLOCKED_MESSAGE', 'Your email address or username or IP address is blacklisted.');

/**
 * implement hook_page_alter()
 * JUST AN EXAMPLE. REPLACE WITH YOUR OWN HOOK OR FUNCTION
 */
function mymodule_page_alter(&$page) {
  drupal_set_message(t(SPAMBOT_DEFAULT_BLOCKED_MESSAGE));
}

In order to be able to see the string in the "Translate interface" page (admin/config/regional/translate/translate), you need to display it at least once in a language different from the default language of your site.


How do I create a summary that is grouped by years first and then months in Views using contextual filters? Instead of the default formatted result of «Created year + month»:

 - Diciembre 2014 (12)
 - Noviembre 2014 (20)
 - Octubre 2014 (23)
 - ...
 - Diciembre 2013 (13)
 - Noviembre 2013 (34)

I would prefer something like:

2014
 - December (15)
 - November (14)
 - October (12)
 - ....

2013
 - December (19)
 - November (21)
 - October (13)
 - ....

I'm using Drupal 7.

In Views you can group results (e.g., by year), which can be found in the format settings. Within each group, the results are sorted according to your sorting criteria.

Although not exactly the same question, I think the answer of Views: how to ASC sort the grouping field #1 and sort DESC its content? is still applicable to your question.


_form_comment_form_alter for certain node type When using the hook_form_comment_form_alter, how do I only target the comment form of a single content type?

Right now it is targeting all comment forms, and I need it to just target the 'Blog' content type comment forms

You should use comment form ID for that content type: hook_form_comment_node_xxx_form_alter

which comment_node_xxx_form is comment form id for content type xxx:

function hook_form_comment_node_xxx_form_alter(&$form, &$form_state, $form_id) {
    ...
}


Is it possible to override a core function instead of just altering it? I would like to add a feature to the core string contextual filter, implemented in core/modules/views/src/Plugin/views/argument/StringArgument.php.

If I use hook_views_query_alter(), I would have to undo everything the core function did first, then roll out my changes.

Is there a way to just completely override the core function instead of only altering the results?

The contextual range filter accomplishes this by presenting the site admin with a configuration page to select which instances of an existing filter should be replaced by the new object. I could follow this route, but I would prefer to update all cases site-wide.

Personally I would make an inheritance from this core plugin, extend it in my own class (classes), and change in the views to use my custom plugin.


page.tpl.php base on a field criteria in views I'm working on creating different themes in different pages of a site base on several conditions.

first, I want to create a page.tpl.php for all view pages in my site.

second, I want to have tiny specialization on it base on the filter criteria field's value or selected field's value in a page view. I mean different page.tpl.php based on fields value criteria.

I need to change the overall theme so it is not duplicate of is it possible to have one views-view--VIEWNAME--page.tpl for multiple views?

I need to know how to access field's value in my "function MYTHEME_preprocess_page(&$vars, $hook) ".

Salam,
You can do this using hook_preprocess_views_view(&$vars). Your code should be like this:

function YOURTHEME_OR_MODULE_preprocess_views_view(&$vars) {
    $view = $vars['view'];
    // the values of the view, filter criteria and the value of fields are in $view
    if(CONDITION1 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages1'
    else if(CONDITION2 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages2'
}

Then create files views_view__custom_pages1.tpl.php and views_view__custom_pages2.tpl.php and theme the view. In this way different themes are defined for the same view.

You also said I need to know how to access field's value in my "function MYTHEME_preprocess_page(&$vars, $hook) ", what variables do you need to find it's value?


Custom breadcrumbs from a breadcrumb builder disappear until I clear Varnish cache Unrelated to this question, which is about how to properly inject breadcrumbs as a renderable item into a node template.. I have a custom breadcrumb builder for certain node types with the same sort of cache clearing issue.

After I deploy code to production, and clear the Drupal cache, about 50% of the time anonymous users stop seeing breadcrumbs on these 3 node types. I find that I have to clear cache again, then clear the Varnish cache on the server, and then they appear again for anonymous users. Am I missing something in the build method?

<?php

declare(strict_types = 1);

namespace Drupal\harlib_breadcrumbs;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Routing\AdminContext;
use Drupal\node\NodeInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;

/**
 * Class ContentTypeBasedBreadcrumbBuilder.
 *
 * @package Drupal\harlib_breadcrumbs
 */
class ContentTypeBasedBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * The AdminContext service.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * The AliasManager service.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    AdminContext $admin_context,
    AliasManagerInterface $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->adminContext = $admin_context;
    $this->aliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) : bool {
    if (!$this->adminContext->isAdminRoute()) {
      $parameters = $route_match->getParameters()->all();

      if (isset($parameters['node']) && $parameters['node'] instanceof NodeInterface) {
        $types = ['story', 'press_release', 'news_mention'];
        $type = $parameters['node']->getType();
        return in_array($type, $types);
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    if ($url = $this->getNodeUrlByAlias('/about')) {
      $breadcrumb->addLink(Link::fromTextAndUrl($this->t('About'), $url));
    }

    if ($url = $this->getNodeUrlByAlias('/about/news')) {
      $breadcrumb->addLink(Link::fromTextAndUrl($this->t('News'), $url));
    }

    $breadcrumb->addCacheContexts(['url.path']);
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);
    return $breadcrumb;
  }

  /**
   * Create a Url object if the alias matches a node object path.
   *
   * @param string $alias
   *   The node alias.
   *
   * @return bool|\Drupal\Core\Url
   *   A Url object, or FALSE if no result found.
   */
  protected function getNodeUrlByAlias(string $alias) {
    $path = $this->aliasManager->getPathByAlias($alias);

    if (preg_match('/node\/(\d+)/', $path, $matches)) {
      $id = $matches[1];
      return Url::fromRoute('entity.node.canonical', ['node' => $id]);
    }

    return FALSE;
  }

}

Pretty sure I found the root cause. I found some errant code here in the else condition.

/**
 * Implements hook_preprocess_block().
 */
function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'system_breadcrumb_block') {
    if (...) {
      $variables['attributes']['class'][] = 'hl__breadcrumb--light';
    }
    else {
      if (!empty($variables['content']['#links'])) {
        if (count($variables['content']['#links']) == 1) {
          $variables['content'] = [];
          $variables['elements']['content'] = $variables['content'];
        }
      }
    }
  }
}

Deleting the entire else block seems to have corrected the issue, unable to replicate it now.


Drush terminated abnormally Drush version 9.7.0 Drush Launch version 0.6.0 Drupal ver 8.7.3 Open social dist 5.5.

The error I get at the command line when running drush topic or drush cr or any Drush command:

  [warning] Drush command terminated abnormally. Check for an exit() in
  your Drupal site.

I have tried reinstalling Drush, removing and reinstalling, clearing cache via the GUI, but nothing seems to help.

I don't know where to check for an "exit() in your Drupal site".

Use an IDE to open your site and search into all your files.

When you find one exit(), comment it and try to use Drush again. Do it until you find the exit() that block Drush.


Display different form of user's name to different users? Is it possible to render a user's username differently to different users?

Here's the use case: I have a username with a user's First + Last name (created using the Realname module). In the user's profile, I have a setting for 'name privacy' - if the user wants to keep his last name private, the name should show as just 'First' instead of 'First + Last' to anyone who is not a site admin.

Would hook_username_alter() work for this purpose? It seems that is not dynamically loaded, but rather is cached when the user object is cached... so it couldn't simultaneously display 'First' to one user and 'First Last' to another user.

Reference: http://drupal.org/node/1194546

Basically, the easiest way to do this involves a couple steps:

First, implement hook_username_alter() in your custom module to change the username dynamically, depending on the context of the username's display (you can, for example, load the global $user object and display one form of the account in question's name to $user's with the role 'teacher', and another form to $user's with the role 'authenticated'...

Second, you will only be able to dynamically control the username as returned by $user->name or by theme('username', account) using hook_username_alter(). You can't change a username dynamically via realname, because that module stores the name in the database and caches it for performance reasons.


How do I give a role permission to set a site variable? I have a custom variable in one of my modules and I want to be able to give permission to that variable to a specific role on my site.

I have the hook_permission function setup and I can see it in the admin/people/permissions interface, but I'm not sure how to implement a hook or whatever to give the user access to admin/config/system/variable/edit/my_custom_variable

One method would be to use something like https://drupal.org/project/config_perms to add a custom permission to the admin/config/system/variable/edit/my_custom_variable path. You can then use this custom permission to grant access to it.


Loop over first three items of a list in Rules I have a list and need to loop only over the first 3 elements of that list in Rules, but I cannot find the option to do this. It seems to be more complicated than I had thought.

Install Conditional Rules so that you can add "conditions" between " rule actions". After that you can create a variable which iterates and use that to stop after the third elements.


Is it mandatory to apply every minor Core upgrade step by step? I have a site in drupal 6.26 and I need actualize it.

I have two options:

6.26 to 6.27 to 6.28

or

6.26 to 6.28 directly

What is the best method? Thanks

You can go from 6.26 directly to 6.28.

The most critical part, is the database update, because tables and fields can get modified, added or removed. The upgrade process in Drupal takes care of executing every single database update step.


Main Menu Display Description as span Tag I modifed my main menu using the following code, but I need the  elements only for the first level menu items, not for the sub-menu items.

How can I achieve this?

function neofelis_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $element['#title'] .= '' . $element['#localized_options']['attributes']['title'] . '';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Looks like your friend is: $element['#original_link']['depth'];

You would adjust your conditional to be something like:

 // Not sure if top level depth is 0 or 1 for this so experiment with that a bit.
 if ($element['#original_link']['menu_name'] == "main-menu" &&
     isset($element['#localized_options']['attributes']['title']) &&
     $element['#original_link']['depth'] == 0
 ){
    $element['#title'] .= '' . $element['#localized_options']['attributes']['title'] . '';
 }

Check out this comment from the drupal documentation.


Preview different then output in views I'm a newbie in drupal. So I have this view which Im saving as a block and the way it displays in the preview of the view and on the page is different. Any ideas?

If you have any questions about my configuration just ask I didn't know what to include :)

This displays data after all the filters, arguments, etc are applied. It's kind of like the raw output. You're theming will be displayed when the actual page is loaded with the block enabled for that page.


Alter entity reference autocomplete field I have made a module to alter the way entity reference works with autcomplete fields. I have override the entity_reference_autcomplete function where i have changed the following line:

        $key = "$label ($entity_id)";

with

        $key = "$label";

It seems to work when completing fields in form , but after the form has been submitted the autcomomplete field gets blank and the result is not saved . How can i solve this issue ?

This should be done by writing a custom CTools EntityReference selection plugin.  Your new class would just extend EntityReference_SelectionHandler_Generic_node and I think it would only need to override the getLabel() method to make things "just work".


Why does my site whitescreen with content? I am creating a drupal 8 site.  I have only installed two modules so far, Devel and Varnish.

However anytime I try to create an article and save it any page on the site that isn't an admin page is just White screen of Death.

I have no idea what could be causing this problem.  Why would it cause the white screen?

Drupal 8 is still in beta so things are still going to be rough there.

WSOD's are usually a symptom of some PHP error being hidden by the web server (many default PHP setups don't advertise errors). The d.o. page on WSODs gives good advice on how revealing these errors and diagnosing the problem.


Build StackExchange-style url's I'm looking for a way to build what I call 'StackExchange style' url's with Drupal 7. In my definition, that means:

A node has a path alias containing both a unique identifier and the node title. For instance, if I'm writing a story and every chapter is a node, chapter 4 (titled "The day I became a lobster") would get www.example.com/chapter/4/the-day-i-became-a-lobster.
If a user knows the chapter, but not the title, he can just go to www.example.com/chapter/4, which will redirect to www.example.com/chapter/4/the-day-i-became-a-lobster.
If the title changes (www.example.com/chapter/4/the-day-i-became-a-lobster becomes www.example.com/chapter/4/the-day-i-became-a-penguin), or if the url is mistyped (www.example.com/chapter/4/the-day-i-become-a-lobster), the old or incorrect url redirects to the new / correct url.

I want this behavior because:

In some cases, my users know a product number but not the title. This way they can easily figure out the url.
Having the title in the url is good for SEO and user experience.

I guess the best approach would be to build the complete url using Pathauto and set up a redirecting mechanism that kicks in when the path start with 'chapter/[id]' but it's not a valid path alias.

Of course I can create a custom module, implementing hook_menu for the 'chapter/%' path, lookup the correct chapter node and call drupal_goto, but maybe there are better methods. How would you do it?

PS. I posted a similar question in the issue queue of Redirect, because that module looks related and very promising.

I wrote a custom module to do this very thing. I use Pathauto to automatticly create aliases for my nodes, in the form of questions/123/title-of-node-here. The following code creates a /custom404 page. I configure my "Default 404 (not found) page" (in Site information) to custom404. The module picks the node id out of the url, checks for its existence, and then redirects to node/%nid. Finally, the Global Redirect module will take over and redirect the user to the canonical url.

/**
 * Implements hook_menu().
 */
function custommodule_menu() {
  $items = array();

  $items['custom404'] = array(
    'title' => 'Page not found',
    'access callback' => TRUE,
    'page callback' => 'custommodule_page',
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function custommodule_page() {
  $path = _custommodule_request_path();
  $parts = explode('/', $path);

  // The following lines matche a path alias to a content type
  // map /questions/%nid/%title to the 'question' content type
  _custommodule_match_nid($parts, 'questions', 'question');
  // map /websites/%nid/%title to the 'website' content type
  _custommodule_match_nid($parts, 'websites', 'website');

  drupal_set_title(t('Page not found'));
  return ' ';
}

/**
 * custommodule_request_path() is copied from globalredirect_request_path
 */
function _custommodule_request_path() {
  if (isset($_SERVER['REQUEST_URI'])) {
    if (isset($_REQUEST['q'])) {
      $path = $_REQUEST['q'];
    }
    else {
      // This is a request using a clean URL. Extract the path from REQUEST_URI.
      $request_path = strtok($_SERVER['REQUEST_URI'], '?');
      $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
      // Unescape and strip $base_path prefix, leaving q without a leading slash.
      $path = substr(urldecode($request_path), $base_path_len + 1);
    }
  }
  else {
    // This is the front page.
    $path = '';
  }

  // Under certain conditions Apache's RewriteRule directive prepends the value
  // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
  // slash in place, hence we need to normalize $_GET['q'].
  $path = ltrim($path, '/');

  return $path;
}

function _custommodule_match_nid($parts, $path_root, $node_type) {
  if (count($parts) >= 2 && $parts[0] == $path_root && ctype_digit($parts[1])) {
    $id = $parts[1];
    $args = array(
      ':nid' => $id,
      ':type' => $node_type,
    );
    if (db_query('SELECT count(nid) FROM {node} WHERE nid = :nid AND type = :type AND status = 1', $args)->fetchField()) {
      if ($alias = drupal_get_path_alias('node/'.$id)) {
        _custommodule_goto($alias);
      }
    }
  }
}

function _custommodule_goto($path) {
  $options = array(
    'fragment' => '',
    'query' => NULL,
    'absolute' => FALSE,
    'alias' => FALSE,
    'prefix' => '',
    'external' => FALSE,
  );
  unset($_GET['destination']);
  drupal_goto($path, $options, 301);
}


How to delete all data when uninstalling a module without going in manually in PHPmy Admin? Whenever I have a troublesome module, I have to uninstall it, then delete the folder, then go play around PhpMyAdmin to delete junk it left in my database.

This is prone to causing errors and breaking stuff...

Is there a way to uninstall modules cleanly, to delete ALL data?

I have no access to Drush on the server also...

Modules should clean up after themselves. If they aren't, you should report it in the module's issue queue.

But, at least with D7, there isn't really much that should be left in the database. Most modules that create tables delete them when they are finished. The biggest area where things are left behind is in the variables table - many modules don't clean these out. You can safely delete them after module uninstall though.


Trying to create a widget that submits a form and takes you to another search page The original example http://www.trellon.com/content/blog/apachesolr-and-facetapi uses an auto submitter, which I don't want. I'm trying to modify it to use checkboxes and submit with a submit button, however that doesn't appear to be working. I can select different boxes and submit, but it doesn't take me to another search page.

class ResourceLibraryWidget extends FacetapiWidget {
   /**
   * Renders the form.
   */
  public function execute() {
    $elements = &$this->build[$this->facet['field alias']];
    $elements = drupal_get_form('resource_library_facetapi_select', $elements);
  }
}

function resource_library_facetapi_select($form, &$form_state, $elements) {
  // Build options from facet elements.
  //$options = array('' => t('- Select -'));
  foreach ($elements as $element) {
    if ($element['#active']) {
      continue;
    }
    $options[serialize($element['#query'])] = $element['#markup']; //. '(' . $element['#count'] . ')';
  }

  $form['select'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    //'#attributes' => array('class' => array('ctools-auto-submit')),
    'default_value' => '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find Resources'),
    //'#attributes' => array('class' => array('ctools-use-ajax', 'ctools-auto-submit-click')),
  );

  // Lets add autosubmit js functionality from ctools.
  $form['#attached']['js'][] = drupal_get_path('module', 'ctools') . '/js/auto-submit.js';
  // Add javascript that hides Filter button.
  //$form['#attached']['js'][] = drupal_get_path('module', 'example') . '/js/example-hide-submit.js';

  $form['#attributes']['class'][] = 'resource-library-checkbox-facet';

  return $form;
}

Why isn't it working the way I intend? I'm trying to change different values on the submit button, but that doesn't seem to do anything.

It's not clear from your question, so I will assume that you are missing the following:

/**
 * Submit handler for facet form.
 */
function resource_library_facetapi_select_submit($form, &$form_state) {
  $form_state['redirect'] = array(
    $_GET['q'],
    array('query' => unserialize($form_state['values']['select'])),
  );
}


How to customize a specific content type display? I have a content type which has many fields. My problem is that all fields displays in rows like this picture:

How can I customize these fields? for example I want them to arrange like this one:

Also I want to change some font-size (in the red box in second pic). What should I do?
thx.

with the FieldUI, (enable in modules), you can place the fields,
see here /admin/structure/types.
with display suite you can even do it more sophisticated.

but in the end you want to have your own theme, or adjust the one your using for css etc.


change weight of fileds programmaticaly in drupal 7 I have a registration form with different attribute like

Captcha and security questions which are coming from different modules.

I want to change the display order of form elements.

and i am using this code in my custom module

function tenantwallet_form_user_register_form_alter(&$form, &$form_state){
    $form['#pre_render'][] = 'tenantwallet_form_alter_weight';

}
function tenantwallet_form_alter_weight($elements){

    $elements['field_first_name']['#weight'] = -50;
        $elements['field_last_name']['#weight']= -49;
        $elements['field_company_name']['#weight']=-48;
        #field_company_number, field_secondary_number, field_mobile_or_landline,field_gst_number, field_share_my_info, field_company_logo,field_facebook_id, field_mobile_conformation_code,field_date_of_birth,, field_gender, field_id_proof,field_secondary_id_proof, field_mobile_number,field_promo_emails_notifications,field_sugar_id, captcha,
        $elements['captcha']['captcha_widgets']['#weight']=-50;
        $elements['pass']['#weight']=-47;
        $elements['questions'][0]['question']['#weight']= 45;

    return $elements;
}

But this is not working. Can anybody tell me how to solve this.
Thanks

it seems there are different scope in your form .
Like question and captcha are in different scope. Try to give weight for each scope too.
Then it will work for you. Like

 $elements['questions']['#weight']=50;


Displaying fields from an entity reference of another entity's field I have three content types: compositions, recordings and artists. Compositions have entity references to artists for the field composer.  Recordings have entity references to compositions for the field composer and to artists for the field recording artist.
This is what I want to do:

I would like to display a page with a list of all the compositions and their composer (entity reference to Artist content type).  No problem here.
I would like another field with the field recording artist (an entity reference field in content type Recording) that is being referenced by an entity reference for the content type composition.  This is the problem.

I think the main problem is I'm trying to call a field from an entity reference's entity reference.  Is there a way to build that bridge?

You can use custom Displays to daisy-chain entity reference fields in this fashion (unless I misunderstand your requirements).

To do this...

Install the Entity View Mode module.
Then in configuration - system - entity view modes, create a new display for the entity in question and make sure it is attached to the recording type. Give your new display a self-explanatory name such as "embedded recording" to avoid confusion later.
Next, go to your recording entity's display mode settings, (eg 'manage display') and in the new "embedded recording" display make sure the Recording Artist entity reference field is visible.
Finally, go to your Composition entity's display mode settings (its 'manage display'), and for the Recording entity reference field, choose rendered entity as its format and pick "embedded recording" as its view mode (this option becomes available if you click on the little gear icon on the right hand side).

(Of course this would be far easier if you could add new display modes from the manage display setting! One day perhaps...)


Scaling images on upload I'm using managed_file in a form to uplaod multiple images (D7).

$form['img_upload1'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg')),
'#default_value' => variable_get('img_upload1', ''),
'#upload_location' => 'public://uploads_users/mydir/'.$userId,
);

Allowed file-extension are checked when the user chooses an image and in the form-validate-function the filesize is checked. The images should have a max hight of 730px or max width of 970px.

I can find the dimesions of the uploaded picture bud don't know how to resize it. Is there a way to add a scaling-function (an image-style?) to the managed_file-formfield or to the validation-function to resize the image before ore after the upload?

Thanks

UPDATE
Thank you for your hints. The idea behind all was to have the original files available in a defined dimensions for an other purpose. Bud I see the benefits of using the "Drupal-way".

There's no need to scale your images when you upload them, the usual method is to serve a cached version of the scaled image when it's displayed. This is usually accomplished by setting up an image style in the Drupal admin UI that has the effects you need, and then using theme_image_style() to output that image:

$file = file_load($fid);
$options = array(
  'style_name' => 'image-style-machine-name',
  'alt' => 'Alternative Text',
  'path' => $file->uri
);

$image_output = theme('image_style', $options);

Doing it this way gives the added benefit of your having the original uploaded file available at any time (for example to link through to as a full-sized version of an image, or in a lightbox, etc.)


Domain access on views I am using domain_access module for multisite. I have two different domains (www.example.com, www.example1.com). If i created a view it will be displayed in both the sites. Now i need to create a view only for the particular domain (www.example.com), It should not be displayed in another domain (www.example1.com).
There is any solution in drupal?

Domain views module

Part of the Domain Access suite.
Provides Views integration for Domain Access.


How to link a view to a user profile created using views I created a view which displays users on my site.  In the view, the "name" of users links to their individual profile.

Now i want to have more control over information displayed to users when they view other peoples profile.

To achieve this, I am of the opinion that i need to create another view to display the user profile. Where i see a challenge ahead is how to make my first view link to the individual user profile based on my new view.

Please, how do i achieve these or is there a better way?

Thanks in anticipation.

Hope this will help  you,

As I understand you have 2 views, first view is to list the users and the second view is to show the particular user detail information.

In Drupal 7 you can achieve it easily.

Let say the first view path will be users/listing and the second view path is user/%/other.

Steps

In first view where you are listing all the users, add another field UID and pull it to the top and exclude it.

And go to USER NAME field and uncheck Link this field to its user and goto Rewrite results and check Output this field as a link and enter user/[uid]/other and save it. [uid] is taken form the Replacement patterns

Now its time to create new view which will be showing the user information based on the user id. In this view we need to add the contextual filter, based on that the user detail will be shown.

Add contextual filter


Prevent hook_form_alter to works only on frontend not in admin? I have used a hook_form_alter to alter a form fields value randomly and its working fine, but the problem is that when i open this webform in admin panel its just change the value  which i dont. Its should keep the same value which is submitted by frontend user. i want this hook to work in case of frontend only not for admin.

you could use the global variable $user to achieve it.

<?php

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if($user->uid == 1) {
    return;
  }
  else {
    //alter fields logic goes here
  }
}


How to display list of nodes that share the same Parent taxonomy term as current node I have a vocabulary set up called (for example) "Produce". And it has parent terms like "fruit" and "vegetable". Child terms are like "banana", "apple" and "cucumber", "squash".

Whenever I create a new node about fruit or vegetables, I use a content type that I created.
In this content type, I have a field set up called "field_produce_and_name". So when I create a new "Fruit" page, called "papaya", I also create "papaya" as a child taxonomy term to "fruit". And I set the field field_produce_and_name to "papaya".

When someone is viewing the "papaya" page/node, I would like a sidebar menu list to display the titles of other "fruit" nodes. That is, a list of nodes that share the Parent taxonomy term as "papaya".

I have tried using the contextual filter "Content: Has taxonomy term ID (with depth)" but it still isn't working :(

I also think that maybe I need to add a relationship, but am unsure how/which one.

Any ideas?

Yes, add a relationship for the taxonomy field and the parent contextual filter will be available.