Using taxonomy exposed filter in a view ends in MySQL can only use 61 tables in a join Scenario

One hierarchical vocabulary called Countries with 300 taxonomy terms, one for each country, indenting like:

America (level 1)

Anguila (level 2)

Antigua y barbuda (level 2)

... (level 2)

Europe (level 1)

Austria (level 2)

Armenia (level 2)

... (level 2)

One content type called Office, then you add a field called Country, and its type is taxonomy reference, related to you recent created vocabulary called Countries.
After that, you create a few nodes: the first is called 'My secret office', checking Afghanistan in its country field. The second node is called 'My beautiful office', checking Albania.

Now you think it should be interesting if you could have a page where you can see a list of all your offices. The finest way to achieve this is by creating a view. To do so, you create a view page with this configuration:

Filter criteria: Content: Content type (= Office)
Page settings: Path: /offices

Then you visit your new page /offices and you can see 2 offices: My secret office and My beautiful office. Everything works as expected.

Then you add a country filter in you page. Going back to views configuration:

Filter criteria: Content: Has taxonomy term (exposed, Show as hierarchical) related to Countries.

You return to visit your page, and you can see a filter listing 300 countries and your 2 offices. You are on fire, so you decide to test your brand new filter:

You check Afghanistan option, and click Search; then you only see My secret office. Great.
You check Albania option, and click Search; then you only see My beautiful office. Awesome.
You now check Afghanistan, Albania, Algeria, Andorra, Angola and so on until you have checked all your 300 countries. The correct output should be your 2 offices, since you have no more; so you click search and BAAAM: White Screen of Death. But you are smart, and you have allowed PHP yo show the error log. You see that MySQL had a failure:

SQLSTATE[HY000]: General error: 1116 Too many tables; MySQL can only use 61 tables in a join

It follows the entire query Drupal is trying to execute. You notice everything is fine EXCEPT for this:

LEFT JOIN {taxonomy_index} taxonomy_index_value_0 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = :views_join_condition_1

LEFT JOIN {taxonomy_index} taxonomy_index_value_1 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_1.tid = :views_join_condition_2

LEFT JOIN {taxonomy_index} taxonomy_index_value_2 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_2.tid = :views_join_condition_3

LEFT JOIN {taxonomy_index} taxonomy_index_value_3 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_4.tid = :views_join_condition_4

and so on. Drupal is using the left join technique to access the database. The problem is that Drupal is using one left join for each taxonomy termed checked, meaning the first one is related to Afghanistan, the second one to Albania, the third is for Algeria, and so on.

¿How can I make a search using more than 61 options?

I think it is not a crazy thing that an user could search for offices in America and Europe, resulting this in more than 100 countries being checked. While looking for a solution, I have wrote a litle Javascript code that prevents the user from marking more than 50 countries so he doesn't face the WSoD.

Setup:

Drupal 8.8.1 (core and all its modules updated)
I'm not using any contributed module related to taxonomy or views
PHP 7.1
MySQL 5.5

UPDATE

As discussed here, this issue was caused by some missconfiguration at view level and normally should not occur. Read the full post to get the full picture on how you can step on this error.

ORIGINAL ANSWER

I'm adding my findings as answer since comments have limitations both on styles and length, but by all means THIS IS NOT an actual answer to the question.

I've tried to reproduce the describe behavior using an exisitng Drupal site that I'm working on:

I've a content A with a er field targeting vocabulary B
I've generated over 300 terms with hierarchy
Added 2 nodes tagged with 2 of the generated terms
Created a view as described in the question, but with a slight change: I've one display using "Has term" filter an another display "Has term (with depth)" filter; I explain below why I did this.

The reason using two displays with these two filters is because I saw that "Has taxonomy term" filter (plugin id taxonomy_index_tid) is implemented by \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid which extends from \Drupal\views\Plugin\views\filter\ManyToOne. Reviewing the code I saw that neither the ManyToOne base filter or the TaxonomyIndexTid implement JOIN queries. On the other hand \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTidDepth extends from TaxonomyIndexTid and has this on it's ::query() method

public function query() {
  ...
  // Now build the subqueries.
  $subquery = Database::getConnection()->select('taxonomy_index', 'tn');
  $subquery->addField('tn', 'nid');
  $where = (new Condition('OR'))->condition('tn.tid', $this->value, $operator);
  $last = "tn";

  if ($this->options['depth'] > 0) {
    $subquery->leftJoin('taxonomy_term__parent', 'th', "th.entity_id = tn.tid");
    $last = "th";
    foreach (range(1, abs($this->options['depth'])) as $count) {
      $subquery->leftJoin('taxonomy_term__parent', "th$count", "$last.parent_target_id = th$count.entity_id");
      $where->condition("th$count.entity_id", $this->value, $operator);
      $last = "th$count";
    }
  }
  elseif ($this->options['depth'] < 0) {
    foreach (range(1, abs($this->options['depth'])) as $count) {
      $field = $count == 1 ? 'tid' : 'entity_id';
      $subquery->leftJoin('taxonomy_term__parent', "th$count", "$last.$field = th$count.parent_target_id");
      $where->condition("th$count.entity_id", $this->value, $operator);
      $last = "th$count";
    }
  }

  $subquery->condition($where);
  $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", $subquery, 'IN');
}

As shown it does LEFT JOINS to work with the selected depth and hierachy. All though after selecting all 300 terms in both displays I was unable to reproduce the described error (see screenshots below).

Has taxonmy term

Has taxonomy term (with depth)

Also as commented @mpdonadio the filter is using WHERE IN to filter the terms and delegates to LEFT JOIN when dealing with hierarchy.

Maybe these can shed some light on your error.


what is the default file template in drupal when you set your own theme? What is the default template in drupal when you set your own template and you don't have page.tpl.php
??
where does the html beeing rendered from?

If the active theme doesn't have a page.tpl.php, the default page.tpl.php from core is used.

See Default theme implementations for more information.


Displaying Ubercart order history for customers in their "my account" page I currently have a small store set up with Ubercart where customers can purchase the items I have listed. They go through the process of purchasing and then receive an order confirmation email. On this email their is a link to "Check Order Status". That is what I want however, when the link is clicked they are taken to their "My Account" page and nothing is displayed.

Question: Because Ubercart gives this link I assume their is some sort of information that can be displayed (ie order history/status). Is their an area in the configuration that I can insert the information or is it even possible.

So after long last, by accident, I found the option. In Drupal 7 go to Home » Administration » People and select the permissions tab. Once there navigate down the "Orders section" within that section you will be given the option to allow users to view certain order information. Select the relevant information and you are good to go. Be careful not to give them access to things they should not be able to see (these options are also available there as well).


Hook Function to Footer I would like to know how to hook a function in the footer area right before the  tag. The function would produce html.

function html_footer(){
    does stuff
}
places_in_footer('html_footer()');

I've done some research on the subject but it seems like there are a lot of different methods but all of them are deprecated. So I'm not sure what the right method would be.

For example in wordpress it would be:

function your_function() {
    echo '
This is inserted at the bottom
';
}
add_action( 'wp_footer', 'your_function' );

You can create one block and add the html content and place this block in the footer region. This content will place inside the  tag and after the main content. Thats mean you will get your content before the closing  tag.


Programmatically Access custom user field I added a Node-reference field (machine name: field_node) to all users at:

example.com/admin/config/people/accounts/fields/

I am now working in a custom module & hook_node_access

How do I access the Node-reference field programmatically when the user is logged in?

You can get field values from any entity with field_get_items(); the logged in user is available in the global $user object, and to load fields onto that object you can use user_load().

Put those together and you get something like this:

// Get a fully loaded entity object for the logged in user.
$account = user_load($GLOBALS['user']->uid);

// Extract the field items
$field_items = field_get_items('user', $account, 'field_node');
if ($field_items) {
  // This will be 'target_id' if you're using the Entity Reference module,
  // or 'nid' if you're using References
  $column_name = '?';

  $nid = $field_items[0][$column_name];
}

That's the abstract code if you like.

It's worth bearing in mind that hook_node_access() is passed an $account object already (which will be the logged in user if the access check is happening for them) so you would probably be better off using that to check against. You might still need to run it through user_load(), it'll be easy enough to check that with a bit of debugging.


how to get this functionality? views: Format options in ctool modal modify field data In views module, when we edit view page and add fields to it, there is an option Format:unformatted-list and when we click on unformatted-list, a popup appears displaying radio buttons of grid, table,jump-menu, etc. Choosing any of the radio button, the field adjust themselves in either grid, table, whatsoever the option we choose.

I need the exact functionality of choosing radio buttons, modify my fields display output.

Thanks in advance.

You may use Display Suite module

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!


Manual crop is not working when authenticated user adds a new content I am using the Manual Crop module in my site. Admin and authenticated user can add a content. If admin adds a new content, manual crop enable after picture uploading. But when authenticated user adds a new content manual crop module is disable.

It enable only after save content. After saving content error message comes like this: "Chose cropping styles".

What can I do in this moment in order to do enable cropping after uploading.

Manual Crop (currently) doesn't have any permissions of itself, the File entity permissions are only required if you're using the Media module.
If you're using an administration theme for node adding and editing, then the users that are allowed to edit nodes should have access to it.


Render content type via Form Block module using module_invoke I am attempting to use the Form Block module so that I can place one of my content type forms in a block.  I seem to be able to get to the block but I'm not sure how to render it.  If I do a print_r($block) I see the block contents but I don't see anything to do with rendering it.

$block = module_invoke('formblock', 'block_view', 'csc_newsletter_subscription');

// Normally I would do something like this if it was just a block_view
$variables['newsletter_subscription_form'] = render($block['content']['#markup']);

And then I would be able to take the $newsletter_subscription_form variable and display it in my tpl file, but this does not seem to work.

What am I missing?

You can print a Block which is generated by a module like this.

$block = module_invoke(<module name>, 'block', 'view', <block id>);
print $block['content'];

User created block

$block = module_invoke('block', 'block', 'view', <block id>);

example:

$block = module_invoke('block', 'block', 'view', 20);
print $block['content'];

In Your cas, since the forms are in blocks you can simply manage them via exmple.com/admin/structure/block path :)


When paging through a block, another block on the page disappears I am using Drupal 7 with Organic Groups and Views. Currently within my team node I have 2 blocks appearing with the proper filters in place. The first block is configured to only appear only on pages with the group content. The second block displays 1 item per page and has a pager appearing belong the content in order to page through the multiple nodes belonging to the block.

I have noticed whenever I go to another page through the pager at the bottom of block 2 the 1st block completely disappears. Am I suppose to configure the first block differently? I don't know what I am doing wrong.

Edit

I would also be willing to remove the pager and make it so that if you click the second block's title it brings you to an alternate page/view/block that displays all of the content yet I haven't figured out a way since then it isn't on a group page anymore and I don't know how to grab (or set it up to grab) the group id to filter the content by.

A couple of things come to mind.

On the block that disappears, does it have an argument that is defined by the URL?
or in your block settings, have you accounted for a wildcard for subsequent pages?


Localize views menus links I need a way to localize menu Items pointing to Views in a menu that has field translation.

I cannot create them neither from views nor manually (weird access denied messages).

EDIT: Here comes the original post. The title was "Translate the main menu with preserving English in case the translation is missing". I learned a thing or two in the process ;-)

I think I am doing something basically wrong...
I have set up a basic multilingual site with fields (entity) translation. Now, all works fine up to the menus. If I translate the menus, however, only the menu links that have actually been translated show up in the other languages. What's more, the menu structure does in other languages does not preserve the weights of the particular links.
What I'd like is to happen is:

English (or other provided) menu link show up when no translation is available.
The translated links preserve the weights.

Settings the menu links to "language neutral" solved the issue to a point. I cannot apply this practice, however, to views. Menu Items from views have English by default. What's more, when I remove the menu item in Views menu and try to make a  menu item that points to it by path, I get:

  You are not authorized to access this page.

Any ideas?

You should set in the content type translation settings, to show no fallback language, and set all english nodes to English, rather than Language neutral (if they are such).


Best way to organise content I am making a site which will deal with various micro-topics about a subject.

Each subject will have the following:
i) A backgrounder (one-time)
ii) A news blog (obviously recurring)
iii) FAQs (basically static)
iv) Set of links / documents (static too, but can simply be updated)

My problem is about organising the content.

(A) First option
* Every topic itself will be a taxonomy term
* Create 4 content types: backgrounder, blog, faqs, links

First, the problem here is that soon I'll run into probably a few thousand topics i.e. a few thousand taxonomy terms.
Second, since each term page will have to serve as the homepage for that topic, I have no clue how to organise such a page.

(B) Second option
* Each topic will be a node.
* Each facet (backgrounder, blog, faqs, links) will be CCK fields.

First, the problem here is that it would probably look awful, if the newsblog becomes longwinding.
Second, managing this might become difficult.
Third, since most of the content will be CCK inputs, the actual node area might not have any content. Searc indexing becomes a hassle.

Right now I am quite clueless.

Any advice towards the right direction would be of great help.

Subir

First off, this isn't really a question that has a single correct answer.

It is really up to the site builder as to how they want it to work and it depends greatly on the use cases of the site and any business rules related to the content.

As such, it isn't the best question for a site like this, however I will say a couple of things:

Having thousands of taxonomy terms is ok if your content requires it. You might have a thousands of taxonomy terms and tens or hundreds of thousands of nodes. That's fine.
The second option you mention doesn't sound like a good idea. Mainly the use of fields as blogs etc. doesn't sound right conceptually. Plus handling revisions, permissions, comments for blog posts etc. is going to be a hassle to say the least.
The first option mentioned doesn't necessarily have to have the term page as the topic homepage. It could be done other ways, like having the backgrounder node as the topic homepage or using a views page with arguments to be the homepage.
Another possible solution is to have the backgrounder node be the home page and link everything to that via an entity reference field, removing the need for taxonomy at all.
As for laying out the home pages, consider using the panels or context modules combined with views.

These are not nearly all the possibilities, there are a bunch of other ways things could be done, so you can see you will not be able to get someone to give you a definitive answer.


Drupal 7 Theming: Generate styles to a file instead of inline In my field.tpl.php, I have used PHP to write a string of CSS. The content of the string varies according to the field options.

I then add this string of css to my theme using drupal_add_css(). The style is then added to my theme, but it is added inline.

Is there a way to make the string of CSS to be written to an external stylesheet instead?

If you change the content of the CSS file every time the template file is invoked, then you could use code similar to the following one. The code is longer than it should be because I am using a custom function whenever the equivalent Drupal function would output a message error.

function mytheme_data_save($data, $destination, $replace = FILE_EXISTS_RENAME) {
  if (!file_valid_uri($destination)) {
    watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination));
    return FALSE;
  }

  if ($uri = mytheme_unmanaged_data_save($data, $destination, $replace)) {
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid      = $user->uid;
    $file->status   = FILE_STATUS_PERMANENT;
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
        $file->filename = $existing->filename;
      }
    }
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
      $file->filename = drupal_basename($destination);
    }

    return file_save($file);
  }

  return FALSE;
}

function mytheme_unmanaged_data_save($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  // Write the data to a temporary file.
  $temp_name = drupal_tempnam('temporary://', 'file');
  if (file_put_contents($temp_name, $data) === FALSE) {
    return FALSE;
  }

  // Move the file to its final destination.
  return mytheme_unmanaged_file_move($temp_name, $destination, $replace);
}

function mytheme_unmanaged_file_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $filepath = mytheme_unmanaged_file_copy($source, $destination, $replace);
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
    return FALSE;
  }
  return $filepath;
}

function mytheme_unmanaged_file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $original_source = $source;
  $original_destination = $destination;

  // Assert that the source file actually exists.
  if (!file_exists($source)) {
    if (($realpath = drupal_realpath($original_source)) !== FALSE) {
      watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
    }
    else {
      watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
    }
    return FALSE;
  }

  // Build a destination URI if necessary.
  if (!isset($destination)) {
    $destination = file_build_uri(drupal_basename($source));
  }

  // Prepare the destination directory.
  if (file_prepare_directory($destination)) {
    // The destination is already a directory, so append the source basename.
    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  }
  else {
    // Perhaps $destination is a dir/file?
    $dirname = drupal_dirname($destination);
    if (!file_prepare_directory($dirname)) {
      // The destination is not valid.
      watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
      return FALSE;
    }
  }

  // Determine whether we can perform this operation based on overwrite rules.
  $destination = file_destination($destination, $replace);
  if ($destination === FALSE) {
    watchdog('file', 'File %file could not be copied because a file by that name already exists in the destination directory (%directory)', array('%file' => $original_source, '%destination' => $destination));
    return FALSE;
  }

  // Assert that the source and destination filenames are not the same.
  $real_source = drupal_realpath($source);
  $real_destination = drupal_realpath($destination);
  if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
    watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
    return FALSE;
  }
  // Make sure the .htaccess files are present.
  file_ensure_htaccess();
  // Perform the copy operation.
  if (!@copy($source, $destination)) {
    // If the copy failed and realpaths exist, retry the operation using them
    // instead.
    if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
      watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
      return FALSE;
    }
  }

  // Set the permissions on the new file.
  drupal_chmod($destination);

  return $destination;
}

This is how you should use the code.

if (($file = mytheme_data_save($data, 'public://mytheme_css') !== FALSE) {
  if ($instance = file_stream_wrapper_get_instance_by_uri($file->uri)) {
    $url = $instance->getExternalUrl();
    drupal_add_css($url, array('type' => 'external'));
  }
}

With the code I am using, the file used to contain the CSS styles is deleted the first time the cron tasks are executed, if the file has been created 6 hours earlier.


Allow user to delete own account In admin/people/permissions I checked the boxes next to the "Cancel own user account" and "Select method for canceling own account" but in the user profile (user/NID/edit) the Cancel account button is not present.
Why? What could I have forgotten?

I have assigned the right role.

Thank You.

Make sure you are not using user 1, because you can't cancel user 1.
Clear caches after changing permissions.

Update:
Check for any modules you have which may affect Permissions.
In this case Administer Users by Role may be lacking some permissions that you need to set.


Hook within an exisiting hook? I have one hook, "hook_form_commerce_checkout_form_alter" and that is modifying something on my checkout process. Within that though I have a switch statement that if true I want to use "hook_commerce_checkout_router" to skip the page. Is this allowed? I can't get any signs of life via DPM. I ran through a bunch of other modules and can't find anything helpful

Since you're already loading the form, your switch statement won't do anything. If you want to skip the page, you'll need to implement hook_commerce_checkout_router() in your module so that you can control if it shows up or not.


How to hook into adding watchdog entries by other modules? Is it possible to write some code to intercept the process of adding Watchdog entries and filter them before adding to the log? Or is there a module that allows for watchdog filtering before adding to log? (I searched but nothing found) This would be useful if there are tons of well-known messages (like page not found from the same referrer or the same IP) that obfuscate the log.

Unfortunately hook_watchdog doesn't provide a return value which could block the insertion of the log entry in the database.

Note though that the responsible module for inserting the entry in the database is dblog. You could disable that and write your own implementation of it, although you'd have to replicate lots of functionality.

Another idea is to have a frequent cron job deleting the relevant log entries from the database table.


GET method form is not processed I want to build kind of a search form in Drupal 8: On submit, it shall load itself again, but below the results shall rendered. And the URL shall contain the search term, so that the result page is linkable.

This is my minimal example. My current problem ist, that the submitted form value is not fed to $form_state.

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

  $form_state->setMethod('get');

  $query = $form_state->getValue('query');
  // Unfortunately, this is empty, even after submit.

  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Query'),
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Search'),
  );

  return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild();
  $form_state->setAlwaysProcess(TRUE);
}

When I comment out $form_state->setMethod('get');, it is working as I want: query is readable in the rebuild form and set as default value in the text field.

But with setMethod('get');, query is empty and no default is set.

I thought that $form_state->setAlwaysProcess(TRUE); makes sure the values get processed, even via GET method, as the documentation suggests. But apparently, something is missing. Any ideas, what?

I could solve the problem myself, based on this solution for Drupal 7.

Instead calling the form directly in the router, I define a page callback in my_module.routing.yml.

my_module.form:
  path: '/my-module-form'
  defaults:
    _title: 'My module form'
    _controller: '\Drupal\my_module\Controller\MyModuleController::searchForm'

In MyModuleController, I load my form via the builder.

public function searchForm() {

  $form_state = new FormState();
  $form_state->setMethod('get');
  $form_state->setAlwaysProcess(TRUE);
  $form_state->setRebuild();

  $form = \Drupal::formBuilder()->buildForm('Drupal\my_module\Form\MyModuleSearchForm', $form_state);
  unset($form['form_build_id']);
  unset($form['form_id']);

  return $form;
}

The code of form then is like in the question above.


order of execution of hook_node_presave and custom submit function Does hook_nood_presave execute before or after a custom form submit handler in the same node ? and I need to perform some action after the node contents have been saved in the database. So, where should put this code ?

In the core system hook_node_presave() is only ever invoked once, from inside node_save() itself. In the context of a node add/edit form it's called by the original form submit handler, which unless you've explicitly engineered otherwise, will be run before the call to your custom submit handler.

Similar to your other question the submit handler isn't really the best place for this logic, as that code will literally only run when a form has been submitted (not when a node has been added programmatically for example).

After node_save() has saved the node data to the database, it invokes one of two other node hooks...hook_node_insert() and hook_entity_update() (obviously depending on the current operation).

One of those hooks will be called after the data has been committed to the db so will be perfect for your needs.


Help with displaying views with EVA I am struggling with displaying a view in a node. I have installed EVA module and have created a view of products categorized for that node (Restaurant Type).

The entity displays in the node but I'm having trouble contextualizing the view. How do I dynamically provide the context when the page containing the entity is viewed.

I am normally a PHP programmer and a newbie recently thrown into the Drupal framework. I have been able to print out the criteria (in php template) and display the entity but I am failing in making them play together.

I presume that the "Criteria" I am able to pry out of the template is the long way round solution to my issue, how do I configure my "entity view attachment" to display a contextualized list. my file structure always contains the variable and resolves as "*.com/restaurants/steak_houses" where "restaurants" is the node and "steak_houses" is the context criteria.

I need help in feeding that data to the entity.

== Updated. Rewrite the answer, provide step by step screenshot ==

P.S. you also need References, I apologize that didn't mention it.

Create a Content Type called Restaurant, everything by default, save.

Create a Content Type called Product

Add Node Reference field for Product Content Type.

Create an instance of Restaurant content.

Create an instance of Product content, set the node reference field to the resturant just created.

Next, create a new EVA view.

Add filter => Content type => Product

Set Entity to node, Bundle to Restaurant

Add Contextual filter, select the node reference field created.

Provide default value => Content ID from URL

So you overall EVA view set up should be something like this:

Next, an important step: clear the cache, then refresh the restaurant node page to see the change:

You can see the Product One has been attached to the Restaurant.

You will get it. :)


How to hide block while field in database is empty? I have 2 blocks for the same content type (Banner):

block 1 = filter criteria : field video:input(not empty)
block 2 = filter criteria :

field video (is empty)
field image (is not empty)

What I want :

if field video is empty : show only block 2 and hide block 1
if field video is not empty : show only block 1 and hide block 2

Any suggestions how to make this work?

Part 1: Install the Rules block visibility module (and Rules)

You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the value of your field video (i.e. if it is empty or not).

Part 2: Create 2 appropriate Rules Components

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

  Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.

  Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components, that should help to understand its concept.

By looking at these samples, I was able to create another Rules Component which looks like so:

{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the user's uid is YES or NO equal to 1.

With that, we're coming close to an actual answer to your question: create 2 such Rules Components (1 for your block 1, and 1 for your block 2). And within each of those 2 Rules components, you only have to adapt the Rules Condition (as compared to my sample Rules Component here, apart probably from its machine name or so):

Rule 1 (which will be used to manage the visibility of Block 1) should have a condition like "field video is NOT empty".
Rule 2 (which will be used to manage the visibility of Block 2) should have a condition like "field video is empty".

Part 3: Set Block Visibility using the Rules Component

Head over to the "Block" settings for each of your 2 blocks. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".

Obviously, all you have to do is select Rule 1 for Block 1, and Rule 2 for Block 2.

Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


Change admin menu item How would I unset this menu item: Content > Add Content > Article

I would like to programmatically disable that path-page (node/add/article), or even better use that path for another page. I tried using hook_menu_alter(&$items). Does not work for that path, while on others custom menu items that I created using hook_menu it does work.

Update:
This is simple code that I tried (unset the $item key):

mymodule_hook_menu_alter(&$items) {
     unset($items['node/add/article'])
}

Admin menu is an yet another menu, which builds programmatically. So you can modify items using hooks registered for any menus.

If you would like to disallow atricle creation by specified role, just remove appropriate permission.

If this does not helps, look at admin_menu_menu_alter() and theme_admin_menu_links().


How can I add user information to orders administration pages? I'm using Commerce User Profile Pane to capture Drupal Users profile fields directly in the Commerce checkout pages : as I have several custom customer fields (birthday, passport number...), I found this more accurate than storing this data in Billing information.

How can I display the collected informations along with the billing information data (name, address), in the order view page : admin/commerce/orders/%, and in the quick edit view ?

I can't find any view or .tpl for such task.

As per Andy's advices about Drupal Theming, I used devel_themer, and could find immediately the correct template : commerce_backoffice/theme/commerce-order--backoffice.tpl.php.


Retrieve node information in VIEWS template(s) I have figured out I need to override two templates:

views-view-fields.tpl.php
views-view-unformatted.tpl.php

Basically my node has an "align" property which I need to access in both templates to properly generate the expected markup.

<?php echo '<pre>'; print_r(get_defined_vars()); exit; ?>

Using this I can see I have a monster of a structure at my disposal but the I am nervous about traversing such a structure as the slightest change to it's arrangment means my template(s) would break!!!

Ideally I would like to implement a preprocessor such as:

How can I add variables from a preprocessor function to be used in an unformatted view template?

Basically add the "align" value from the node to a simple variable which I can then access and check inside both templates listed above...

Suggestions???

You can use hook_preprocess(&$variables, $hook)to find out which hook you have to react on, in your case it should be hook_preprocess_views_view_fields() and hook_preprocess_views_view_unformatted().

Next you have to find a way to access the node object. If your view is node based, then there should be an nid somewhere in the variables array. Don't be afraid to dif into the $variables array. You can use dpm (devel module) or print_ror whatever you're comfortable with. You can't really break anything without manipulating the array.


Add values from feed into the users database table I am new in Drupal. I am currently building a stand alone website (non Drupal website) but want people to register through the custom form and all the users data to go into the Drupal's database.

So the admin can manage the users through Drupal admin.

I am initially thinking to use a custom form so users can insert the information and then store all the values in JSON file and then install a module in Drupal to get the JSON's information and then store them into the Drupal user's table.

I will really appreciate your support and suggestions.

Thanks.

Your best bet is to use HEADLESS Drupal. This means using Drupal as a backend, but with the front end being entirely separate to that. You do this by creating a REST server in Drupal, through which you can perform various actions, such as registering and logging in users.

If you are using (or will use) Drupal 7, a server can be created through the Services module. If you are doing it in Drupal 8, it is part of core.

You should set up your system to use OAuth2 authentication. This requires the OAuth2 server module, though I'm not sure what is necessary for Drupal 8.

With the REST server set up, you can create a form on whatever site you want, and you will then register the user through the REST server. Users can be authenticated (logged in) the same way.


Trouble with FieldItemList::view I have a custom content entity that renders fine in its page view and form. I'm now trying to view one of its fields in a table using an EntityListBuilder, but the following code throws an error message:

public function buildRow(EntityInterface $entity) {
  $row['id'] = $entity->id();
  $row['email'] = $entity->email->view();

  return $row + parent::buildRow($entity);
}

Results in:

  Fatal error: Call to undefined method
  Drupal\my_module\Entity\MyEntity::render() in
  /.../core/lib/Drupal/Core/Template/Attribute.php on line 294

Apparently the view builder expects a render() method, which I do not have, and which I do not want to implement, since the entity renders fine otherwise...

Also tried EntityViewBuilder::viewField() with no success.

Even when I'm viewing a node instead of my custom entity, I get the same message.

The function buildRow returns a render array. You can put simple strings directly in the array, because later it will be put in another html structure like a table. An example from core, where it is used both ways (CommentTypeListBuilder.php):

public function buildRow(EntityInterface $entity) {
    $row['type'] = $entity->label();
    $row['description']['data'] = ['#markup' => $entity->getDescription()];
    return $row + parent::buildRow($entity);
  }

So using the '#markup' element is optional. You can use it to be on the safe side, when you don't know how your render array is processed.

For complex elements you need a render element. The method view() would generates this:

$row['email'] = $entity->email->view();

But this does not work. The problem seems to be in the custom entity. According to the error message there is a call to an undefined method render, which should be defined in MyEntity. Your entity does not know how to handle the email field.

If you don't want to theme the field, you can use the value as markup:

$row['email']['#markup'] = $entity->email->value;

Or you can put the field as an object:

$row['email'] = $entity->email;

Or you can build your own render array, for example as a link:

$row['title'] = array(
      '#type' => 'link',
      '#title' => $entity->label(),
      '#url' => $uri,
    );


Theming forms : what am I doing wrong? I've got a simple form which I would like to run through a theme function of mine. What I do is that I've got a form builder function where I define the form. I've then used hook_theme() to define which theme function Drupal should use to theme the form.

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_form' => array(
      'render element' => 'form',
    ),
  );
}

Drupal does invoke the theme function. However, I've got a call to drupal_render($variables['form']) to actually render the form in my theme function. What happens then is that Drupal seems to go into a loop as this call results in mymodule_theme to be called again (and again, and again...).

function theme_mymodule_form($variables){

  // Add custom text on top.
  $output = '<span>' . t('Table description goes here') . '</span>';
  $output .= drupal_render($variables['form']);

  // Return output.
  return $output;

}

When I do a dump of $variables passed to my theme function, I see that #theme is set to 'mymodule_theme'. Should I at this point change it to 'form', and not 'mymodule_form' as I'd just like to render the form as a plain form? How should I really render the $variables'[form'] in my theme function to make it appear as a plain old form? Should I rather use theme('form', $variables['form']) for that?

As far as I understand, drupal_render($variables['form']) takes care of rendering the form and all its children, as opposed to to theme('form', $variables['form']) which only renders the immediate form and not children.

I'd be really happy if someone have the time to enlighten me on this :-)

In Drupal 7 you need to use drupal_render_children() instead of drupal_render() for the $form. Otherwise, if the form has the #theme property set you will get an infinite loop (as your theme function will invoke the form builder to run your theme function again, and the cycle will continue).


ckedittor automcalliy convert < When I copy a link and put into CKeditor (drupal)

After I switch back plain text it changed to be like this:

&lt;iframe width="420" height="315" src="//www.youtube.com/embed/q4Rgh5JNWf4" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;

How can I solve this?

First put your text format to Plain Text mode and then paste your <iframe> code on the editor, now you switch back to "Full HTML" or "Filtered HTML" mode (for which your text editor is set to display).

Hope this is what you are looking for. Hope this helps. :)


How to display the same node twice in one teaser? I added some new fields to Basic page:

teaser image
teaser title
teaser subtitle

Now I want to show 2 separate blocks in teaser that point to the same node (basic page). Is it even possible?

Example of teaser

Teaser block 1

title: Buy Acrobat
subtitle: View our software
image: acrobat.png

Teaser block 2

title: Buy InDesign
subtitle: Software for low prices
image: indesign.png

Both teasers should lead to the same basic page "Buy software".

Notice that teasers are displayed on home page (option "promote to front page") and taxonomy (View: Taxonomy).

There are a lot of ways you could accomplish that.

One way that seems to match your requirements is using the field collection module.

You could have a multiple value field collection field on your content type and that field collection could have your title, subtitle and image fields.

It depends somewhat on all your requirements though.

For example, this might work very well for your views (like the taxonomy one) if you want both blocks to show one after the other (since you have a view of nodes and these are both on the same node), but maybe it wouldn't be as good a solution if you wanted them spread out (in which case it might be better if they were 2 separate nodes).


Entity Print Module: Create PDF from HTML I´m trying to use the entity_print module for generating a PDF in Drupal 8.
I want to print out HTML. My module has no entities it gets data from a solr server and generates HTML output.

My first thing is to make a route and a sort of flag to fire the pdf generation:

mymodule.page_detail:
path: '/detail/{Title}/{ObjIdentifier}'
defaults:
_controller: '\Drupal\mymodule\Controller\myController::detailpage'
Title: ''
ObjIdentifier: ''
ViewPdf: '0'
...

mymodule.page_detail_pdf:
path: '/detail/pdf/{Title}/{ObjIdentifier}'
defaults:
_controller: '\Drupal\mymodule\Controller\myController::detailpage'
Title: ''
ObjIdentifier: ''
ViewPdf: '1'

...

Then in my Controller I check for

if (isset($myModuleViewPdf) && $myModuleViewPdf == "1") {
  ...

Now the entity Print magic should come into play.
I use the services and make a print engine and a print builder:

$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');
$print_builder = \Drupal::service('entity_print.print_builder');

Now I´m struggeling somehow. When I look over the functions docroot/modules/entity_print/src/PrintBuilder.php

I see that they are using entities for the output but I want to use HTML.
How can I do this?

Greetings
Lars

If you want to send the PDF directly to the user then you can do something like this:

// Get your HTML from Solr.
$html = $this->getHtmlFromSolr();

$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');

$print_engine->addPage($html);
$print_engine->send('mydocument.pdf');


Is possible to redirect all 404's to the front page? I use Drupal 8.2.3. Is it possible to redirect all the pages returning a 404 error to the front page?
I am not sure the new Drupal 8 Redirect module (that combines the Drupal 7 Global redirect module with the Drupal 7 Redirect module) would help me to achieve this exact task.

If you go to the Basic Site Settings (/admin/config/system/site-information) and enter in "/" for the default 404 (not found) page does that work for you?


How Can I change the machine name of product type How can I change the machine name of product type (in drupal commerce ) after it created and has several content , as example I has tv porduct type I want to change it to LCDTV , How can I change it?

You can alter the machine name through the database to change the product type. See table commerce_product_type and alter the 'type' column.

Make proper adjustments in commerce_product for products using the old type. You could execute something like the following SQL query

UPDATE commerce_product SET type = REPLACE(type, "tv", "lcdtv");

Be sure to test this on a local or development version of the site.

UPDATE: As mentioned by Clive, you also have to update field data/revision tables.

You'd want to run UPDATE field_table_name SET bundle = REPLACE(bundle, "tv", "lcdtv"); on any field_data_* or field_revision_* table that relates to your product type.


Why is my form handler not running? I've created a custom module which creates a form and shows it in a block but whenever I submit it, it just refreshes the page and doesn't seem to execute the submit handler at all.

I'm going crazy trying to get this to work.

I've stripped the code right back but it's still not working.

<?php

// declare block info
function paypoint_block_info() {
    $blocks['paypoint_block'] = array(
        'info' => t('Paypoint Payment Form'), // block admin title
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

// declare block functions
function paypoint_block_view($delta = '') {
    switch ($delta) {
        case 'paypoint_block':
            $block['content'] = drupal_get_form('paypoint_form');
            return $block;
            break;
    }

}

function paypoint_form($form, &$form_state) {
    $form['#attributes'] = array('class' => 'content-page-form');

    $form['strForename'] = array(
        '#type' => 'textfield', //you can find a list of available types in the form api
        '#title' => 'Forename',
        '#size' => 30,
        '#maxlength' => 37,
        '#required' => TRUE, //make this field required
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Make a payment'),
        '#attributes' => array('class' => array('btn', 'btn-default')),
    );

    return $form;
}

function paypoint_form_validate($form, &$form_state) {

}

function paypoint_form_submit($form, &$form_state) {
    drupal_set_message($form_state['values']['strForename']);
}

The validate function seems to get called, just not the submit one. I put print_r($form) in the validate function and got this: http://pastebin.com/Yt6T6Cr8

Your code looks fine to me. I think you might be on to something with your last comment, there might be something interfering with the hook.

One thing you might wanna do is run module_implements and look for the submit hook. That should give you a list of modules that implement that hook. At the very least you can check to see if there is anything strange going on with those modules.


How do I use an image as term reference in Drupal 7 and Commerce Kickstart? I want to display a list of fruits in flavours taxonomy. I can easily display the term as term reference but I want an image (specifically the taxonomy image) as the list and clicking the image of the taxonomy the main image of the product should change, i.e. when clicked in strawberry it should show up strawberry cake.

Its term reference is working perfectly fine but I just want the images in place of text.
I have done with color and it works fine.  In other words I need a solution for how to display taxonomy image in the same way as they display color in Commerce Kickstart.

[Acknowledgement: The solution given in comments to self by Saurav works.  Since Saurav hasn't been seen in nearly a year, and comments are ephemeral at SE, I've taken the liberty of expanding the solution suggested in these comments into a full answer, so that the question and answer shall not be deleted as "abandoned" as defined on SE.]

First, install and enable the Commerce Fancy Attributes module.

Then, follow the steps suggested under "Example usage" on the Commerce Fancy Attributes project page, but instead of adding a text field, add an image field for Vocabulary and add the image you want to display:

Create an Image vocabulary. Add an image field that shall hold the images you want to use.
Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the Image field (with the label hidden).
Create several terms with images associated. Use the image small icon size so that the display wont be distorted.
Add an Image taxonomy_term_reference field to a product type.
When you add the Image field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms". For the "Attribute selection widget", and choose the type "Rendered term".

Example:


How to display the views page title in a custom fieldable block Goal:
To create a custom fieldable block as available out of the box in D8, which also shows the page title of a a views page, if the page it is displayed on is a views page.

I created a custom block type, and added an image field for the block background.

I then copied and modified the block template to include:

{% if title %}
  <h1>{{ title }}</h1>
{% endif %}

But the views title does not show up. The page source shows nothing rendered. I enable theme debugging and the new block template is being used.

Views sets the title configured in a Views page statically in the route definition. Get this title from the current route in a preprocess hook for your specific block content UUID. Add a routecache context, so that the block changes the title when you visit different pages:

function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_content:12345678-1234-5678-90ab-1234567890ab') {
    $variables['title'] = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');
    $variables['#cache']['contexts'][] = 'route';
  }
}


Send out a unique (unprotected) link per user I'm the admin of a Drupal site with 200+ users. I sort of rolled into this, so I'm no Drupal expert, although I've managed to understand it quite good now.

This is a site for our sportsclub and we want all existing users to confirm their membership (of the club) for the coming season.

We would prefer to do this a simple as possible and send each user a link which, when clicked on, will confirm their renewal. Ideally, this is a link with some sort of unique hash, so we can make it unprotected. This would avoid having to log in.

We want to do this (keep it as simple as possible) because we've noticed a lot of members just don't do it (go to the site, log in, go to the correct page if not already there, and click the yes link to renew).

Is this possible (with a module perhaps)? Sending out a unique link per user?

I don't know of a single module to do this.

I would suggest looking at the VBO module (views bulk operations).

You can create an "email" action and customize what gets sent.

From your description I think the biggest barrier you're facing is that users don't want to login,  and you'd like them to just click a link.

To do that you're going to have to roll your own module and likely make use of a menu hook with a callback to a function that processes the link.


Specific lay-out for every content-type Is it possible to change the layout for a content type through CSS? How do I do it?

Based on the comment of the OP (Niels) I changed my answer:

Each content type page will have a different class (node-type-CONTENTTYPE) associated to the BODY element of your HTML.

So you can add to your CSS file:

body.node-type-mycontenttype1 img { border-color: red; }
body.node-type-mycontenttype2 img { border-color: yellow; }

Original answer:

Wich version of Drupal do you use?

For Drupal 7:

You can use a different template for each node of different content type by creating a template:

/site/all/themes/YOUR THEME/templates/node--CONTENTYPE.tpl.php

You can read on Template Suggestions to know which template you can create.

For the CSS, I suggest you to put everything in your main CSS file and not use a different CSS for each content type.


An Atomic Question about Views Modules and Templates I am a Views newbie. I added a template file to my sub-theme folder with a more specific name (from Theme Information), the file name becomes highlighted, but the file is not used (I'm sure of this cuz I wrote some new lines to the template (
Like, Doah!
, etc.).

Some extra details:

I am using fusion core with a fusion sub-theme (begot from fusion_starter). The fusion sub-theme is activated. I've not changed much.
The custom view is fully created, has a menu entry, and displays an end user content page with the correct data.
I currently have only two "views-view-*" template files between the directories containing the two fusion themes.

fusion_core/views-view--page.tpl.php (edits to this page ARE visible on the end user "content" page).
fusion_my_subtheme/views-view--my-view--default.tpl.php (the trouble file)

Click Theme: Information to find "views-view--my-view--default.tpl.php" is listed as the most specific file name available under Display output.
Theme Information highlights this template file name bold. And, when I renamed this file, the Theme Information display returned an error message that the file is missing--therefore I conclude the Drupal/Views app is finding this file.

Why, if this file name is highlighted, is this more specific template file located in my sub-theme directory not being used by Drupal?
Is it possible there is an order to cache clearing, or template refresh? I feel as though I'm trying to catch my tail... :/

If the file name is highlighted, changes are made to that custom file named, then Views Module and Drupal should render the page with changes made to this template--that's "How it works", yes?

Xtian

This is rather strange. The fact that the correct file name is highlighted in the Views theming information section suggests it's set up correctly. However, I'll add some more things to check and see where we end up.

You should also have the views-view--page.tpl.php file in your sub-theme's folder. Strictly speaking, anytime you are overriding a template file with a more specific template file, the default template file should reside in the same directory. So just copy views-view--page.tpl.php to your fusion_my_subtheme/ folder. Then clear your theme registry[1] and try again.

I would also suggest using the Devel Themer module to help figure this out. It will tell you for sure which template file is being used for the View's display.

I usually choose to clear ALL caches instead of just the theme registry. Occasionally I've seen strange problems disappear when I do this.


How to display only the years that have content in view filter? What I have done

I have created a view.
I have added a content type to display .
I have added a filter to filter by node date content and have opted to display the post date as year in the filter.

What I want actually

I wanted to display only the years that have content. I am using Drupal 7.

Which are the ways to do this?

If you go to views page (/admin/structure/views), you will find a view "Archive", you can clone it and use it, it will be displaying content month+year using contextual filter "Content: Created year + month", as you want to display only year, use contextual filter ""Content: Created year" and remove "Content: Created year + month".

Screenshot for contextual filter.

Screenshot of output.

It will list all the years that have content added.

Update

What you can do is to create a block of the view, and place it on the page you want, and then when you will click on an year, you can have the content list accordingly on the same page.


Display terms in relation to the terms of the page I created product sheets related to the terms of taxonomy. How to display a block of view, the products in relations with the currently visited page?
For example if my page is linked with the term "soap" requires that all products associated with the term "soap" appear in the block view.

I made a block view with a pop filter "tid" but I do not know how to parameterize.

version D7

1) Create a view of your products

2) Under Advanced, add a RELATIONSHIP of Taxonomy terms on node

Checkmark ☑ require relationship

3) Add a CONTEXTUAL Filter of Has taxonomy term ID

Select provide default value
Select Taxonomy term ID from URL
Checkmark ☑ load default filter from node page


How to remove height and width attributes from CCK ImageField tags? I am using Drupal 6 with the CCK ImageField module.  By default, it outputs the height and width of the image as attributes of the tag. For my current project, I'd like to be able to override those with CSS. I have not been able to determine which theme function adds those attributes.

Which functions/templates do I need to override to remove those tags?

The attributes are there for browser performance reasons. Overriding them with CSS is still possible. If you want to specify the width, set the height to auto, or vice-versa.


Create new node and assign it to user after they have been registered I have one user role on d8 and have few additional fields on user account so when people are registering they can leave additional data. What I would like to achieve is that when user registers - new content of that specific type would be automatically created (node), assigned to him and the fields on that new content would be populated from those fields on user account which he filled during the registration process.
I was thinking that this is maybe achievable with the Rules but since couldn't find proper documentation for Rules in d8 not sure is this is doable that way.

This is very easy to do in D8 Rules. Here is an export of a Rule which does what you asked - when a new user is created, it creates a new node (of type article, as an example). It then sets the node author to be the new user. It then sets a field of the new node (the body field, in this case) to a value take from the user (the user's email address, in this case). As you can see, Rules are stored in YAML files, and are imported/exported like any other configuration in D8. So you can just import this and you will immediately have a working example which you can then modify to use the specific fields you've defined on your user entity and node type. This Rule additionally displays a system message, which is a very useful way to debug Rules.

langcode: en
status: true
dependencies: {  }
id: create_a_node_for_each_new_user
label: 'Create a node for each new user'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Node fields will be populated from values entered on the user form.'
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: c9428f2d-c0b9-47bf-a7e5-3f2cc8af9f54
  conditions:
    id: rules_and
    uuid: 47b8d622-ed38-4977-8e58-4cca6d89260a
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: d96fd6b5-1638-4b15-adde-5f5d7673fb8f
    actions:
      -
        id: rules_action
        uuid: e09cd52d-76fe-4682-91de-bfed58a651ab
        context_values:
          message: 'Node created using information entered by <em>{{ user.name }}</em> when registering'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: fe2acb55-9234-4754-9d2b-3d1889d1775c
        context_values:
          type: article
          title: 'Article created by Rules for {{ user.name }}'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: 743be03f-d1b7-4251-a1ac-80b17aa5c86e
        context_values:
          value: '{{ user.mail.value }}'
        context_mapping:
          data: entity.body
        context_processors:
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 91f3c8f2-eb47-46e6-a9dd-2affc90e15d2
        context_values: {  }
        context_mapping:
          data: entity.uid.target_id
          value: user.uid.value
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set


How to use a standalone page with a module I'm working on a website that communicates with a bank API.
During the process, the API sends a request to a callback page. I, therefore, created a "callback_bank.php" file, and put it at the root of the drupal folder (along with index.php, cron.php, etc.) so it's accessible by http://www.mywebsite.com/callback_bank.php

How would I go about packaging/deploying that file with the custom module I created, that does the rest of the work ?

Thank you!

Assuming the return path is configurable with the bank, you'd be better to create a hook_menu callback to handle the bank response.

That way you can leverage the Drupal API, e.g access callback to restrict to their IP address range to prevent spoofing etc..

e.g:

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

  $items['payment/callback'] = array(
    'title' => 'Payment callback',
    'page callback' => 'MYMODULE_payment_callback_handler',
    'access callback' => 'MYMODULE_payment_callback_access',
    'type' => MENU_CALLBACK,
    'file' => 'MYMODULE.pages.inc',
  );

  return $items;
}

The bank can then request https://www.yoursite.com/payment/callback?param1=foo&param2=bar


Hooking into an update of the db system table Essentially I want to be able to monitor all updates to the db system table, by catching all updates to the db system table (for a particular theme's record). We have encountered some odd bugs whereby all themes are periodically (and apparently randomly) disabled, and I need to be able to log further information whenever this theme is disabled. What is the best way to approach this?

Alternatively is there a way to hook into the function for whenever a theme is enabled/disabled?

You should be able to use hook_themes_disabled().

The following code in a module will put themes being disabled into the Drupal logs:

function MYMODULE_themes_disabled($theme_list) {
  foreach ($theme_list as $key => $themename) {
    watchdog('MYMODULE', '%themename was disabled.', array('%themename' => $themename), WATCHDOG_NOTICE);
  }
}

EDIT:  Forgot to mention this, but hook_themes_enabled() is used in exactly the same way, so you could easily just modify the hook above to check when a theme is enabled.


Apache Solr Search proper syntax in url? Can anyone provide some info on how to properly execute a filtered apache sold search through the url?  So far I've figured out that

?fq[]=bundle:type

will return a results filtered by that bundle type.  I've also noticed that

?f[0]=machine_name:value

will return results if that particular facet has been configured.  What I want to figure out, though, is how to use the url to send any filter request.  For example, if I want to write a url that would return results based on a particular taxonomy term, how would I enter that?  Furthermore, can any field be used to filter a search?

You should integrate Updated Apachesolr module.
Write some custom menu hook to invoke your custom function.

 $query = apachesolr_current_query();
 $params_query = $query->getParams();

The above two statements will help us to check our solr queryString that we have triggered from our application.

/**
 * Implementation of hook_search_execute().
 */
function Custom_Function($keys = NULL, $conditions = NULL) {

  $filters = isset($conditions['fq']) ? $conditions['fq'] : array();
  $solrsort = isset($_GET['solrsort']) ? $_GET['solrsort'] : '';

  $response = NULL;
    $filt = array();
  // add custom filters if you want to add few custom filters in certain conditions.
   if($_GET['some key'] == 'some condition') {
        $filt[] = array('name' => 'entity_type', 'value' => 'trend_tips');
      }else{
        $filt[] = array('name' => 'im_16_field_category', 'value' => $_GET['category']);
      }
  $filters = $filt;
  $results = apachesolr_search_run('apachesolr', array('q' => $keys, 'fq' => $filters), $solrsort, 'search/' . arg(1), pager_find_page());

    // Set name for search results
    $query = apachesolr_current_query();

    $params_query = $query->getParams();

    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
 }
/**
 * Implementation of hook_apachesolr_query_prepare().
 */
function CustomeModule_apachesolr_query_prepare(&$current_query) {

  // add query filters for Style tips and trends
  $current_query->addParam('fl', 'tm_image,tm_url,content');
  $current_query->addParam('qf', 'tm_title');
  $current_query->addParam('qf', 'tm_short_content');
  $current_query->addParam('qf', 'tm_perex');
  $current_query->addParam('mm', '1<-90%'); // if you write more then 1 word to search, solr search as 'OR'
  $current_query->addParam('bf', 'recip(rord(created),4,5759,5759)^5.0'); // remove time dependency on search results

  // remove following content types (product and page) from search
    $current_query->addFilter('entity_type', 'product', true);
    $current_query->addFilter('bundle', 'page', true);
    $current_query->addFilter('tid', "63", true);
    $current_query->addFilter('tid', "64", true);

  $current_query->addParam('facet.field', 'bundle');
  // add a new facet type for filter trends and tips on search results

}

Please let me know if the above codebase helped to get some grip.

Thanks


What are methods for tracking discussions or issues on Drupal.org On Drupal.org, there are a number of discussions or issues that I subscribe to and wish to track. Do folks use any particular method to receive push updates or alerts when replies are added to threads?

Is typing in "subscribe" still the only method for tracking discussions?

I dislike having to "check" on webpages to be notified of updates. I'm more of an RSS and Google Reader tracker.

Thankfully, the "+1 subscribe" phenomenon is dead: you can now track issues without commenting. To track an issue, you can just click the giant "Follow" button now available in the sidebar:

Followed issues will show up on your Drupal.org account under Your Posts.

If you want to track all the issues for a project, there are a few additional options:

You can subscribe by e-mail by going to a project page and clicking on Subscribe via e-mail under the Issues for PROJECT heading.
You can subscribe to an RSS feed if you go to the issue list for the project and click the link at the bottom of the list (but your reader should also autodiscover the feed).


Redirect user to dynamic url I am writing a custom rule, I do not know how to approach getting the correct URL for the redirect.

I have a page - website.com/content/newsletter-activity-001 that needs to redirect an anonymous user to website.com/content/activity-001 until they are logged in.

I have a reference field in 'newsletter-activity-001' that holds the title to 'activity-001'. I want to write a rule that will apply this for newsletter-activity-002 and so on as the site content grows.

How do I dynamically pull that url out and place it into the redirect path? Would tokens do it?

The tokens [site:current-page:path] & [site:current-page:url] will retrieve the current Drupal path & the full URL, respectively.


Add a prefix to all path with hook_url_outbound_alter and/or hook_url_inbound_alter I'm trying to add a prefix to all path aliases, without changing the URL's destinations (internal path) of my website.

I'm setting a $_SESSION var with hook_init() when a visitor arrive on the website. This $_SESSION var is determined by the incoming URL of the visitor.

The website is should be accessible by different URL like:

http://www.mydomain.com/ (default)
http://www.mydomain.com/thisevent
http://www.mydomain.com/whatevent ...

So if the $_SESSION var is "thisevent", I'd like to change all default path like this:

http://www.mydomain.com/some-page into
http://www.mydomain.com/thisevent/some-page
http://www.mydomain.com/another-page into
http://www.mydomain.com/thisevent/another-page ...

I think this could be done with hook_url_outbound_alter() and/or hook_url_inbound_alter() but I can find any clear examples to implement my goal.
I found this post but the author didn't post his solution.

Any help appreciate.
Thanks

I finally made it but not without the help of a sympathetic module: PURL.

And here's my final solution:

Create a custom module
In the mymodule.module file create 3 functions:

/**
 * Implements hook_purl_provider
 */
function mymodule_purl_provider() {
  return array(
    'mymodule_provider' => array(
      'name' => t('My module provider'),
      'description' => t('Sets a prefix for URL.'),
      'callback' => '_mymodule_prefix',//I didn't really use this callback and I don't really know how to :-)
      'example' => 'my-prefix',//anything you want. only for UI I think
    ),
  );
}

function mymodule_purl_modifiers() {

  $mymodule_events = _get_all_events();//custom function to get some data

  foreach ($mymodule_events as $kid => $e) {
    $modtab['mymodule_provider'][] = array('value' => $e['alias'], 'id' => $e['nid']);//this array must be structured like this!
  }
  return $modtab;
}

function _mymodule_prefix(){
  $event = _get_one_event();//custom function

  if ($event) return true;
}

then you can go in /admin/config/search/purl to configure PURL with your data you've just created with mymodule.

In /admin/config/search/purl/types you select the type you need (I checked only "Path")
In /admin/config/search/purl/list you should see your modifiers you've created with mymodule.
And in /admin/config/search/purl you can select witch type you use for your provider

I am a bit sad because I didn't manage to use the 2 hooks (like purl does :-) but the good news is that "it works"

Cheers.


A contributed module without an issue tracker on Drupal.org? The project page for the RNG - Events and Registrations module doesn't seem to have the typical block (column right) with title "Issues for moduleX" (similar to the block for pretty much any other moduleY on Drupal.org). Not sure if there are other modules for which this block is missing also.

Instead its project page does include some links to other sites (though not for "documentation requests" ...), i.e.:

Bug reports and feature requests.
Support requests.

What happened to this module's issue queue on Drupal.org?

It seems that within the edit section of any project page (which is available to e.g. the project maintainer), inside the Issues tab, there is a checkbox with label Enable issue tracker.

By default, this checkbox is enabled. But if you disable it, the block (column right) with title "Issues for moduleX" is not shown anymore.

And if you re-enable that checkbox again, the block is also shown again ... And the issues that existed before the block is disabled, seem to still exist. So unchecking that checkbox does not delete all existing issues (as it should be I think).


Render Twig template as XML I want to send an XML mail using Drupal's mailManager.

I have created a custom twig template in my module that will the the mail body.

Here's what my template looks like, my-module-xml-mail.html.twig:

<record>
  <name>{{ name }}</name>
  <phone>{{ phone }}</phone>
  <email>{{ email }}</email>
</record>

And my template definition:

function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module_xml_mail' => [
      'variables' => [
        'name' => NULL,
        'phone' => NULL,
        'email' => NULL,
      ]
    ]
  ];
}

And where I send the mail:

$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => $rendered,
]);

The problem is that when the mail is sent all the XML tags are stripped and only the values from the tags are sent.

How can I send the XML as plain text?

I thought about creating a my-module-xml-mail.xml.twig if that's possible, but when "kinting" the result from the renderer service it looks like renderer is not stripping any tags.

Do I need to send any headers to the mail, in order to send the XML as plain text?

I found a solution myself.

The problem is that Drupal's mail system converts HTML to plain text, and therefore strips all HTML tags.

A workaround to this is to replace all < and > characters with their unicode string and send the mail as text/plain.

I did like this:

$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => str_replace(['<', '>'], ['&#60;', '&#62;'], $rendered->__toString()),
]);


How to limit form submission per user per day and week? The goal is very straightforward. I need a form to limit each user to 1 submission per day and 3 per week.

What I found:

Webform:
The "Form settings" in webform has the "Per user submission limit" setting. It does not allow me to make more than 1 validation. I'm not able to have both per day and per week in the same form.

Entityform:
I found people use hook function on node limit on Drupal 8. This may work on Drupal 7 Entityform but I don't know how to write that syntax.

Rule:
It may possible to use Rule module but I don't see any connection with period of time validation.

//////
PS: My question is about the limit on Webform(or Entityform) submission for authenticated users.

Make a custom module to implement hook_node_access, i will post some code based on a user date field that compares 'today' with this user-date-field and return access deny if dates comparison goes beyond 'today', and another with today+7 days, you will have to adapt this code to your needs; please add in user profile a date field, this field it has to be updated by rules every time a user adds content of your 'special content-type', maybe you will need 2 user-date-fiels, one for each 'special-contentype' if you need help with this last comment please ask.

// replace HOOK with yourmodulename and field machine names
function HOOK_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  global $user;

  // check if not anonymous
  if($user->uid!=0){

    //check if not administrator role, admin will have allways access
    $user_role = '';
    if (in_array('administrator', $user->roles)) {
      // do fancy stuff
      $user_role = 'administrator';
    }

    if (!$user_role == 'administrator') {

      $user_logged = user_load($user->uid);
      $user_date_field = $user_logged->YOUR_USER_DATE_FIELD[LANGUAGE_NONE][0]['value'];

      // today date in UNIX date stamp
      $today_int = date('U');

      // your user_date_field in UNIX time stamp
      $date_int = (int)strtotime($user_date_field);

      // check if 'today' is > than user_date_field
      $diff = $date_int - $today_int;
      $diff = round($diff/86400); // diff in days betwen 2 dates

      // today comparison
      if ($diff >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }

      //  1 week comparison
      $diff7 = $diff + 7;

      if ($diff7 >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today +7 days' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME_7') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }
    }
 }
}

NOTE, if you do not want to add fields to user profile form, it could be done by adding variables to logged-user by HOOK_entity_property_info_alter(&$info), if this is needed please ask.

EDIT:

please specyfy in your question that is about webforms, so, above code do not apply, i'll leave it, could be usefull for someone else.

what you can do is still keep 'user_date_field', install the following mudules: flags, rules and panels.

I will explain only ‘today’ settings, same thing for ‘1 week settings’, only in this last case you will need another field (or user-variable) to store how many webforms has submitted this user in current week.

Steps:

• enable rules, rules scheduler, flag & panels modules.

• make a user flag ‘user-posted-a-webform’

• in rules:

• make a component, unflag current user (it will be invoked later).

• make a rule, flag user when submit a webform, update 'user_date_field' with site-current-date

• in panels make a page and add your webform, add a rule (inside panles content section) make it visible only if user is NOT flagged.

• Return to your rule, add an action “schedule component evaluation”, choose your component, inside action setting, on ‘scheduled evaluation date’ enter ‘+1 day’.

• Done

COMPONENT unflag-user


Imported blogs not showing up under proper tab In using Acquia/Drupal Commons and the Feeds module, we have successfully pulled in a few WordPress feeds. While the Organic Group is assigned and the newly created feeds appear in the OG's Home tab, they do not show up under the blog tag until I visit each one, click the edit tab, and then click save.

Given that, I assume I haven't mapped something that the group_tab_blogs View is searching on.

Additionally, if I copy the Query produced from group_tab_blogs live preview, copy it into a mysql client, and run, the results do show up. So that leads me to believe that it's something in the view filters.

Current Mapping between Source (Feed node) and Target (Blog node):

Current group_tab_blogs settings:

Update:

I can fix this by a manual running the query below. Once we set the field field_group_sticky_value of from table content_field_group_sticky to 'Not Sticky' it is now showing up.

 update content_field_group_sticky set field_group_sticky_value='Not Sticky';

However, I can't just map target fields Sticky and Group Sticky to just any value. I've already tried Published Date. So now I either need to run the above query on a trigger or adjust the view.

Well, that query list above was the key. So I just threw it into a module cron. When feeds are imported on each cron run, this query runs and corrects the null value in the table.

function hook_cron() {
      db_query("update content_field_group_sticky set field_group_sticky_value='Not Sticky' where field_group_sticky_value is null");
}


How should I link (public) files to nodes? I have many resources (mainly PDFs) that need to be imported to my site.  Previously the files would manually be placed in sites/default/files/mydir and linked to the node like this:

Read More

This does work, but I am guessing there are probably strong advantages to actually using the content system - perhaps being able to better organize/track/update files.

How do I place files inside of nodes so the file still appears inline with the rest of the content, while actually being tracked by Drupal?

UPDATE: I missed the 8 tag

Drupal 8.x

UPDATE 2:

So this got trickier. The only way I was able to accomplish it was using these steps:

Add a field to the node, I called mine "Media"
Instead of selecting "File" from the dropdown list, I selected "Other" under reference, and "File" on the next page, this creates an entity reference field rather than a file field.
Add a file through file/add
In your node, start typing the filename of the file you've added
In the body field, enter this token: [node:field_media-formatted:0:entity_reference_entity_view:default]

The token inserts the rendered entity for the reference field into your content, you can edit how it looks (for images e.g.) through the display settings for file types (May require the File Entity module), so you can display a link rather than a rendered file.

Someone pointed out in a thread I saw a couple of months ago:

  Drupal 8 is stable with exactly 0 contributed modules installed

That said, moving to Drupal 8 with requirements that fall outside of the scope of core may be premature for someone who isn't prepared to develop their own solutions yet, and this particular solution may change since parts of it rely on contributed modules.

Hopefully this will be an appropriate answer in the future

Very similar to how it would be handled in Drupal 7, but because of module availability there are some tweaks. The modules you would need are Token, Token Filter, and File Entity Browser.

The steps are the same as below essentially, but I think the token may use the underscore instead of a dash: [node:field_files:0:url].

Also, once the Token module is installed you can see a list of tokens at admin/help/token.

Drupal 7.x

There are several mechanisms available to achieve this. If you are using a wysiwyg editor (such as CKEditor), they sometimes have plugins available to allow you to add files directly into the content, but based on what you've stated you need, I think possibly the Media, Token, and Token Insert modules would be a good place to start.

The media module provides a file browser and upload mechanism that works with the core Drupal file system, making it possible to reuse files easily in different pieces of content.

The Token module extends Drupal's core token mechanism, and the Token Insert module allows you to use tokens in text fields.

The basic steps would go something like this:

Install all 3 modules, make sure you have the core File module enabled.
Go to the "Manage Fields" page for the content type you plan to use these files in and add a "files" field.
Add the files that would be used in your article to the files field, either through uploading or using the file browser.
Reference the files by index in a token in the text field, a list of available tokens are available here.

This is untested so may require some tweaking, but if the machine name for your file field is "field_files", the link in the text area would probably look something like this:

Read More

That would print the link for the first file that is attached to the node.

There will, of course, be some configuration pages you will have to go through for the media module and field settings, but it's hard to give you any direction on those since they are all very much dependent on your particular installation.


How to access a remote site using the command line (with drush)? I don´t know how to use drush nor the command line, so I´ve started to read some tutorials, and watch some videos. I´ve installed the drush windows installer, because I have windows.

The thing is that all examples I´ve read so far, start with localhost. What if I have my devel installation in a shared hosting or a VPS, in the cloud? How to access that?

Using my ftp program, I access it using hostname ftp.mysite.com the username and the password to that account. How may I do that with the command line?

Thanks!

go into your drush folder
Copy the file examples/example.aliases.drushrc.php to root of your drush folder and rename it to aliases.drushrc.php
Read the comments in that file and this slideshare
create your aliases for both the local site and development site (on shared or vps)
make sure you have a proper ssh connection setup to your remote server


Create bundles programmatically using ECK (Entity Construction Kit) The ECK module allows users to create custom entities.

When using this modules UI it is possible to create an entity type, and then attach multiple bundles to the entity.

It is also possible to create new entity types via code. This page shows an example which is as follows:

$entity_type =  new EntityType();
$entity_type->name = "eck_employee";
$entity_type->label = "Employee";
// Following line is taken from the eck_example.install file
$entity_type->addProperty('name', 'Name', 'text');
$entity_type->save();

This doesn't however show how to create and attach bundles.

Is it possible to attach bundles to entities when creating them via code (using ECK)?

I just found a blog article here which gives an example on how to do exactly this:

After creating the entity type with the example code I gave in the question a bundle can be created as simply as this:

$entity_type_bundle = new Bundle();
$entity_type_bundle->name = 'eck_employee';
$entity_type_bundle->entity_type = 'eck_employee';
$entity_type_bundle->save();


CSS or and JS aggregations all makes site slower! It is well known among Drupalists that generally, Aggregation of CSS\JS files should hasten webpage loading times in Drupal... So why the opposite is true for my site this time?

PSI test score for my Drupal 7.37 site after No Aggregation whatsoever: 72/100
PSI test score with CSS aggregation only: 59/100
PSI test score with JS Aggregation only: 70/100
PSI test score with Both file types
aggregation: 67/100

Bottom line: the natural aggregation options do the opposite of their inherit aim --- They are slowing my site instead of hasting it! Any reasons you could suggest for such wired behavior? Thx.

You're confusing PSI and webpage loading times; they are not the same thing.

PSI is series of benchmarks for optimizing performance. It's a checklist Google provides to give you suggestion for improving performance. It doesn't gauge what your site's actual speed is. Use your browser's network activity inspector if you'd like to analyze site load times against CSS/JS aggregation.


First display promotions in a view I use the "discount" module, I created a view to display my products but I can not find how to display the products on sale first in my view

Hi checkout you view setting
like this http://prntscr.com/bscbkf
then add filter on it
http://prntscr.com/bscc0e
now you can see result
http://prntscr.com/bsccbh
Also explain some more details


Redirect from edit page and prepopulate form I would like to redirect user from node edit page to node add page but with prepopulated form. So all fields of the form would be pre-filled with copies of values of node edited before. Is there a way how to get these values and fill them in the form?

You can try using Node Clone module...

Project page says

  The module provides two mechanisms to clone current content. The
  default pre-populates the form for adding a new node, but nothing is
  saved to the DB until that form is submitted. With the alternative
  save/edit method, a copy of the current node is saved to the DB, and
  then presented in the edit form. When using the save/edit mode, the
  admin can set whether a confirmation screen is required, and in all
  cases you can set whether to reset the publishing options on a
  per-content-type basis.


What can I do to improve the size of csv file that can successfully be imported via Feeds and Commerce Feeds I am using Feeds and Commerce Feeds to import product lists into my Drupal Commerce store.
I'm finding I have to keep the csv files really small for the import to succeed? As soon as the file is too big (the exact threshold size does not seem to be consistent) the system generates a 403 error as follows:

An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /batch?id=260&op=do StatusText: Forbidden ResponseText: Access denied

The file that resulted in this error was 577kB.

The only way around the problem is to have multiple csv files. These all have to be maintained and updated individually, which is very inefficient.

What can I do to improve this state of affairs?

The 403 HTTP code translates to access denied, which doesn't points to a problem in the size of the CSV file. Since it's using the batch API, which splits up the job in smaller chunks, it doesn't look like that it is the size of the file that is the problem. You should investigate the watchdog (dblog) and see if you can find the root cause.

This is the best answer I can provide with this limited information.


Incorrect branch when adding modules with composer Edit: Gist of my complete composer.json

I'm seeing some confusing behaviour with Drupal branch names when adding modules using composer - specifically I seem to be getting the 7.x version of the module rather than 8.x.

This is a composer based setup, running 8.3.0-rc1 - composer.json includes:

"drupal/core": "8.3.0-rc1"

My understanding has always been that for modules, whenever you specify the branch in composer, you remove the 7.x- or 8.x from the start.

e.g. I wanted the tagclouds module 8.x-1.x branch, so I did:

composer require drupal/tagclouds:1.x

Yet what it actually installs is 7.x-1.9+30-dev

Composer output:

 - Installing drupal/tagclouds (dev-1.x 54086ae) Cloning 54086ae717

I also ran drush ups and got:

  Project was not packaged by drupal.org but obtained from git. You need
  to enable git_deploy module

So I add and enable git_deploy the same way.

composer.json:

"drupal/git_deploy": "2.x"

again it installs a 7.x release (7.x-2.2+10-dev)

Any obvious mistakes?

Other things I've tried:

Explicility listing the stability in the version constraints, e.g. 2.x-dev instead of 2.x, and 1.x-dev not `1.x'. (The documentation suggests composer adds this by default though.)
Using composer update nothing to regenerate the composer.lock file

Make sure you are using the correct repository endpoint for Composer. For Drupal 8, it is https://packages.drupal.org/8.

Your composer.json file should contain a repository key like so:

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


Staging process -- how NOT to overwrite user content/data @ DB push to Production site? I've finally gotten my Drupal7 Development->Staging->Production file & db syncing all working nicely using a mix of rsync, rsyncd, git &, where it doesn't cause more/unnecessary work for me, drush.

Not the cleanest approach, but all working quite nicely.

Until i realized ...

a DB push from Staging->Production that contains changes I've made & QA'd @ my Staging site (for modules, site config, etc), will overwrite any/all user data/content @ the Production site. Unless, of course, I specifically identify & exclude the tables that contain data/content -- and simply don't inclue them in the push.

My question is -- other than manually checking -- is there a reliable method (a pre-existing static list?  a sql query on table names? something?) to know those tables to exlude?

This

How to migrate from test environment to production environment?
How to migrate from test environment to production environment?

in addition to countless other threads I have found, mentions "Features" and "Deploy", and basically says "it's hard".  If the answer's "in there", I haven't wrapped my head around it yet.

Again, I've got the mechanics working as I want them.  This last step is identifying -- and voiding overwrite of! -- the user content/data at the Production site.

This is a big architectural issue and as answers to the other question says: UUIDs in core in D8 will be a big improvement. They'll give all content a unique ID (independent of the content id in the database), and so if you make important modifications to content in some staging phase, the software could reconcile which content is worth transferring.

There's a UUID project for Drupal 7, which I believe Deploy module can use in this way.

  The integration with Services module alters all UUID enabled entity
  resources (nodes, users, taxonomies etc) to be based on UUIDs instead.
  This way it becomes easier to share and integrate content between
  sites. This functionality is used by Deploy module.


Drupal 7: How can I get path for node or term in drupal with php code? I must build a block that retrieves children of a specific term id by selecting it through $node->title of a page.
So, I get it with taxonomy_get_termBy_name.
With this $term->tid I can get children of it by calling taxonomy_get_children().
Ok, it returns an array of children.
For each child I must take name and path in order to build an .
How can i retrieve these properties?
I am unable to find a module that performs these operations, so I must build my own block.

You can use the l() function to do this.

Example:

$link = l('Link Title', 'node/' . $node_id);
$link = l('Link Title', 'taxonomy/term/' . $term_id);


drupal commerce no. sold per product I want to create a rule based on the number of sales per product. Is there a data selector to get the number of sales per product? If anyone can point me in the right direction, I will be very grateful!

I don't think you'll find that particular condition out of the box. Conditions for rules are pretty easy to write though, check Commerce Conditions for some easy to follow examples.


Share data from view How can I share data from a view to an excel file. I just need a report.

Or can anyone suggest a solution from which I can extract the data from a view?

I think Views data export module is what you need.