How to apply a patch file in composer to a submodule of a module? I've added the patch to composer.json like this:

  "drupal/admin_toolbar_tools": {
    "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
  }

However, admin_toolbar_tools is a sub-module of admin_toolbar (admin_toolbar/admin_toolbar_tools).

I ran composer install, but it doesn't trigger the patch apply process.

The patch I am trying to apply is the following one (https://www.drupal.org/files/issues/2019-01-26/admin_toolbar-media-link-3026216-8-option3.patch).

diff --git a/admin_toolbar_tools/admin_toolbar_tools.module b/admin_toolbar_tools/admin_toolbar_tools.module
index 9ac389c..1f8a36b 100644
--- a/admin_toolbar_tools/admin_toolbar_tools.module
+++ b/admin_toolbar_tools/admin_toolbar_tools.module
@@ -621,20 +621,23 @@ function admin_toolbar_tools_menu_links_discovered_alter(&$links) {

   // If module Media enabled.
   if ($moduleHandler->moduleExists('media')) {
-    $links['admin_toolbar_tools.add_media'] = [
-      'title' => t('Add media'),
-      'provider' => 'admin_toolbar_tools',
-      'route_name' => 'entity.media.add_page',
-      'menu_name' => 'admin',
-      'parent' => 'system.admin_content',
-    ];
+    // Displays media link in toolbar.
+    if (in_array('entity.media.collection', $routes)) {
+      $links['admin_toolbar_tools.media_add_page'] = [
+        'title' => t('Add media'),
+        'provider' => 'admin_toolbar_tools',
+        'route_name' => 'entity.media.add_page',
+        'menu_name' => 'admin',
+        'parent' => 'system.admin_content',
+      ];
+    }
     // Add node links for each media type.
     foreach ($entityTypeManager->getStorage('media_type')->loadMultiple() as $type) {
       $links['media.add.' . $type->id()] = [
         'title' => t($type->label()),
         'provider' => 'admin_toolbar_tools',
         'route_name' => 'entity.media.add_form',
-        'parent' => 'admin_toolbar_tools.add_media',
+        'parent' => 'admin_toolbar_tools.media_add_page',
         'route_parameters' => ['media_type' => $type->id()],
       ];
     }

Use admin_toolbar.

"drupal/admin_toolbar": {
  "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
}

Then run composer update or composer update --lock if you want to apply your new patch and do not want to update any packages.


How do I pass an additional variable to function theme_item_list I need an additional variable to be available to the function theme_item_list. How do I correcly pass my variable so that I can alter the function like so:

function theme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  $MY_VAR = $variables['MY_VAR'];

Here is my render array:

  $node->content['list'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#weight' => 2,
    '#prefix' => '
',
    '#suffix' => '
',
  );

Thanks

Implement hook_theme_registry_alter() to let Drupal know about the new var:

function MYTHEME_theme_registry_alter(&$registry) {
  $registry['item_list']['variables']['MY_VAR'] = NULL;
}

Then override the theme function:

function MYTHEME_item_list($vars) {
  // Copy/change original theme_item_list as required.
  // $vars['MY_VAR'] is available as long as it has been passed in.
}

And just make sure you pass the var in your render array:

$node->content['list'] = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#weight' => 2,
  '#prefix' => '
',
  '#suffix' => '
',
  '#MY_VAR' => 'foo',
);


Display if and when a particular field exists [I have been on D6 for ages, and just shifting to D7.]

In D6, I was using the following in the node.tpl.php:

<?php if (content_format('field_occupation', $field_occupation[0]) != '') : ?>
<?php foreach ($field_occupation as $occupation) { ?>
<strong>Primary occupation: </strong><?php print content_format('field_occupation', $occupation) ?><?php } ?>
<?php endif; ?>

But this doesn't seem to work in D7.

How can I make it work?

Welcome to d7 - just in time as d6 will soon become unsupported.
In D7, content_format is deprecated.

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

Check out this for how to render entity fields in d7: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

You'll have to adapt your existing script to this new rendering method. It might be a good opportunity to clean up the presentation and readability of the script so that you'll be prepared for the inevitable migration to d8!


How to keep domain consistency (with or without www)? Some search engines make a difference if the site is found in example.com or www.example.com. So it's important to redirect all users from example.com/some-page to www.example.com/some-page, or the other way around.

Is it possible in Drupal 7?

I found the answer. The .htaccess file contains the following comments.

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Uncommenting one of those rewriting rules is all you need to do.


How do you change the email recipient of drupal 7 webform based on checkbox value using hook form alter? How do you change the email recipient of drupal 7 webform based on checkbox value using hook form alter?
I have a group of checkboxes (Texas, DC, Maryland, Virginia). I would like to change the recipient if Texas is checked and use the default for the other options. I do not want to change the key of the checkbox component to the Texas email address because I need to state which location was selected in the email template.

You do not need to use hook_form_alter for this, you can set this up in Webform on admin, here is how:

Go to the Edit interface of your webform
Go to E-mails
At the bottom, choose 'Component value' and choose your checkbox field, click Add http://cl.ly/image/1K3V2N3k3q30
At 'Component e-mail options' you can specify an email address for each option http://cl.ly/image/1g3c1r15060r

Description below says:

"You may enter an e-mail address for each choice. When that choice is selected, an e-mail will be sent to the corresponding address. If a field is left blank, no e-mail will be sent for that option."


How to send author an email after they post content? When I user saves a piece of "my_custom_content_type" I want to send the user an email, basically "your content has been submitted, will be published after review"
I know this is a core feature for webforms, but what is the best way to accomplish this for Custom Content Types?

One easy way to do that is with the Rules module

Event: After saving new content
Action: Send email.

Here's an example Rules export (for article) that can be imported via the UI at admin/config/workflow/rules/reaction/import

{ "rules_review_notification" : {
    "LABEL" : "Send review notification email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "mail" : {
          "to" : [ "node:author:mail" ],
          "subject" : "[Notification] Content submitted for review",
          "message" : "Your content has been submitted and will be published after review."
        }
      }
    ]
  }
}


Attaching a view to a content type that takes the content type's taxonomy terms as arguments What I am trying to do is create a content type with a taxonomy vocabulary field. When creating the content type and selecting one or more of the terms, I would like the content type with an attached view to render the node with a list of nodes (ex: teaser views) that share share the content type's selected taxonomy terms.

In the past I have used Insert Views and listed the taxonomy terms. I would like a more elegant solution so a user can just use a selection list or term radio buttons.

How would I go about attaching a view and passing the taxonomy terms of the content type to the "attached" view?

Thoughts?

Thanks.

Rich

You can pass to the template, a variable which contains the second view value

function mymodule_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle){
    case 'customtype':
      if( $view_mode == 'teaser' ){
        $entity->test['test'] = array(
          '#markup' => views_embed_view( 'view_2', 'default', $entity->field_custom['und'][0]['value'] ),
        );
      }
    break;
  }
}

Then, in your theme, a node--customtype.tpl.php, you can render the variable:

print render($test);


Multiple Values to Trigger #states How can I have multiple values trigger the Form API's #states?

Say for example, I wanted this field to be visible not only if the value is 5 (currently works below), but wanted to make the field visible if the the values are 3, 4 or 5.

'#states' => array(
    'visible' => array(
       ':input[name="field_star_rating"]' => array('value' => t('5')),
    ),
),

As a note, I tried the following and it does not work.  It only works if the value is '4'

'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5')),
        ':input[name="field_star_rating"]' => array('value' => t('4')),
    ),
),

This also does not work, it too only works if the value is '4':

'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5'), 'value' => t('4')),
    ),
),

Here's what you need:

'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array(
            array('value' => t('5')),
            array('value' => t('4'))
        ),
    ),
),


Adding template to garland, preprocess page doesn't work So I am trying to add an additional page to garland at http://site.com/processfront, this code does not seem to run and or change the template. I know the code is being run however, since i get an error if i purposefully mess up syntax. But, I tried defining some other arbitrary variables and printing them and that didnt work either... What's going on? Thanks

function phptemplate_preprocess_page(&$vars, $hook) {
  $vars['tabs2'] = menu_secondary_local_tasks();

if (arg(0) == 'processfront') {
   $variables['template_file'] = 'page-processfront';
 }

If processfront is an alias for a specific node, let's say 228, then its system path is really node/228 and arg(0) will be node.  If you've set your system up so that this node is your front page, you can just use page-front.tpl.php and drupal will take care of it automagically.  Otherwise, you can use drupal_get_path_alias() and check against that.


How to clean up multiple Drush Composer installs? I've been setting up a new Ubuntu 16.04 laptop for Drupal development. I had trouble installing Drush using Composer, but eventually got things working. Today, while setting up Drush tab completion, I discovered five instances of drush.complete.sh:

$ locate drush.complete.sh
/home/monkey/.composer/global/drush/drush/vendor/drush/drush/drush.complete.sh
/home/monkey/.composer/vendor/bin/drush.complete.sh
/home/monkey/.composer/vendor/drush/drush/drush.complete.sh
/home/monkey/.config/composer/vendor/bin/drush.complete.sh
/home/monkey/.config/composer/vendor/drush/drush/drush.complete.sh

*cough* I think I need to clean things up and start from scratch. How can I correctly uninstall all these Drush instances?

composer global remove drush/drush will get rid of either the ~/.composer or the ~/.config copy, depending on your current configuration.  However, if you are no longer using the components that you installed via composer global, you can just use rm -rf to delete the directories you don't need, which is vendor and bin in ~/.composer and ~/.config.


how to print view title in views-view-unformatted.html.twig? I have to style the view title
and print it in the unformatted twig. how can i achieve this ?

As per @Clive's comment

{{ view.getTitle() }}


Form with Site Content that Creates an Entity with User Created Content and Site Content Combined Webform and EntityForm do not seem to have the ability to create entities.

Please help me find modules that can be used to build a Planning Form that creates User Created Planning Entities for the use case below. Any further tips or modules for the bonus features would also be greatly appreciated.

Minimally Viable Product:

At its core this is a way for Authenticated Users to plan for a conference. The user views videos, pictures and text then saves notes about the videos, pictures and text, and later accesses an entity they created with the original videos, pictures and text grouped with their user created content. So a video about networking at a conference has a form below it for the user to make notes they can see later and know it’s notes for that particular video.

Parameters:

Three Entity Types:

Conference Node  Content Type (that provides access to the Conference Planning Form)
Conference Planning Form (for viewing standard Drupal Fields and saving user created content)
User Created Conference Planning Entity (for future viewing and editing of Conference Planning Form site admin and user created content)

The user does not need to actually book the event through this feature. This feature is to help them stay organized.
If there is a way to have the user save their User Created Conference Planning Entity on the front end that would be great but not required.

Use Case:

User finds a Conference Node they are interested in.

User selects a button to plan for the conference and they are taken to a standard site wide Conference Planning Form.

The Conference Planning Form (hopefully an entity) contains instructions and tips created by the site admin (such as videos, pictures, links or text), and a form field the authenticated user can use to create notes (links and text) grouped with the field or a group of fields the site admin created  that display on the Conference Planning Form to generate a User Created Conference Planning Entity.

The authenticated user fills out the form fields they would like to use and saves the Conference Planning Form to create a User Created Conference Planning Entity  which is added to their list of User Created Conference Planning Entities.

Later the user can access the User Created Conference Planning Entity they created to add content to the form entry fields
The user can access the User Created Conference Planning Entity they have created to view notes they created.

Bonus Features:

After saving the Conference Planning Form and when viewing the User Created Conference Planning Entity the user created, the original content from the Conference Planning Form is displayed and grouped with each form field of content the user created the first time they saved Conference Planning Form and created the User Created Conference Planning Entity.
The ability to for the sited admin to provide site wide generic Conference Planning Form or a custom Conference Planning Form for any Conference Node.
The ability to automatically displays fields on the Conference Planning Form referencing the Conference Node the user came from with the referenced fields (possibly with Entity Reference module) grouped (possibly using Field Group module) with a form field the user could add notes to.
A site admin created task list that can be on the Conference Planning Form that would also show on the User Created Conference Planning Entity that could be checked off (possibly using the Flag Module.
The authenticated user can create a custom task lists on the User Created Conference Planning Entity that they can checked off.

check out Flexiform module. This can be used for adding/editing entities using custom form. It has its own drawbacks though. So far I couldn't find a way to create multi-step form using the Flexiform. The documentation says it is WIP. Not sure if it is available now.

Here is the article with the comparison on multiple form modules.


Internal mail system How do I allow users send emails to the other users?
What module can I use to allow users to email each other?

I don't know about 'best' (although @Berdir might have something to say on the matter ;) ), but Privatemsg would probably be perfect for this:

  Privatemsg allows your site's visitors to send private messages to each other.

It also provides e-mail notifications of new messages.


How do I turn off clean URLs only for logged-in users? The end-goal is to use filters to support AWS' new CDN dynamic content feature.

This isn't possible in Drupal core because the clean url check occurs so early in the bootstrap phase, i.e. before you would be checking for permissions, settings, etc. One hacky possibility is to try and determine in your settings.php file if a session is open and then enable the clean_url settings dynamically:

$conf['clean_url'] = 0;

But even that would probably be swamped by your htaccess settings and mod_rewrite.


How to create Nested Accordion in Drupal 7? 2015

-- Jan

-- Feb

  -- Link 1

  -- Link 2

2014

-- Jan

-- Feb

  -- Link 1

  -- Link 2

I want same views accordion feature on this listing with expand or collapse feature .

First user select year then month then we show the node title according to month & year .

Drupal View Accordion triggers the accordion for the innermost Group Header. Though Nested Grouping can be done but the accordion effect will only applied to inner group.

For this we have to apply our own JS. I have created a module in which current accordion plugin has been extended, which itself was extending view plugin style. And additional setting has been added to it for nested accordion.

I have committed a [D7] Views Nested Accordion module on sandbox for this.


Unable to update header value using hook_views_pre_render? I have create the header value using Global: Unfiltered text (Global: Unfiltered text) .

BY us hook_views_pre_render i want to update the header value . How can I update the header value .

How to update header text in hook_views_pre_render provide the solution for the header value to update but its not working for me

    function mytheme_views_pre_render(ViewExecutable $view) {

      if ($view->id() == 'works') {
//    enter code here
             $my_value='No result found';
             $view->display['page']->handler->handlers['header']
             ['area_1']->options['content'] = $my_values;

        }

      }
    }

$view->display['page']->handler->handlers['header']
             ['area_1']->options['content'] = $my_values;

please change the value of the area_1 if anyone want change the header value programmatically .

Just hover the Global: Unfiltered text (Global: Unfiltered text) header value and you will get the area_1 value .


In Yosemite not able to generate the styles folder, I upload the project in a ubuntu test server, and it works I know this is a question related to permission. The only thing I have changed in my environment is that I upgrade to Yosemite, I check apache everything is working fine.

This question has been asked in here and in others. I checked every possible solution. Here is what I have done:

Change the permission in every possible way  even to 777 in local environment. It still gives the error
Change the apache user to my username and staff group, and make sure I have the set the right user and group
Clear the cache every time that I make a change
Use drush to flush the image as recommended in here

I have uploaded my site to a ubuntu server. It generates the files perfectly there without any trouble. Any ideas what it is happening in my local machine that it is not generating the styles folder and give an access denied error? I can upload files btw, it is just not able to create the folder styles and its files.

Probably not a permissions problem: the default php GD library on yosemite comes without png support, so drupal can't generate png images (like the default sample.png). You can very easily install another version of php.


Why doesn't the view read cookies on AJAX refreshment? I use views_extras module to get default argument froom cookies.
It works ok.

But if I set a cookie value using javascript and then refresh a view using ajax the view still shows result for previous value.
So the new value affects only if I reload page.

Why and how to make ajax requests use current cookie?

Btw, I wrote my own module to read cookie value and use it as default
argument: the result is the same with views_extras module.

I figured out that an ajax view already has argument stored in drupalSettings.views.ajaxViews["views_dom_id:..."].view_args

So the view gets this argument and use it instead of default argument from cookie. So we need to change the value of argument as well as cookie.


Multiple Ubercart? Trying to do a multi-seller site. Hello Drupal community. I'm trying to create a seller's site. This is what it needs to do:

A seller will have his own system in which customers can buy him directly.

The products that the seller will sell will be in common from all the sellers. But each seller will need to be able to set his own price.

I found ubercart (I found it amazing!!!), and it does much more than I'm asking for. I would like to know what should I do? Write a module from scratch? Extend Ubercart? Is there a multiple ubercart possibility?

Thanks for the replies!

Have a look at Marketplace.

The modern alternative to ubercart is commerce and there is a marketplace module too, though it's still in beta.


POSTing a FormAPI form to another path? I have a simple form, presenting an "Order this" button. That form is placed on a node. When people press that button, I want to start an ordering-workflow.

Currently the Drupal-way seems to be:

Add form to node on node/123,
User clicks form-submit, POST goes to node/123.
hook_form_submit() gets fired, receives POSTed values trough form API.
In that function, the POSTed-data is stored in a Session; then a drupal_goto() sends redirect-header to /shop/checkout, user GETs /shop/checkout.
Code building the /shop/checkout page must retrieve information from Session to build the checkout-workflow.

How can I simply send the POST to /shop/checkout and present my HTML there, based on the POST, instead of all the intermediate goto and session-spaggetti?

The trick is to simply set $form['#action'] to whatever URL you want to POST to.

Like this:

//....
$form = array(
  //..build the FAPI array
);
$form['#action'] = "shop/checkout";
return $form

In the place where you build the form. And the POST is sent to "shop/checkout".


How to I tell a Views Block to only pull Snippets belonging to the same OG as the container page? I have a few pieces to my existing puzzle:

Node Type  Snippet
View with Block Display called Snippets Block
A context rule to put the Snippets Block inside a container page

How to I tell a Views Block to only pull Snippets belonging to the same OG as the container page?

To start:

I've created the following relationship and contextual filter, but the containing page doesn't show the expected node teasers.

Node Type's Fields:

(view larger)

Current View set up:

(view larger)

As fullerja said, you can use a Contextual Filter but you may also need to define a Relationship first so that the view pulls in the OG that goes with the snippets.

If this page is showing OG content, hopefully it has the OG's slug in the URL. If that's the case then you can use that path for the Contextual filter.

These answers might be helpful for the specific configuration:

Organic Groups Views Contextual Filters
How do I display all the nodes in an organic group?


how to save a field created by using hooks in database I added fields mobile no,landline no, using the below code to the form which i created with webform module. when i fill the fields along with two added fields and submit them .i cannot find the two added field in results.how can i make them appear in results.

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

if($form_id == 'webform_client_form_2') {
  $form['mobile no'] = array(
  '#type' => 'fieldset',
  '#title' => t('mobile no'),
  '#collapsible' => TRUE,
  '#weight' => 30,
);
$form['mobile no']['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action1.'),
);

$form['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This is a test to see the form_alter hook in action.'),
  '#title' => t('land line no'),
  '#weight' => 10,
);
}
}

first create submit button

$form['submit_button'] = array(
                '#type' => 'submit',
                '#value' => t('Click Here!'),
                );

when you create submit it calls this function and feilds submitted or updated to your database

function form_try_form_submit($form, &$form_state)
            {
                echo '<pre>';
                var_dump($form_state['values']);
                echo '</pre>';
                $insert=db_insert('DB')
                ->fields
                (
                    array
                    (
                        'phone' => $form_state['values']['phone']
                                 )
                 )
            }


Deleting modules from the database that aren't on the filesystem How do I remove modules that are referenced to in the database but have already been deleted from the filesystem?

This occurred because I had extra modules in my staging site, and I pushed the db to production. I would like to know how to clear out any modules from the db that aren't found on the filesystem.

Try the Schema module.

This module compares the live database structure with the schema structure declared by all enabled modules, reporting
on any missing or incorrect tables

  The Schema module provides additional Schema-related functionality not provided by the core Schema API that is useful for module developers. Currently, this includes:

  Schema documentation: hyperlinked display of the schema's embedded    documentation explaining what each table and field is for.
  Schema structure generation: the module examines the live database    and creates Schema API data structures for all tables that match the
  live database.
  Schema comparison: the module compares the live database structure    with the schema structure declared by all enabled modules, reporting
  on any missing or incorrect tables.


Add class to views row using a template I'm using Views 3 with Drupal 7. I'm trying to dynamically add a class to the "views-row" line of a view based on the node type. I have a view with a relationship which is duplicating items when a relationship exists. I thought by adding a class for the node type into the views-row line I could hide the field in the row. I'm not sure whether I should be overriding views-view-unformatted.tpl.php or views-view-fields.tpl.php, to add the class and how I can extract the node type from the data to add it into the the classes for that line.

I'd be grateful for any guidance.

Ben

Views itself will tell you which file to use as a template.  Go to the config page for the relevant view and choose Theme: Information under Other.  This will print out a list of potential templates; the template shown in bold is the one that is in use.

To get the node type, you can use the dpm() function of the devel module.  For example, if you have devel enabled, you can simply insert dpm($row) in the template file, load a page containing the view in your browser, and then dig through the output.


Override default profile view with profile2's profile fields I have made 2 profile 'A' and 'B' with profile2. Profiles are searchable by all users including 'anonymous' user type.

A user search for user named 'a' then search result appears. When I click on that result, it shows default user profile view (Only History: Member for) not the profile2 fields associated with user 'a'.

As I want to show profile2 field in search not the just default one. Please help in this regard.

I thought Profile2 had an option to override that.

Maybe you could use Global Redirect or Path Redirect to redirect users visiting the account page to the profile page.

Another option could be creating a view for the searches, and then adding the user/profile relationship.


Restore drupal commerce cart if paypal payment gets failed I want my user to see what he added to his cart after redirecting from paypal, if his/her paypal payment gets failed or user by himself abort/cancel transaction(may be intentionally or by mistake). I want to preserve the state of cart for user.

Right now drupal commerce clears user's cart if payment gets failed.
Please help.

Following solution worked for me

function custom_module_commerce_checkout_page_info_alter(&$checkout_pages) {
  $checkout_pages['payment']['status_cart'] = TRUE;
}


Changing Webform's submit button's text The famous Webform module gives a beautiful nicely designed "Submit" button.

How can I change its text from "Submit", to anything else? I want to change it to another language but I found no way to do it by the UI, or by the Translation mechanism.

Well, normally the webform provides you the facility to edit the submit button form text at

Go to webform->form settings->Submit button text

Or either way you can use the string override module

Hope it may help you!


What version of jQuery does Drupal 8 use? How can I find out what version of jQuery a particular release of Drupal 8 core is using?

If you want to save some time, you can go to the Javascript console and type jQuery.fn.jquery which works on any site using jQuery, not only Drupal sites.

At the moment Drupal 8 core uses jQuery 2.1.4, but it looks like jQuery 3 has been implemented in Drupal 8.4.x.

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


Call AJAX callback on page load I've been reading the whole day but I cannot find a complete example for a basic AJAX call on load page.

I followed this tutorial: and this example:

I was able to register the callback, controller and commands but the only way to trigger the ajax call is creating a link and is triggered on click event (as the example does)

XXX

I need to trigger that ajax call but when the page is loaded, is there any way?

Thanks

Funny how those tutorials did not mention Drupal behaviors, which will trigger once the page is loaded. This is a good tutorial on them (Drupal 7, but same principles apply).

Basically all you should do is call your callback function from a behavior to get the same effect as jQuery's document ready callbacks.

Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    // Call callback here.
  }
};

And while you are at it, I recommend reading up on behaviors as they help to streamline your javascripts and keeps them in closed scopes.


How to, in a View, get list of links up against each other (concatenated without line breaks when displayed)? I have a Drupal 7 view that gives me a list of links to recently added content of a specific type. For what it's doing, it's working fine.

However, it puts every content item in a separate
 causing it to appear on a line of its own. I'm using the Unformatted list output format with all fields set as inline.

I want to simply list all the items concatenated.

Currently the view renders as approximately the following HTML:

          DATE1         -
          TITLE1

          DATE2         -
          TITLE2

...

I can get rid of the DATEs easily enough; that's just one of the fields being displayed. I was able to add the separating commas (using Custom text), and can easily use CSS to hide the last one if there's no better way. The problem is that I want the view to then basically render in the browser as something not entirely unlike:

  TITLE1, TITLE2, ...

for the specified number of entries, where each TITLE is a link to the relevant LINK, the browser displaying them all in one normally-word-wrapped line.

How do I accomplish that?

Seemingly no matter what I try, the newlines remain in the browser-rendered output. Google was decidedly unhelpful, although I'm not ruling out that I searched for the wrong terms.

Just in case it makes a difference, I am using the MAYO theme.

Under Format click on settings and uncheck Add views row classes and uncheck Add striping (odd/even), first/last row classes

Edit:

You could use html list instead of unformated list.

Then use css to add the comas see JS Fiddle

or

since you added the commas's manually you could display inline or float left see this answer


Add /usr/login welcome screen Drupal8 newbie here (using better login and system caching is on),

I wanted to just add a php page before the login page that says something like :

"Please follow the rules of our site, click accept button to agree and login in:"

                                   [Accept Button]

After pressing the button it forwards you to the normal /user/login page. Any tips would be great, it seems harder than it should be, we really don't want to use JQuery/JS.

You can do this by creating a custom module:
Example:

MODULE_NAME(mydata)
creat routing file. (mydata.routing.yml):

     mydata.redirect_form:
       path: '/user/redirect'
       defaults:
         _form: '\Drupal\mydata\Form\RedirectForm'
         _title: 'Redirect User'
       requirements:
         _permission: 'access content'

Create .module file (mydata.module):

use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

function mydata_preprocess_page(&$var){
    if(empty($_SESSION['terms_accepted']) || $_SESSION['terms_accepted'] != 'ok'){
        if (\Drupal::routeMatch()->getRouteName() == "user.login"){
            $path = Url::fromRoute('mydata.redirect_form', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();

        }
    }
}

Create file in module folder src/Form/RedirectForm.php:

namespace Drupal\mydata\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RedirectForm extends FormBase {

    public function getFormId() {
        return 'redirect_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
        if(!empty(@$_SESSION['terms_accepted']) || @$_SESSION['terms_accepted'] == 'ok'){
            $path = Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();
        }

        $form['test'] = [
            '#type' => 'item',
            '#markup' => t('Please Follow the rule of our site,click accept button to agree and login-in: '),
        ];

        $form['submit'] = [
            '#type' => 'submit',
            '#value' => 'Accept',
        ];

        return $form;

      }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $_SESSION['terms_accepted'] = 'ok';
        if($_SESSION['terms_accepted']){
            $form_state->setRedirect('user.login');
        }
    }
}


how to get the values of a view in _preprocess_views_view_fields drupal7 I have a view of multiple content types. I only select the name and an image from those content types so I'm sure what the format of output is going to be. how can I get the field values of view in MYTHEME_preprocess_views_view_fields?

kpr() function doesn't work here because for every content type there is a specific name for fields, say for content type A and B it is field_A_name and field_B_name.

thanks

hope this will help,

     function yourtheme_preprocess_views_view_fields(&$vars) {
    if ($vars[view] -> name == 'yourviewname') {
         foreach ($vars[view]->result as $key => $value) {
            kpr($value -> field_field_name['0']);//here you will get the name field RAW value and  RENDERED value in array.
        }
    }
}


how to display sub menu under the respective main menu I want to display main menu in custom menu block and display all sub menu below the main menu block on clicking the respective main menu. Iam able to display main menu but not able to display respective sub menus below the clicked main menu. Please help

I would like to give a reference if my reqiurement is not clear. The submenu created in the site http://stmarksumc.com/node/159 is what I am looking for.Can anyone please   suggest me any solution to the issue Drupal 7?

Thanks for your help.

You have to use the module menu block. This module allows you to display child items of a certain parent item of a menu.


How to pass a value validated in Webform to the User's profile page? There are hundreds of users on my Drupal 7 website. I don't want to manually enter the birthday value for each user in their profile. Hence why I created a webform where the user puts the user's birthday.

This value should then after validation by the current user be stored permanently in the user's profile where I created an empty birthday field.

How do I pass the value?

Using the "Webform Rules" module, you should be able to have the Rules module react on an event like "Webform submitted". So create a custom rule using this Rules Event, and then add the required Rules Actions. Here is a blueprint of these Rules Actions:

Fetch Entity by id, of type user, using the uid of the user who submitted the form (= current user).
Set a data value, for the field of the user's profile where you want to save that birthday, where the value is the birthday entered in the form.
Possibly (not 100% sure) you may also want to add Save entity, to actually save that field in the profile.

Make it right before you make it better ...

But what about a user submitting the same form again, with a different value for birthday? If you don't want that to happen, you might want to add the Flag module like so:

Flag a user after submitting the form (using Rules), using some global flag.
Improve the 1st rule above, to add a Rules Condition to verify that the user has not been flagged yet.

PS: This answer applies to D7 ...


Is there any elegant way of excluding form element from the `values` array of the `FormState`? I know that the values array can be cleaned up in the validation or submit callback, but can we somehow mark the element itself to be not put in the values array of the FormState?

Not within the building of the form as far as I know. You'd need to strip out the values you don't want in the submit handler as you mentioned.

This is probably the easiest way to remove the default form values:

$values = $form_state->cleanValues()->getValues();

That will remove: form_id, form_token, form_build_id, op


Play Buttons of SoundManager2 are disabled in Ajax o JS I have a views that call a content type with soundmanager fields (360 style) with pager.

On the first page show 3 soundmanager fields and play ok, but in the second page by ajax the no longer played in the input play btn.

In the second page the input play not function.

I tested with 3 options:
Infinite scroll module.
Custom js code for the scroll in the same page.
Views Module load more.

In all feel the same, in the second page loaded in ajax or js buttons play of SoundManager are disabled.

appreciate your help

Add below script in Ajax call

<script>
soundManager.reboot();
</script>


Loop through a multi value entity reference field working only on the first selected item 1) I have an entity reference view articles_per_user listing all nodes of type article authored by the current logged in user.

2) On the Article Entity, there is a taxonomy reference field field_article_country referencing the taxonomy vocabulary: "Countries" (One value is allowed)

3) On the User Entity, there is a multi-value taxonomy reference field field_user_article_countries referencing the same taxonomy vocabulary: "Countries" (Unlimited value are allowed)

4) On a Webform, I have an entity reference field articles referencing the above entity reference view 'articles_per_user' with unlimited values where the users can select one or more article.

5) When Webform is submitted, I want to:

Load each selected Article.
Get value of the field_article_country
Load the current logged in user entity.
Set the retrieved value to field_user_article_countries
Save the User entity.

Quick Demonstration:

Say the Current User selected on the Webform 3 articles where:

Article 1 has field_article_country = United States
Article 2 has field_article_country = Egypt
Article 3 has field_article_country = Spain

After the Webform is submitted, the field_user_article_countries at the User Entity must have 3 values selected:

United States
Egypt
Spain

The error I am facing is at field_user_article_countries, I see only one value selected:

United States

Below is my code:

// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Load the account of current logged in user.
    $CurrentUid = \Drupal::currentUser()->id();
    $CurrentUser = \Drupal\user\Entity\User::load($CurrentUid);

    // Get the selected 'Articles' Value.
    $ArticleIDs = $values['articles'];     // NIDs

    // Load all "Articles" according to their IDs.
    $Articles = \Drupal\node\Entity\Node::loadMultiple($ArticleIDs);

    // Loop through loaded articles entities.
    foreach ($Articles as $Article) {

    // Get the "Article Country" Value from the loaded article.
    $ArticleCountry = $Article->get('field_article_country')->target_id;

    // Set the 'User Country' value on the user account.
    $CurrentUser->set('field_user_article_countries', $ArticleCountry);
    }

    // Save the User account.
    $CurrentUser->save();

}

foreach ($Articles as $Article) {

  // Get the "Article Country" Value from the loaded article.
  $ArticleCountry = $Article->field_article_country->target_id; // shorter way

  // Set the 'User Country' value on the user account.
  $CurrentUser->field_user_article_countries[] = ['target_id' => $ArticleCountry]; // use array

}


Cloning a live/production site to a test/development version I am administering a drupal 6 high traffic, high user base website and I would like to have it cloned into a development version in order to test modules before deploying on live.

I am unable to find anything related to this, no matter how hard I try.

What are the implications of cloning a live site into a test version on another server?

What aspects should I have in mind when doing this?
e.g. avoid user notifications via email from test server

Thanks!

For most of our D6 and D7 sites we use drush to clone and sync staging and development environment from the production server.

Basic setup of the test/staging environment should be done using drush make or cloned from your version control.
Then you can sync the data using drush sql-sync [paramenters] [source] [destination] and user generated content using drush rsync [source] [destination].
Depending on your setup it might be advisable to run a script that truncates your user table or similar.

Both drush and drush make is easily installed using Homebrew or similar.

From now on you can easily resync your database using sql-sync as often as needed.


How to hide certain taxonomy views from user? I have one general taxonomy view wich has this alias mask /taxonomy/term/%.

What I need is to hide views for certain taxonomy terms like 'canada' from display while it'll remain showing the other ones the same way it was before.

Out of the box Views only has 2 different types of access management:

Via role
Via permission

However, it's an all-or-nothing control; you can't do it on a per contextual argument basis (for a taxonomy in your /taxonomy/term/% view).

What you can do, is create your own Views access plugin (or perhaps one already exists, look through drupal.org for 8.x Views projects). Take a look at the access plugin code docs or this tutorial as primer on how this is done.


How can I trace a HTTP 500 (Internal Server Error) at `admin/reports/status`? I get a HTTP 500 (Internal Server Error) at admin/reports/status

I see no errors at admin/reports/dblog

How can I trace this?

Check the Apache/nginx/other server error log, 500 errors almost always appear in there.

As neok notes, checking the validity of your .htaccess file would also be a good thing to do. If required extensions are missing for .htaccess directives a 500 error is often the result


how to add javascript with #attached and hook_page_alter I tried to add js to pages by means of #attached, as it seems to be the recommended way. From what I understand, this involves altering a render array. hook_page_alter seems to me like good candidate.

As per https://www.drupal.org/node/756722 (and answers below), I came with:

function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

The file does not get attached, though. If I use

drupal_add_js($my_path . '/module_test.js');

it does get attached (it's not a problem of the js file, access persmissions, etc.).

What is wrong?

PS. I asked a related, but apparently wrong-headed question here

The code that finally got it included an important change with regard to @AyeshK 's answer. The [attached] is not put at the top level if $page , but inside ['content'] or ['header'].

The adapted code from the Format#1 is now:

function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'
  );
}


Disable (or workaround) form rebuild with managed_file field I'm using the Form API to create a custom form. It has a managed_file field and some other fields, some of which are required. If any of the required fields are not filled in, the file upload for the managed_file field doesn't work, and produces an error informing the user to fill out the required field first before the image upload can process.

I'm assuming this is because the form is being rebuilt when the form uploads, but is there a way to stop it from checking for required fields? Surely there is a way, as node edit forms have this functionality working.

Here is my form code (simplified):

function create_event_form($form, &$form_state) {

  $form['event_image'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg jpeg gif png')
    ),
    '#upload_location' => 'public://event_images/',
    '#required' => FALSE,
  );

  $form['event_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Event Name'),
    '#required' => TRUE,
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Create Event'),
  );

  return $form;
}

If event_name field is empty when attempting to upload a file, the upload will not process.

This was happening due to the Clientside Validation module being enabled.

For anyone having this issue, I had to override the form settings in Clientside Validation for this particular form, setting "Validate fields on submit" to "No".


What plugin control html_attributes? The html.html.twig template contains the following line.

<html{{ html_attributes }}>

On my site, it outputs the following markup.

<html lang="ru" dir="ltr" xmlns:article="http://ogp.me/ns/article#" xmlns:book="http://ogp.me/ns/book#" xmlns:product="http://ogp.me/ns/product#" xmlns:profile="http://ogp.me/ns/profile#" xmlns:video="http://ogp.me/ns/video#" prefix="content: http://purl.org/rss/1.0/modules/content/  dc: http://purl.org/dc/terms/  foaf: http://xmlns.com/foaf/0.1/  og: http://ogp.me/ns#  rdfs: http://www.w3.org/2000/01/rdf-schema#  schema: http://schema.org/  sioc: http://rdfs.org/sioc/ns#  sioct: http://rdfs.org/sioc/types#  skos: http://www.w3.org/2004/02/skos/core#  xsd: http://www.w3.org/2001/XMLSchema# ">

What plugin or core function controls it?

They're added in template_preprocess_html:

$variables['html_attributes'] = new Attribute();

To alter them, you can implement hook_preprocess_html in your theme or module.


How do I set the drush tmp directory? I understand how to use /etc/drush/drush.ini; however, I don't know what exactly to put in there in order for Drush to use a different temp directory when creating an archive-dump.

$options['dump-dir'] = '/path/to/dumpdir';

found in example.drushrc.php :)


Installing Drush 8 in ubuntu 16.04 I am having problems installing drush 8 in ubuntu 16.04. when i insert the following command in the terminal

composer global require drush/drush:dev-master

i get the following error

I have also tried the documentation from drush.org

php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush

but i get the following error msg

  bash: drush: Is a directory

I am currently stuck.

drush/drush:dev-master is not Drush 8, it is Drush 9.  To install Drush 8, try composer global require drush/drush, or better yet, use cgr.

For notes on installing Drush 9 via Composer, please see drush dev-master requires codegyre-robo.


How to make the title field of a node/add form hidden or locked I'm prepopulating the title of the node/add/content_type using the URL. I would like this form to be hidden or locked so that the user can't accidentally edit it. I've been looking though the Drupal documentation and haven't found a way to hide fields at all. Any help would be appreciated.

I'd probably just hide it with CSS to be honest.
Either that, or I'd use Automatic Nodetitles to populate the title with tokens (path token in your case) as it has the option to hide the title field AND auto-generate it with minimal effort.

"auto_nodetitle" is a small and efficient module that allows hiding of
the content title field in the form. To prevent empty content title
fields one can configure it to generate the title by a given pattern.
When the token module is installed it's possible to use various node
data for the auto generated title - e.g. use the text of a CCK field
(since 5.x).

Another option would be to use hook_form_alter() and set #disabled to TRUE to disable user input.


Is there a way to display the product image as a radio button instead of a select box when selecting a product in a product display? Currently im setting up my Commerce and I want to be able to replace the default select box on the product display. This select box only comes up when there are multiple products referenced. I want each option in that select box as the Product's Image Field. Yes I can use the radio button, but you can only output the title of the product in the radio selection box.

Currently I'm only getting this when i select radio button as the formatter

My end goal is this:

You could do this through jQuery easily. All you do is add your own jQuery file through your theme info file:

https://drupal.org/node/171213

Then write some jQuery that adds a css class to the label when the page loads up and handles the clicking of the checkboxes/radios like:

(window).load(function() {
var myImageButton1_label = $('#some_drupal_label_ID');
var myImageButton1 = $('#some_drupal_checkbox_ID');
myImageButton1_label.addClass("button1_off");
myImageButton1.attr({'checked' : false});

myImageButton1_label.click(function(event){

if (myImageButton1.attr({'checked' : true})) {
myImageButton1_label.removeClass("button1_on").addClass("button1_off");
myImageButton1.attr({'checked' : false});
}

else {
myImageButton1_label.removeClass("button1_off").addClass("button1_on");
myImageButton1.attr({'checked' : true});
 }

});

Then hide the actual radio button with CSS and style your label to be an image. Then jQuery will handle the switching of classes and checking those radio buttons for you. Note this is a simplified example so you'll need to expand upon this for your needs. This an older article, but appears to be relevant: http://tutorialzine.com/2011/03/better-check-boxes-jquery-css/


Multistep form makes same submissions I created a Ctools Multistep form. Its working fine. But when a user opens this multistep form in two tabs and fill the form fields simultaneously and submits it, both the submitted forms have same values for all the fields. Means both the submissions have same data.

When I have submitted this form in different browsers simultaneously, then both submissions have their own data.

I followed this tutorial to make Ctools Multistep form : http://www.xenyomedia.com/content/4-steps-form-multistep-form-ctools

I think, the problem is with $object_id = 'ctools_multistep';, because its same for both the forms in different tabs. Thats why it creates the same submissions for both forms.

Can anyone help me regarding this?

You have picked up correctly, the root cause for this issue is the object_id used by ctools multistep form, which is being generated per session. And for different tabs in a browser, we have the same session. So basically we need to figure out a way to get different object_id for each tab. This can be done in two ways:
1. Modify session mechanism to have a different session per tab. (Difficult)
2. Use query_parameters to handle two different requests. (For eg: time as id)

So, using 2nd way to solve our the problem:
Get object_id dynamically.

$object_id = _module_get_object_id();

Ensure if id exists in URL, else return newly generated id.

function _module_get_object_id() {
  $params = drupal_get_query_parameters();
  if (isset($params['id'])) {
    return $params['id'];
  }
  else {
    $params['id'] = time();
    return $params['id'];
  }
}

and most important step, for adding id in URL as query parameter we need to add following code in the ctools_multistep_wizard_next function:

drupal_goto($form_state['redirect'][0], array('query' => array('id' => $form_state['object_id'])));

Reference: http://savaslabs.com/2015/06/23/implementing-ctools-multi-step-form-block.html


Insert an article and fields with db_insert function or SQL I want to add an article to the db using db insert along with its field like tags and image.

A sample code i tried(below) is adding data to the db but I can't find any entry in the

db_insert('node')
  ->fields(array(
    'title' => "hello world",
    'created' => REQUEST_TIME,
    // 'body' => 'you did it!',
    'uid' => 1,
    'vid' => 5,
    'type'=>'article',

  ))
   ->execute();

If not this, can it be done using a normal sql query?

Why I want to do this way instead of nodesave?

I don't want any hooks working on this process.
This is a temperory fast solution I want for a project.

If you need to save a node without invoking any hook, then use the same code node_save() uses, excluding the part invoking hooks.

  $transaction = db_transaction();

  try {
    if (!empty($node->nid) && !isset($node->original)) {
      $node->original = entity_load_unchanged('node', $node->nid);
    }

    field_attach_presave('node', $node);
    global $user;

    if (!isset($node->is_new)) {
      $node->is_new = empty($node->nid);
    }

    if (empty($node->created)) {
      $node->created = REQUEST_TIME;
    }
    $node->changed = REQUEST_TIME;
    $node->timestamp = REQUEST_TIME;
    $update_node = TRUE;

    if ($node->is_new || !empty($node->revision)) {
      if (!isset($node->log)) {
        $node->log = '';
      }
    }
    elseif (!isset($node->log) || $node->log === '') {
      unset($node->log);
    }

    if (!$node->is_new && !empty($node->revision) && $node->vid) {
      $node->old_vid = $node->vid;
      unset($node->vid);
    }

    if ($node->is_new) {
      drupal_write_record('node', $node);
      _node_save_revision($node, $user->uid);
      $op = 'insert';
    }
    else {
      drupal_write_record('node', $node, 'nid');
      if (!empty($node->revision)) {
        _node_save_revision($node, $user->uid);
      }
      else {
        _node_save_revision($node, $user->uid, 'vid');
        $update_node = FALSE;
      }
      $op = 'update';
    }
    if ($update_node) {
      db_update('node')->fields(array('vid' => $node->vid))->condition('nid', $node->nid)->execute();
    }

    // Call the node specific callback (if any). This can be
    // node_invoke($node, 'insert') or
    // node_invoke($node, 'update').
    node_invoke($node, $op);

    // Save fields.
    $function = "field_attach_$op";
    $function('node', $node);

    $delete = $op == 'update';
    node_access_acquire_grants($node, $delete);

    unset($node->is_new);
    unset($node->original);
    entity_get_controller('node')->resetCache(array($node->nid));

    db_ignore_slave();
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }

I didn't remove the call to node_invoke(), since that calls the hooks implemented by the module implementing the content type, and those hooks are necessary for the content type to work correctly.
I also left the call to db_transaction() because, in the case one of the operations fails, all the operations are rolled back, and the database is left in a consistent state, which means (for example) that every table will refer to the same node version ID.


Can feeds importer grab fields, too? I'm working outside the area of what I know about Drupal. We're looking at using feeds importer to migrate a number of nodes. However, I didn't see anything in the documentation about its ability to grab fields attached to those nodes. Can it? How do I configure it to do so?

We're using node export currently, which works well, but is tedious since we're doing it one-by-one.

It can, yes. We've used it extensively to import contacts (nodes) into a homebrew CRM.

After creating your Feeds Importer, you should see "Mapping" as the last item in your settings panel to the left. After configuring the rest of your importer to work with your export's format, the Mapping Settings of the processor will allow you to map source fields in your dataset to target fields in your actual destination content type. Your nodes should have the appropriate fields filled in on import.


Node registration form - redirect after submit short question. I'm using node registration module. Can i use hook_form_alter to redirect to some custom page after form submit?

To redirect user to a particular page after the form is submitted you can use $form_state['redirect']

eg:

//Implementation of hook_form_alter()
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    switch($form_id) {
        case 'form_id_of_the_form_to_alter':
            $form['#submit'][] = 'custommade_custom_submit';
    }
}
//Custom submit handler
function custommade_custom_submit($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = 'whatever/link/to/redirect';
}

Hope this helps.


Displaying static text on a view that disappears after hitting 'Search'? I have a view with a Search block exposed to users. What I would like to achieve is:

I would like to display a text in the View's body itself under the Search box. This text should disappear once a user enters a term and hit 'Search".

Is this doable? I hope someone can help me out.

Thanks


How can I set up free shipping? I am having trouble setting up free shipping on my Commerce project.  I added the Free Shipping module, but when I go to configure, I don't have any options.

The shipping costs for all of our products are absorbed by the manufacturer (who also drop-ships the product, so we don't care about FedEx, UPS, etc).  Therefore, I want to show a free shipping line item during checkout.

I installed the Shipping module (7.x-2.x-dev), and I don't see options to create Shipping Services or Shipping Methods.

How can I configure our store so all products are free shipping?  I watched a few screencasts, but none of them seemed to apply to what I'm wanting to do.

I use Flat Rate module to do the same. You can set free shipping with help of this module very easily.

Once you enable the module, navigate to Store->Configuration->Shipping->Shipping Method->Flat Rate.

You will find Flat Rate under Shipping Method tab. Click Add a flat rate service.

Add something kind of Free Shipping, give it Title, Display title & Base Rate as 0.

Now visit Shipping Service tab. You will find your added flat rate service in there. Click Configure Component & put any condition you like e.g. Data Comparison to commerce-order:commerce-order-total:amount for any amount.

Now When ever your condition matches, this Free shipping service will apply if you have put Shipping service in Shipping pane under Store->Configuration>Checkout settings.


How do I redirect user_view_page to user_profile_form? I do not really need the user_view_page on my site and I want to redirect calls to user/%user to the user_profile_form. I only want this change for regular users, not for administrators.

I already tried to accomplish this with hook_menu_alter, but that would change it for all users including the administrator.

How can I do this?

I've solved this problem in the past with the Rules module.

Event:
User Account page is viewed

Condition:
User has role(s)

Action:
Page redirect
Parameter URL:[account:edit-url]

I created the rule and added the screenshot here: http://i.imgur.com/xjMPpIM.jpg

Here is also the exported rule:

{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_view" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "[account:edit-url]" } } ]
  }
}

I hope this helps!


Override custom module template I created a custom module with its own template file to display the content with the following code.

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'theme_mymodule_list' => [
      'template' => 'templates/list_mymodule',
      // name of the template file, minus the '.tpl.php'

      // these are the template variables that will available to your template
      'variables' => [
        'myvar1' => NULL,
      ],
    ],

  ];
}

With the code above I'm able to get the template from the module directory (sites/all/modules/mymodule/templates/list_mymodule.tpl.php), but now I decided to make a theme for the site, and I want to override the custom module template file with the usual approach of copying-pasting the file into the theme and clear the cache.

How do I override the template used from a custom module from a theme?

What you describe is something that Drupal core already does. Take as example the Node module; it defines its own template file (node.tpl.php) that is then overridden from themes, such as the Bartik theme, with their own template file (in the case of the Bartik theme, with templates/node.tpl.php).

What is wrong in your implementation of hook_theme() is the name you give to the template file. Despite what it could seem, the template key doesn't allow to give the template name an arbitrary name; the name must match the theme name you are using, in your case mymodule_list. You can replace the underscores in the theme name with hyphens, but that is the only change you could do.

See Override template files based on template filename as well as hook name, where the user suggesting the change says:

  Turns out the template file name needs to exactly match the array key used in hook_theme() (with the exception of dashes and underscores). In the case of my example, the template value would need to be my_abc_index and the file name my-abc-index.tpl.php. Failure to do so will result in an un-overridable template.

(I slightly changed formatting, and the spelling of a word.)

Also, as you see in the code used from Drupal core, the theme_ prefix in the the theme name is not necessary.

function node_theme() {
  return array(
    'node' => array(
      'render element' => 'elements',
      'template' => 'node',
    ),
    'node_search_admin' => array(
      'render element' => 'form',
    ),
    'node_add_list' => array(
      'variables' => array('content' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_preview' => array(
      'variables' => array('node' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_admin_overview' => array(
      'variables' => array('name' => NULL, 'type' => NULL),
      'file' => 'content_types.inc',
    ),
    'node_recent_block' => array(
      'variables' => array('nodes' => NULL),
    ),
    'node_recent_content' => array(
      'variables' => array('node' => NULL),
    ),
  );
}


Export translations of field labels Drupal 7. I work on multi language site. I have a content type with entity translation fields. I've added translation to field labels and settings on my DEV copy of site and now I need to export and import it to Production.

Is there any module in Drupal 7, that helps me to export and import field labels/settings? Or maybe someone tell me, how to export values from "locales_source" and "locales_target" tables and import it to my Production database? Because I see only "lid" auto increment field in both tables.

Locales Source table

Locales Target table

Problem resolved by Drupal standard translation export. I just check "Fields" and select "Existing strings and the plural format are kept, only new strings are added." when Import *.po file.

admin/config/regional/translate/export


Using the l() function within a node description field I'm converting an old site to Drupal, and I need to convert all the old URLs to the new system, which uses pathauto. I can turn the old links into node paths (eg. node/28), but I ideally want the aliased paths to show instead. I've found the l() function, but how do I go about applying it to links within the description field of nodes?

If you already turned old links into node/28 format, you don't need to touch your content any more. You can simply use Internal Links module that will replace it live with the current alias. The benefit is - with this module if alias changes, content still links to a node by node's id, and links stays valid.

  The Internal Links Title filter inserts HTML title attributes into links to other nodes on a site (if no title attribute already exists) using the linked node’s title as the HTML title attribute’s value. It also replaces href values which are in the “normal Drupal path” form (e.g. ) with a URL alias, if one exists.

Emphasis mine.


Need to redirect the homepage to a different url but keep the site live and accessible A website built in drupal now client has come back and said the url needs to direct to another address. We want to keep the site up and working for various reasons so how do I go about doing this?

homepage needs to redirect to another site
the existing website homepage needs to be moved to a different page /main or /homepage and accessible only thru the direct link

how do I do this?

They are many solution to redirect from the page.

If you are using Apache you can use .htaccess to redirect the front page to a different website. This would be the faster due that is on the server level. Here is more information about redirects on Apache.
If you are using Nginix here are some instructions
Another option would be doing it on the theme level. If have access to the theme you can write  sites/all/themes/YOURTHEME/page.tpl.php.

<?php
   if(drupal_is_front_page()) {
     header("location: http://www.RedirectPage.com");
     exit;
   }
?>

If you dont have access to the theme or to the server. The easiest way to have a redirect is by using the meta tag. You can add a block to the front page and add the following code.

     <meta http-equiv="refresh" content="10; url=http://www.RedirectPage.com/">

For more information about Redirect check this article.


Drush unable to bootstrap to database I am not able to get drush to work properly:

1) I can download modules & themes through drush but I cannot enable them (more details below).
2) Also I cannot use the omega commands even though they are listed (more details below).

= I installed Composer & Drush as per docs.drush.org/en/master/install/
= Drush is properly installed on my computer, when I type drush version I get: Drush Version : 7.0-dev

My system setup: Linux mint 17 KDE with Xampp 1.8.3-4

I guess my problems are (partly?) caused because Drush was not able to start (bootstrap) the Drupal database. So I run mysql from command line:

user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

In my system mysqld.sock is in a different location, namely /opt/lampp/var/mysql/mysql.sock. So I created a symbolic link in /var/run/mysqld/ but this has no effect. Still have the same problems. Maybe caused by permissions?

I have spend a few days of and on (had to stop out of frustration) and I cannot get drush to work.

Details of my problems:
1) I can download modules & themes through drush but I cannot enable them:

user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush en disqus
Command pm-enable needs a higher bootstrap level to run - you will need to invoke [error]
drush from a more functional Drupal environment to run this command.
The drush command 'en disqus' could not be executed. [error]
Drush was not able to start (bootstrap) the Drupal database. [error]
Hint: This may occur when Drush is trying to:

bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See drupal.org/node/1428638 for details.
Drush was attempting to connect to:
Drupal version : 7.34
Site URI : http://default
Database driver : mysql
Database hostname : localhost
Database port :
Database username : root
Database name : drush
PHP executable : /usr/bin/php
PHP configuration : /etc/php5/cli/php.ini
PHP OS : Linux
Drush version : 7.0-dev
Drush temp directory : /tmp
Drush configuration :
Drush alias files :
Drupal root : /opt/lampp/htdocs/drush
Site path : sites/default

When I add

'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',

or:

'host' => '127.0.0.1',

to settings.php as per this post I get following error:

user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush en disqus
PHP Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /opt/lampp/htdocs/drush/includes/database/mysql/database.inc on line 46
Drush command terminated abnormally due to an unrecoverable error. [error]
Error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in
/opt/lampp/htdocs/drush/includes/database/mysql/database.inc, line 46

2) Also I cannot use the omega commands even though they are listed:

user@mylaptop:/opt/lampp/htdocs/drush/sites/all/modules > drush help --filter=omega
All commands in omega: (omega)
omega-export (oexp) Exports the theme settings of a given theme from the database to the
.info file.
omega-guard (ogrd) Runs guard for the given theme including Compass and LiveReload by
default.
omega-revert (orev) Reverts the theme settings of a given theme by deleting them from the
database.
omega-subtheme Creates a Omega subtheme.
(osub)
omega-wizard (owiz) Guides you through a wizard for generating a subtheme

OK I've got drush working:) For other people who might have a similar problem (hope I use the right terms):

I had to install "php5-mysql" (and dependencies) in Linux (for example through "synaptic package manager"), php5-mysql is a MYSQL module for PHP5 which contains mysql PDO support. With this I was able to enable modules and use the omega commands. Drush uses the PHP installed in Linux and not in Xammp, I had this module in Xampp but not in Linux.

You can see which php.ini file drush uses by typing "drush status" in your terminal.

You can see which php.ini file is used by your web server by navigating to admin/reports/status of your drupal site. Next click the "more information" link on Drupal's status page's PHP section. This shows the phpinfo() page. Locate the Configuration File (php.ini).

To check that the mysql PDO support is installed (part of "php5-mysql"), type the following in a terminal:
php -i|grep PDO
If support is installed you should see something like this:
PDO
PDO support => enabled
PDO drivers => mysql
PDO Driver for MySQL => enabled


Show last, last two or last three nodes depending on role I'm working on a site where members can have three different roles.
Gold, Silver and Bronze.

Now I'm trying to set up a view that will display the:
last three nodes of all Gold members and
last two nodes of all Silver members and
the last node of all Bronze members,

I want all these nodes displayed together on the homepage, randomly ordered. And I just can't figure out how to do this.

I can make a view that shows all last nodes of all users. And I tried working this out with "views field view" making different views showing nodes per user and combining these views in one view but then I am not able to randomly order them.

Well I hope someone can help me out here.
Thanks in advance

Create a fresh (block) view that displays all nodes.  Then you can add a relationship to Content: Author.

After adding the relationship, you will be able to add a new filter for User: Roles that uses the Author relationship.  Set this filter to your Gold member role.  Set the view to display 3 items.

Add a new Attachment display:

Under attachment settings, attach it to your first views display (the gold member display).  Attachment position should be "After".  Set the User: Roles filter to show Silver members and set the "Items to display" to 2 items.

Add another Attachment view and repeat the last steps, setting the User: Role to Bronze and changing the Items to display to 1.

Now when you view the block, it will show 3 gold, 2 silver and 1 bronze node.


Disable Inline Form Errors I'm encountering the bug described at "Login form error message is redundant and does not make sense". In short, if a user enters invalid credentials once, an inline error message appears on the user login page. When the user enters valid credentials and successfully logs in, the user sees an error message at the top of the screen (e.g., "1 error has been found: username"), but that is no longer correct.
According to this blog post one can disable inline form errors for a particular form by adding $form['#disable_inline_form_errors'] = TRUE; to the form definition, and I have seen that code snippet elsewhere, too. But I can't find any instructions for implementing it. Does anyone have an example?

The core issue you linked to has a patch that is apparently working, so it may be easier to patch with Composer instead of adding code to a custom module.
But, if you want to use the $form['#disable_inline_form_errors'] = TRUE;, this is what you can do:
First, create a custom module.  You need to follow the instructions on the first four pages:

Getting Started - Background & Prerequisites
Prepare a Module skeleton
Naming and placing your Drupal module
Let Drupal know about your module with an .info.yml file

Then, in the MYMODULE.module file, add this code:
/**
 * Customize the user login form.
 */
function MYMODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#disable_inline_form_errors'] = TRUE;
}

What this code does is use hook_form_alter to target the user login form.  Lots of Drupal's form behaviors can be customized in this way.
You then need to go to the module administration page and enable your custom module.


Views: Display users with a gmap attachment I have location, gmap and profile2 modules installed on my site.
In a profile type I have added a location field so that the user can add his/her location on profile edit.

I want to display all users with a map in the header. The map will have the markers for the currently displaying users.

For this purpose I have created a page view where I displayed all the users with a pager.

Then I added an attachment and select the style format as "Gmap" and in the settings I have tried both for Data source "Location.module" and "lat/long".
And attached it to the page.

But the view does not display any map.
Any one who have some idea about this?

Try using getlocation module. In order to show gmap with views, you need google api key. Getlocation module comes up with blocks and views with api key already embeded in code.


How to add tables relations into custom entities content type? I have a custom content entities in my Shop module.

I want 2 tables :

Orders
Order line

I create a custom content entity for orders, but I ask about the way to do the order line.

Do I need to create a second custom entity content and make a field reference orders table inside?

Or there is a way to declare subTable into the main entitie (orders for me)?

First, forget about tables. Drupal 8 mostly takes care of that for entities.

Think about data structures instead: entities and fields.

What do you want?

Two separate entities, both possibly extensible with additional fields, maybe different bundles (e.g. product and shipping line items). Then make two entity types, with a reference field from line items to the order.
Simpler, non-extensible line items. Then you can design them as a custom field type and add that as a base field with unlimited cardinality. (In this case, they will be stored in a separate table, but you don't need to know about that for the most part).


How to add a link in a menu with query parameters in paths I want to add this link : resources?field_resources_type_tid_i18n[0]=130 in the main menu
that point to a view with exposed filter.
But When I save my link I just find resources without query parameter

There are multiple ways to solve this problem.

Use the absolute URL of the page, instead of the Drupal path.
Write a module that provides a menu item via hook_menu(), e.g. for the path resources/field_resources_type_tid_i18n/130. The page callback for the menu item would either redirect to resources?field_resources_type_tid_i18n[0]=130 or serve the desired page directly.
Add a rewrite rule to the webserver configuration, the translates resources/field_resources_type_tid_i18n/130 into index.php?q=resources&field_resources_type_tid_i18n[0]=130 and add resources/field_resources_type_tid_i18n/130 to the menu.

Solution 1 is the most simple, but not very flexible. You need to touch the menu links database table if the absolute URL of the site changes. Adapting the link to the currently used scheme (http:// or https://) is not possible.

I prefer Solution 2, but it requires knowledge about Drupal module development.

I do not like to rely on URL rewriting to provide essential functionality, so I do not recommend Solution 3.


Issue implementing Ajax in form I created a basic page which has a basic form and implements ajax, or attempts to do so. My issue is that it doesn't seem to be functioning as it should. What might be Ajax, only works after I press enter in the textfield, which submits the data and refreshs the page, although I don't think it's ajax at work, rather the form functioning normally, I changed the #event to blur and the #keypress to false but everything is still entirely the same. Ultimately ajax isn't working, if anyone can clear this up that'd be grand.

<?php
/**
 * @file
 *  Creates form page which implements ajax
 */

/**
 * Implements hook_menu();
 */
function formajax_menu() {
    $items['formexample'] = array(
      'title' => 'Form Ajax Example',
      'description' => 'This is a page generated via hook menu
                        which displays a form with ajax support',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('formajax_form'),
      'access callback' => TRUE,
    );
    return $items;
 }

function formajax_form($form, &$form_state) {
  // create a fieldSet
  $form = array();
  $form['data'] = array(
      '#type' => 'fieldset',
      '#title' => t('Form Ajax Example'),
    );
 // Create textfield
    $form['data']['textinput'] = array(
      '#title' => t('Name'),
        '#description' => t('Your Name Here'),
        '#type' => 'textfield',
      // add ajax property with callback and wrapper
      '#ajax' => array(
          '#callback' => 'formajax_callback',
          '#wrapper' =>  'replace_this',
          '#effect'  => 'fade',
          '#event' => 'blur',
          '#keypress' => FALSE,
        ),
    );
    // create item dependant on textfield
    $ajax = (!empty($form_state['values']['textinput']))
             ? $form_state['values']['textinput'] : 'John';
    $form['data']['ajax_response'] = array(
      '#type' => 'item',
      '#title' => t('Ajax Response'),
      '#markup' => t('Your Name is' . $ajax),
      // prefix item with div id of wrapper
      '#prefix' => '
',
      '#suffix' => '
',
    );
    return $form;
 }
// create callback which will return data
function formajax_callback($form, &$form_state) {
    return $form['data']['ajax_response'];
}

Take the #'s off the nested #ajax values.  IE

  '#ajax' => array(
      'callback' => 'formajax_callback',
      'wrapper' =>  'replace_this',
      'effect'  => 'fade',
      'event' => 'blur',
      'keypress' => FALSE,
    ),


7 - HTTP error 400 when calling system_retrieve_file()? I'm using hook_feeds_after_save and the simpleHTMLdom library to migrate inline images for a feed import. After I detect that an image tag exists and the url is qualified/valid I build a stream wrapper for the image file and call system_retrieve_file.

  $dirPrefix = 'archive';
  $uri = file_build_uri($dirPrefix . '/' . $filepath);

  if (file_prepare_directory($uri, FILE_CREATE_DIRECTORY)) {
    $destination = $uri . '/' . $filename;
    system_retrieve_file($img_url, $destination, TRUE, FILE_EXISTS_REPLACE);
  }

However, I receive 400 errors on each image;
HTTP error 400 occurred when trying to fetch http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg.

If I just plop this url into a browser I get a 200 and the image is displayed. Same when I test this in something like the Advanced Rest Client application.

Also, I'm developing this site in a local environment.

Anyone have any clue how to debug this or why I may be receiving a 400 response?

In my case, I needed to encode urls, but not how you may expect with PHP's urlencode or rawurlencode.
For example, I needed to convert http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg to http://DOMAIN.COM/C8B195/assets/images/01%20Grapes%203.jpg. I'm not sure why system_retrieve_file or drupal_http_request had a problem with the spaces.

  $encodedPath = rawurlencode($path);
  $encodedPath = str_replace('%3A', ':', str_replace('%2F', '/', $encodedPath));


Loop through nodes of same content type I currently have a page template set up in its page-node-946.tpl.php. $content is being populated by that node numbers content. I need to loop through and display a teaser for all content nodes and certain type. I need some instruction on how to do it. Maybe I've gone wrong by trying to do this with a page-node template.

You can use Views for looping throug nodes. Just build Views that show list of certain nodes, then call it into your template file, like this: print views_embed_view('VIEWNAME', 'DISPLAY_ID');
But creating for each page one node template file is not good way for this (you will got many count of this page-node-XXX.tpl.php files, for serving all of these you will take more time, even you want to change something little), node-TYPE.tpl.php will better with more common page.tpl.php.

p.s. Also customizing page via Panels without template have better UI.


Different page--user.html.twig for different user roles I have a few user roles - simple user, editor and contributor.

How to make different profile pages for all of this roles?

Now I can work with:

FILE NAME SUGGESTIONS:
   * page--user--16.html.twig
   * page--user--%.html.twig
   x page--user.html.twig
   * page.html.twig

But I want work with page--user--somerole.html.twig (not (!) user--page--somerole.html.twig)

Thank you for any help.

It's not much different from how it got solved in the other question you asked. You just have to target page this time. So hook_theme_suggestions_HOOK_alter() becomes hook_theme_suggestions_page_alter().

And you need to check if you are currently on a user page before you add the suggestion.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Get user roles.
      $roles = $current_user->getRoles();
      foreach ($roles as $role) {

        // Add template suggestion per role.
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}

Alternatively, if you want the suggestion to be added only for a certain role, try that:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_match = \Drupal::routeMatch();

  // Check if on user page.
  if ($route_match->getRouteName() == 'entity.user.canonical') {

    // Get current user
    $current_user = $route_match->getParameter('user');
    if ($current_user instanceof \Drupal\user\entity\User) {

      // Add template suggestion for certain role.
      $role = 'somerole';
      if ($current_user->hasRole($role)) {
        $suggestions[] = 'page__user__' . $role;
      }
    }
  }
}


create an commerce order list view with payment method I would like to create simple orders list with chosen payment method.

Problem: If customer goes through checkout process at once (without returning from checkout review and changing payment method) there would be only one payment method for an order, which is ok.

However, if customer returns from checkout page and changes payment method and then completes checkout - the order has 2 payment methods attached to it.

Now, inside view I can add relationship to Commerce Order: Payment Transaction, which causes duplicates. So I choose Commerce Order: Representative payment transaction, which gives me only one payment method (Now I can use payment method field). Inside relationship I can select representative sort criteria - in my case it would be transaction id (descending). However, sorting does not seem to work. The view always outputs the first payment method chosen when creating the order.

Is anything wrong with the view or is it better option to delete the unused payment transactions?

Question: what is the recommended way of keeping only one (last) payment method.

As per the "... which causes duplicates ..." in your question: you may be able to prevent those by using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Consider an example like so (with the duplicates included):

order id1 with payment id1
order id2 with payment id2
order id2 with payment id3
order id3 with payment id4

For this example, to only show the last payment method, sort by payment id (but descending!), and on the order_id filter repeats. So that only the last row for every order_id will be shown.

The new Views results with these changes applied for the above example should now look like so (with no more the duplicates related to payment id2):

order id1 with payment id1
order id2 with payment id3
order id3 with payment id4


Layering fields on top of each other in views I use Drupal 6 with Views 6.x-2.10.

I have a spotlight region on my page where I want to display a picture and a description of the next upcoming event.

I want the description text to be on top of the image, in a div with half transparent background, sort of [---image--[description]-].
The image and description are fetched with a view. How do I style it so that one field in the view (the description) is on top of the picture field?

It would be easy to do if I could get the content in

, but the view puts a hell of a lot of other divs around it, making it impossible to have the description inside of the picture div.

What should I do?

I find that the easiest and simplest solution is pure css. All you need to know, is the height of the box with text, then it's a simple matter of using margin-top: -?px; and creating a background with opacity. One option could be an image.


Drush make: simplexml_load_file(): I/O warning : failed to load external entity "" Project.php:74 I'm facing a very strange issue with Drush wget and OpenSSL on my mac book (MacOSX Sierra).

When I launch drush make site.make command (which should theoretically download the all modules) it fails with the following error:

Failed to get available update data from https://updates.drupal.org/release-history/workbench_og/7.x
simplexml_load_file(): I/O warning : failed to load external entity "" Project.php:74

I tried

wget https://updates.drupal.org/release-history/rate/7.x

and I got the following message:

https://updates.drupal.org/release-history/rate/7.xResolving
updates.drupal.org... 151.101.113.175
Connecting to updates.drupal.org|151.101.113.175|:443... connected.
OpenSSL: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
Unable to establish SSL connection.

Same message with flags:

wget https://updates.drupal.org/release-history/rate/7.x --no-check-certificate

Here I found exactly the problem that I have but, even if reinstalling openssl and upgrading the version (current version is OpenSSL 1.0.2l 25 May 2017) the problem persists.

Did someone has the same kind of issue?
And, in case, how did you handle it?

Thank you in advance!

This workaround fixed my issue:

In drush.inc

if ($use_wget) {
  drush_shell_exec("wget --no-check-certificate -q --timeout=30 -O %s %s", $destination_tmp, $url);
} else {
  drush_shell_exec("curl --insecure --tlsv1 --fail -s -L --connect-timeout 30 -o %s %s", $destination_tmp, $url);
}

so weird anyway...


How to keep Views argument results in panels display I'm working with Views and Panels and I am having troubles keeping the results of a View argument within Panels.

I have a content type for events, and I want to display a list of previous events grouped by year. Through Views, I created a Views panel with an argument based on the year of the event date to display the list of years (2011, 2010, 2009, etc.). The Views panel displays just fine within my Panels variant, but whenever I follow one of the links, the results are not within Panels anymore.

I'm sure I'm missing something very obvious but I can't seem to get this to work properly.

Ok, I think I have this sorted out but wouldn't mind some advice if I went about it the wrong way.  To recap, the goal was to have a list of previous programs sorted by year and have that results page stay within the layout set in Panels.

Within Views

Create a Content Pane to filter out only the programs content type with the Argument set to display a 'Summary, sorted descending' based on the year of the program.  This will be used to display just the years of the previous programs in a list and will be added to main Programs page.
Create a Page to filter out only the programs content type with the same Arguments.  Set the path of this page to 'programs/previous'.  This will be used to view the actual results of the list created above.

Within Panels

Create a new Page with the Path set to 'programs/previous/%view'.  In the Arguments section, set it to Managed Page.  In the Content section add the page created within Views and make sure the Send Arguments option is checked.
Within Node Template (which controls the main layout of the entire site), add the Content Pane to the Programs page.

Therefore, when a visitor goes to the main Programs page ('/programs'), they will see a list of the previous programs in the right hand corner and clicking on each one will bring them to the appropriate page (such as '/programs/previous/2001') while keeping everything in Panels.

I'm a little confused as to how all works (for instance, how does the Content Pane inherit the '/programs/previous' path from the Page?) but am glad it works as planned.  Hope this helps others and please don't hesitate to let me know if I could have achieved this in a simpler way!

Bob


Multiple FAQ pages using FAQ module I am using the FAQ module in drupal7. My website has many pages which should have a FAQ of their own. So adding FAQ from "Add Content" adds and lists all the FAQs in different categories in the "faq-page". For example, I have two applications so i need dedicated faq page for application 1 and 2.

Is this possible using the FAQ module ?

Yes, the FAQ module provides the ability to have separate categories of FAQ via the taxonomy module as per the project page:

  "In addition, if the 'Taxonomy' module is enabled, it is possible to
  put the questions into different categories when editing. Users will
  need the 'view faq page' permission to view the built-in 'faq' page
  and will need the 'administer faq' permission to configure the layout,
  etc."

To use the individual faq categories, use the urls: faq-page/[tid] - where the [tid] is the term ID of the category you want.

You can also use views to make additional faq pages for specific categories if you like.


Sub theming Seven theme Is it possible to create a subtheme for the core Drupal  Seven theme (in drupal 7)? If so, how do I do this? I had already tried to do it a few months ago to override the templates for Simplenews but it wasn't working.

Creating a sub-theme is pretty basic:

Create a sub-dir for your themes in your configured sites dir (e.g. sites/default/all/my_subtheme).
Copy over the .info file of the theme you want to subtheme (e.g. themes/seven/seven.info) to your new theme directory with it renamed to match your directory (e.g. sites/default/all/my_subtheme/my_subtheme.info).
Edit your sub theme .info so that it also contains the line base theme = seven. You can optionally give it another name or description.

From there you should be able to enabled it and start using it. You can copy over other resources that you'd like override in your subtheme. In your example, you can create templates subdirectory (e.g. sites/default/all/my_subtheme/templates) and copy the simplenews templates that you wish to override.


Connecting multiple data entities to the user object I need to create a simple order system in Drupal 7. This will be a site for a meat wholesaler so I don't need a webshop.
Users are able to register and fill in a webform to order products. However I'll need to handle different shipping addresses for the users, and let them choose a shipping address upon ordering.
What I have in mind is connecting the shipping addresses to the user object (billing address is already on the user form).

Which method is better?

Create a field collection entity for the shipping addresses and add it to the user form
Leave the user form alone and create a new content type that can be added/edited by users and use the UID to decide which address belongs to which user

I'd like to let users edit their shipping addresses anytime on their user page, preferably independently from the other datas.

If anyone done something like this before, please share some ideas.

You would probably be best to create a Shipping Address content type. You should also look at the Address Field module to collect the addresses rather than field collection.

Then you can create a simple view to list the shipping addresses (Node Tile not linked) using a contextual filter on uid. Then set up a node reference field in your webform using the view to provide the values. The user can then select which shipping address to use for his order.

On the user page you mav use the same view (separate display listing titles as edit links) to let them edit their shipping addresses, and give them a link to add new addresses if necessary.


How to get devel content generate module to only include one image per dummy content creation I'm using devel generate and it randomly adds multiple images to articles.

I can limit the number of words in the title.

Is there an option to limit number of images or text lenght?

you can set the image upload limit in field setting itself.

-Anas


Is there a way to make a keyboard shortcut for Save on the node edit page? It would save a lot of time not having to scroll to the bottom of the page to save edits to a node.

Are there modules which achieve this?

Keyboard Shortcut module might be the one you are looking for , Project page says

  The Keyboard Shortcut Utility module enables you to create keyboard
  shortcuts on your website. You can create a shortcut to go to a page
  (internal or external) or call a JavaScript function.


Force Field Required based on Widget Type I'm using the GeoField module to geocode fields for mapping on my site. There is an issue with the current stable release of this module.

If Widget Type is "Geocode from another field" this field must be marked REQUIRED or GeoField will create this error:

Notice: Undefined index: default_value in geofield_field_presave()

Is there a way in Drupal 7 that based on the widget type you can FORCE the required option for a field? This would be a solution to this problem. Thanks!

you can group them together with field group,
and then mark that group as required.

but the manual work in the Field UI is neede here ..