Prevent redirect after submitting the form In Drupal 7 profile2 module, want to make profile2 edit form to stay on the form itself
after clicking SAVE button.

With the following code, it stays on the form itself and displays the values correctly.
But it does not save actually. When coming back to the form, it still shows the previous
values there.

So the following code makes the submitting to stay on the form itself but does not save
the result into database.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'profile2_edit_main_form'){
    $form['actions']['submit']['#submit'][] ='custom_profile2_edit_submit';
  }
}

function custom_profile2_edit_submit($form, &$form_state) {
  unset($_GET['destination']);
  unset($_REQUEST['edit']['destination']);
  $form_state['rebuild'] = TRUE;
  $form_state['redirect'] = REDIRECT_URL;
  drupal_set_message('Changes were saved');
}

I have achieved to make the desired redirection like this:

function redirect_to_edit_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "page_article_node_form") {
        //$form['actions']['submit']['#submit'][] = '_redirect_to_edit';
        $form['#action'] = '?destination=node/' . $form['nid']['#value'] . '/edit';
    }
}

Reference:
https://www.drupal.org/node/1074616#comment-5115792


permission denied when using batch I have just switched over a site live and I'm having problems regenerating the XML sitemap.

When I try, I get:

You are not authorized to access this page.

The URL is: www.example.com/batch?op=start&id=207

What could be causing this?

Thanks

EDIT:
I have created a new role with every single permission and assigned the user I'm logged in with to this role. Still no luck1

Had to manually run the cron via the browser to generate.


Does page.tpl.php get overwritten on updates? Does page.tpl.php get overwritten on Drupal updates or are edits safe because it's in the theme folder? For some reason the developer put the footer HTML in here instead of creating a block for it... why I don't know.

For an drupal core update, you transfert every files/ folder except the sites folder for drupal 7.

Because in this folder, you have the setting.php and all your modules (custom or contrib) and your theme.

For module update, you can use the drupal ui or transfert the module update in the sites/all/modules folder.

So normaly, your theme and your page.tpl.php cannot be overide by an drupal core update.


Contextual filter and path alias I'm using Contextual filter on a view block which reads values from URL.
This works on pages that created by Panels; however, it doesn't work on nodes(content type).
I'm using url alias for nodes. It seems like even though the url displayed in defined alias, it doesn't pass the alias value when contextual filter read the node's url.
The field that I'm using for the url alias is text list field.

Is there any way to make a view block with contextual filter on both pages and nodes?

Drupal 7.12 | views 7.x-3.3 | panels 7.x-3.2

I ran into a similar problem recently.  The issue is that internally the "Raw value from URL" doesn't get its data from the URL, it gets its data from the unaliased url.  So if you have a node with an alias like mysite.com/foo/bar, you would expect 'bar' to be the argument passed with a path component of 2.

However since foo/bar is actually node/123, internally it becomes node/123, and '123' is what gets passed to the view.

I have opened a ticket in the views issue queue (http://drupal.org/node/1658352). Hopefully it will see some light with a proper fix, as I dont believe that the expected behavior is to retrieve the unaliased path.


Unable to connect to smtp server I'm having some problems with sending e-mails from my drupal site.
It was working just fine before.

Some information:

The site is using webforms so I checked the issues here: http://drupal.org/node/344668
None of them solved the problem.

The server recently upgraded to a new version of litespeed (maybe this is relevant?)

The site is also using the STMP Authentication module.
It's using the gmail smtp: smtp.gmail.com
Running on port 587 (so with TLS enabled)
Authentication is required and correctly filled in.

Both e-mail addresses are filled in (the default server e-mail address and the e-mail address used by SMTP auth.), both of them are correct addresses in the form of info@sitesdomain.com .

The recent logs show 3 messages:

Sending mail to: my@emailaddress.com
Error sending e-mail from site e-mail address : SMTP error: Could not connect to SMTP host.
Error sending mail from site e-mail to my e-mail address.

The drupal version is 6.2, webforms version is 6.x-3.2 and stmp auth version is 6.x-1.0-beta5

I've checked the STMP Authentication Support issue queue but there are no relevant item there that can help me. And if there are, then there are no answers.

I don't know how to take a look in the stmp log. I wouldn't know where to find it.

Any help would be appreciated.

Thanks,

Mike

So I mailed my hosting provider for some addition information about the server, the logs and such. And it turns out that they did not allow any traffic on port 587 except for traffic going to the google ip addresses. However google has recently changed the addresses for their smtp servers and the hosting provider did not.

So if there is anyone with a similar problem, I suggest you contact your hosting provider to see if they allow traffic to the google ip's on port 857 and if those ip's are correct.


Left Join query causing 'Column not found' error In Drupal (v7.22) I'm trying to modify a query in a module so that it checks the value of an additional field from another table while looking for a result. I've been going through the documentation but cannot seem to stop my version causing an error. The original working code was:

$result = db_query("SELECT nid, type FROM {node}
WHERE type IN (:type) AND LOWER(title) = LOWER(:title)",
array(':type' => $node_types, 'title' => $page_name,));

I've then added in a left join:

$result = db_query("SELECT nid, type FROM {node} AS entity_id
LEFT JOIN {field_data_field_test}
AS nid ON node.nid = field_data_field_test.entity_id
WHERE node.type IN (:type) AND LOWER(node.title) = LOWER(:title)
AND field_data_field_test.field_test_value = :test_value",
array(':type' => $node_types, 'title' => $page_name, 'test_value' => $tvalue,));

But it gives the error:

PDOException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'node.type' in 'where clause': ...

Any help would be appreciated.

You made 2 mistakes:

For complicated queries, use db_select(), not db_query(). That way you will use enough of built-in failsafes to know what exactly went wrong.
If you insist on db_query(), or need an UNION or something db_select() simply cannot create, never use unbracketed full table name. That's why aliasing exists.

Your query should look about like that:

$result = db_query("SELECT nid, type FROM {node} n
LEFT JOIN {field_data_field_test} f
ON n.nid = f.entity_id
WHERE n.type IN (:type) AND LOWER(n.title) = LOWER(:title)
AND f.field_test_value = :test_value",
array(':type' => $node_types, 'title' => $page_name, 'test_value' => $tvalue,));


Getting the right TID with 2 parents I'm trying to develop an script to upgrade nodes with a term reference.

But my source has 3 columns (copy to an in a db table) to the term tree, example:

fieldnames: ref1, ref2, ref3
fields: CAR -> REDCAR -> DARKRED

I can't use term name because it has is duplicates on the tree. Example:
fields: CAR -> REDCAR -> DARKRED
fields: BIKE -> REDBIKE -> DARKRED

How to get the right TID and verifying the tree with my DB table?

Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree.

So I made my own function. (note I'm not a php pro)
TABLE
CAT1|CAT2|CAT3

function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('name', $node->cat3)
  ->propertyCondition('vid', 3)
  ->execute();

// check if has more than one
if (count($result['taxonomy_term']) > 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]->name == $node->cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
          }
        $a++;
        }
      }
      $c++;
    }
    $i++;
  }
} else {
  $mytid = array_shift($result['taxonomy_term'])->tid;
  // Found no multi parents...
}
}
}


How to change a node add form without changing the node edit form I'm using drupal 7

I'm writing a custom hook_form_alter something like this

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
        {
            // Do something
        }
}

it seems that both the node add form and the node edit form are using the same form ID. I'm wondering if there is a way to determine weather you are editing or adding a node and make changes to the form accordingly. Do they always have to be the same exact form?

node_object_prepare(), which is called from node_form() (the form builder for the node editing form), executes the following snippet to verify if a node is being added, or edited:

  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

In your case, you could use code similar to the following one:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "rating_node_form") {
    $node = $form_state['node'];
    if (!isset($node->nid) || isset($node->is_new)) {
      // The node is new.
    }
  }
}


Add #ajax to an existing form I'm trying to add the #ajax property to the add form of a simple existing content type.  I thought hook_form_alter would be the way to go, but the code below doesn't get me the updated results I'm looking for.  I've essentially repurposed this code from a hook_menu function that creates the fields manually, attaching the #ajax at creation, so I think the code itself is okay.  I'm just not sure if I'm using the incorrect hook, or if I'm missing something, or what the problem is.

function ajax_test_form_example_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_username']['#ajax'] = array(
        'callback' => 'ajax_test_example_callback',
        'wrapper' => 'ajax-test-example-wrapper'
    );

    $form['text']['#prefix'] = '
';
    $form['text']['#suffix'] = '
';
}

function ajax_test_example_callback($form, &$form_state) {
    if(isset($form_state['values']['username'])) {
        $form['field_number']['#description'] = 'Hi  ' . $form_state['values']['username'] . '!';
    }
    return $form['field_number'];
}

Turns out that in order to add to an existing field you have to drill down into the array.  The correct place to add the property is

$form['field_username']['und'][0]['value']['#ajax']


Taxonomy term block linked to a view I have a list of Authors listed as taxonomy terms .
 I also have a view list of Contents named Topics

I need to display the taxonomy terms of Authors in a View block (lets say in the home page).
and then link each term to its related content view page (displayed as List).

Thanks in advance.

You need to have 2 views:

First view: Author's content:

View should be a page.
Add all the required field.
set path to be like author/%/content.
Add a contextual filter for the content taxonomy term field (author).

Second view: Authors list

View should be a block.
Add field with term ID (author ID) and mark it to be excluded.
Add field with term name (author name).
Mark the term name output field to be overridden as a link.
Set author name as link text
Set author/[tid]/content as link path. (You can find correct value for term id in token replacements)

P.S. If you use panels it will be a bit different.

P.P.S. You can use standard taxonomy/term/% for the "First view: Author's content" view.


Drupal 8 views slideshow not displaying images I created a content type with title, body, and slide (image) fields. I created a view block (format: bootstrap carousel, fields: slide).

After I place the block in a region, I see the slideshow block, but I don't see the image. I only see blank slideshow on my site and views.

How do I display images in the slideshow?

Views > settings next to format > selected image field to display.

Views > Select Settings next to format > selected Slide(image) in Image drop down list. I am not sure this is a best solution. At least I can see the image now.

 field to display.


hook_node_insert() sporadically not being fired after node_save() I have a situation where, every once in a while, I'll save a new node, and hook_node_insert() appears not to be called--AT ALL, for any of the modules that implement it. For example, if I look through recent log messages, there is no watchdog message pertaining to the new node; no "your node has been created" message is displayed to the user; none of my custom modules which implement hook_node_insert() are fired. Yet, the node appears to have been successfully saved: It show up after being saved, shows up in content listings, etc. (Though anything that was supposed to happen via another module's hook_node_insert() call does not happen.)

The maddening thing about this situation is the "sporadically" part: Most of the time everything works as designed, and hook_node_insert() fires, but once in a while it doesn't.(Maybe, once out of ten or twenty times, it doesn't fire.)

So at this point I'm just looking for any clues or hints as to where I should be looking for the problem.
Is there anything that this kind of strange sporadic behavior might point to?

One thing I've wondered is if this could somehow be related so some kind of cache issue. Specifically, I'm using memcached on my site, which I'm using to hold every cache table from my database. Could there be some kind of issue there? I'm starting to experiment with removing certain tables from the memcached cache (like cache_form), but no leads yet.

The only other note I'd make is to ensure that you don't have an & (ampersand) in front of $node in your function definition.  I was porting from a drupal 6 site's nodeapi function and was using hook_node_insert(&$node) and it wasn't until I removed the ampersand that it started working.


Create donation product with Commerce Kickstart I've installed a fresh copy of Commerce Kickstart 2 and then installed Commerce Donate.

After the installation, step 1 of the Commerce Donate readme says:

Create a donation product at Administration » Store » Products

I go /node/add/add-product and choose the type Donation. When creating the product there is a select field called product with no options.

It seems like I'm creating the display node not the actual product.

How do I create the actual product?

EDIT: Just found the same question on the Commerce Donate issue queue: Problem Creating Donation Product.

Someone replied on the Commerce Donate issue thread with a solution.

The solution is to manually go to: /admin/commerce/products/add/donation where you can then make your product.


Adding a class to select options from Views Exposed Filters Currently I have a views exposed filter for a "City" field. Typical output looks like:

<option value="Liverpool">Liverpool</option>

I would love to be able to add a class to this such as:

<option value="Liverpool" class="north-west">Liverpool</option>

I currently have a CCK field "field_region" which is set to "North West" for Liverpool - so it would be brilliant if anyone had any suggestions with how to achieve this on my exposed form input.

Cheers,
Garry.

Normally this would be accomplished with hook_form_alter, but sadly Drupal 6 doesn't support attributes in the options Form API element, which means you can't add any classes to it.

You're going to have to do this with Javascript. :-(

You can't start with something like this:

  $('.view-NAME_OF_YOUR_VIEW .views-exposed-widget option').each(function(index) {
    $(this).addClass($(this).val());
  });

This will get you

<option value="Liverpool" class="Liverpool">Liverpool</option>

I know it's not perfect, but sadly that's probably the simplest route.


Allow customers to add arbitrary data to products when adding to cart I've got a product type called workshop and I want customers to be able to specify the names of their kids when they add a workshop to the cart. If I could figure out how to add any arbitrary data at all I'm sure I could carry this through to where I ultimately want it to be, which is that the arbitrary data would actually be a choice of some number of Paragraph entities referenced by their user profile, but all the solutions I have been able to find seem to be for Drupal 7, so I'm dead in the water.

Any suggestions?

For the benefit of anyone who comes looking, the answer is that the fields need to be added to the order item type. Commerce sees each product as a sort of Platonic object and stamps out instances as order items -- think line items. You can add fields to this. Whee. Unfortunately, you can't reference Paragraph entities because, as ridiculous as it seems to me, Paragraph entities only support a single reference.


Can`t access config panel after the installation of Ubercart and e-commerce modules Fatal error: Call to undefined function dpm() in /home/u275855040/public_html/sites/all/modules/ecommerce/ec_store/ec_store.tokens.inc on line 10 How to fix that?

You are using dpm function to print variable. To fix this issue you just need to enable the devel module or comment the dpm function.


How do I add Google Scholar meta tags to a custom content type? I use drupal 7 and I have custom content type named "Journal"
I want add Google Scholar meta tags to "Journal" nodes.
Like this:

<meta name="citation_journal_title" content="Journal Name">
<meta name="citation_authors" content="Last Name1, First Name1; Last Name2, First Name2">
<meta name="citation_title" content="Article Title">
<meta name="citation_date" content="01/01/2007">
<meta name="citation_volume" content="10">
<meta name="citation_issue" content="1">
<meta name="citation_firstpage" content="1">
<meta name="citation_lastpage" content="15">
<meta name="citation_doi" content="10.1074/jbc.M309524200">
<meta name="citation_pdf_url" content="http://www.publishername.org/10/1/1.pdf">
<meta name="citation_abstract_html_url" content="http://www.publishername.org/cgi/content/abstract/10/1/1">
<meta name="citation_fulltext_html_url" content="http://www.publishername.org/cgi/content/full/10/1/1">
<meta name="dc.Contributor" content="Last Name1, First Name1">
<meta name="dc.Contributor" content="Last Name2, First Name2">
<meta name="dc.Title" content="Article Title">
<meta name="dc.Date" content="01/01/2007">
<meta name="citation_publisher" content="Publisher Name">
<meta name="robots" content="noarchive">

I tried the Metatag and Custom Meta modules. With the Metatag module, I can't add custom meta tags; with the Custom Meta module, I can't add custom meta tags to a content type.

How can I achieve this?

There is a module that allows adding Google Scholar meta tags: https://www.drupal.org/project/metatag_google_scholar . However, it is only available for Drupal 8.

I post this answer anyway, in case it might be useful (as an inspiration for a backport, for instance).


Migration from SQL table with no ids I'm trying to migrate from a SQL table using migrate module.
The fields in the table are a unique file hash (media), an url, a drupal internal path.
In the class extending SqlBase I have this function:

  public function getIds() {
    // The row property that represent the unique id for the id map.
    $ids['media'] = array(
        'type' => 'integer',
        'alias' => 'm');
    return $ids;
  }

It seems that migrate only accepts integers and requires ids to fill its migration map.
Is there a way to migrate with a string hash or without any id?

You do have to have an ID - and you can use your hash here simply by defining it with 'type' => 'string'.


Custom output for user profile list I have a "user list" view, which displays an "unformatted list" of user accounts.

While the row display is controlled via views-view-unformatted.tpl.php and customizing it works, the row plugin "user" in views/modules/user/views_plugin_row_user_view.inc directly outputs the user profile into the row.

Now as I already have a customized user-profile.tpl.php I cannot customize it for both view row and user profile page...

How do I implement custom display of user profiles in the user list, then?

It's trivial, but—did you try changing the row plugin to Fields instead of User?
With fields, you have granular control over the display of the user profile, so this might in effect be what you're looking for.


How to save images using Services 3 I have found some very detailed tutorials about Services 3. I appreciate them very much here is a  small list.

http://drupal.org/node/1354202

How to add multiple images to a node using node.save service?

http://drupal.org/node/1699354

But i cant find a way to upload images from the mobile app to the server. Is that possible ? Where can i get some example ?

Is there in Services core to accomplish this ? Every solution looks like i need o code something to get it work.

I had a requirement once like this where, using web service I have to create a node that will also save image. The following code uploads and saves image using web service.

// File validator.
$validators = array(
  /**
   * Defaults already allow png, jpg etc. If more needed to be supported,
   * edit here.
   */
  'file_validate_extensions' => array(),
  'file_validate_size' => array(),
);

foreach ($_FILES['files']['name'] as $field_name => $file_name) {
  // Save the file and get file object.
    $file = file_save_upload($field_name, $validators, file_default_scheme() . "://");

  // Check whether image is uploaded.
  if ($file->fid) {
    $node = new stdClass();
    $node->type = 'CONTENT_TYPE';
    $node->title = 'TITLE';
    $node->language = LANGUAGE_NONE;
    $node->uid = 'USER_UID';
    node_object_prepare($node);

    $node->field_custom[$node->language][0]['value'] = 'SOME_VALUE';
    // File upload here..
    $node->field_image[$node->language][0] = (array)$file;

    $node = node_submit($node);
    node_save($node);
  }
  else {
    return services_error(t('File upload failed'), 406, t('File upload failed'));
  }
}

NOTE: Following code was tested using services 3. Also it was an iOS app that was consuming this web service, and it worked there.

NOTE: File uploaded with POST request.

I tested the above code using a Google Chrome plugin called REST Console. To install the plugin search for "rest console" in Chrome Web Store and install the first plugin you get in result (with up green and down blue arrow)

Hope this helps!


Find the parent node type of the commerce product being added to the cart I have a product variation "Apparel", and a corresponding content type provided by kickstart "Apparel".

I have added a new content type "Product kit", which has an entity reference field pointing to "Commerce product" entity and "Apparel" is one of them. A single product kit node, can contain products of different types : "Apparel", "Luggage", "Cups", etc.

Using the newly created Commerce Product Kit module I have an option to add all the products stored in the entity reference field in a "product kit" node to cart.

I need to find a way to check if a product has been added from the "Product display" node or "Product kit" node. Is there a way to do this? I checked into hook_commerce_cart_product_add, but it doesn't help me identifying the source node type of the product. Any pointers would be appreciated.

Generally speaking, the line item for each product in the cart has a data array with a context sub-array that includes information identifying the context from which the product was added to the cart. In the case of a product added from a node's Add to Cart form, this array would point to the specific node ID and even name the reference field responsible for generating the form.

If I were you, I'd use the Devel module's dpm() function to inspect the contents of the line item's data array. Drilling down through the context array you should discover how to get the information you're needing. Just make sure to use a !empty() check before assuming a particular key in the array exists!


How to model players and rosters in a team sport site I'm very new to Drupal and I would like to know, from a general design standpoint, how you would enter players of a team into drupal. I don't want to add them as users because they should not be able to log in etc.

Each player could have fields like Name, Picture, etc.

Is this really a content type? Because the players are not published alone. Or is it necessary to create a custom module for this?

These players are then used to show the current roster. This could be done with a View and custom template I guess, but I'm not sure. They are also used in game reports (who played in that particular game and maybe the stats)

If I have a database of players somewhere, I would like to have a field that allows me to select a particular player. So basicly I must reference a content type inside another content type. I have not seen that option though.

No technical details are required, just general hints to modules or advice how to accomplish this task.

I would say yes, player is a content type in this case. Every player node would represent something (the player) that still has a meaning when you would take it out of its context (the team). Setting it up as a distinct content type will allow for more flexibility in the future, for instance showing player biographies, or transferring a player from one team to another.

If you want to hide the player nodes from regular visitors, you can use the Rabbit Hole module.

To make references between nodes, there are several options. Entity Reference is good and pretty straight forward. It allows you to add a field on the 'team' node type in which you can reference nodes of the 'player' type.

The Relation module is more complex but it can do a lot more. Relation doesn't store the references in the node itself, but it creates a new relation entity for each relation. Those relations can be 1-to-1 or 1-to-many and they can be bi-directional or one-directional. Since relations are entities, you can even add fields to them. For instance, if you define a relation that stores which players play for team X, a field on that relation could store the year/season when that happened. As you can see this offers a lot of possibilities, but it might introduce more complexity than you need.

How you can create the roster depends on the way you build your team-player relations. If you use Entity Reference to create a players field on the tem node, then the roster could simply be a display of the team node. When Drupal displays the team node, Entity Reference can fetch all related player nodes and render them in a view mode of your choice (eg. it can use the teaser view mode of the player node). If you use Relation,  you should use the Views module. The Relation module has pretty good Views support (though I haven't used that feature a lot myself) as you can see in this video tutorial.


Weird apostrophe issue Using Drupal version - 8.7.4. Added a 'Text (plain, long)' field for news summary to news content type.

There is a news view that shows all recent news items with the summary.

I created a new news item and pasted the summary from a document from Google Drive.

The apostrophe shows up as &#039; on the view but in the drupal edit page, it shows a '

Any thoughts on why this is happening? Any solutions? I am completely clueless. Thanks for reading.

This is a known issue with CKEditor.

In your case, the ampersand character & is being escaped as &amp; which is causing the HTML entity for your apostrophe to appear as &amp;#039;.

The entity for the ampersand is well-formed, so the ampersand appears in your rendered output. But this causes the entity for the apostrophe to be malformed, so it appears as a literal string.

There's a CKEditor config that you can do to force a simple ampersand, but I'm not sure how it will affect other text fields site-wide (which will no longer have their ampersands escaped), so proceed with caution.

Perhaps someone with more CKEditor experience can tell us if there's a way to configure this more narrowly.


Node edit layout based on Role I want Authenticated users to be able to add content (a custom content type). However, they should not see all the fields.

Users with a Role of "manager", should be able add/edit this content type, and see all the fields.

I've created a custom module, using hook_theme and hook_form_alter to hide the display of fields, but i don't know how to do this based on user or role. With the module active, even the admin user is blocked from seeing all the fields.

What is the best way to setup a custom node edit form based on Role, or at minumum, bypass for the Admin user?

For example, I have hide the form fields in erp_reco--node-form.tpl.php, and hide the revision, author, comments etc in hook_form_alter.

How do i hide fields then based on Role?

 function cct_erp_reco_theme($existing, $type, $theme, $path) {
return array(
    'erp_reco_node_form' => array(
        'arguments' => array('form' => null),
        'path' => drupal_get_path('theme', 'ERP').'/templates/forms',
        'template' => 'erp_reco--node-form', 'render element' => 'form',
    ),
); }

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'erp_reco_node_form') {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

as @Human love mentioned there is a module out there to accomplish this Field Permissions. There is usually a module to do just about anything in Drupal -- but therein lies the problem; 80+ modules later you may regret installing so many modules.

There are plenty of examples of leveraging Drupal Core and not just using 3rd party contrib modules to meet your needs to keep a lean(er) codebase. Here's an example with EFQ from Phase2 in place of using Views.

That being said you just need to check for a UID or Role in your hook_form_alter. See the next 2 examples:

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Allow admin.
if($form_id == 'erp_reco_node_form' && $user->uid !== 1) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

Or:

function cct_erp_reco_form_alter(&$form, &$form_state, $form_id) {
  global $user;
// Dont show items for SOME_USER_ROLE.
if($form_id == 'erp_reco_node_form' && in_array('SOME_USER_ROLE', $user->roles)) {
$form['revision_information']['#access'] = false;
$form['options']['#access'] = false;
$form['path']['#access'] = false;
$form['comment_settings']['#access'] = false;
$form['author']['#access'] = false;
$form['path']['#access'] = false;
$form['menu']['#access'] = false;
}
}

Ideally the contrib module will be more flexible in the long run for many many content types etc. But, if you understand your own requirements then this is perfectly fine.


How to get Ajax to load first? After updating module webform_paymethod_select I noticed that Ajax on webforms stopped working. I was unable to edit any existing webforms or create new ones. This happens when JS Aggregation is enabled. Clearing caches did not help.

Console shows two error messages:

TypeError: D.ajax is undefined
  var beforeSerialize = D.ajax.prototype.beforeSerialize;

TypeError: Drupal.ajax is undefined
  Drupal.ajax.prototype.commands['getBlock'] = function(ajax, response, status) {

The first error is coming from jQuery update and the second one is coming from the boxes module. Disabling boxes module worked for me but it left an important part of my site broken.

I believe the reason is that Ajax is unable to load before boxes requires it. After this Ajax just does not load at all.

If anybody can help me out, I would appreciate it.

EDIT:

I couldn't quite figure out how to get Ajax to load before everything. I tried changing its weight in drupal_add_js() and modifying hook_boot() to get it to load first. This seemed dangerous as i couldn't guarantee that it would only apply to the pages i needed Ajax to be first in. I then turned to figuring out how to encapsulate the boxes modules' JavaScript code that was throwing this error. I noticed that the code was being encapsulated with the following:

(function ($) {
  ..
})(jQuery);

Drupal suggests using :

(function ($) {
  // All your code here
}(jQuery));

That didn't work either, so i used the following instead and this made the error go away (except for the error jQuery Update is throwing):

jQuery(function($){
  ..
});

I am now able to edit existing webforms. I don't really understand why this worked, so if anybody can provide some insight i would appreciate it.

It could help.

add php function:

use Drupal\Core\Ajax\AjaxResponse;

Class AnyClass extends FormBase {

public function buildForm(array $form, FormStateInterface $form_state) {

/**
 * Running the library drupal core ajax
 */
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';

}

}


What are the various roles supported by the Group module? The Group module is an alternative for Organic Groups. For each group you can specify appropriate permissions, and this for various "roles" that are specific to the Group module (these roles are not the typical/global roles of a typical Drupal site).

Question: what are the various roles supported by the Group module?

Here is a summary of the various roles used by the Group module:

Configured Global Roles: These roles can be configured via the admin interface of the Group module, they are available (to grant permissions) for all individual groups (regardless of the "Group Type"). These roles cannot have permissions that vary per group type (they are all the same). Typical examples of such roles could be "Group Moderator" or "Group Administrator".
Special Global Roles: These are the special (hardcoded) roles named "Outsider" (= a signed in user that did not join a group) and "Member"  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. Unlike Configured Global Roles, these roles can have different permissions sets for each group type. Special case: the role "Anonymous" is related to a user that is not signed).
Group Specific Roles: These roles can be configured per group type and will only be available on groups of that group type. As an example, for a group type like "Class", you could configure roles such as "Teacher" and "Student".


How to embed HTML and CSS in a custom form element? This worked in Drupal 7 but isn't in Drupal 8.

$form['covid-19'] = array(
    '#markup' => '
Due to the COVID-19 situation, we will only be purchasing e-books and e-audiobooks at this time. You are welcome to enter your information for print books, DVDs, or CDs, and they will be purchased when the libraries re-open.  Inter-library Loans [loans from outside Yavapai County] are suspended for now.
',
);

I want the div with style info to stay intact so I can just comment it out when the crisis is over. Then I want to leave it there as a placeholder ready for the next crisis.

In this example, the strong tag makes it through but the div does not.

I also tried setting the div info as a #prefix and #suffix but that didn't work either.

Is there a way to do this?

Thank you!

Markup strips away some tags and attributes. Here is a way to do it.

Add a class to your form

$form['#attributes']['class'][] = 'crisis';

Add css rule to your theme's css

.crisis {
    display: none;
}

if you do not have a library and a .css file to use, you need to create them. Define a library in your theme or module in your THEMEorMODULE.libraries.yml

crisis:
  version: 1.x
  css:
    theme:
      css/crisis.css: {}

create css/crisis.css file and put your css rule(s) in it

and attach the library to your form

$form['#attached']['library'][] = 'THEMEorMODULE/crisis'

and clear cache

NOTE: The above (pseudo)code is not tested.  For more information please have a look here


Change the permissions needed in a service to get info from a module? I'm adding Services integrations to the Room Reservations module. A service I need to expose is the times when reservations can be made. I found a function inside room_reservations.inc (the function is _room_reservations_facility_hours()) and created a action type of service pointing to that function.

The problem here is that only the administrator user can have access to the output of this web service, whenever another user (even with the Administrator role) consumes the service I receive a 403 error. Is there a way I can solve this?

The Service declaration

$room_service = array(
    'room_reservations'=>array(
    'actions'=>array(
    'get_times'=>array(
      'help'=>'Gets the hours and the days reservations can be made',
      'file'=>array(
        'type'=>'inc',
        'module'=>'room_reservations',
        'name'=>'includes/room_reservations.service'
        ),
      'callback'=>'_room_reservations_service_get_open_hours',
      ),
  ),
),

The callback function (which connects to _room_reservations_facility_hours())

function _room_reservations_service_get_open_hours(){
  $dates = _room_reservations_facility_hours(TRUE);
  $i=0;
  $realDates = array();
      foreach ($dates as $key => $value) {
      //array_push($realDates, $dates[$key]);
        //$realDates[$key]=$dates[$key];
        if ($i<8) {
          $realDates[$key]=$dates[$key];
          $i++;
        }

    }
  //$standarized[] = $dates;
  $standarized[] = $realDates;
  return $standarized;
}

Edit: I'm already using the CSRF Token as a header when consuming the service

Sounds like an authentication issues - have you read up on tokens? There's a couple of modules out there, one pretty recent, plus some doc:

https://www.drupal.org/project/services_token_access
https://www.drupal.org/project/services_token
https://www.drupal.org/node/2424977


How to display the form fields of content type in a table using custom template file? I have created a content type Article including the fields Field 1, Field 2, Field 3 ......

All these fields have multiple values. I also created the custom template for this content type.

Now I want to display all fields of the form in a table and use only one button Add another item to add a line for all the fields.

Add the following snippet in template.php of your active theme;

<?php
function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'article_node_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'node--add--article',
            'render element' => 'form',
            ),
    );
}
?>

Then create a template file called node--add--article.tpl.php (same as the 'template' field in template.php.)

This is node--add--article.tpl.php:

    <?php print drupal_render_children($form['field_1']); ?>
    <?php print drupal_render_children($form['field_2']);  ?>
    <?php print drupal_render_children($form['field_3']);  ?>

<?php print drupal_render_children($form);  ?>

Now Clear Cache and see the result.


THEME_preprocess_field() not recognised in template.php I'm using Drupal Bootstrap. Mail (password reset, user blocked etc..) from admin sends messages without preserving line breaks.

I tried this to fix this issue, but THEME_preprocess_field(&$vars, $hook) doesn't work for me.

Try with THEME_preprocess_field(&$variables, $hook), replace the &$vars with &$variables


image disappears which uploaded with managed_file type I have implemented a configuration page which is at admin panel. It is something like this:

  $form["footer"]['xyz_cust_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image title'),
    '#default_value' => variable_get('xyz_cust_image'),
    "#description" => t("Image description"),
    '#required' => TRUE,
    '#upload_location' => 'public://',
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg')
    )
  );

but have a different situation. the thing is I successfully upload image and it is appearing when i upload it at the browser for that day. When the day passed, the image disappears. When I looked to variable table, the record exists; but the image not appears.

Drupal prunes files that haven't been explicitly marked as permanent. This happens on a cron job, which explains the delay you're seeing.

To avoid this, you need to add a submit handler to your form which updates the status of the file. e.g.

MYMODULE_some_form_submit($form, &$form_state) {
  $file = file_load($form_state['values']['xyz_cust_image']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}


How State is specific to the specific environment, when its actually pushed to all environments with DB sync? I am working with a Drupal 8 setup when production, test and development environments which periodically sync database. In Drupal 7 it was easy to override the $conf variables in settings.php to force a site in maintenance mode. However, in Drupal 8, the maintenance_mode is not a configuration anymore, but a state that is not possible to override from settings.php, so we have to use additional drush command after each sync to put one of the environments to maintenance mode.
And I am confused how come State API documentation asserts it's environment-specific, when in fact, it gets synced together with database and it is not easy to keep environment-specific settings using State API.
On the contrary, $config is easy to override in settings.php (which is excluded during sync), so it does provide easy way of setting environment-specific configurations.

When you copy your development/testing database to your production
database, you're effectively replacing your production site's state
with your development site's state. Therefore if you put your
production site in maintenance mode, then import a database that says
the site is not in maintenance mode, then your site will stop being in
maintenance mode.
Conceptually, state is specific to an environment, so long as you
aren't copying your database when you push changes from development to
production.
Your solution may be to avoid doing these database imports altogether.
If you are just making configuration changes on your local development
site and just need to push those, you can export the site's
configuration to code, commit it to version control, push that config
to production and then import it. (See
https://www.drupal.org/docs/configuration-management for info.)
If you are creating content in the local development environment that
you need to push to production, then you may want to look at using the
Migrate API.
If you absolutely must push these database updates but want the
production site to remain in maintenance mode when you do it, then
you'll need to put your development site into maintenance mode before
copying its database to production.


Easy Way to change all instances of 'Content Types' in admin to a different phrase For a project I am working every Content Type available to a user is a 'Survey'.  The terminology 'Content Type' confuses the users.   I was wondering if there was a simple way to change all menu instances of 'Content Type' to 'Survey' in the admin.  I was thinking use hook_page_alter but this could grow teduios and be difficult to maintain.  Has anyone ever done this before? Thank you.

To do this with just one or two strings in the user interface ("Content Type" is such a string), you can use the String Overrides module.

If you end up re-writing lots of phrases, you should make a custom language since String Overrides will cause a performance hit if you use it for too many things.


How to show only current user registration list in Node registration view? I have used views for registration type and listed as table. They listed all registered details to everyone. But I need to show only current user registration list in the table using views contextual filters.

Add Configure contextual filter.

Select the Name field.

Checked "Provide default value".

Type select box select: User ID from logged in user.

Refer


Showing block in specific urls and content types I'm using this code to show block in specific urls and content types.

<?php
  $match = TRUE;
  // block is visible on the content types entered here
  $types = array('product_display' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }

  if (strpos($url, "somewhere")) {
    $match = TRUE;
  }
  // copy paste these for additional URLs
  $tids=array_keys(taxonomy_get_children(7));
  foreach($tids as $tid) {
    if (strpos($url, "taxonomy/term/".$tid)) {
      $match = TRUE;
      break;
    }
  }
  return $match;
?>

It works but the block shows in some other urls too, any idea why?

You could do one more thing over it.

Just remove the block from the assigned region and render that block using module_invoke() in the template file page.tpl.php.

<?php
  $match = TRUE;
  // block is visible on the content types entered here
  $types = array('product_display' => 1, 'page' => 1);
  $url = request_uri();
  if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $match = isset($types[$node->type]);
  }

  if (strpos($url, "somewhere")) {
    $match = TRUE;
  $block = module_invoke('block', 'block_view', 'block_delta');
  print $block['content'];
  }

Render your block with the applied condition as you want.
If you just want to display block at some specific urls and content types.

It works well for that!


Don't show a field if it is not filled in What is the best way to don't show up a field if it is not filled in.

I have a content-type for the homepage: (Machine name: home_pagina).

There is a field for my client to give a warning-message if necessary: (Machine name: field_aandachts_tekst).

The warning message has to show up in a colored box/div. But if the field is not filled in, the box/div should not show up.

I tried to achieve this with a field-template....

I already have a "field.tpl.php" created. So i thought if a create a special field template for the field (field_aandachts_tekst) i could put the colored box/div in there. And if the field is not filled in the box/div would not show up also.

But it seems that the field-template for the (field_aandachts_tekst) is not used...

My template for controlling the view of the (field_aandachts_tekst) is called:

field--field-aandachts-tekst.php

but it seems this template is not used... (instead it uses: "field.tpl.php")

The code in my "node--home_pagina.tpl.php" looks like this:

print render($content['field_aandachts_tekst']); surrounded with php-tag ofcourse

Any tips or suggestions are good!

Thanks,
Kristof

Okay dear readers,

I find the solution/problem:

I forgot the extension .tpl in my template name. Stupid of me. Everything is working fine now.

Thanks for reading!

kristof


Redirect to a Multi-site Install Failing We're trying to redirect a subdomain to a multisite install on an Amazon EC2 Server.  The initial redirect worked like a champ -- it went to the raw IP and we created a directory in sites (sites/54.235.145.17) matching the IP address.

So, now we're trying to do "Masked Subdomain Forwarding" from godaddy.com and it isn't working.  It is always resolving to the raw IP address directory.  We've done:

Created the matching subdirectory:
(demo2.kcl.com)
Created a separate database for the new site
Modified settings.php to access said database

The directory listing:

drwxrwxrwx 6 bitnami daemon  4096 Feb  7 02:20 .
drwxr-x--- 9 bitnami daemon  4096 Jan 27 22:13 ..
drwxrwxrwx 3 bitnami daemon  4096 Jan 29 12:39 54.235.145.17
drwxrwxrwx 5 bitnami daemon  4096 Feb  2 07:53 all
drwxrwxrwx 3 bitnami daemon  4096 Jan 29 12:36 default
-rwxrwxrwx 1 bitnami daemon  2365 Jan 16 21:45 example.sites.php
drwxr-xr-x 3 bitnami daemon  4096 Feb  7 04:06 demo2.kcl.com
-rwxrwxrwx 1 bitnami daemon   904 Jan 16 21:45 README.txt

If I'm reading the documentation correctly, this should work but it is not.  As I said, it simply resolves back to the raw IP address.

Any solutions or even just things to check would be greatly appreciated.

Thanks in advance!

Scott.

(NOTE: IP and domain names have been changed to protect the ... spammable.)

From the looks of your folder structure you're missing the most important file for a multisite install...sites.php.

Copy example.sites.php to sites.php, edit it to add all sites in the installation to their respective paths, and try again...it should work.

These are the code samples example.sites.php for convenience:

// URL: http://dev.drupal.org
$sites['dev.drupal.org'] = 'example.com';

// URL: http://localhost/example
$sites['localhost.example'] = 'example.com';

// URL: http://localhost:8080/example
$sites['8080.localhost.example'] = 'example.com';

// URL: http://www.drupal.org:8080/mysite/test/
$sites['8080.www.drupal.org.mysite.test'] = 'example.com';

The format is:

'<port>.<domain>.<path>' => 'directory'


How to resolve "Referenced error: Highcharts not defined" when using Easychart? I installed the Easychart module 7.x-3.7 in my Drupal 7.51 site. Using Highcharts 4.2.7 in libraries 7.x-2.3. I extracted highcharts and easychart-master contents into all/libraries/highcharts and all/libraries/easychart folders respectively. Easychart_ex and Chart contenttypes are shown when adding content.

However in my browser console I am getting this error:

  Referenced error: Highcharts not defined.

I tried all the suggestions mentioned in the Notes at the end of the answer to "How to plot a chart from CSV uploaded in a content type?", but none of them helped.

Is there any Easychart latest module I am missing or is it the way it is supposed to work (only with Highcharts 4.2.7) is a question left to Drupal!

Easychart 7.x-3.7 recommends version 4.2.7 of the Highcharts library. This is also what you can see in this specific commit.

And the Easychart project page states "... v4.x of the Highcharts library".

So it appears that using Highcharts 5.0.3 is not yet supported, which probably also explains the folder problems you described in your own answer. I don't think that you're missing anything else (or some other "latest" module) that you're missing (as long as you stick to the recommended version of Highcharts you should be fine).

PS: Be aware that there is also the feature request about "make use of new Highcharts 5.0.0 methods" (for the Easychart plugin).


Programatically linking an image to content (Drupal 7) When I create a block through views I can easily link it to the content page by setting link image to in the field's settings.  But I also have some blocks that are created programmatically and I would like to similarly add links to these images.  How would I do this?

EDIT: Here is the code I use to create the block:

  $block = array();
  $rows = array();
  $format = 'l, F j, Y  - G:i';

  $header = array('Project Name', 'Screenshot' , 'Submitted');
  foreach ($results['node'] as $nid_array) {
    $row = $nid_array->nid;
    $node = node_load($row);
    $path = $node->field_icon_thumbnail['und'][0]['uri'];
      $variables = array(
    'path' =>  image_style_url('icon_thumbnail',$path),
    'alt' => 'Thumbnail',
    'title' => 'Thumbnail',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
    );
      $image = theme('image', $variables);

      $rows[] = array(
    l($node->title, "node/$node->nid"),
    $image,
    date($format, $node->changed)
      );
  }
  $rows = array_reverse($rows);
  $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');
  $block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
  );
  return $block;

You can use the l() function to wrap the image in a link. As it's HTML you'll need to pass the html option to the function so that it isn't run through check_plain():

$image = theme('image', $variables);

$linked_image = l($image, "node/$node->nid", array('html' => TRUE));

$rows[] = array(
  l($node->title, "node/$node->nid"),
  $linked_image,
  date($format, $node->changed)
);


Migration not skipping a row I have a talent for finding the hard issues.  I have a custom migration class importing taxonomy terms.  The class is an in-house customization, and we have it working happily on other sites.  On my site, it is not working.  There is a chance this is related to the data, which is coming from the client and possibly not clean.  Here is my issue.  I am implementing the public function prepareRow($current_row) with the intent of skipping some rows that I know will cause trouble.  Specifically, anything with a non-numeric id value.

I know the function is called, I see "Gojira!" appear
I know the value that is causing an error
The function is not being respected by the system.

Here is my function:

public function prepareRow($current_row) {
  $safe = FALSE;
  if(is_numeric($current_row->id)){
    $safe = TRUE;
    // problem value is $current_row->id == 'n'
  }
  if(!$safe) {
    print('Gojira!'); // this is seen in the migration ui
    //die();  // this is ignored
    return FALSE; // this is ignored
  }

  // allow parent to skip a row
  if (parent::prepareRow($current_row) === FALSE) {
    return FALSE;
  }
}

Here is the error I see on the migration ui page:

Migration failed ... General error: 1366 Incorrect integer value: 'n' for column 'sourceid1' at row 1

Please help.

The hint that solved this was in the error message:

for column 'sourceid1'

This column is in the Migration class's map table, where it tries to make a record of what it has processed.  The "fix" for this is to prevent the errant data from getting that far in the system.  I am coding a custom getItem to do the filtering for this issue there.


How do I fetch user profile data in search api entity (node) view? I've one search api index view of node type. Then each user have profile. So I wanted to fetch profile data of that entity created user. In normal view it can be easily done with relationship. But in search api view not able to create relationship. Any idea?

Same way I wanted flag relationship also but it's not happening in search API view. Normal view it's fine.

Your search api view is only able to list what has been indexed, so you should add the node author to the search api index.

After this, in search api, you should be able to add 'related fields'.

After adding items to be indexed in search api, make sure you reminded your site!


how to find out if a custom filter handler is in use when in hook_views_query_alter() Drupal 7. I have a custom filter handler which needs to amend the views query. As the filter can be added to any view I can't simply check for view name in the hook_views_query_alter()

I know the filtername exists somewhere in the $views parameter to hook_views_query_alter() within its arrays of array of objects I have yet to find an efficient way of checking if the filter is in use.

anyone come up with a solution to similar?

Found a way, you can check for the filtername in the view object
e.g.  if (isset($view->filter['myfiltername'])) {


Deleting unused Distribution modules In the past, when working with Drupal Commerce, I have built it from scratch. This is usually to fine tune exactly the modules I need, and to keep an eye on performance as I add each module.

After doing a few sites this way, I get pretty sick of the process of configuring it all every time, and so with this next project, I have decided to save myself some time, and use Commerce Kickstart 2. I have downloaded it and a had a quick play on WAMP, and its great to have a working site ready to go, with a huge amount of time and worked saved.

However, it feels slow compared to the sites I build from scratch, and there is a lot of modules in this distribution that I wont be needing, and so I will go through and disable/uninstall the modules I don't need.

This still leaves a huge list of modules on the modules page, and even though there is a quick search/filter on the modules page, I would just rather they weren't there.

My question(s) is/are, am I OK to just go and delete all of the modules from the Kickstart profiles folder once I have uninstalled them? Is this considered bad practice for any reason? Will I see any sort of performance increase by deleting them? (I think I will as the system table will be much smaller)

By disabling modules enabled by the profile, you may be working against yourself.  There is known issue that D7 does not enforce module dependencies listed in the .info of a profile.  So if some of the modules you are disabling were enabled on install because they are listed in http://cgit.drupalcode.org/commerce_kickstart/tree/commerce_kickstart.info, then you will find that the profile itself is actually disabled.  You can tell if this has happen by looking in the system table and/or the status report.  In the system table, the status on of the profile will be 0.  In the status report you'll see the profile's name, but no version number. You can read more about the D7 issue in https://www.drupal.org/node/1170362.  Some progress has been made on addressing this in D8 in https://www.drupal.org/node/820054.

Because Drupal also uses a variable to tell which profile is being used, a disabled profile may not cause any issues beyond preventing update status lookups.  But if a module is being included as a dependency in the .info, it's worth taking the time to understand why the profile's maintainer added that dependency in the first place.

As far as removing modules with a status of 0 to achieve a slightly smaller system table, that is unlikely to have a measurable impact on performance.  Where you may see a performance hit is from lots of extra .info and .install files. Creating the list of modules at admin/modules requires scanning several directories for .info files.  Checking for updates scans the .install files for any update hooks that haven't already been applied.  Beyond that, modules that are not enabled shouldn't be impacting the performance when Drupal renders a page.

You should consider using https://www.drupal.org/project/profiler_builder to generate your own profile and .make from one of the sites you built from scratch.  That would give you the advantage of getting another site started quickly without the overhead of a general purpose kickstarter style profile and distribution.

If you do create your own profile, please consider sharing it on Drupal.org so that other members of the community can benefit from the a more efficient (while less robust) Commerce configuration.


Is it possible to create a view to show a field from a user acc and content? when i create a view in Drupal7 i have to choose what i want to display ( like Users, Content, Terms ... ) .

Is it possible to choose Users and Content?

My problem is:

I have a geofield field in the User Account and in 2 content types. I need a view where i can display this field from all Nodes and Users in one view.

Has someone a trick or a solution for this? I can't find anything about this...

Thanks Flo

To do that you need to link the user account some how to content which i assume could be possible using  $node_author, you also need to connect both the contents with each other using reference field.

In drupal view you can use Relationships tab which available above the Arguments in the center colum of the view add/edit form. To learn about Using View's relationship pleases refer to How To: Using View's Relationships


How to do I stop product URLs changing each time I delete and re-import? Kickstart 2. I'm importing products using Feeds Importer. Every time I delete a product and re-import I get a sequential number appended to the end of the product's URL. For instance, I import MyProduct and its URL is mysite.com/products/MyProduct. I delete that product and import again and now the URL is mysite.com/products/MyProduct-0. Next time -1, etc.

I tested removing all products, truncating the commerce_product and commerce_product_revision tables and that didn't help.

So, how do I keep the URLs from changing? I'd prefer to fix the actual problem, not just use PathAuto or some other process afterwards to change the URLs.

Thanks.

There are two ways:

Don't delete them. Import them and let Feeds update them.
If you can't use above (for example no proper UUID on them), after node deletion, go to http://example.com/admin/config/search/path/delete_bulk and delete old aliases as well - that will free addresses for reuse.

Flipping "published" on and off is the way Drupal is designed to work, not deleting and re-uploading.
On the other hand, path module implements hook_node_delete() - hook called for each node deletion by node_delete_multiple() and node_delete() to delete aliases of deleted nodes. If it isn't, it's a core bug , or incompatibility between modules. You can fight to have it fixed, or try to implement hook_node_delete() on your own. Code of original implementation is very simple:

function path_node_delete($node) {
  // Delete all aliases associated with this node.
  path_delete(array('source' => 'node/' . $node->nid));
}

Of course to get it to work you may need to use some code from inside path_delete() to get query work properly, or to omit call to hook_path_delete() if one of it's implementation is buggy.


Limit the number of discount per product to 1, Commerce Discount I'm trying to make a one time discount for each product of a certain type per customer.
If the user buy a product he will have a discount on it, but he cannot have it a second time.

How can I do that.

So far I couldn't figure out how to limit it for the product itself.
Maximum usage determines how many times a discount may be applied across all customers or to a single customer's orders, which in my case should be empty (unlimited).

Where is the setting to limit the number of use per product to 1?

Is it a rule I need to code?

Cheers

You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag each product by the customer, after such discount was applied (for the first time). To actually flag such products by the customer, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

Any time a customer buys a product, you can verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no flagged this product already (by the flag you created for this purpose)".

If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.


Move required span of fields outside the label Normally in Drupal if a field is required, the Asterisk sign would render inside the <label> tag in a <span>. for some reasons I'd like to move the span outside the <label> and beside the label tag.

thanks.

You can achieve this goal via implementing theme_form_element_label.

I hope you already know how to implement or override theme.

e.g.

function MYTHEMENAME_form_element_label($variables) {
  $element = $variables ['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element ['#title']) || $element ['#title'] === '') && empty($element ['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element ['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element ['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element ['#title_display'] == 'after') {
    $attributes ['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element ['#title_display'] == 'invisible') {
    $attributes ['class'] = 'element-invisible';
  }

  if (!empty($element ['#id'])) {
    $attributes ['for'] = $element ['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title', array('!title' => $title,)) . "</label>" . $t('!required', array('!required' => $required)) . "\n";
}

Put this function on template.php


How to remove the Destination parameter from an URL in Drupal 7? I have a blog posts, and when an anonymous user visits it and and clicks the link "Login" or "Register" to post comment (under blog entry), then its url looks like this:

  http://example.com/user/login?destination=node/55%23comment-form

But I don't want that parameter of destination here. I just want a simple link like so:

  http://example.com/user/login

Any suggestions?

Finally I got the solution by using hook_url_outbound_alter in my theme template. I tested it successfully.

function moon_url_outbound_alter(&$path, &$options, $original_path) {
 // here "moon" is my theme, use your own.
  switch ($path) {
  case 'user/login':
  unset( $options['query']['destination'] );
  break;
 }
}


Is it possible to generate an URL object from a path? Can I generate a

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x

from a simple path, e.g. "/products/widget" ?

(assume /products/widget exists in the system and is a canonical path)

Use Url:fromRoute () and pass in the route's name and arguments. You can also use fromUri() for external paths. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromRoute/8.2.x

I usually find the route name by searching the routing.yml files for the path.

Alternately, you can do this. How to get the Route object from an URI?


Cache max-age and varnish ESI I need to display a custom block on my homepage. This custom block retrieves some data that are not managed by Drupal. Since no event will happen in Drupal to say that those data have changed, the max-age cache property seems the way to go, and it's OK for me. The block appears exactly as expected, but the problem is thst the cache for this block seems to never expire. Actually, the block is never refreshed.

After researching, I found Setting cache max-age to 0 has no effect on Block built using BlockBase? that explains max-age cache property doesn't work as expected for anonymous requests. After adding the mentioned trigger, everything seemed to be all-right on my development environment.
Once on the production environment, it's the same as before: The block is never refreshed. Talking to the hosting provider, I was told that Varnish is used to cache the whole page, and I should use an ESI (Edge Side Include) to render this block with its own cache logic managed by Varnish.

I don't really know how to implement it in a clean way in Drupal. My first idea is to use a controller, render the block markup, and return in a response, forcing the needed cache-control header. This is the code I thought of for such controller.

$block_manager = \Drupal::service('plugin.manager.block');
$plugin_block = $block_manager->createInstance('my_block_id');
$buildedBlock = $plugin_block->build();
$renderedBlock = \Drupal::service ('renderer')->render ($buildedBlock);

$response = new Response(
    $renderedBlock,
    Response::HTTP_OK,
    array('content-type' => 'text/html')
);
$response->setSharedMaxAge(60);
return $response;

I feel it is a totally unclean way to do this. Does anybody a better approach to propose? Would my code work?

max-age 60s is pretty low for the frontpage. Does the data really update that frequently or is it just that it could update but usually it doesn't happen every minute?

One possible approach to solve this would be to fetch that external data on a cron job that runs every minute. If and only if you detect a change, you invalidate a cache tag, which invalidates your frontpage. This approach is interesting when the data does not actually change that often most of the time. Because your cache is valid as long as possible.

And it has the added benefit that you do not rely on the external system when users are actually accessing your frontpage. Your block simply delivers the data from state which you update in the cron job.

That said, if you do want to influence the max-age header, then you need to implement your own Response subscriber. You could also use a module like https://www.drupal.org/project/cache_control_override, but you have to carefully test different pages to see if it might disable caches in more places than you expect, e.g. a language switcher block can currently do that.

  And uninstall the Internal Page Cache, it caches even uncacheable responses like this and you don't need it if you use Varnish

If and only if you have cache tag invalidation configurated and integrated with Varnish. If not, my recommendation would be to use the internal page cache module and set the default external max-age to a very short time, e.g. 1 minute. Then varnish can cache responses for that long and will revalidate against the internal page cache after that time.


Add image to RSS Feed We are using the Feed Display for a view where we want to display all Articles in a rss.xml file. Below are the View settings. However, we cannot find a way to add an image attribute that meeting the RSS 2.0 specs.

How can we add an image to the RSS feed display?

View settings:

Format: Rss Feed
Show: Fields | Settings
Fields: content: title, content: body, tracker: updated date, content: link to content, content: authored by
Feed settings: path = some/path/rss.xml
Filter criteria: published = yes and Content type = Articles

When you click on settings in the Show section, we assigned the fields.

title field -> content: title
link field -> content: link to content
description field -> content: body
creator field -> content: authored by
publication date field -> tracker: updated date

What we tried:

Include field_image under fields and hide from display
Rewrite the output of the body to include the following <enclosure url="{{field_image}}" length="100" type="image/jpg" />
The {{ field_image }} is the available token after reordering field image under Fields section so that it is above body field.

Results of what we tried:

<description>some body text  **blank space where <enclosure> should display** </description>

Expected output (cannot get this result because <enclosure> is stripped even when Strip HTML is false):

<description>some body text</description>
<enclosure url="{{field_image}}" length="100" type="image/jpg" />

I found there is a patch that works for exactly what we need. Support enclosure field in Views RssFields row plugin


Why isn't this Config API Code saving options? I can see the form, using the Config API, and submit it. However, it doesn't save the changes. Here is my code:

    <?php

namespace Drupal\my_config\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MyConfigForm extends ConfigFormBase {

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

  protected function getEditableConfigNames() {
    return [
      'my_config.config',
    ];
  }

  public function buildForm (array $form, FormStateInterface $form_state) {

    $form['author_config'] = array(
      '#type' => 'textfield',
      '#default_value' => \Drupal::config('config.factory')->get('author_config'),
      '#title' => 'Author of Config',
      '#required' => TRUE,
    );
    $form['language'] = array(
      '#type' => 'radios',
      '#title' => 'Language',
      '#options' => array(
        'EN' => t('English'),
        'SP' => t('Spanish'),
        'FR' => t('French'),
        'DE' => t('German'),
      ),
    );
    $form['drink'] = array (
      '#type' => 'select',
      '#title' => 'Select your drink',
      '#options' => array(
        'RB' => t('Root Beer'),
        'SD' => t('Sunny Delight'),
        'WR' => t('Water'),
        'OJ' => t('Orange Juice'),
      ),
    );
    return parent::buildForm($form, $form_state);
  }

  public function submitForm (array &$form, FormStateInterface $form_state) {

    \Drupal::service('config.factory')->getEditable('my_config.config')->set('author_config', $form_state->getValue('author_config'))
     ->set('language', $form_state->getValue('language'))
         ->set('drink', $form_state->getValue('drink'))->save();
    parent::submitForm($form, $form_state);
  }

}

This is my routing file:

my_config.settings:
  path: '/my-config/config'
  defaults:
    _form: '\Drupal\my_config\Form\MyConfigForm'
    _title: 'Configuration Form'
  requirements:
    _permission: 'administer site configuration'

This is wrong:

'#default_value' => \Drupal::config('config.factory')->get('author_config'),

It should be:

'#default_value' => \Drupal::config('my_config.config')->get('author_config'),

This is the entire form:

$form['author_config'] = array(
  '#type' => 'textfield',
  '#default_value' => \Drupal::config('my_config.config')->get('author_config'),
  '#title' => 'Author of Config',
  '#required' => TRUE,
);
$form['language'] = array(
  '#type' => 'radios',
  '#title' => 'Language',
  '#default_value' => \Drupal::config('my_config.config')->get('language'),
  '#options' => array(
    'EN' => t('English'),
    'SP' => t('Spanish'),
    'FR' => t('French'),
    'DE' => t('German'),
  ),
);
$form['drink'] = array(
  '#type' => 'select',
  '#title' => 'Select your drink',
  '#default_value' => \Drupal::config('my_config.config')->get('drink'),
  '#options' => array(
    'RB' => t('Root Beer'),
    'SD' => t('Sunny Delight'),
    'WR' => t('Water'),
    'OJ' => t('Orange Juice'),
  ),
);

Probably using $this->config the problem will be solved too


Using drupal_form_submit for pass-through to external login on click I need a way for already authenticated users to be able to click a menu link and have a POST submitted to an external site, allowing them to be logged in automatically. This is kind of the opposite from many of the other SSO questions I've seen. I have no control over the other service. Here is where I'm at right now:

Created a module that registers the desired path as a page callback function
Added a menu link for that path
Added a form builder function to generate the necessary fields
In the page callback, I'm using drupal_form_submit to submit the form

I've verified that the form, when rendered, has the correct action and method parameters, and all the necessary fields, and when submitted manually, it works as expected, but when submitted programmatically using drupal_form_submit, nothing happens. I don't really have a way of knowing what the redirect URL should be, as it's controlled by the 3rd party site, so I can't use drupal_goto. Is there any way to have drupal_form_submit honor redirects from outside the site? I really don't want to have to use curl directly, if possible.

Is there any way to have drupal_form_submit honor redirects from outside the site?

Not really - drupal_form_submit() is invoked as a result of Drupal receiving a form POST  on the relevant action URL - it doesn't care about how it's been invoked, and doesn't care about the URL itself (the form's already been submitted, so the action is obsolete by that point anyway).

If you need to POST form data to an external site, but have the processing done by Drupal, your only option is to use cURL or similar.


Title in node--article twig template In node--article.html.twig

<article{{ attributes.addClass(classes) }}>
  {{ created.content | date("d/m/Y") }}
  {{ content.title }}
  {{ content.body }}
</article>

The title is not displaying. How do I do this?

You can use:

{{ label }} or {{ node.label }} or {{ node.getTitle() }}.


Adding steps, breadcrumbs, or navigation to multistep webform I have a multi-step webform (about 10 pages), and I want the user to simply be able to skip ahead of their current location if they have had more progress previously.

I've been trying to use the Webform Steps module, but it's totally inaccurate and it shows the same button name for every form i.e. Step 1, Step 1, Step 1, not Step 1, 2, 3 etc. There's no customisation options for it, and I'm not comfortable with hacking it.

I've tried a couple other Modules, and they have similar behaviour, or they cannot actually link to other pages, as in the anchor tag is empty.

Is there a Module capable of doing this? Or do I need to do it myself? I'm relatively new to Drupal, and my PHP isn't that strong.

Any help is extremely appreciated!

It seems the issue of the Webform steps module.

  webform_steps-7.x-1.x is the currently stable version. It works with webform-7.x-3.x only.

Webform steps module doesn't work well with Webform 7.x-4.x version. see the issue

If you're using webform-7.x-3.x version. Here are the steps to make it work.

Webform steps module uses pagebreak labels as Step labels. So go to your form webform settings and change the pagebreak labels as you want to use as steps

For example if you want to use label steps as Step-1, Step-2 .. Step-10. Change the page break labels like Step-1... Step-10


How to move files already uploaded to a new subfolder? I've got a bunch of files in sites/default/files that I'd like to move to a sites/default/files/subfolder to avoid a big mess.

The fields uploading files have been configured to put them in the right folders in the future. What I'm looking for is a solution to organising files already uploaded.

Any suggestions?

It sounds like you're looking for File Maintenance.

  Ever wanted to move files from your sites/default/files directory (or
  whatever you have configured) to a (new) subdirectory? Never did it
  because you knew it's a damn mess since you need do move the physical
  file, adjust the database files table and look through all the
  node_revisions table and other content to adjust the link to the file
  so as not to break your site?

That should cover any files that are managed under the files table (pretty much any field you should have). If you have any other files under sites/default/files that aren't managed by Drupal, then custom redirect htaccess rules should cover those files.


How add related nodes to content profile? In Drupal 6, I am trying to list the links to nodes created by that user and/or nodes which have her name in their tags below the profile. But I could not figure out how to do either. I appreciate your help.

You can load nodes by various parameters. Just give the parameters which you want to load.
See here Here is for Drupal 6 also.

If you had a code in D6 to load a node using an array of conditions to match against in the database query like this:

<?php
$param = array(
    'type' => 'your_node_type',
    'title' => 'your node title',
    'status' => 1,
);
$node = node_load($param);
?>


Is there an easy way to move user data between 2 sites? I am totally new in Drupal, and I am using Drupal 7. I was asked to move data between two sites that don't even have the same structure, and have different fields.

Can anything bei done with a tool like Drush, or with MySQL?

You could possibly use views to output the data you want into a csv file (with views data export module) and then import the data into the destination site using Feeds module. This technique has worked well for me on a number of occasions.

Additionally, you could try the Features module but this is quite complicated and may be difficult to get your head around initially.


webform_submission_insert $submission values I am writing a module where I need to grab the submission values of a webform

I am using the webform_submission_insert hook found here however when I print out the $submission array using this:

drupal_set_message('
'.print_r($submission).'
', 'warning');

All I get is this:

1

It appears to me this hook is not working correctly and is not populating the array. How can I get the submission values?

I am using Webform version 7.x-4.0-alpha6. The webform I created has about 10 different input fields.

I was printing the array out incorrectly. Using this code to print works:

drupal_set_message(''. print_r($submission, TRUE) .'');


How to change the query for content type in d6 to d7? I have a code in D6 which is as given below

In Drupal 6 for each content type we had seperate table like content_type_[content_name]
--------------Drupal 6---------------------

    SELECT nid, field_id_value, field_oid_value,field_sts_value
    FROM {content_type_bstatus} fsa INNER JOIN
    ( SELECT MAX(nid) as maxnid , field_oid_value  // subquery
      FROM {content_type_bstatus}
      GROUP BY field_oid_value
    ) fsb
    ON fsa.nid = fsb.maxnid
WHERE fsa.field_sts_value <> 'success'

In Drupal D7 we have seperate table for each fields within the content type like
 field_data_[field_name]
and content_type is included only in nodes table
So, I am trying to implement the above code in D7

In Drupal D7 what i have tried is as follows but could not the exact solution

------------------Drupal 7----------------------------------
For the subquery above I have implemented the code below

SELECT MAX( entity_id ) , field_oid_value
FROM  `field_data_field_oid`
GROUP BY field_oid_value

How can I add the rest of code ..I have tried something which does not work
How can I write the code in d6 to d7 . I am using db_query in d6 and would use db_query or db_select but
HOW CAN I USE THE CONTENT TYPE FIELDS WHICH ARE HAVING SEPERATE TABLES in d7 database structure??

You should add a new view by the UI. Then, you can display the generated SQL query, by activating the sql display below the views UI:

admin/build/views/tools (D6)
admin/structure/views/settings (D7)

You'll see live, what the sql query is :

Copy/Paste the sql and rearrange it


how to use entity_load() result? I am quite new to Drupal so this question may be very simple or basic. I created a module and I've extracted list of a custom content type for each user by using EntityFieldQuery and then I used entity_load to make the results ready. the question is how should I use the $archive_items in my template ?!?

<?php
$archive_items = entity_load('node', $archive_items_nids);
?>

Your function will give an array of entity objects, indexed by their entity_id's. So:

foreach ($archive_items as $entity_id => $archive_entity) {
  /* Process each entity */
}

will allow you to iterate through the entities and to do what you need to each. Beyond that, we will have to know what result you are trying to achieve.


Drupal views autocomplete filter inserts html tags I have a site containing Free tagging field using text autocomplete widget option. A view is created with exposed filter for free tagging with autocomplete option. However the results provided via suggestions when entering a tag has html tags, in particular < p > tag.

Is there a way that the tags can be stripped off? Upon selecting the Unformatted dropdown and Unformatted suggestion in the filter option in views  option, it displays the numeric id instead of text.

@MPD: Yes the problem was due to the formatter. The field format was set to Filtered HTML. Once I changed that to Plain Text in Views Exposed Filter settings for the autocomplete filter for the field, it worked. It was a simple change that I did not notice.

Thanks.


Separate domain for a single language I have a website with three languages (Polish, English, and French) with English being the default. English and French should use a URL like domain.com/en and domain.com/fr; Polish should use a separate domain, domain.pl.

How can I achieve this?
I've seen suggestions to use hook_language_negotiation_info(), but it's not working for me at all.

This is can be done using TMGMT, from the TMGMT domain setting you can set up configuration per domain. You can also check out this module => https://www.drupal.org/project/domain_site_settings


How do I use the form hook alt to edit fields of inline entity form? I am trying to use the hook_form_alter to modify the fields of an Inline entity form in a commerce product display node.

I know how to edit a normal field but this does not work for an entity form field. How do I go about editing a field, for example changing the price field label?

Thanks
Robert

As per IEF's API docs, you've got:

hook_inline_entity_form_entity_form_alter()

  Perform alterations before an entity form is included in the IEF widget.
  hook_inline_entity_form_reference_form_alter()

  Perform alterations before the reference form is included in the IEF widget.

  The reference form is used to add existing entities through an autocomplete field

hook_inline_entity_form_table_fields_alter()

  Alter the fields used to represent an entity in the IEF table.

  The fields can be either Field API fields or properties defined through hook_entity_property_info().

I think the first would be most appropriate here, probably something like (guessing at the array keys here, they might be different):

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['commerce_price']['#title'] = t('New title.');
  }
}


Why do the facets display the wrong amount of results ? I have two facets that are bound to the Content Type and the Publish Status of my content.

When I do simple keywords search, it works properly, the amount of result corresponds to the real results displayed.

However, when I use double quotes to narrow down the search, the search works as expected, but the amount of result is completely messed up.

The search yielded only one result, but the amount of result is not correct.

All the indexes were rebuilt, the caches were cleared, but the issue remains.
Where could this issue come from ?

I'm using Solr Version: 8.x-2.2 and Facets Version: 8.x-1.1

All that time, I was using the default Search bar from Drupal 8 (which comes with the Search API module).

The thing is, the results in the facets were the ones that were given after Solr handled the search, and not the Search module from Search API.

For basic requests like a few keywords, both search engines yielded the same results, so the facets corresponded to the result, but my configuration of Solr didn't seem to handle double quotes.

In short : Search API handles the double quotes and displays the good results, but Solr didn't handle the double quotes so the facets results were wrong.


Block plugin's render array values ending up in $variables['content'] instead of $variables I've got a bizarre issue where my the render array from my block plugin's build() method doesn't seem to be properly interpreted by the template. I've got the following setup.
function my_module_theme(){
  return [
    'block__my_module__user_header' => [
      'render element' => 'children', // also tried without this
      'variables' => [
        'tabs' => NULL,
        'user' => NULL,
      ],
    ],
  ]
}

and my block plugin class
public function build() {

  $render_array = [
    '#theme' => 'block__my_module__user_header',
    '#tabs' => $this->getTabs(), // returns an array of data to handled in twig
    '#cache' => [
      'contexts' => [
        'route',
        'user',
      ],
    ],
  ];

  if ($user = $this->getContextValue('user')) {
    $render_array['#cache']['tags'] = $user->getCacheTags();
    $render_array['#user'] = $user;
  }

  return $render_array;
}

But then, when I inspect the variables in theme_preprocess_block(), all of that render array information from build() is sitting in $variables['content']. Same in the actual twig template, and same result if I remove ['#cache'] from build(). I'd expect to be able to access {{ tabs }} directly, but instead the data is sitting in {{ content['#tabs'] }}. Aside from that inconvenience, it also means that any cache tags/contexts I try to set in build() don't end up in the actual render array so they're completely ignored, which is a problem because the "tabs" as rendered in twig are dependent on this context.
I'm completely perplexed, as the same pattern works fine for hook_theme/block plugins in some of my modules, but this issue crops up in other modules.

This is how block templates work, they render the variable content.
{{ content }}

Your code though is using a block template inside of a block, which doesn't make sense, because the block template is wrapped around the block by Drupal automatically. You probably want to build the inside of the block like a controller output by using a custom template not derived from a block template, which you do when you don't start the template name with block__.
See https://www.drupal.org/docs/theming-drupal/twig-in-drupal/create-custom-twig-templates-for-custom-module


Change block location on page by page basis? I am working on a custom theme that's inheriting defaults from Bartik. I want to specify that the 'recent content' block should appear in the content area on the homepage, but the left sidebar on article pages.

I see how to specify a specific area for the block on a specific page, but no way to set a different area on a different page or duplicate the block. I'm thinking it might be most logical to duplicate it, so I have front-page recent content and regular recent content, since they might look a little different. But not sure how would I go about doing that?

I am assuming 'recent content' is "just" the output of a view, so, if I that is correct, you can create any numbers of blocks with that content by just going into views and clone()ing the display and thus creating another block that could then be placed wherever you want.


How to add facebook like/share button to every new text I post? I would like to add facebook like/share button to every new post on news site without doing it manually every single time I post new text. Similar question has already been answered, but I wonder if there is solution that doesn't include much code intervention, for example, is it possible to do it just with Facebook Like Button Module or something alike. Thanks in advance.

Hope this will help you,
You can achieve this with two module views and facebook
after enabling both module go to the structure tab of drupal,click on this

put Fcaebook application Id here:

You can create application id from this link
on reference to ur facebook account.
Than inside Facebook social go to "Presets"
click on add
fill up this form

for like button put only the name and select radio button of "facebook like button plugin" and select your content type,
save the form,
Go to view to create a new view,

Select respective field of your node and below that select the "Node:Facebook Social plugin", on settings of this field put your preset name as below

Finally you will get the face book like button on every row of your view.


Creating commerce users programmatically I need to import customer data from CSV files with billing and shipping data using Drupal 8.8 and Commerce 2.
I want to create the customer with its address data programmatically, but i do not know how to create billing and shipping.

I create the user as:

 $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
 $user = \Drupal\user\Entity\User::create();
 $user->setPassword('password');
 $user->enforceIsNew();
 $email="xyz@email.com";
 $user->setEmail($email);
 $user->setUsername($email);
 $user->set("init", $email);
 $user->set("langcode", $lang);
 $user->set("preferred_langcode", $lang);
 $user->set("preferred_admin_langcode", $lang);
 $user->activate();
 // Save user account.
 $user->save();

How do i create its billing and shipping data?

you got 2 options 1 migrate them, such as (https://www.drupal.org/project/migrate_source_csv)
 or make an admin form to submit the csv file and get the content...
but really you need to be create profiles for this billing info...

// Save user account.
$user->save();
// Add billing info.
$the_user_created_id = $user->id();
$profileStorage = \Drupal::entityTypeManager()->getStorage('profile');
$profile_data = [
 'type' => 'customer',
 'uid' => $the_user_created_id,
 'status'=> 1,
 'address' => [
   "langcode" => "",
   "country_code" => "AU",
   "administrative_area" => "NSW",
   "locality" => "SOME PLACE",
   "dependent_locality" => null,
   "postal_code" => "2000",
   "sorting_code" => null,
   "address_line1" => "Some Street",
   "address_line2" => "",
   "organization" => "47",
   "given_name" => "firstname",
   "additional_name" => null,
   "family_name" => "lastname",
  ],
];

$new_profile = $profileStorage->create($profile_data);
$new_profile->save();


How can I include ratings in the site, with reference stored in the node table? I need to implement ratings for my site. I have already stored the data in the node; now, I need to store the average ratings point in the node field type which I have created. It must be the reference for the ratings table.

How can I implement this?

You can use Fivestar module for this.

  The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7.

You configure which content type should have the Fivestar module enabled; you can also set the permissions for the users who can vote etc. You will have multiple option to show the vote result on the configuration page of module.

I have used it in 3-4 e-commerce websites and it works simply great.


What is the best way to alter image style in view for a teaser I have an image style set for all my nodes for teasers.  There is one view that I need it to display differently.  Is there a way I can alter in code?

I know that I can just change my setting from Content to Field and modify the image style that way but I am looking for a way that I can do it in code.

While I would generally just access this from the field output type from the View. I would recommend looking into some theme adjustments (and preprocessing Views). Since you are outputting content to the Teaser, you could add some additional verification from the template (https://www.drupal.org/node/53464).

Some helpful links would be:

template_preprocess_views_view_fields
theme_image_style


How to implement invitations limits per user when using the Invite Module? So, basically, I'm trying to create a private invitation-only forum. I'm using the invite module.

Is possible to set invitation-restrictions? For example, each user can only invite a total of 3 users, or a user can only send one invite per month?

Also, do unclaimed sent invites expire?

Invitation expiration

Quote from the Community documentation about the Invite module (from its installation instructions):

  Invitation expiry: Set the expiry period for user invitations, in days (default select up to 365 days).

So the answer to your 2nd question do unclaimed sent invites expire? is YES. That's what's stated also in comment #3 of the issue about Set expiry date to never.

Setting invitation restrictions

Looks like this feature "used to be available in a prior version of the module". And according to comment #3 of the issue about Limit invitation per user/role, it should be back some day.

While waiting for that to happen, you may want to use some type of Rules integration. Such as the solution as included in the issue about Rules integration for D7. It includes a patch for the 7.x-2.x version (status "RTBC"). If you're using 7.x-4.x however, then note the issue status "Needs work" ...


How can I integrate Magento in a site? Does anyone know of a way to integrate Drupal 7 with Magento?

I see that the Magento module doesn't have a version for Drupal 7, but I'd like to keep my Drupal installation shiny and new at the start of the project. I'm talking to the powers that be about using the commerce module instead, but I suspect that's going to be a non-starter.

The easiest and simplest way to integrate drupal with magento is using magento API. http://www.magentocommerce.com/api/soap/introduction.html. Magento API provides all the functions necessary for e-commerce operation. You can get the list of all categories, products, product reviews, shopping cart feature etc.