How do I display category items in a view content pane? I created an Events content type.
I created a vocabulary that has two category terms, Events and Plays.

I have a view that contains a list of all content of type Events.

Each Events listing displays with the category term as the title/link.

The link should go to a page that has a content pane (not a view page) containing a list of all of the Events with that tag.

I already have a page set up with two columns. When I click on any term in the list of Events, I want to navigate to this page (or an iteration of it, based on term selection), and one of the columns should contain the view pane with the view of events of just that category that was clicked on.

In other words, I want the destination of the term links to be a page containing the content pane of items of that category (i.e. not just a page view.)

So, the view looks something like,

Movie (term)

movieName

movieTime

Play (term)

movieName

movieTime

Movie (term)

movieName

movieTime

Play (term)

movieName

movieTime

Movie (term)

movieName

movieTime

The term field is configured to be a link.

If I click on Movie or Play I want to go to a page that has a content pane containing a list of all of the Events tagged with Play or Movie, depending on which I clicked.

On the view, I set up a Contextual filter:

Content: Has taxonomy term ID

I set up a Relationship:

Content: Taxonomy terms on node

How can I set this up so that clicking on the category will take me to another page with a column containing a view content pane that displays a list of Events based on that clicked tag?

Try this...

In your view that displays movies and plays, add the term id (tid) to the list of fields.
Rearrange your fields so that the tid field is above the term name field.
In the tid field settings, check Exclude from display.
In the settings for the term name field, check Rewrite the output of this field. In the text box underneath, enter this:

[placeholder2]

Expand the Replacement patterns section of the dialog box to see what to insert in place of placeholder1 and placeholder2. Click Apply to close the dialog box, then save your view.

Now, in your content pane view, you simply have to match up the contextual filter with the tid. One way to do that is in your contextual filter settings, click the Provide default value radio button, select Raw value from URL from the dropdown, and set the path component to match where placeholder1 appears in the link generated in your other view.

This is the simplest way to do it and it has some limitations (e.g. a non-intuitive Url) but hopefully is enough to get you on the right track. One you're comfortable with it you can experiment with different arguments and different ways to pass them. The link below has a good description of how to use contextual filters:

https://www.metaltoad.com/blog/using-drupal-contextual-filters-views


Correct way of passing variables between hook and tpl.php I asked a similar question a few months ago, but the truth is that there is very little information about the correct way of doing this.

The simplest way is to use the arg() function, but as the docs clearly state, that is the wrong way of doing it. While trying to follow the correct steps, this is what I have so far:

A menu with the necessary paths:

$items['products/search/%/%'] = array(
        'title'             => 'Products search filtering',
        'description'       => 'Show review categories.',
        'page callback'     => 'ThemeSearchProducts',
        'page arguments'    => array(2,3),
        'access callback'   => 'user_access',
        'access arguments'  => array('access content'),
        'type'              => MENU_NORMAL_ITEM,
        'file'              => 'includes/mymodule_reviews.inc',
);

These arguments are sent via ... arguments (sorry for the joke). to the themesearchproducts function

/**
 * THEME List of reviewable products
 *
 */
function ThemeSearchProducts($arg1, $arg2){

//  $output = theme('search_products', $arg1);
  $output = theme('search_products', 'test');

  echo 'args in theme: ' . $arg1 . $arg2 . ' || ';

  return $output . theme('pager', 10);
}

The echo works fine, but now the question becomes how do I send this variable to the hook_theme of the module, and from there to the tpl.php? I have something like the following:

function MYMODULE_theme ($existing, $type, $theme, $path) {
    $path = drupal_get_path('module', 'MYMODULE'); // . '/templates';
    // ADD THE templates DIRECTORY
    $path = $path . '/templates';

    return array(
            // as in 'theme('verbose_method',...)
            'main_reviews' => array(
            'template' => 'MYMODULE-main_page_reviews',
            'path' => $path,
            'variables' => array('forums' => NULL, 'topics' => NULL),
            ),

as you can see, the module now calls the tpl in templates/MYMODULE-main_page_reviews.tpl.php, but I cannot find the correct way to send a variable from  the previous callback to the hook_theme. Adding a new argument to the MYMODULE_theme throws an error, and I cannot get rid of it, not even by adding (for example) this new argument in ThemeSearchProducts, like this:

 $output = theme('search_products', 'test');

Is using variable_set also incorrect? I'm trying to follow the "Drupal Standard Practices" as much as possible, but this last step is eluding me.

The arguments you pass to theme() when you invoke a theme function are not passed to hook_theme(), and from there to the template file. They are passed directly to the theme function, or the template file, in the case the theme function is using it.

hook_theme() defines the arguments used from the theme function. How those arguments are then passed to theme(), and to the theme functions, depends from the Drupal version:

With Drupal 7, they are all passed in an array, which in your case is similar to the following one:

array('forums' => $forum, 'topics' => $topic);

hook_theme() defines the default arguments used for the variables when no value is given. In your case, you could use array('forums' => $forum); and NULL will be used for 'topics'. (Replace $forum with the value you need to use.)
With Drupal 6, you pass the variable as single arguments to theme(), for example as in theme('search_products', $forum, $topic). As with Drupal 7, the default value is used when you don't pass that argument.

In both the cases, the variable declared for the theme function in hook_theme() is the name of the variable passed to the template file. In your case, $topics, and $forums are two variables accessible from the template file.

As side note, the template file you declare in hook_theme() with "template" for your theme_search_products() needs to be search-products, or search_products; Drupal will add the extension .tpl.php to the name, when looking for the template file. You cannot have a theme function that is declared as example_one, and the template file that declared to be example_two.
Also, you are trying to use theme_search_products(), but your hook_theme() implementation doesn't define that theme function. The code you are showing contains the definition for theme_main_reviews(). If the theme function you are calling is not defined from another module, that code will not work.


meta tags don't display when not authenticated I'm using Drupal 7, Meta Tags/Open Graph meta tags 7.x-1.0-alpha6.

When logged in, meta tags act as I would expect. I see the meta tags when I view the page source.

When not logged in, the meta tags are missing. What could cause this?

You have a patch for this issue. There is a README.txt file updated.

All you need to do is to render meta tags in your page--front.tpl.php, add following in this file of your theme:

<?php
 render($page['content']['metatags']);
?>

Or you can try to add this in your template.php file of the theme:

<?php
function THEMENAME_preprocess_page(&$vars) {
  if (!empty($vars['is_front'])) {
    metatag_page_build($vars['page']);
  }
}
?>

Just replace THEMENAME with the name of your theme.


On node view page show a link or button that executes an action? The closest that comes to this for D5:
http://drupal.org/project/node_operations_block

I am familiar with creating VBO Actions, but not sure how to create it for a node operation. Such as a link or a button, that creates a new node with default values for example.

You can use the Flag module to put that "button" on the node. Then using Rules you could execute a VBO or simply use rules to create that content. Don't forget to look at Rules Bonus Pack for more goodies.


How can I pass proper querystring when Search from Drupal using my custom search box? I have this search form in my drupal site.

<form id="mysearch" method="get" action="<?php echo $base_url.'/search/node/'; ?>">
   <input type="text" maxlength="150" id="search" name="s" class="input">
   <input type="submit" value="Search" class="button">
</form>

I have problem is that when I am submit the form it will pass the query like that

http://mysite.com/search/node/?s=xyz

Here I would like to change the URL something like this to search in my site.

http://mysite.com/search/node/xyz

Can anyone help me how can i achieve this thing.

I have put this code for URL Change:

$("#adminbarsearch").submit(function(e) {
    $url = $("#adminbarsearch").attr("action") + $( "input:first" ).val();
    e.preventDefault();
    window.location.href = $url;
});

Instead of this Can we change the URL by using the .htaccess

If you use the default search block for Drupal, it will give you the functionality you need.

EDIT: Go to Structure > Blocks and enable your Search Form Block by adding it to a region.

If you perform a search using your default search block, it will redirect to a path in the format /search/node/QUERY where QUERY is what you are searching for.

By default the search form outputs (for example):

                <form action="/" method="post" id="search-block-form" accept-charset="UTF-8">

Search form

                                Search
                                <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

                                <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

                            <input type="hidden" name="form_build_id" value="form-4gEUIDHcVH7lHHH3JpkfkVs9xBmPhHXdDQAMFMF9dHA">
                            <input type="hidden" name="form_token" value="afNo5gRQlaauXmqeZYDf80o5dEwKlg0VP6U-Ir8-p6k">
                            <input type="hidden" name="form_id" value="search_block_form">

                </form>

Now if I search for "test", it redirects to /search/node/test


Issues removing text decoration from links in a custom block I'm replacing the Bartik menu with a custom one. To do this, I'm building a custom block and placing it appropriately.

That all works. However, I am having issues with Text Decoration: No matter what I try, I cannot remove the line from under links, and I have also noticed a "Doubled/offset" text look. When I edit the code on 'Tryit', everything looks fine; when I unclick 'source' in the block editor, everything also looks fine.

When I update the page, I see these issues.

My entire block code is the following one.

Home

Gallery

Contact

Extra

☰ Menu ☰

Here is an image of the issue:

Notice both the underline, and the 'Doubled text'? Thats what Im trying to get rid of. Thank you in advance.

For the text-decoration, try to use !important attribute.

For that "doubled text", you need to use text-shadow: none.

If text-decoration still doesn't work, you can try border-bottom: none for that line, too.


Drush: Watchdog search explained Can somebody explain how watchdog searching works? I can never get it to locate the log entries I'm looking for.

Let's say I have the following watchdog entries:

476722  10/Jun 10:31  notice    content  page: updated Protective Factors in Elementary School.
476723  10/Jun 10:31  notice    php      Notice: Undefined offset: 3 in _menu_translate() (line 777 of /var/www/html/domainnamehere/includes/menu.inc).
476724  10/Jun 10:40  notice    content  page: updated School/District Administrators.
476725  10/Jun 10:42  notice    content  page: updated Teachers.
476726  10/Jun 10:42  notice    php      Notice: Undefined offset: 3 in _menu_translate() (line 777 of /var/www/html/domainnamehere/includes/menu.inc).

All of following return "No log messages available":

drush wd-show "Undefined offset"
drush wd-show "%Undefined offset%"
drush wd-show "menu_translate"

If I want to find all of the "Undefined offset" watchdog entries, what Drush command do I have to run?

You could just pass the stdout from Drush as the stdin to grep.

Example:

drush wd-show | grep 'Undefined offset'

As a bonus - If you want the errors in a file, try the following:

drush wd-show | grep 'Undefined offset' > ~/Undefined-errors.txt

This'll put the errors into a text file in your home directory :-)


How to update relative image paths on domain migration? (Incorrectly generates previous) Problem

(Found the same problem recently, re-wrote question to be more general and useful)

I recently had to change the domain of my site.

On changing it I've found Drupal fails to update the domain of the URL in a lot of the images on my site.

So for example, I changed from domain1 to domain2:

The path for a background image in a CSS file would originally be:

background-image: url (https://domain1.com/sites/all/themes/tefltheme/images/empty1.gif)

After changing the domain it would remain:

background-image: url (https://domain1.com/sites/all/themes/tefltheme/images/empty1.gif)

Nothing I do seems to cause this to re-generate. Has anyone else run into this? Where is Drupal storing this information?

What I've done

Clear caches
Flush memcache, varnish and drupal
Wipe all Advagg files and re-generate
Set the base URL in settings.php

On the back-end it recognises my URL has changed for example /admin/config/system/site-information shows domain2 in all the prefixes.

(I can fix this by putting an exact path in all my CSS etc, but obviously I'd prefer to avoid this.)

If your CSS file and "images" folder are in "mytheme" folder, the CSS string should be:

background-image: url(../images/homepagenew4.jpg);


hook_form_user_register_form_alter() does not customize user registration form I have implemented a hook_form_user_register_form_alter().

function hook_form_user_register_form_alter($form, $form_state, $form_id) {
  $form['account']['name']['#description'] = 'This is your login name. It will be displayed on the forums and in comments. This is not your billing information. Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.';
  $form['actions']['submit']['#value'] = 'Continue to subscription and payment page.';
  $form['#submit'][] = 'custom_user_register_submit';

  dpm($form);
}

When I use the registration page, I get mixed results. First of all, my custom_user_register_submit() function is called when I click the submit button. This is correct.

However, I get no changes to the form elements printed on the user registration page. For example, but button should have custom text. It does not; it uses the default text 'create new account'. Strangely, in the output from my dpm(), the values in those array elements match my custom code! So, it looks like my hook is implemented correctly and the form elements are being changed, but later in the Drupal bootstrap, they are overridden again and brought back to their defaults.

Anybody know a solution?

For all Drupal _alter hooks, you need to pass the variables you need to change as references.

In your function, declaration, $form should be &$form. This makes PHP pass a reference of that variable to inside if your function scope, so changes you make to the $form array persist.

So the function declaration should look like this (to alter both variables):
hook_form_user_register_form_alter(&$form, &$form_state)


How do I create a module that uses composer to manage a 3rd party library? I maintain a module on Drupal.org, the jQuery Colorpicker module, which has a requirement on a 3rd party library. I created a composer.json file in the module root. When I originally installed it, I navigated to the module root and ran composer update, which created vendor folder in my module directory, and loaded the library to this vendor directory. I then released a beta version of the module.

One user who downloaded the library ran composer drupal-update from core, which installed the library to the DRUPAL_ROOT/vendor folder. I'm thinking this is the correct way to go.

So I deleted the vendor folder from my module folder, as well as the composer.lock folder from my module folder.

However, when I run composer drupal-update in my drupal root, it does not install the library to my vendor folder.

I'm not really sure where to go with this - do I need to add something to my module, or is there a required command that needs to be run somewhere for Drupal to install the library when running composer drupal-update? I haven't worked a lot with composer, so I'm trying to find the proper way to do this so my users can use the module in the standard Drupal way.

In order to have composer download a 3rd party library, you need (as you have already done) a composer.json file within your module. This file should contain the required 3rd party libraries. There are however quite strict guidelines for creating a proper composer.json file for Drupal in which you should at least define the following:

{
    "name": "drupal/example",
    "description": "This is an example composer.json for example module.",
    "type": "drupal-module",
    "license": "GPL-2.0+"
}

Running composer from the module root is indeed not recommended as this might become quite time consuming when installing many modules, not to mention updating all of them once in a while.

Luckily the Drupal guys have done some work, allowing composer to manage all Drupal dependencies, which is out of beta since a few weeks.

This allows you to use composer from the Drupal root to require modules as well. During the downloading of the module all dependenies of it will be resolved as well.

On a small sidenote;
Reading through that blog post again leads me to assume the following should also be included in your module's composer.json file (as of writing the first link also shows an outdated message):

    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }

As for your situation, it seems you should commit a file similar to this to Drupal.org:

{
    "name": "drupal/jquery_colorpicker",
    "description": "jquery_colorpicker module.",
    "type": "drupal-module",
    "license": "GPL-2.0+",
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        ...
    }
}

And then run composer require drupal/jquery_colorpicker from your Drupal root.

UPDATE:
After reading that blog post for the fourth time, I came to conclude that the repositories part is with high probability only required for the root composer file and thus not required for individual modules.


Query to get termID, term name and number of posts that has that term I can figure out how to construct a db query that fetches term id and term name. But how do I associate a count of nid's that has this term? I'm looking to do this programatically through the DB api.

Any help would be greatly appreciated, as I'm running low on time.

See the example for Views Group By -- "List top 10 most frequent terms applied to a specific node type and the number of nodes for each term."


How do I modify /user to a custom URL? I have some small Drupal 7 sites that don't require me to log in all the times, and there are no users. I would like to change the user login path to something else to deter bots targeting Drupal installations on the /user path.
How can I achieve this?

I can add a CAPTCHA, but I want to change the path too.

See the Rename Admin Paths module. The purpose of this module is to secure drupal backend by overriding admin path. You can change user/login to something like member/login.
I would also suggest adding a redirect in your htaccess to the standard user/login user/register. This way Drupal doesn't also have to serve up the 404 when a bot tries to access those pages. Huge performance savings.

EDIT: Thinking about this further, you don't need an extra module at all. Just add an alias at /admin/config/search/path/add for user/login, user/register etc, then just add redirects in your htaccess for the old aliases.


Can I search Taxonomy terms within display suite I don't think so, but I'm throwing it out just in case I am incorrect

What do you mean by search?

You can apply ds layouts to taxonomies


How repeating field values in "EntityReference select list widget" as I would with "autocomplete widget" my question is how to display "select list widget" like "autocomplete widget" when
I create or edit an entity, I mean with "add another field". I need this
because I need repeating field values in "EntityReference select list
widget" as I would with "autocomplete widget" or as shown in the module "Double Field".
thanks and sorry for my english

I found everything I was looking for in the Multiple Selects module. Here is a quote about it (from the module's project page):

... provides a widget called Multiple Selects list for the the following fields types:

entity_reference
node_reference
user_reference
taxonomy_term_reference
list_integer
list_float
list_text
list_boolean
commerce_product_reference

Rather than having a multi-select field, this modules allows you to have multiple select fields with the traditional FieldAPI 'Add another item' button.


Can you duplicate a Drupal 7 site and database when a new user registers? I'm building a site that will be used as a template site for new users. Once someone signs up, they should receive a copy of the original master template site, including their own SQL database.

Ideally, the new sub-site would need to receive updates from the master site somehow.

Is there a way to copy and entire site when someone registers? Can this be accomplished with Multi-sites?

Yes, using hook_user_insert() to start the process off.  From a custom module that implements hook_user_insert() you can run any code you want.  However to pull it off you're going to have to write quite a bit of custom code.

Your hook_user_insert() function would need to do quite a lot of steps:

Fetch the database connection information defined in settings.php
Run mysqldump to make a .SQL dump of the database
Run a tar command to make a .tar.gz file of the Drupal codebase (PHP files) and files directory.
Zip or tar or something the sql file, the .tar.gz file, and probably some kind of instructions
Present the file for download.  This is made trickier because you don't want to have the file inside your codebase.. or each time you clone the database you'll pick up all the .zip files from previous users in the next user's .zip file.  You either need to serve the file directly, exclude the zip files from future codebase archives, or serve the zip files out of a directory that won't get zipped into the zip file.
(optional) Clear the user out of the master site so that it doesn't exist for future signups.

You ask about Multi-Sites, that's only relevant if you plan to immediately start hosting the cloned site yourself.  If your plan is to have the user download their files and .SQL database, you don't need to worry about that. (The user will have to worry about loading the SQL dump and setting up a database username and password though, which you'll need to babysit them through or it will never end up working out).

If your plan is to clone the site on your server, then you could do it with a multi site.  Your steps would then be:

Fetch the database connection information defined in settings.php
Run mysqldump to make a .SQL dump of the database
Create a new MySQL database to hold the new cloned site 4. There are security implications here.. if your webserver is allowed to create mysql databases, is it really secure from hackers?
Create a new sites/new.example.com folder for the new site (if it were named new.example.com)
Create a new settings.php file for the new site's database in sites/new.example.com
Load the SQL dump from step 2 into the new database (using the command line mysql command)
Redirect user to the new site.  You will need to use Wildcard DNS (ie. *.example.com woudl match site1.example.com, site2.example.com, etc. and you wouldn't need to add DNS entries for each new site).

While this plan is not impossible, it will be quite hard to get working well.  Your biggest challenge will be helping the users get through the complicated task of creating a new database, setting up username and password for it, loading the SQL dump, configuring their webserver etc etc etc.


Use arguments for drupal views 3 How do you structure and use arguments in a view using the Views UI in Views 3

Arguments in Drupal 7 are the same as contextual filters. Contextual filters are associated with the path of the view (or the view's page). With these, we give a basic determining factor as to how we want to narrow down the view's output. It can be set up on what ever you want it to be. One of the simple ways to do it is by content type or user name.
Check out this page it explains it well. http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments.
I also found these vids while searching  on relationships and contextual filters (arguments). Check them out they put a lot of things in perspective and teach you how to use them both.

Drupal 6:
http://gotdrupal.com/videos/drupal-views-relationships
http://drewish.com/node/127

Drupal 7:
http://vimeo.com/22100751


User Created Slideshow I am new to Drupal and I'm looking for a slideshow of user uploaded images on a user uploaded project. Basically, I want the user uploaded images to be shown on the content page, in addition to text, ratings, comments, etc. I downloaded Views Slideshow and dependencies, then added a field on the content type the images go on, so users can add any number (actually it's capped at 10, but that shouldn't really matter) of images.

After that, I found myself stuck. Every single result on Google was somewhere along the lines of "Create a View and Use it" without enough detail on either.

How do I get a user created slideshow of images on content the user made?

Download field_slideshow module and enable it. After enabling go-to this link and download as jquery.cycle.all.js, place it under sites/all/libraries/jquery.cycle. Clear cache after this.

After enabling go-to manage display and in your image format select as Slideshow.

Attaching screenshots.


How do I get the current year in the footer? I want to put a copyright notice in the footer of my posts, and I want the year always to be current.  I've tried adding

<?php echo date("Y"); ?>

to the Footer, but the actual code shows up; it doesn't get parsed as PHP.

How do I get the footer to display the current year?

That happens because you are creating a custom block, but you didn't select PHP code as input format.

In Drupal 7, you need to first enable the PHP module (php.module); in Drupal 6, you need to first enable the input format on admin/settings/filters. Once you have done that, you will be able to choose PHP code as input format, and write PHP code between <?php ?> tags; the code will be executed, and the output will be the content of the block.


How can I programmatically create a media object and a new file and associate the file with the media object? I am trying to programmatically create a media object and a file, and then associate the file with the media object.  The first part works--I can successfully create the media object and file.  But the second part fails--the media object has no file associated with it.

Here is my code:

//Begin handling file uploads
$file = file_save_data('hey dude', 'public://2019-07/my_example.txt', FILE_EXISTS_REPLACE);

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => '0',
  'name'=> 'Test Name',
  'created' => date('U'),
  'changed' => date('U'),
  'moderation_state' => 'published',
  'file' => [
    'target_id' => $file->id(),
  ],
];

$drupalMedia = Media::create($media_arr);

$drupalMedia->setName('Test Media Object')
  ->setPublished(TRUE)
  ->save();

my_example.txt is created in the files directory, and the media object "Test Media Object" is also created, and I'm able to attach it to a node.  But there is no file in the new media object!  Am I missing something here?

Ah, I always figure it out after I say I can't do it.  Once I specified the document type, it worked:

$media_arr = [
  'bundle' => 'file',
  'langcode' => 'en',
  'uid' => \Drupal::currentUser()->id(),
  'created' => date('U'),
  'changed' => date('U'),
  'moderation_state' => 'published',
  'field_file_document_type' => 1409, //1409 is the id for pdf
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
];

Edit: I should mention that 1409 is the id we use for pdfs, yours will be different.  The field_file_document_type just needed to have a value in it to work.


Paragraph image URI with image styles in paragraphs-item.tpl I have Paragraph bundle with Multi Value Image Field which is limit of 3 numbers. i tried to print these three images separately because i want to used different image styles for each images. I tried like this:

<img src="<?php print image_style_url('size_400x600', $node->field_image['und'][0]['uri']); ?>"/>
<img src="<?php print image_style_url('size_750x524', $node->field_image['und'][1]['uri']); ?>"/>
<img src="<?php print image_style_url('size_550x365', $node->field_image['und'][2]['uri']); ?>"/>

In the code it display the uri without the file name like this:

What will be the correct way to do this?

Probably your best bet is to have something along the following in the 'paragraph--ptype.tpl.php' file:

<?php print theme('image_style', array('style_name' => 'size_400x600', 'path' => $field_image['und'][0]['uri'])); ?>
<?php print theme('image_style', array('style_name' => 'size_750x524', 'path' => $field_image['und'][1]['uri'])); ?>
<?php print theme('image_style', array('style_name' => 'size_550x365', 'path' => $field_image['und'][2]['uri'])); ?>

Where ptype is obviously the paragraph type that has this field.

I originally answered for Drupal 8 because I missed the D7 tag. Doh! I'm leaving the original answer below for reference.

First, a good way to apply an image style in an image field template:

{% for item in items %}
  {{ item.content|merge({'#image_style': 'size_400x600'}) }}
{% endfor %}

For your use case, you could do something like:

{% for item in items %}
  {% set style = 'size_400x600' %}
  {% if loop.index0 == 1 %}
    {% set style = 'size_750x524' %}
  {% elseif loop.index0 == 2 %}
    {% set style = 'size_550x365' %}
  {% endif %}
  {{ item.content|merge({'#image_style': style}) }}
{% endfor %}

However, since the twig code is starting to get complicated, you should probably think about handling it in a preprocess function.

Alternatively, you can do some of this at the paragraph template level (assuming the image field is on the paragraph):

{% if not paragraph.field_image.isEmpty() %}
  {% if not paragraph.field_image[0].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[0].entity.uri.value | image_style('size_400x600') %}

  {% elseif not paragraph.field_image[1].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[1].entity.uri.value | image_style('size_750x524') %}

  {% elseif not paragraph.field_image[2].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[2].entity.uri.value | image_style('size_550x365') %}

  {% endif %}
{% endif %}

You will need the twig_tweak module for that. Some of the safety checks in there may be extraneous. YMMV. As before, the complex twig code means this would be good to put into a preprocess function.


Random order in a view I'm working on a Drupal 7 site that lists hotels at the moment. To make it fair on the hotels who have signed up the listing page needs to be in a random order on each visit. You can click through to view a hotel's details details on a separate page. I need the site to "remember" the order the hotels were in so that when you go back to the listings they're in the same order and so the next/previous buttons work on the hotel details page.

I'm currently listing the hotels in a view so I'm a bit stumped as to how I can get this to work.

Thanks.

You can setup Views to cache the query. This will probably be globally, (meaning the every one will see the same list for X time). It's not bulletproof but it's an easy solution. Alternatively you need to do some cache per user, which could be quite tricky or some custom code.
Update
By default Views allow you to clear the cache every 5 min (and other predefined values), if you add the cache actions module, you get rules based clearing of cache. With the use of rules you are able to setup the clear cache event to fire at a specific time of day (triggered by cron) and other special conditions that you are able to build with the power of rules.


I want to place my business page linkedin feed onto our Drupal website. Is it possible? This question is most likely more about LinkedIn. I can't find answers to this question anywhere. It is as if no one ever asked it.

I have follow links to the linkedin business page. I have share links to the visiting user's linkedin feed.

Take a look at these links:

https://www.drupal.org/docs/8/modules/get-linkedin-posts

https://www.drupal.org/docs/8/modules/get-linkedin-posts/how-to-setup-get-linkedin-posts-module

I haven't played with Linkedin or with this module, but that's what you need if I understand right.

It's up to you if you install it or not.


How to not index comments in search_index? I'm using drupal search, the core module.

I want to not index the comments in the search_index

In the node.module, the "function _node_index_node($node)" loads and renders the node. Comment content is loaded and indexed here. I would like to not load the comments content here in order to not index this content. How can i do this ? Thanks

NB : i'm drupal 6, but tips in 6 or 7 are welcome

There doesn't seem to be an easy way to do this in drupal 6.

It gets added in hook_nodeapi() but the comment module, so comment_nodeapi().

There is no way to override what gets added in this manner.

So you would have to hack the comment module to make it no longer do that by removing the 'update index' part.

Hacks
A note on hacks:
In cases where you really do have to hack core, I recommend creating a patch file for the change and give it an informative name.
Then commit to your version control the change and the patch.
Keep a list of any hacks you might have, along with their purpose, which files have been changed, and their relevant patch file, in your developer documentation.

Then when you go to upgrade drupal next time you have the patch file, so you can update, then apply the patch (if the patch doesn't apply cleanly you can re-roll it).
Easy.

This way if you ever hand over the project the next person will have it easier too.


Print CCK field "A" if CCK field "B" has a value of "Z" I want to print a CCK field (we'll call it CCK field "A") only if the value of another CCK field (we'll call it CCK field "B") matches a string. CCK field "B" is a select-list field with two options: "red" and "blue". I'd like to display the value of CCK field "A" only if the value of CCK field "B" is "blue". If the value is "red", then CCK field "A" should not be displayed at all.

How can I do so?

Thanks!

THIMK! Test the value of Field B before printing Field A.

<?php
if(isset($node->field_field_b['und'][0]['value']) && ($node->field_field_b['und'][0]['value'] == 'blue')) {
    if(isset($node->field_field_a['und'][0]['value'])) {
          print $node->field_field_a['und'][0]['value'];
    }
  }
 ?>


Can PHP pages be ported into Drupal "easily"? If I have a php page, just a regular webpage that php retrieves database information from, dumps it out in tables, css, divs, all that.  Is it extremely difficult to port to Drupal?

I ask because if I don't use drupal, then I have one page with all my content and presentation and model all mixed up.  If I don't, then I've either got another framework I'm using, or I'm rolling my own.

Problem is that I need to build some pages now, but Drupal is not ready.  I can't delay, so later I want to integrate them.

I was hoping for advice on at least the best way to write a page that I know will later be in Drupal.

edit:  How do I write a php page in such a way that it is best prepared for later integration?

Well, you don't really. If you are accessing the database in anyway you should be using the Drupal database API. There are a lot of things that you should do using Drupal API's if you are going to use Drupal. However, with that said, you can run any PHP you want in any Drupal node. So, there is nothing special you need to do in order to write your PHP code to work within Drupal. However, you really should think through your implementation before you being and determine which parts should use Drupal.

Also, it only takes about 3 minutes to setup a Drupal installation. So, you could just setup a dev site in no time flat and develop inside that. Even if you don't have a server you can download a few applications that will act as a server like XAMPP which will give you Apache, PHP and MySQL so that you can install Drupal and begin working.


Detect page redirection and execute code I have two modules which I am trying to make work in synch.

The first module creates a dynamic page and redirects users if certain conditions are met. The redirect URL takes to following form: testsite/event/registration/success/277/466.

When the redirect happens, I want my second module to detect the redirection and pickup from when the first module left off. I am trying to make it check and determine if the user is on: testsite/event/registration/success/*/*

Is this possible and can anyone give me some direction, please?

You may be able to use hook_drupal_goto_alter to achieve this. It'll get called during the processing of the redirection.


How to theme Logintoboggan Access Denied Login Page I am looking to override Logintoboggan's default access denied login page. I can't seem to find what I name the template file and what the defaults are that are required. Any help is appreciated.

Assuming Drupal 7, if you are trying to override LT's toboggan/denied page, eg, what overall structure you see when you land on www.example.com/toboggan/denied, you could copy your theme's page.tpl.php to page--toboggan--denied.tpl.php and modify whatever you wanted in there. (If Drupal 6, the new name would be page-toboggan-denied.tpl.php.)

If you are instead (or also) trying to override the output of LT's theme function that produces the You are not authorized to access this page message on that page, you could create a function in your theme's template.php file:

function YOUR_THEME_lt_access_denied($variables) {
  return t("Whoa, Dude!  You aren't allowed in here!");
}

that would override LT's theme_lt_access_denied() function, which is just a quick:

function theme_lt_access_denied($variables) {
  return t('You are not authorized to access this page.');
}

Or, you could instead create a template file called lt-access-denied.tpl.php in your theme that would accomplish the same thing with some potentially more fanciness:

<?php
  // contents of lt-access-denied.tpl.php
?>
<div class="tsk-tsk">
  Whoa, Dude!  You aren't allowed in here!
</div>

In any case, if you are trying to override any of the other theme functions in LT, or any other module for that matter, you would first look in the module and search for the hook_theme() to see what's available, and in LT, that would be the logintoboggan_theme() function found in the logintoboggan.module file.  Another great resource is Drupal 7 Template (Theme Hook) Suggestions which details the template names and variants used in Drupal core modules.


How to create a node from an other node template? I would like to have a form for the creation of a node (let's name it news) when you are on the page of an other type of node (let's name it movie). So on /node/31 (of type movie) I would like to have the node content and a form to create a news

I thought about using a Webform but after all it felt like trying to hack the Webform with a trick. Moreover since the form already exists (at path node/add/node_name), I might be able to reuse it but I don't know if it is really possible.

What should be the right way to do it ? With a webform ? By exposing the form for the specific node ? By creating a custom form ? Maybe an other solution I didn't think about ?

Use Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks

Select your content type for the form. Place block in region and for visibility select the other content type.

If you rather render the block using a template file, ex: node--movie.html.twig you can use Twig Tweak and print it out using {{ drupal_block('block_id') }}


Save Ubercart order in database, processed through custom payment gateway I am developing a custom payment gateway module for ubercart, I am able to complete an order on the third party payment system using their api and its working fine, the problem I am facing is how to save that completed order in the database. If we will see in paypal payment gateway for ubercart when we complete an order, Under store option we have an option to view the orders and there status (please check screenshot below), this is the same thing I want to achieve, in-short how can I keep track of orders processed through a custom payment gateway.

I know there is a hook uc_order_save($order) in ubercart, but I am confused how to implement it, so that it can interact with the internal values of ubercart orders. I am sure there will be a way in ubercart to achieve it.

You do not need to implement that hook.

First you need to be sure whether the payment service method is gateway or redirect. Depending on this, the payment complete function is different.

Within that function, regardless how it is implemented, here is a list of functions that are helpful.

uc_cart_complete_sale()

  This function is utilized by the default checkout system and can be
  used by third party checkout integration modules to complete a sale.

uc_order_comment_save()

to leave comments in the order regarding the payment outcome, as well as watchdog()

uc_payment_enter()

  This function logs a payment for an order in the payment receipts table.


Display webservice response in a paged table I have data I am receiving from a webservice call that I would like to display in a paged Drupal table. How can I do this? Can I use theme('table') and attach a pager to it somehow?

You need a generic array pager for paging data that isn't available in your Drupal database.
There's a community documentation page available providing information about the subject.

From the page Paging non-SQL data:

With the following function, you can use the Drupal core pager with any array with only two lines of code:

/**
 * An generic array pager for Drupal.
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9.
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

The usage is as simple as:

  $output = '';
  $tree = taxonomy_get_tree($vocab->vid);
  $tree = pager_array_splice($tree, 5);
  // Do something with the 5 terms
  $output .= theme('pager', array('quantity' => 5));


CKEditor disappeared Was in my Drupal 6 site editing some pages and CKEditer suddenly disappeared in the Edit screens.

I did nothing to anything else & have no idea why the CKeditor fields are no longer showing up when I edit content?

I recommend you to do the following and I hope it will fix your issue

Clear drupal cache then check CKeditor field
If nothing changed then try to open your site on different browser
If nothing changed then try to look if you have any javascript errors when you edit any content/node/settings; use firefox with firebug add-on
If nothing changed then try to uninstall the module then install it again
Also try to disable javascript optimization under performance menu


Open A image When the site loads How to open a image when the site loads like in this site. Can this be done wtih lightbox or colorbox

You can use Splashify module for this

  Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.

Otherwise you can try with lightbox and custom scripts an example is given here


how to separate taxonomy hierarchy in pathauto with slashes Pathauto seems to have a different way of aliasing taxonomy hierarchy.

From Taxonomy Menu:

Classifieds > Cars > Aston Martin > DB9 Coupe
Classifieds > Jobs > Accounting

What I want is something like this for the url:

classifieds/jobs/accounting (not accounting-jobs-classifieds)

(Note that Pathautho generates this with dashes in reverse order as well.)

In Pathauto, I'm using this pattern: Default path pattern (applies to all vocabularies with blank patterns below)

[term:parents-all]

Confused.

There is a clever way to do this by using join:/

In my case, I used:

[node:field-taxonomy-skolski:parents:join:/]

where field-taxonomy-skolski is the field for choosing the term from the taxonomy tree.
Forward slashes will be stripped, though there is a setting under

Administration » Configuration » Search and metadata » URL aliases » URL aliases - settings

at the bottom of the page for PUNCTUATION drop-down. Set to slash (/) "no action" instead of "remove".


Are all updates (revisions) to a user recorded in the logs? A user was created just over a week ago and at some point was given a particular role by an administrator. Will this update (the role given, the date/time of the update and the admin who made it) have been recorded by default in the database somewhere? I don't have any special user modules installed on the site e.g. User Revisions. When I tested just now by giving roles to a user and then looking in "recent log messages" (filtered to "user"), my update didn't show there, so I'm guessing the answer's no, but if there is a way to retrieve this info it would be helpful.

Unfortunately not: Changes to a user are not logged (even though newly created users are), and the user entity does not support revisions in core (as of Drupal 8.4.2).

You could add an extra submission function with hook_form_user_form_alter() that creates a log message.


What does parent::form($form, $form_state) do? I'm not able to understand what parent::form($form, $form_state) does in a content entity form. If I comment it out, the entity form still get rendered.

class AdvertiserForm extends ContentEntityForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    /** @var \Drupal\redirect\Entity\Redirect $redirect */
    $advertiser = $this->entity;
    $form['status_code'] = array(
      '#type' => 'textfield',
      '#title' => t('Redirect status'),

    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
      $form = parent::form($form, $form_state);

  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity->save();
    drupal_set_message(t('The redirect has been saved.'));

  }
}

What does parent::form($form, $form_state) do, exactly?

If you look at ContentEntityForm::form(), the method called with parent::form() since ContentEntityForm is the parent class, you will notice what exactly it is doing.

  $form = parent::form($form, $form_state);
  // Content entity forms do not use the parent's #after_build callback
  // because they only need to rebuild the entity in the validation and the
  // submit handler because Field API uses its own #after_build callback for
  // its widgets.
  unset($form['#after_build']);

  $this->getFormDisplay($form_state)->buildForm($this->entity, $form, $form_state);
  // Allow modules to act before and after form language is updated.
  $form['#entity_builders']['update_form_langcode'] = [$this, 'updateFormLangcode'];
  return $form;

It doesn't significantly change the form, so it is expected the form doesn't apparently change, or it is rendered the same if you don't call parent::form(), but (as the comment says), it allows modules to act when the form language is updated. You could not see anything different, but you are actually avoiding modules can do anything when the form language is changed.


which version is this cache_set function belong to? The function I have commented out is in Drupal 5.x and I've seen a lot. I　want to know which Drupal version the function I haven't commented out belongs. This is the function that I have seen on the site that I am working on. I am about to replace the site by Pressflow. But I met some problem with cache_set function. Serialized seems a new column and this function is so different. So I really don't know which version of Pressflow in 5.x that I can use for my site...

/*
function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = NULL) {
  $created = time();
  db_query("UPDATE {". $table. "} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, $created, $expire, $headers, $cid);
  if (!db_affected_rows()) {
   print_r($data);
    db_query("INSERT INTO {". $table. "} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, $created, $expire, $headers);
  }
   //mysql_query("INSERT INTO tbj_cache_views (cid, data,created, expire,headers) VALUES ('aaa', 'adsfadfasdfdffa', ".$created.", ".$expire.", NULL)");
}
*/
function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = NULL) {
  $serialized = 0;
  if (is_object($data) || is_array($data)) {
    $data = serialize($data);
    $serialized = 1;
  }
  db_lock_table($table);
  db_query("UPDATE {". $table ."} SET data = %b, created = %d, expire = %d, headers = '%s', serialized = %d WHERE cid = '%s'", $data, time(), $expire, $headers, $serialized, $cid);
  if (!db_affected_rows()) {
    @db_query("INSERT INTO {". $table ."} (cid, data, created, expire, headers, serialized) VALUES ('%s', %b, %d, %d, '%s', %d)", $cid, $data, time(), $expire, $headers, $serialized);
  }
  db_unlock_tables();
}

That looks like the D6 cache_set().

Pressflow versions are API compatible with the Drupal versions. So if your site is D5, you should use Pressflow 5.

Mixing up Drupal 5 and Drupal 6 code is a recipe for disaster. So if you are doing this stop. Pressflow 5 cache.inc includes this...

function cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = array()) {
  $headers = serialize($headers);
  $created = $_SERVER['REQUEST_TIME'];
  db_query("UPDATE {". $table. "} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, $created, $expire, $headers, $cid);
  if (!db_affected_rows()) {
    @db_query("INSERT INTO {". $table. "} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, $created, $expire, $headers);
  }
}

This is probably what you should use.


Extra template name suggestions for main-menus based on regions In the first look, the process of solving this problem maybe seems very easy, but this problem makes me really confused.
Imagine that I want to have two main-menu one in the header (primary menu/ top bar) and another in the footer region of my site with different style and template.
By default, there is no file suggestion that differentiates which twig file to be used for a menu based on the region.
That's why I follow below article to add block region as the id of main-menu and make block's template name suggestion unique and dedicated for next customization.

Drupal 8: Theming menus by KristianKaa

function THEMENAME_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}

function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

But the following HTML comments, are the theme hook suggestions added by the debug function, for the Main navigation blocks after adding those codes.

Header section:

<!-- FILE NAME SUGGESTIONS:
   * menu--main.html.twig
   * menu--main--mainnavigation-2.html.twig
   x menu.html.twig
-->

Footer section:

<!-- FILE NAME SUGGESTIONS:
   * menu--main.html.twig
   * menu--main--mainnavigation-2.html.twig
   x menu.html.twig
-->

As you can see from the suggestions, there is nothing to distinguish the two menus from one another based on regions.
I think this template name suggestion hasn't any efficiency in this case because what's that suggested isn't semantic.

So my main question is: How can I add extra filename suggestions for main-menu based on regions not block Id? Or
How to get the current region inside the Hook_theme_suggestions_menu_alter, to add my own suggestion?

I read below posts also but all of those add block Id as twig suggestions for menus:
Additional twig suggestions for menus
How to create a custom Twig Template for Menu Block
How to make a theme hook suggestion for menu according to the region?

You should install the Menu Block module, which will let you dictate the name of the instance of the menu for easy theming. It is then up to you to give it a name.

TBH you don't want to get in the game of trying to manipulate region suggestions based on what it may or may not contain.


In which database table does the number views of a node get stored? I'm using Drupal 7. After enabling the Statistics module (part of Drupal core), I see, under each node, how many times it has been read (e.g. "4 reads").

I wonder where this number of views of a node (e.g. "4 reads") gets stored in some table in the Drupal database.

As well as statistics there is the aptly titled Node View Count module

https://www.drupal.org/project/nodeviewcount

It has a few advantages over the native stats module in the way it counts and also has views integration so you can get some nice tables up and going quickly.


How to acess API rest/views using token or login? I have a Drupal 8 website. I need to access the list of articles using www.myexample.com/rest/views/articles.

I could get the token using curl --header "Content-type: application/json" -b cookies.tt --request POST "https://www.myexample.com/user/login?_format=json" --data '{"name":"myname", "pass":"mypassword"}'.

How do I use cUrl to pass the token or user/pass and get 'rest/views/articles' in JSON format?

I tried curl --header 'authorization: Bearer {D12G7AajU9NdUAb260zqwCimfdddR1Krg5}' --url https://www.myexample/rest/views/artigos/format?_format=json,
but it returns an error.

UPDATE

I follow the @Ismail Cherri suggestion, seems a progress in the question but give me back :

"message":"The used authentication method is not allowed on this route."

In drupal website the config :

/entity/view/{view}
is set to :

GET
formats: hal_json, json
authentication: basic_auth

and
/entity/entity_view_mode/{entity_view_mode}
is set to :

GET
formats: hal_json, json
authentication: basic_auth

anyone could help?

First of all, does your endpoint require authentication to begin with?
If yes, then use this https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities as a guide though it is for a POST request.

UPDATE
You need to know which authentication method are you using, e.g. basic_auth, cookie, Oauth, etc?
According to the method, you should formulate your request. The use of X-CSRF-Token is for Cookie Authentication.
It might be in your case that you successfully got the token, but you're using it on an endpoint which requires Basic Auth.
As I see in your posted REST configuration, you're actually using Basic Auth, thus your request should look something like this:

curl --request GET \
  --url http://example.com/entity/view/{view} \
  --header 'authorization: Basic HASH_HERE' \
  --header 'content-type: application/json' \


Paginate options in checkbox of a form field I have a custom form with a field of type checkboxes,options for which I am getting from another function which takes an array as input, do some theming on options value and return options back to form,

Here is how my another function looks like

function mymodule_twitter_accounts_as_options($twitter_accounts) {
  $options = array();
  if (is_array($twitter_accounts)) {
    foreach ($twitter_accounts as $twitter_account) {
      $key = $twitter_account->twitter_id;
      $options[$key] = theme('image', array('path' => $twitter_account->profile_image_url)) . mymodule_twitter_account_basic_info_block1($twitter_account) . mymodule_twitter_account_basic_info_block2($twitter_account);
    }
  } return $options;
}

The array $twitter_accounts is coming from a database query, which is extending drupal pagination but I do not think the extended pagination will be helpful here as I need to show a global pagination for all the options rendered in the form later.

Edit:

The reason I am using a form is only because of the reason that once user checks checkboxes and submit the form, I am doing some operations using checkboxes key values, If there is an alternate to use of custom form that will be good too.

Might be no one will land up here,still adding the answer and foolish doubts I had

The pagination done for query to get options works! .

The reason I was in doubt before was because of using the query results as option of checkbox field, the time I added themed the pager while rendering the form, I got the pager which worked out of the box!

How I figured out if pagination working with the query was by adding ?page=1 in the url manually which changed the checkboxes , it ensured me I just have to theme the global pager :) .


Accessing text field with multiple values in a twig file Here is my use case: I have a content type which has a field referencing multiple other entities. Those entities have a text field with multiple values.
So I do
{% for ref in node.field_references %}

and then inside the loop
ref.entity.title.value

To have the title of the referenced entity. This works. Then I try to list the values in the text field:
for value in ref.entity.field_name_of_text_field

But without success. Is there something else that must be done first?

Both loops iterate field items, so when you name the loop variables accordingly the code should be more understandable:
{% for ref_item in node.field_references %}
  {% for text_item in ref_item.entity.field_name_of_text_field %}
    {{ text_item.value }}
  {% endfor %}
{% endfor %}


Upload File upload and generate url I have a site where there are several links to a single file.

Is there a module that allows me to upload a file into the CMS, generate a link and use it as for these links?

The Module would need to keep the same file name if re-uploaded.

Thanks in advance.

Try to use Attachment Links module. Read the README.txt file for better understating.


How to generate my own patches to update core for security when fuerstnet.de's "Drupal upgrade the easy way" page is out of date? For Drupal 7, under the current host I'm using (which doesn't provide things like drush), I've found that patching is the easiest approach to updating core. However, the commonly-referenced page which provides the .patch files for doing this ("Drupal upgrade the easy way") has not updated for 7.67, which contains a security-fix.

Rather than go back to the old way of doing things by following all the steps found within UPGRADE.txt, what process can I use to generate a patch for upgrading my own site?

Per https://www.computerminds.co.uk/articles/quickly-update-drupal-core, Github itself can create patch-files for you. You can use commandline curl or wget to download the appropriate patch easily:

curl 'https://github.com/drupal/drupal/compare/7.66..7.67.patch' > "drupal-7.66-to-7.67.patch"

Alternatively, you can download the tar'd (or zipped) packages for both your current version of Drupal and the target and recursively diff them as described here, resulting in a functionally-identical patch-file.

This can then be tested out in the normal way:

patch -p1 --dry-run < "drupal-7.66-to-7.67.patch"

And then applied if no hunks failed:

patch -p1 < "drupal-7.66-to-7.67.patch"

Note of course that just because patching succeeded, it doesn't mean the successfully-applied patch hasn't broken your site in some way, so be sure to  back up everything (files and Drupal database) before patching, trying this first on your dev site, running tests, etc. before repeating the process for real in production.

Gotcha!

If you've upgraded using fuerstnet.de before, Drupal may falsely continue showing security-update warnings, because at least one package with $file->info['project']=='drupal' and $project['project_type']=='core' will still be considered out of date. That's because some of your .info files may contain extra lines which override standard version-numbers:

; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

Based off of experience, generating your own patch as described above will not remove this information, since it is not present in the vanilla packages, and the files containing these extra lines won't necessarily fail to patch either, if no changes to the vanilla editions' code occurred in the last update. (Common because .info files don't change very often.)

These extra lines need to be removed (or adjusted, if you prefer) before Drupal will stop complaining that you're behind on core updates, even though you're actually up-to-date.


Add labels to superfish sub-menu s Long story short, I'm building a Superfish menu structure that looks like the following:

http://i.imgur.com/3h0KQGX.png]1

I'm using superfish & have everything in order except the labels on each of the sub-menus (GUIDES and BUSINESS STRATEGIES in the image)

How can one duplicate the parent link & add it to the sub-menu as a label above the links?

Ideally the strcture would look something like:

Link 1

Link 2

    Link 2

Link 3

Link 4

      Link 4

Link 5

Link 6

Thanks All, I'm stuck on this one, open to any & all solutions.

Edit: I should have specified that the labels need to be added automatically. I don't want to make the client add a bunch of duplicate labels by hand if I don't have to.

Take a look at the Special Menu Items module. What does it do?

"Special menu items is a Drupal module that provides placeholder and separator menu items" (1)

A placeholder is defined as

"A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it." (1)

Which matches your description of 'labels' in your question.


Problem with creating own module Block with an SQL query I’m trying to create a custom module that implements a block to display something I haven’t been able to do with the Views 2 module.
I’ve tried to look at some guides and tutorials, but I haven’t got any result yet.

I can print out the first SELECT attribute in the first row. The first row make sense since I don’t loop through it but still I’m confused on how to do the rest.

function sn_most_contributed_block($op='list', $delta=0) {
  if ($op == "list") {
    // Generate listing of blocks from this module, for the admin/block page
    $block = array();
    $block[0]["info"] = t('Most Contribution this week (custom module');
    return $block;
  }
  elseif ($op == 'view') {
    $mce = db_result(
      db_query("SELECT node.uid, COUNT(nid), users.picture AS users_picture, users.uid AS users_uid, users.name AS users_name, users.mail AS users_mail FROM node node INNER JOIN users users ON node.uid = users.uid WHERE (node.type IN ('leads',  'qa',  'qa_comments',  'til_salg',  'tips_tricks')) AND node.created >= UNIX_TIMESTAMP( CURDATE( ) - INTERVAL 1 WEEK ) AND node.created <= UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1 DAY ) GROUP BY uid ORDER BY COUNT(nid) DESC LIMIT 0 , 5")
    );

    $block_content .= "Most contributed members are: " . $mce';
    $block_content .= "
In here should be the user image
";
    $block_content .= "
In here should be the username
";

    if ($block_content == '') {
      $block['subject'] = 'contribution test';
      $block['content'] = 'yay';
      return $block;
    }
    else {
      // set up the block
      $block = array();
      $block['subject'] = 'Most contribution this week';
      $block['content'] = $block_content;
      return $block;
    }
  }
}

I’ve tested my query in the database environment for my Drupal site and it works and print everything it should out correctly.

For looping the query, I tried this code with no result.

while ($contriUser = db_fetch_object($mce)) {
  $contriUser [] = $contriUser->uid;
}

I have also tried the following code.

while ($contriUser = db_fetch_object($mce)) {
  var_dump($contriUser);
}

Any help on how to solve this or if someone has an alternative solution to get the most contributing members last seven days it would be much appreciated.

For most contributing members you may want to look at the user points modules, they give you a lot of very nice features.

A couple of quick pointers with your code as you are asking.

Your query should use parameters and be formatted according to drupal coding standards, this helps for security and portability. The coder module can help you with this.

To get the results you will probably want something like db_fetch_array in a loop

 $result_set = db_query("SELECT ...");
 while ($result = db_fetch_array($result_set)) {
   $block_content .= ...;
 }

I hope this helps a little.


How to output a field as a link in D7 On the user/edit pages I would like to display a link based on a (text?)'field'
The link should only be displayed to users with the proper permission.
For this, I'll use the Field Permissions module.

My problem is that I don't to know how to output the field as a link.

I have tried the Link module but this seems to give users the ability to input a link.

In my case users should only see the link on their account page.

Any help appreciated.

it sounds like you aren't trying to add a field, but rather, are trying to DISPLAY a field (link, more specifically) on the user account page.

What you need to do is simply edit the user profile template of your theme to show the link you need in the footer/header or wherever else you need.

Something like the below should work:

Go into our drupal root folder and from /modules/user/ copy the user-profile.tpl.php file and paste it into your theme's /templates folder
It should just have code that looks like this to begin with:

<div class="profile"<?php print $attributes; ?>>
   <?php print render($user_profile); ?>

Add your link at the bottom, making the template file something like

<div class="profile"<?php print $attributes; ?>>
    <?php print render($user_profile); ?>
    <?php if (in_array('my_role', $user->roles)): ?>

My link

    <?php endif; ?>

Make sure you clear your caches, visit a user account page, and make sure it's all working.
Adjust the HTML above as you see fit...


Customising image in the first row in a views I would like to be print for the first row in different display style for the image field.
Thx all!

Title1

Title2

Title3

Title4

I tried using the php field.
Something like:

<?php
  if ($view->row_index == 0) {
    print $row->field_foto_principale;
  } else {
    print "other";
  }
?>

But I can not render the image.

you can also use hook

function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'your_view_name' && $vars['view']->row_index == 1) {
    // your code
  }
}


Group by parent terms from indexed node in views Based on this question, I've obtained an "Indexed Node: Taxonomy Name" field in my view.

How can I group the results by parent terms? When I group by the term field (Format > Settings > Grouping field Nr.1), no parent terms are displayed.

You can also add the parent term to the index.

So if you have field_category as your term field you will be able to index field_product_category:parent.

Note that you may have to use the "Add related fields" section at the bottom of the fields admin page for your index to add the parent term relation before you can add the parent term tid or term name etc.

Then in your view also add the parent term name field and exclude it from display and then group by it.


Custom View : display fields linked to file upload field? I'm trying to accomplish this simple thing but cannot find a way to do it.
If someone could guide me a little bit because I'm going inside deep crazy methods and classes, but I'm sure I'm going the wrong way and there's a simple way to accomplish this :)

I have a view block, that displays these fields :

Content: Title (the title)
Content: Image (Image)
Content: Pdf (File Upload)

So, the title, the image and the file upload are displayed.

I would like to output something like this :

<a href="__link_to_my_pdf__">
    __Title__
    __Image__
</a>

Is there a way to do this through the view management ?
If not, what could be the right way ? Twig ? Preprocess ? Module ?

I tried through a views-view--myviewblock.html.twig to get the variables inside {{rows}}, but spent 4 hours and failed.

Thanks in advance.

Thanks for the link, I'll read it.
I finally got an answer on drupal.org that suits perfectly.
The idea is to use the "Custom text" field :

  Add title, image, file and Custom Text field to your view.
  List item
  Edit Title, Image field and check exclude from display option and
  save.
  Edit File field and check exclude from display checkbox, In
  Formatter drop down select "URL to file" and save.
  Edit custom text field
  Click to "REPLACEMENT PATTERNS"

  Here you can find tokens for title, image and file fields. E.g. {{ title }} fir Title field and {{ field_image }} for image
  field.
  Copy {{ title }} {{ field_image }} and paste it to Text.
  Then click to "REWRITE RESULTS"
  Check "Output this field as a custom link" and enter File field token {{
  field_my_file }} to "Link Path" textfield. Save this field.
  Save the view and now its ready.


After altering form I cannot save changes in nodes In drupal 7:
I have Answer content type and alter the form for that type:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'answer_node_form') {
    // disabling some fields (ie. #access title field to false)
    // setting defaults values
    // adding one hidden field (that shouldn't be inserted into database)
  }
}

A when I'm trying to submit edit form, the process of PHP takes too much time and Apache restarts.
Do you have any idea what is wrong? Maybe when I send the form, it shouldn't have any additional fields?

I could paste the code but I think it's insignificant.

As @NikhilMohan says, you can't just remove fields like the title; they're required for validation. Event setting #access => FALSE has strange results in my experience.

What you could do instead, is set a value for the fields you're hiding, and change their #type to 'value'. That way the element will still exist on the server side, and validation/submission won't break.

e.g.

$form['title']['#type'] = 'value';
$form['title']['#value'] = 'Some default value for the title';


How to create a log in and register link in the secondary menu I am trying to configure my login block on the front page such as that it appears on a separate page. I want the links to this page (that is, login and register) to appear in the secondary menu. I am using Zen with Drupal 7.

Create a new entry in the secondary menu and point it to /user or /?q=user.


Can't hide fields in user registration form at new menu path I have a menu path which rendered User Registration Form.  The problem is I did hide fields like "Email", "password" and "status" by setting #access to FALSE. It is not working.

When I have done the same thing in hook_form_alter(), it does work.

This is my code.

/**
 * Implements hook_menu().
 */
function MY_MODULE_menu() {
  $items['admin/author/create'] = array(
    'title' => t('Author'),
    'page callback' => 'MY_MODULE_author_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Author form.
 */
function MY_MODULE_author_form() {
  drupal_set_title('Create Author');

  // Getting User Register Form
  $form = drupal_get_form('user_register_form');

  // Change Username to Author Name
  $form['account']['name']['#title'] = 'Author Name';

  // Exclude User Registeration Elements
  $form['account']['mail']['#access'] = FALSE;
  $form['account']['pass']['#access'] = FALSE;
  $form['account']['status']['#access'] = FALSE;

  // The path to which the form will be submitted.
  $form['#action'] = url('admin/people/create');

  return $form;
}

I think I can alter the form in MY_MODULE_author_form().

Is there anything wrong with my code?

Follow Drupal's standards and change your hook_menu:

/**
 * Implements hook_menu().
 */
function MY_MODULE_menu() {
  $items['admin/author/create'] = array(
    'title' => t('Author'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MY_MODULE_author_form'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );

  return $items;
}


Drupal Commerce: Can I have product list and checkout in the same page? I have a D7 site and I´m trying to implement Drupal Commerce.

I just need a page where the user can select the product from a list, and give some information about himself (billing information). And at the bottom it should be the "buy" button.

I don´t want a cart, the possibility of "continue shopping" and stuff like that.

How may I do that with Drupal Commerce? I´ve watched all day the videos and read some documentation, but it really seems over complicated when you just want a simple thing (opposed to a big ecommerce site).

Any guidance, tip or help will be very much appreciated. Thanks!

Try Commerce Express Checkout

  The Express Checkout button redirects to the Checkout page directly,
  without going to the Cart first, It also removes the Review page and
  adds the Payment checkout pane to the Checkout page, so the whole
  checkout process is done on one page.

Ckeck

http://www.drupalcommerce.org/discussions/952/all-checkout-steps-one-page
http://atendesigngroup.com/blog/express-checkout-drupal-commerce


Get multiple results from entity reference relationship in views In a view that displays content of a type that uses an Entity Reference (specifically User reference), I add that relationship but even though multiple users may be/are referenced by the content I only get one of them. Am I missing some sort of configuration?

In the relationship description: "A bridge to the User entity that is referenced via field_users"

EDIT: So after a private discussion with @Anil Sagar it seems that you cannot -using entityreference alone- display multiple results of the referenced entities in one row of the Entity the view displays.

The best you can get is:

Article One
body
image
user1 name
user1 surname

Article One
body
image
user2name
user2surname

(users 1 and 2 are referenced by Article One).

Verify Distinct Checkbox in View Query Settings. You should disable it.
Verify number of items to display is more than one.
Make sure no filters or contextual filters added that will effect the view results.

I just added a entity reference field to Article Content Type. And then added a relationship to the entity in view using Relationships. It does show multiple values.

I am not sure what other configurations are enabled in your view. See below query generated using views for above scenario.

SELECT node.title AS node_title, node.nid AS nid, users_field_data_field_user.name AS users_field_data_field_user_name, users_field_data_field_user.uid AS users_field_data_field_user_uid, node.created AS node_created, 'node' AS field_data_body_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_user} field_data_field_user ON node.nid = field_data_field_user.entity_id AND (field_data_field_user.entity_type = 'node' AND field_data_field_user.deleted = '0')
LEFT JOIN {users} users_field_data_field_user ON field_data_field_user.field_user_target_id = users_field_data_field_user.uid
WHERE (( (node.status = '1') ))
ORDER BY node_created DESC
LIMIT 5 OFFSET 0


Views - Exposed Filter for 2 Field Collections with Same Fields I have a content type with 2 Field Collections(both set for unlimited values), they are Author and Editor. Both field collections are using the same fields(first_name and last_name).

In a Views that I created has both field collections displayed. And I would like to exposed the First and Last Name, but they are not searchable without a relationship. Meaning I have to have 2 First Name and 2 Last Name filters exposed with different relationships.

How to make 1 first name filter exposed and searchable for both Author and Editor?

PS: I have done many other searchable Views page, but this is different(2 field collections with same fields).

You need to make the base table for your View the Field Collection table rather than the Node (content) table.  You'll need to add a filter to only show the type(s) of Field Collections you wish to query.

Now you'll be querying all Field Collections of the selected type(s), regardless of whether they're considered authors or editors.  Simply add exposed filters to query on the first_name and last_name fields.

The real question is: what do you want actually displayed?  If you only want data attached to the Field Collections displayed then that's easy enough.  If you want to pull data from the host nodes beyond merely the NID then you're going to end up with 2 separate relationships to the nodes (one for each field) and you're probably not going to be able to get the UI you want out of that.

A much easier approach to all of this would be to put all of the "people" related to a node in a single Field Collection field and differentiate between Author and Editor by way of an additional "type" field in the Field Collection.  You could then construct very straightforward views to query across all types of related people.


Why do I get PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'"? $rtid = arg(2);

$query = "SELECT node.nid AS nid FROM node
  WHERE (node.nid IN (
    SELECT tn.nid AS nid
    FROM taxonomy_index AS tn
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th ON th.tid = tn.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th1 ON th.parent = th1.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th2 ON th1.parent = th2.tid
    WHERE (tn.tid = :rtid) OR (th1.tid = :rtid) OR (th2.tid = :rtid)
  ))
  AND (node.status = '1') AND (node.type IN ('product'))
  ORDER BY node_created DESC
  LIMIT 1 OFFSET 0";

$result = db_query($query, array(':rtid' => $rtid));

After I tried some times with the help of other users' answers, I got lost. This is the code I tried, but it gives me an error ("PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'").

$query = db_select('node', 'n')
  ->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition('tn.tid',$rtid )
      ->condition('th1.tid',$rtid)
      ->condition('th2.tid',$rtid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

$query->join('taxonomy_term_hierarchy', 'th', 'th.tid = tn.tid');
$query->join('taxonomy_term_hierarchy', 'th1', 'th.parent = th1.tid');
$query->join('taxonomy_term_hierarchy', 'th2', 'th1.parent = th2.tid');

$result = $query->execute();

The error you get is caused by the fact you don't use tn as alias of any database table.

The code I would write is the following one.

$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'ti', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

$query->join() is really doing an INNER join; if you need to make a LEFT OUTER join, then the code is the following.

$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

As side notes:

$query->join(), and $query->addJoin() returns the alias they used
In the conditions passed to $query->join(), and $query->addJoin() %alias is replaced with the table alias the method is using

SelectQuery::addJoin() avoids conflicts between aliases using the following code.

  $alias_candidate = $alias;
  $count = 2;
  while (!empty($this->tables[$alias_candidate])) {
    $alias_candidate = $alias . '_' . $count++;
  }
  $alias = $alias_candidate;

  if (is_string($condition)) {
    $condition = str_replace('%alias', $alias, $condition);
  }

Writing code similar to the one I used, you are sure not to cause any conflict between aliases, and it is useful in the case the code is changed successively, or part of the query is populated from a function.
In this case, the join part could have written as follows, and it could still work correctly.

$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th1.parent");


I can't access the modules page I have installed a few modules for the site; one of them is causing an error, and I can't access the modules page.

The error I see is the following one:

  Fatal error: Call to undefined function ctools_include() in
  /var/www/vhosts/haweraprezchurch.org.nz/httpdocs/sites/all/modules/features/includes/features.ctools.inc on line 226

How can I access the module page?

In my case I am using Drupal 7.

I always find the simplest way to deal with this is just to go to the system table in the site's database, and set the status column for the problematic module to 0.

After clearing the cache tables (either with Drush, or manually) you should be able to access the modules page again.


What are "Text format" option in standard Drupal? I would like to know if in Standard Drupal, the comment form allows you to select a text format such as "Full HTML", "Plain Text" and "Filtered HTML" when commenting or even posting an article?

I have installed some module like WYSIWYG, CKEDITOR,IMCE, .., so now I am confused and do not know if the reason I have the option to select format text when commenting is because of the modules that I have installed or not?

"Full HTML", "Plain Text" and "Filtered HTML" are default Textformats in Drupal, they determine which elements are allowed in the input and what gets filtered.

The wysiwyg editors only add UI controls to the field so user don't need to know HTML to style their output. If you don't want anonymous users to use formats like 'full html' you can turn it off in the permissions and give access to full html only to administrators or roles you trust.


Preprocess language switcher block I'm trying to modify the output of the language switcher block to make the output more inline with other menu styles on my site. However, I can't figure out how to modify the output.

I'm attempting to use the following:

function my_module_preprocess_block(&$variables) {
  var_dump($variables['elements']['#id'];
}

This gets every block on the page except for the language switcher.

How can I preprocess or modify this?

We added a filter to drop the languages that did not have translations from the language switcher.  Here's the code from that:

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function mymodule_block_view_language_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#pre_render'][] = '_mymodule_language_block_prerender';
}

FYI - Used pre_render because I was removing links from the [content][[#links] element.


How to mass update recurring date rules? I would like users to be able to mass update recurring date rules possibly using VBO and Rule sets.

For example: user would like to add "exclude date = 01/01/2012" recurring date rule for all selected nodes' dates where date is a new field added to a content type.

How to do this ?

---=EDIT=---

I have already build a basic Rule with the following code:

{ "rules_change_end_date_for_selected_content" : {
    "LABEL" : "Change end date for selected content(s) (Test rule)",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Content", "type" : "node" },
      "event_end_date" : { "label" : "Event End Date", "type" : "date" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } },
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "event" : "event" } } } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-event-date:0:value2" ],
          "value" : [ "event-end-date" ]
        }
      },
      { "entity_save" : { "data" : [ "node" ] } }
    ]
  }
}

What should I put instead of node:field-event-date:0:value2 to modify the date rule end date ( not the first date enddate). I would like to change the date until this node repeats but I cannot see tokens for the date repeating rule.

This sounds like it will need a custom module, However have you tried the bulk update module?, you could extend this and adapt it for dates, I do not have any code examples, as it does sound quite complex.


How can I build a popup in drupal? I am working with Drupal 7, and I have a block generated by the Views module with titles of many articles. When the user chooses a title, I want a popup with title, body, and image to appear.

Is it possible with any module?

you can use lightbox2 module.

And here is the description that how will you use it.


How to programmatically change the weight of children in a taxonomy vocabulary? I am trying to edit an existing vocabulary to change the weight of the children. Any idea?

Change the weight property on the term object.

$term = taxonomy_term_load($tid); //$tid = your taxonomy term id
$term->weight = 10000; //Whatever weight value
taxonomy_save_term($term);


Webform submitForm hook I am using drupal 8 and webform 8.x-5.0-beta25. I have a multistep form with ajax enabled, 5 pages.

I need to alter the confirmation message but I haven't been able to figure it out. What I want to achieve is change the message depending on some form values the selected on the last question. I've created a custom module and extended the WebformHandlerBase and created a confirmForm function but I am not seeing anything once the form is submitted.

Again, it is submitting through ajax so I am not sure if that has anything to do with it.

Here is what I have tried so far

/modules/custom/cbed_ux/src/Plugin/WebformHandler/QuizWebformHandler.php

<?php
namespace Drupal\cbed_ux\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformInterface;
/**
 * Form confirm handler.
 *
 * @WebformHandler(
 * id = "quiz_handler",
 * label = @Translation("Quiz Handler"),
 * category = @Translation("Quiz Handler"),
 * description = @Translation("Quiz Webform handler."),
 * cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 * results = \Drupal\webform\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class QuizWebformHandler extends WebformHandlerBase {
  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    kint($webform_submission);
    drupal_set_message ('submitted!!');
  }
}

The form submits, but I do not see my kint or set message

Did you attach your WebformHandler to your webform via /admin/structure/webform/manage/WEBFORM_ID/handlers?

Your QuizWebformHandler::submitForm method does not match the WebformHandlerInterface::submitForm definition and should be throwing a fatal exception.


Creating a custom url when navigating to a custom module form I have created a custom module which can be visited via the address
http://myhost.me/my_module/form where it will show my created form. Is there a way wherein instead of using http://myhost.me/my_module/form I can navigate to http://myhost.me/mynewmoduleurl without breaking anything? I'm currently using Drupal 6. Please help. Thanks.

There are multiple ways.

You could use hook_menu() to declare a new path with the same callback (while still leaving the old one intact).
You could use Redirect module.
You could create a .htaccess redirect. (A 301 redirect is the proper way to do it if you want the new one to permanently replace the old one.)
You could create a new Path Alias.


Views : Use a custom template field even if it's excluded from display In a Views, I have two field :

Link field : With 1 to n links to display (excluded from display)
Body field : Who use the previous link field (via rewrite output and token)

I have created a custom template for display link field like I want.

Here is my problem:
When I render my Views, my custom template isn't used for display my links...
He use the display function defined in the link field settings.

Is there a way to force View to use my template ?
Any suggestions to do this?

Edit : Some screenshot of fields and theme informations

Link field :

Body field :

Theme Infos :

To use the custom template for a particular field you should use the template suggestion from Theme:Information from advance section of your view, Select the suggestion template form the them info as the screenshot for field NID
 . Create that template inside the your_theme/template folder. Don't forgot to clear the drupal cache.


Can you tag individual searches per search in order to apply different filters to each? I've got a site where we use solr to generate some menu items and other custom lists as well as running the default search. The issue I'm running in to is all the different hook_apachesolr_query_alter calls across several different modules seem to be getting applied on top of each other stopping everything from working as expected.

Is there an identifier I can look for, or that I can add, in order to identify which query is currently being altered so I can filter them appropriately?

This is what I want to be able to do:

<?php
if ($query->name == 'special_menu'){
  $query->replaceParam('qf', 'sm_vid_Colour');
}
?>

(This is a dupe of my post on Drupal.org at http://drupal.org/node/1976224 but I wasn't getting any love there and thought I'd try my luck here!)

I found a solution that worked for me. Here it is in case anyone else wants to do something similar, or in case someone wants to suggest a better way of doing it!

So the situation is that for a single page, I need to run a handful of SOLR queries to determine what should show up and what should not. Each of those queries works on different fields, so we need to be able to add a different 'qf' parameter to each of them. This gets harder however, when all hook_apachesolr_query_alter calls trigger on all searches! (See the related issue about enabling 'qf' #1659184: Allow apachesolr_search_search_results() to accept 'qf' (query fields) parameter)

After a lot of experimentation I found that the only field I could manipulate when starting a query and fetch and act on in hook_apachesolr_query_alter was using the search path value in a custom $search_page. This is how I did it:

<?php
$search_page = array(
        'env_id'   => 'solr_server',
        'settings' => array(
          'apachesolr_search_per_page' => 25,
          'spellcheck' => FALSE,
        ),
        'search_path' => 'ducks-BiGhE3Nxv34lyTKVoka74WI3r9yjJyc5ohiuJkeCiqp8gJunyWk3gXMDK8W',
      );

      $search_terms = array('"duck"', '"cheese sauce"');

      // Only run if the solr is enabled server environment is detected.
      if (module_exists('apachesolr') && apachesolr_environment_load($search_page['env_id'])) {
        $results = apachesolr_search_search_results('"' . implode(' ', $search_terms). '"', NULL, $search_page);
?>

Then, in hook_apachesolr_query_alter for this particular module/query:

<?php
function pet_or_dinner_apachesolr_query_alter($query) {
  /* test that this is a 'ducks' query */
  if (stristr($query->getPath(), 'ducks')){
    /* now apply different settings depending on the current page */
    $node = menu_get_object();
    if (isset($node->type) && $node->type == 'pets') {
      //Search only the Pet field
      $query->replaceParam('qf', 'sm_vid_pet');
    } elseif (isset($node->type) && $node->type == 'meals') {
      //Search only the Meal field
      $query->replaceParam('qf', 'sm_vid_meal');
    }
  }
}
?>

I don't know if it's necessary, but I put the extra long random string in the 'search_path' so that I didn't have any site visitors accidentally tripping over it. I don't think it is publicly accessible though. Someone else can confirm or debunk that concept!

But there we go, a hook to be able to perform custom modifications on concurrent queries. Definitely not clean but it gets us over the line!

I'll leave this question open in case someone has a better answer.


Set views exposed filter using url In a view an exposed filter of type taxonomy reference exists, the referenced taxonomy vocabulary contains about 15 terms, the functionality I'm trying to get is to allow user call view with a default value for filter, so if user enter the path sitename/view-name/term-name the view would be load with entities of term term1.

I used contextual filter for limiting entities to those having specific term-name but the problem is, if user selects another term name, rather than the one specified in contextual filter, the view returns no result (term reference in node accepts only one value).

So I wanted to know if there is a solution to set the exposed filter default value based on url?

Well after some research I could found the answer. Actually drupal itself do provide such functionality and there is no need to code or ...

When exposing a field as filter to user, in filter settings window a filter identifier can be set (this can't be empty and is filled with field name by default), this is shown in image below :

in above example the identifier is set as cat, in this situation the path sitename/view-address/?cat=term-1 will load the view with my exposed filter assigned as term-1 and corespond entities.


How to inject a fake class into container when running WebTestBase tests? I've got a form class, and I'm injecting my custom functionality class into it via constructor. That class is added to the container via the services.yml file defined in my custom module.

I'd like to test that the form is functioning correctly, but for testing purposes I'd like to replace the class that's injected into the form with a fake one.

Both real and fake classes implement the same interface. The form is working with that interface.

My test file:

<?php
/**
 * @file
 * Contains \Drupal\my_module\Tests\FormTest.
 */

namespace Drupal\my_module\Tests;

use Drupal\my_module\Tests\Fake\FakeClass;
use Drupal\simpletest\WebTestBase;

class FormTest extends WebTestBase
{

    public static $modules = [
        'my_module',
    ];

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

        $fake = new FakeClass();

        $this->container->set('my_module.real_class', $fake);

        // $this->container->get('my_module.real_class') returns a FakeClass object.
    }

    public function testFormWorks()
    {
        $this->drupalGet('my-form');
        $this->drupalPostForm(NULL, [], 'Submit');
        $this->assertRaw('Form is working.');
    }

}

When I'm running the test, the real class is being used, which is not the desired test behaviour.

I can't figure out what I'm doing wrong here. Any help is appreciated.

Update: the issue is not specific to forms. Same thing happens in page controllers.

Here's the solution.

Let's say your module A defines a new service.

In order to alter that service, you need to create a separate module B and follow the steps outlined in Overriding the default service class section on https://api.drupal.org/api/drupal/core%21core.api.php/group/container/8.

Make sure to list module A as a dependency in module B info.yml file.

Add both modules to the $modules array in your test class, and everything will work. $this->container->set() is no longer needed.

That issue on drupal.org: https://www.drupal.org/node/2700739