Modal Bootstrap in page.tpl.php Have been struggling with view and modal to display related node content for a few days, but in vain.

In view, a page is to display / list only thumbnail images (Display Suite) with rewritten link to trigger the modal with data-target. Then bootstrap modal code is placed in page.tpl.php.

So on view page, on click the thumbnail, the modal shows up. The problem is how to display title, body and images? Tried <?php print $node->title; ?> but when refreshing the view page, it shows blank page.

Is it not possible to display related node content of the thumbnail on modal?

Have tried Bootstrap modal and JQuery Ajax Load but they don't work at all. Documentation isn't clear either.

Help very much appreciated

If you want to show your node in a modal, a simpler approach would be to use the Colorbox and the Colorbox node modules (the last one has Views integration).

So after installing both modules, go to your View; in your Fields, when you click on any of them, you will see that the option "Link this field to the original piece of content" now has another one that says "Display the content inside of a colorbox". Check it, and it will make your nodes open in a modal window (colorbox).


Which hook for code after a node has been deleted from the DB? I'm running Drupal 7 and I want to re-save the user account of the node author after deleting a node of content type picture.  I want to do this because I have some code called in hook_user_presave() that counts the number of pictures a user has added and saves it in an integer field in the user.

I looked at hook_node_delete() and hook_entity_delete() as suggested in this question, but when then are invoked, the node is not yet deleted, so if I save the user at that point, the int value is one more than it should be (because the deleted file has not actually been deleted yet).

Is there a hook for responding to node deletion after it has taken place?

Related question: Hook for reacting after adding node

There isn't one. If you look at node_delete_multiple(), which node_delete is a wrapper function for, you can see that the only hook invocations (the above hooks) are triggered before the DB delete statements.

If your Drupal site only allows deleting through the node/$nid/delete form, one alternative to a post-delete hook is appending a submission handler to the node deletion confirmation form:

function MYMODULE_form_node_delete_confirm_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_node_delete_confirm_submit';
}

function MYMODULE_node_delete_confirm_submit($form, &$form_state) {
  //@TODO: Post-node-delete code here
}


manually adding terms to nodes directly from db I have lots of nodes in my system. I want to add them some taxonomy terms.

I have a CSV file for each term, and in this file I have the list of node id's. Example:

apples.csv:

5
9
12
24
....
....

SO I need node 5, 9, 12 and 24 to have the term "apples".

I wrote a php script to directly add that term to each of the nodes. That script populates the table "field_data_field_category" correctly.

I can also see the term on the node page.

The problem is the nodes dont appear in the term page. Also if I create a view to display nodes of specific term, it becomes empty.

Is there another table to keep the node - term relationship?

EDIT:

I just found that there is another table keeping the relationship between node and term: taxonomy_index: "Maintains denormalized information about node/term..."

How does this table populated? On a cron run? Because I see some of my node - term pairs there. Some not.

You may use the Feeds module to update all your nodes with new terms.


How to list all available entity types? How to list all available entity types in Drupal using drush?

Related:

How to get list of all node types?

Drupal 7

drush eval "print_r(array_keys(entity_get_info()));"

Drupal 8

drush eval "print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));"

as per Jason suggestion,

or:

drush eval "print_r(array_keys(\Drupal::entityManager()->getDefinitions()));"

as per @RaisinBranCrunch suggestion. Note \Drupal::entityManager() is being deprecated in 8.x.


How to make the commerce_kickstart distribution fully multilingual? I just downloaded and installed the Commerce Kickstart 7.x-2.0-rc1 distribution.

Now I'm in the process of making it fully multilingual. I have no problem with the products.

But I don't know how the make multilingual the Search blocks (Facet) which you can see in the left sidebar in this demo. I already enable the taxonomy_translation module, then I'm able to translate the terms used by the facet. But if I switch languages the facet shows all terms regardless the language the term is in. I also enabled the facetapi_i18n but I see no changes at all.

Any suggestions about how to do this?

You'll want to look at these two different resources:

Configure entity translation for Drupal Commerce

and

Search API Entity Translation


Translate Entity Permission per Content Type I'm using Entity Translation and I have a user role that should be able to translate nodes of type article but no other content types:

User A should see the Tabs "View, Edit and Translate" for a node of type article but not on node of type "company".

Within the permissions there is only allow translation or not at all. How can I do this? Right now I'm hiding the tabs in my page.tpl if the content type is "article" and the user role fits, but that is not the same as revoking the permission.

It won't be possible unless you write the code yourself or find someone willing to code it.

This feature request is now Closed (won't fix)


How many libraries is too much before there is a performance issue? We are using Paragraphs module to allow for selecting of up to 15 different Paragraph Types. As part of this, each one requires its own CSS and JS since they are vastly different. We already have a common set of CSS and JS that can be shared (25% overall), but there is a large percentage (75%) that is unique to each Paragraph Type.

We were able to combine lots of the CSS and JS, which resulted in the creation of 10 libraries and 1 general library to help with the management of these types. We are concerned that if we add more Paragraph Types the number of libraries could increase to anywhere between 20-30 as newer Paragraph Types are needed.

How many libraries is too much for a custom subtheme before it cause a performance issue (if any)?

Since there is no extra preprocessing needed per Paragraph Type, we simply add them using the {{ attach_library('mytheme/name') }} in twig templates. The only hook that is used is the one to add the general library.

mytheme is a subtheme and is set as default and enabled

Examples:

paragraph--carousel.html.twig

{# this is the paragraph type specific library #}
{{ attach_library('mytheme/carousel') }}

 {{ content.field_title }}

 {{ content.field_sub_title }}

 {{ content.field_description }}

 {{ content.field_image }}

paragraph--jump-menu.html.twig

{# this is the paragraph type specific library #}
{{ attach_library('mytheme/jump-menu') }}

 {{ content.field_title }}

mytheme.module

function mytheme_preprocess_paragraph(&$variables) {
  // Add general library for paragraphs.
  $variables['#attached']['library'][] = 'mytheme/global';
}

In Drupal, the best way to do your CSS is to keep it componentalized, and attach the CSS using #attached directly to the item to which it belongs. This way, the CSS is only ever attached when needed, and if a user overrides the render array further down the pipeline, removing the element to which the assets are attached, the assets will not be attached to the page, including unnecessary CSS.

Then you turn on CSS aggregation (or even better, use the ADVAGG module), and Drupal will handle the heavy lifting, aggregating the files as needed for the page.

So the answer to your question is that there aren't too many libraries. What is more important is effective management of the CSS/JS you are attaching.


How to change the position of a block in a particular page? I have a Drupal's default User Login block in Side bar first region at the last position. Reference page: http://indiansnakes.org/snakes

The proposed home page has been redesigned and the User Login block has to be displayed in the Footer Fourth region. Reference Page: http://indiansnakes.org/homepage

So, the User Login block should appear in footer fourth only for this new homepage but for the rest of the pages in websites it has to continue to stay in the Side bar first region. In normal scenarios if it was a custom block, then I can create a clone of the same block and change the visibility per page / set of pages. But User Login block is system defined and it does not allow me to clone or duplicate it.

I tried searching if someone has already addressed this issue but it seems like not. Looking forward for thoughts.

Edit:
Nearest I could find is this: Change block location on page by page basis?. But the solution there was to create multiple blocks from same view, unfortunately User Login is not based out of views for me.

You can place the default User Login block in Sidebar first region at the last position. You can exclude this block from being shown in Homepage using 'Visibility settings' which is available in the block edit page.

Then you can use front page template page--front.tpl.php and render the block manually by passing the block markup through hook_preprocess_page().

function THEME_NAME_preprocess_page(&$vars, $hook) {
  $front_page = drupal_is_front_page();
  if ($front_page) {
    $user_login= block_load('user', 'login');
    $vars['user_login'] = _block_get_renderable_array(_block_render_blocks(array($user_login)));
  }
}

Then you should print the $user_login variable in the front page template inside the Footer Fourth region.


entityFieldQuery not returning term references - not in field_data but are in field_revision So, I'm pretty new to drupal(7) - any help here greatly appreciated.

What I'm trying to do is use entityFieldQuery to return a list of nodes that have a given term in them.

I have a field, "field_crafts", where crafts is a term reference, and points to a specific vocabulary. I also have a 'tags' field.

If I use fieldCondition('field_tags', 'tid', $n), the entityFieldQuery works fine, and returns all nodes with the given tag.

But if I do the very same thing on field_crafts instead, it returns no results.

I've poked around in my database, and it appears that field_data_field_tags table has data in it, but the field_data_field_crafts does not. However, the field_revision_field_crafts table does. And when I load up the node in the UI, it does indeed remember which terms I have ticked in the list of checkboxes.

So, what's going on here? I imagine that if the crafts data were just to appear in the data table, the query would work fine. Why isn't it, and is there anything I can do?

Thanks!

So, I figured out what was going on -- I was using the 'moderation' plugin and so all the changes I was making were secretly getting marked as 'draft' despite me making the changes as an admin. Doh.


Filter View based on Relationship to Current User Similar to this question, I have an elevated user role (Facilitator) that's associated via profile to a location (content type space) and should see a list of pre-authorized users who have matching profile locations that they can authorize or deny. I've built a view using Views Bulk Operations and have a custom action to change the user role, all of which is working, but I can't figure out how to filter the pre-authorized students by their location matched to the location of the currently logged-in user. Do I have to make a custom filter for this?

EDIT:

The data relationship looks like this:

User -> Profile -> Space

A Profile can have multiple associated Spaces. I want the view to only show users whose associated space(s) match one or more of the associated space(s) of the current logged in user.

In general it doesn't have to be locations, it could be interests, or favorite colors, anything. Any matching of nodes/users by associated data values.

The only way to do this within views is the following:

Make View of using User type
add a Relationship to a Profile2 type (in my case 'Student')
Add Contextual Filter of type profile:student:location
select "provide default value"
type: "php code"
Use the following code:

global $user;
$profile = profile2_load_by_user($user->uid,'facilitator');
if (!$profile) { return ''; }
if (!isset($profile->field_location['und'])) { return ''; }
$locations='';
foreach ($profile->field_location['und'] as $location) {
  $locations.=','.$location['nid'];
}
return substr($locations,1);

Under "More", Set "Allow Multiple Values" to TRUE
Save your Contextual Filter

Using PHP in this manner, you can load the current User and get associated values to filter by. This may be useful in many other contexts and circumstances.


hook to alter custom blocks? I am having a problem with my custom blocks rendering, and I want to programmatically manipulate the blocks to troubleshoot the issue.

I used this question to add this hook to my module:

function mymodule_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message($block->getBaseId());
}

However, when I navigate to my site, I see only the base ids of system blocks:

- page_title_block
- system_main_block
- help_block
- local_tasks_block

My site's header and footer are made of custom blocks, so I should be seeing their ids.

How can I programmatically access my custom blocks?

Edit this is my actual code:

$ cat my_block_hooks.module
<?php

function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getBaseId() );
}

And here's a screenshot:

You can see that all the system blocks show up, but my custom block does not.

This is the custom block as I have it set up:

And here I have it placed in the layout:

And of course, I've cleared the cache many times to get to this point.

What am I doing wrong?

The type of entity you are dealing with defines the hook you need to implement; in this case it is NOT block but rather block_content, as provided by the "Custom Block" core module.

N.B.: It is generally good practice to use more specific hooks when possible, as it will have a general effect on your code's performance, i.e. your hook implementation will be called less times if it is more specific. In your case, instead of going through all blocks available on any page during page loading, you are going through only custom blocks (block_content entities).

In order to get your hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter() implementation to work, you need to replace ENTITY_TYPE with block_content. That should give you the following code (which I tested and works):

use Drupal\block_content\Entity\BlockContent;
...
function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

And the visual result:

Good luck!


Theme Settings value dissapears I am trying to create functionality where administrator can upload header image whenever he wants.

I' using hook_form_system_theme_settings_alter in theme-settings.php and altering form like this:

 $form['theme_settings']['background_file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Background'),
        '#required' => TRUE,
        '#upload_location' => file_default_scheme() . '://public/backgrounds/',
        '#default_value' => theme_get_setting('background_file'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
    );

in template.php using hook_preprocess_page and doing this in it:

$fid = theme_get_setting('background_file');
$loaded = file_load($fid);
$variables['background_url'] = file_create_url($loaded->uri);

and trying to reach $variables['background_url'] from tpl.php file.

When I upload image everything works great, header image is set properly and code has no problem but after a while, I don't really know what happens, for example after 1 day file_load returns FALSE, I just reupload image and everything works fine again.

theme_get_setting('background_file'); always returns file id without problems.

I am missing something? I can't find source of problem.

Thanks.

I think it's because there is a problem in your template.php. Indeed drupal should save your file only temporarly. You have to save your file permenantly with this code

$file = file_load($form_state['values']['background_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);


Benefit of config entities over regular config entries? In Drupal 8 it is possible to store configuration in "config entities".

However, the same can also be achieved with non-entity config entries.

E.g. one example for a config entity schema, from core.entity.schema.yml:

core.entity_view_display.*.*.*:
  type: config_entity
  label: 'Entity display'
  mapping:
    id:
      type: string
      label: 'ID'
    targetEntityType:
      type: string
      label: 'Target entity type'
    bundle:
      type: string
      label: 'Bundle'
    mode:
      type: string
      label: 'View or form mode machine name'
    content:
      type: sequence
      ...
    hidden:
      type: sequence
      ...

The same information could be stored in entries with type: mapping, like so:

core.entity_view_display.*.*.*:
  type: mapping
  label: 'Entity display'
  mapping:
    content:
      type: sequence
      ...
    hidden:
      type: sequence
      ...

In fact, we would not even have to store the 'targetEntityType', 'bundle' and 'mode' as properties, because these are already part of the key (the asterisks in the schema key). We could also omit the 'id', because the key is already a unique identifier, making the id redundant.

Obviously, one would not use entity crud components to deal with those config entries, but call directly the config API, e.g. \Drupal::configFactory->get(..).

Also, one would not inherit from EntityForm, but have custom form classes. But it seems all doable.

Question

So: What would we miss by not using config entities? In which cases would a simple "mapping" be sufficient?

To stick with the example: What can we currently do with 'entity_view_display' entities, that would not be possible if these were just 'mapping' entries?

Background / Use case

My original use case was this one: Custom entries in entity view modes?, which came up when I wanted to port entdispfieldui to Drupal 8.

This question was very specific, so I wanted to ask a more general question about the benefits of config entities.

In this case I decided to use non-entity config entries. One reason was that config entities caused recursion in hook_entity_extra_field_info().

I am going to port more modules to Drupal 8, where the same question will come up, but where I don't have to worry about hook_entity_extra_field_info(). E.g. cfrpreset.

A config entity is useful when there need to be multiple variations of the configuration, think views, image styles, or node bundles. If there is no need to create variations, as in system.site which stores the site's basic information or core.extensions which stores the list of enabled modules, a basic config entry is appropriate.


Putting additional functionality for Commerce Files/License I am making a files selling website with Drupal 7.41. Using the Commerce Files / Commerce License Modules, I have been able to setup the after payment completes, allow file download functionality.

However the files that becomes available to download is just the raw file.
I want the file, which becomes available for download to be a zip/tar file which consists the

File sold
A simple readme.txt
A pdf file consisting license information, made for that particular user transaction. Like Envato!

Is this automation possible?
Can anybody please guide me on how I may be able to achieve this? Even pointing out the path would be helpful!

Here's what you need to get started.

You'll need to create a new license type and extend the CommerceLicenseBase class (or the file class). When your license class (whose parent class is CommerceLicenseBase) gets activated, the ->activate() method ends up calling ->save(). Your new class will implement ->save() and within that function you can:

Generate a PDF.
Generate or load a README.txt.
Create a Zip file.
Store that file and attach it to some entity, email it, etc.


Flag a node but create a view of the nodes that reference it We want our logged in users to be able to Flag/Follow our "Fisheries" content type nodes. Users can then create a "Catch" node in the Catches content type and use an entity reference field (Fisheries) to tag the Fishery in which it was caught.

I therefore want to be able to produce a view which shows what's being caught in the Fisheries that the user follows. If they follow 10 Fisheries the View would contain the latest catches from those 10 lakes in date order.

I can see what Fisheries the user is following with this View:

but I want to see what other content type nodes are referencing this node instead. I hope that makes sense!

You may use Entity View Attachement module. This module attaches a view to an object. this object may be a node, user , ...  . Select the appropriate bundle and it works well


Drupal menu depth limitation I am facing a problem that in my drupal web site, I am having menu depth level is more then 15. By default drupal 7 provides depth level is 9. Is it any way to increase it's menu depth level?

In short :- I need to add more then 15 childrens in my single menu item.

Expamle:-

Menu

-1

--2

---3

----4

-----5

------6

-------7

--------8

---------9

===========Drupal doesn't allow to add more childrens =====

Firstly I would suggest having a hard think about whether you actually need a menu that deep and why.
Then try to think of an alternative way to structure your data to achieve what you need to do.

The reason is that this is not an easy thing to change (and 15 levels of menu suggests possible information architecture issues).

There is a drupal.org issue https://drupal.org/node/274270 relating to this that has some examples on how you can make the change.
The example is for drupal 6 but pretty much the same thing applies to drupal 7.

The problem is that each level has it's own column in the menu links table, so you have to alter the menu links database table to add new columns and then make some changes to drupal core to use these new fields.

As a side note, there is a module called menu depth limit that allows you to set a lower limit but not a higher one.


Change CCK field data type I have a CCK field with a data type 'text', that I want to change to 'decimal'.

I have used a hook_update_N and db_change_field in order to do this.

Here is an example how I tried to do it:

function ptm_foo_update_6005() {
  db_change_field(
    $ret,
    'content_type_',
    'field_foo_value',
    'field_foo_value',
    array(
      'type' => 'decimal(10,2)',
      'description' => 'Foo'
    )
  );
}

But when I execute the update, it gives me the following error message:

  User warning: You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax

Based on the comments on your question, I certainly hope you're doing this in a .install file and not a .module file.

The $ret variable is expected to be a reference, so you'll need to declare it before hand.

$ret = array();
db_change_field($ret ...);

Is your table name really content_type_?

And you may want to look at this and stick in a couple dsm() calls to see what the db_change_field() function is actually passing to MySQL and then you could trouble shoot the query directly.


How can I display a paragraph field excerpt in a search result view? I've spent all day and night battling with Search API (with and without Apache Solr) in Drupal 8.

Does anyone know if you can use Search API to index paragraph content and then in a search views result, get back the "excerpt" of highlighted text from within a paragraph + the title of the node the paragraph is used in?

If you add the specific fields within your paragraphs to search_api fields it will generate excerpts for them. If you just have 'Rendered HTML' of the entire page, it will not create excerpts of paragraph text.


Same tpl.php for multiple blocks I have 14 blocks added through Drupal interface, for all of them I was override tpl.php file because I need some changes there (like block--block--1.tpl.php).

What I want to do is to create just one tpl.php file and apply it for all these blocks. So, if I need to change something someday, I change it just in one file instead 14 files.

How I can accomplish that in Drupal 7?

As per template suggestion for Drupal 7, we have a general format as:

  block--[region|[module|--delta]].tpl.php

  base template: block.tpl.php

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

  block--module--delta.tpl.php block--module.tpl.php
  block--region.tpl.php "module" being the name of the module and
  "delta", the internal id assigned to the block by the module.

Now, in order to override and define your own suggestions apart from these, you can provide new template suggestions in your theme template.php file file using template_preprocess_block as:

function mytheme_preprocess_block(&$variables) {
    $variables['theme_hook_suggestions'][] = 'common_block_template';
}

Now you place(create) this common-block-template.tpl.php file in your themes templates folder and it will be default template for all your blocks and don't forget to clear drupal cache.

Note: This templates will be applied to every block present in your Drupal 7 website i.e. user login block, content block etc.. So make sure you do define logic as per your page requirements as for example if you want to limit this template suggestion for just a uri name mypage, then

function mytheme_preprocess_block(&$variables) {
 if (current_path() == 'mypage') {
  $variables['theme_hook_suggestions'][] = 'common_block_template';
 }
}

UPDATE:
To target delta (with numeric values & to avoid custom module block) the were created using Drupal 7 site building block module:

function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if (is_numeric($block->delta)) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }

If you need to target just block which has delta of 1 then:

function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if ($block->delta == 1) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }


Alternatives to Commerce Coupon / Discount I need to add coupon codes for a e-com shop built using Drupal Commerce, and have been playing with Commerce Coupon and Commerce Discount modules, but I can't seem to fix the problem of coupons being removed during checkout. This has been reported many times (see issues below), with various supposed fixes but I've tried everything and nothing works.

So, is there any alternative for this kind of functionality?

I really only need discounts on full orders (instead of products) but do need both percentage and fixed price options.

Alternatively if anyone has a real fix for the issue please let me know!

Issues for reference:

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

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

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

Both of those modules have caused me headaches, however I know of no alternative.

In order to fix the bug you need to ideally step through Commerce Coupon and Commerce Discount's implementation of commerce_cart_order_refresh and commerce_cart_line_item_refresh.

Line items kept getting deleted for me when they didn't have a properly formatted price.

By implementing my own commerce_cart_line_item_refresh I was able to fix any problems with line items before their code ran.

If I was to do a discount / coupon system again and the spec was not too complex I would be tempted to write something from scratch as both of those modules are suffering from a bit of bloat.


Drupal always creates its own URL aliases, even when I tell it not to I don't know if this is a bug in Drupal, or if there's a configuration somewhere that is causing the problem, but when I create a new page or edit an existing page, Drupal (always? often? sometimes?) generates its own URL alias, even though I've very clearly specified that it should NOT do this, and I've provided one.  The one I provide does get created, but the Drupal-generated URL alias, which is always ugly, gets used instead.  I have to manually delete the Drupal-generated alias in order for the site to work.

For instance, I just added 2 pages, "Privacy Policy" and "Terms of Use".  Even though I specified /terms and /privacy as the URLs (and yes: of course I gave them to Drupal without the initial slashes), I got stuck with /content/privacy-policy and /content/terms-of-use as the URLs for these pages.

I've just had the same issue. I found the reason why it was behaving like that, so I thought I would post the answer here for others with the same problem.

You need to go to Path Settings --> Section "While Updating" (I don't know the exact wording in English as I have the PT version).

Here, you have to select the first option: Do nothing. Keep the old alternative path.

This should solve your question. :-)


URLs defined in a hook broken I have a content type that, on the node page, displays taxonomy term fields, which in turn link to the automatically generated taxonomy term view for that term.

I would like to overwrite the output of these links, which I have attempted to do in the code below.

The problem is that the URL comes out malformed as: /our-work%3Ftid%3D4 rather than /our-work?tid=4. Note that the argument 4 is just an example.

What could be the solution here? Some thoughts:

Am I using the right hook?
urlencode() doesn't seem to work here.
Using Drupal's l() function seems to output HTML, not a processed URL.
Using Drupal's url() function doesn't seem to work either, I get the same output when I build the options array, etc.

function ep3_misc_node_view_alter(&$build) {
    if ($build['#bundle'] == 'work') {
    // We cycle through this array for just integer indexes, since there are also string indices.
        for ($i = 0; isset($build['field_tags'][$i]); $i++) {
            $tid = $build['field_tags'][$i]['#options']['entity']->tid;
            $build['field_tags'][$i]['#href'] = check_plain('our-work?tid=') . $tid;
        }
    }
}

The function that you should use is url(). If you want to output an absolute URL you should use the following code:

function ep3_misc_node_view_alter(&$build) {
  if ($build['#bundle'] == 'work') {
    for ($i = 0; isset($build['field_tags'][$i]); $i++) {
      $tid = $build['field_tags'][$i]['#options']['entity']->tid;
      $build['field_tags'][$i]['#href'] = url('our-work', array('absolute' => TRUE, 'query' => array('tid'=> $tid)));
    }
  }
}

If you don't want an absolute URL, replace the call to url() with the following one:

url('our-work', array('query' => array('tid'=> $tid)))

check_plain() is never used to output a URL; in fact, url() doesn't use it.


Increase security on logon I am using Logintoboggan module but by chance by playing around with Wireshark packet sniffing tools I can see all login details and passwords when users login/register on my site!

Is there a way to encrypt login details and/ or add extra security to this module - Are there better secure modules out there?

Secure Login

For sites that are available via both HTTP and HTTPS, Secure Login
module ensures that the user login and other forms are submitted
securely via HTTPS, thus preventing passwords and other private user
data from being transmitted in the clear. Secure Login module locks
down not just the user/login page but also any page containing the
user login block, and any other forms that you configure to be
secured.
For Drupal 7 and 8, Secure Login module enforces secure authenticated
session cookies, thus preventing session hijacking. For previous
versions of Drupal, PHP's session.cookie_secure flag must be enabled
on the HTTPS site to enforce secure session cookies.

Login Security

With Login Security module, a site administrator may protect and
restrict access by adding access control features to the login forms
(default login form in /user and the block called "login form block").
Enabling this module, a site administrator may
limit the number of invalid login attempts before blocking accounts,
or deny access by IP address, temporarily or permanently. A set of
notifications by email or Nagios may help the site administrator to
know when something is happening with the login form of their site:
password and account guessing, bruteforce login attempts or just
unexpected behaviour with the login operation.


How to theme the separate page for editing profiles provided by Profile2 I'm using D7.
I'd like to theme the separate page for editing profiles provided by Profile2 module(whose URL is MYWEBSITE.com/profile-MYPROFILE/[uid]/edit).
I searched and found the way that somebody has already suggested. And, by reference to that, I tried the way below. But it doesn't work. Can anybody tell me where I made a mistake?

Here is the way I tried but that didn't work...

1st: Create the customthem_theme() below into  template.php file of customtheme theme.

function customtheme_theme() {
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'customtheme') . '/templates',
        'template' => 'user-profile-form',
        'preprocess functions' => array(
             'customtheme_preprocess_user_profile_form'
        ),
    );
    return $items;
}

2nd:  Create the template file user-profile-form.tpl.php and place it in the templates folder of custometheme.

3rd: Code the fields I want to display on user-profile-form.tpl.php
for ex

<html>
<?php

print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
?>

<div>
         <?php  print render($form['profile_MYPROFILE']['field_MYFIELD']); ?>
</div>
</html>

I'm still very new to drupal and, honestly, don't figure out how its system works yet. I'm sorry if this is a very easy mistake to you.
Thanks.

Change where it says customtheme to the actual theme name you are using.

for example if you are using bartik:

function bartik_theme() {
'path' => drupal_get_path('theme', 'bartik') . '/templates',
'preprocess functions' => array(
         'bartik_preprocess_user_profile_form'
    ),

The files should be located in your theme folder.


User name in view arguments and title of page I created a content type named "Post" and allowed certain roles to add posts on my website.

I also created a view that displays these posts, as a page and block view.
Now, I want to add a contextual filter to display posts from specific authors, but in filters I find only the author UID so that my URL is post/1 and so on. Is there a way to have user name instead of user ID as wildcard in the URL?

I also want to set the page title such as "Posts of [user-name]", but I don't know if it is possible to do.

I'm very sorry, but I googled for this but I found nothing.

You can add on "Relationships" (right side of your view edit page, under Advanced) "Content: Author". Now the name of the author (User: Name) will be available to you in fields and/or filters. You could also follow this: http://www.drupalden.co.uk/using-views-display-nodes-author-name


Control number of autocomplete results in drupal? Is there any way to control number of results in an autocompleted field in drupal?.  Usually node reference autocomplete fields provide 10 results, i want to increase the count, is there any global configuration availabe or how can i alter the count?

You will have to make a custom module to alter the result of autocomplete coming from node reference module. This example(taken from here) is for 20 result, you can increase/decrease according to your need.

function MYMODULE_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'MYMODULE_nodereference_autocomplete';
  }
}
function MYMODULE_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();
  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';
  }
  drupal_json($matches);
}


Why Drupal is faster than WordPress in general Some people say that Drupal, in general, is faster(requests per second) than WordPress. I want to know why Drupal is faster. Is it faster because of its cache, sql query or something else?

I see a benchmark here http://sven.webiny.com/benchmark-webiny-vs-wordpress-vs-drupal-vs-joomla-vs-tomatocms/

It's almost impossible to meaningfully compare the performance of Drupal and Wordpress, because their speed varies widely depending on the configuration and installed modules / plugins.  Both are capable of scaling when sites are built by skilled developers.

Regarding the Webiny benchmark, it's almost certain that Drupal's page cache was disabled (the default setting) for the test; I ran the same ab command on an Amazon micro instance and got over 100 requests per second.

That said, the Drupal community has a lot of interest in performance (the High Performance group is a good place to start).  The core development workflow has a process to account for performance issues.  And the ecosystem offers a range of modules to scale even further, including support for memcached, boost, varnish, APC, MongoDB, CDNs, and others.


How create form elements in form theme hook I have a custom module with a from, form submit handler and for theme hook

In some case I need to create multiple form elements (textfields for example with name like "user_input_1"-"user_input_n")

What I did is change $form array in form theme hook and render new elements. But these elements are missing in the post and form submit processing form (even if shown on a page). I realize what it might be not appropriate way of creating new form elements in theme hook OR maybe there is something(function) what will allow me to properly prepare new form elements in theme hook on a fly.

Or maybe there is another way as I know how many elements do I need in submit processing function which rebuild the form and doing something like $form_state['storage']['wizard_step'] = 'step3' (multi-step form). But I don't know drupal very well, just started..

Stuck and spend few hours trying to find appropriate way of solving this. Any help appreciated.
Thanks

Answer is simple: form alter hook allows to manage form content on a fly


Totally override a menu I'm trying to get a menu with my custom classes.

I would like to be able to

// class of the whole ul

// add class "with-sub" if has children
submenu

 // add class sub-menu to sub menu ul

// add the title of the parent as first item of the list
TITLE OF THE PARENT

// add a class to all sub-menu items
 Submenu item

For the first level it's fine. I can use menu_tree and menu_link to get what I want.

I would like to know how to use $sub_menu = drupal_render($element['#below']) and customize the sub menu list.

I don't want to use any module, I want to do all through the template.php.

Thanks in advance

Take a look at theme_menu_tree() and theme_menu_link(). It should be all you need.

Sorry for the lack of examples, but theme_menu_tree is rather self-explanatory, and the page for theme_menu_link provides several examples.


How can I remove or overwrite the YAML validation from a Webform Entity? I am currently building a module that parses raw HTML into a webform using YAML, however I am running into an issue where the name='SomeName' on form elements is causing an error in the YAML keys.

The form relies on the name attribute in order to accurately map the data so I need it to be case insensitive.  I can force a save programmatically with

$webform = new \Drupal\webform\Entity\Webform::create(
// stuff here
);

$webform->save();

However when someone attempts to edit the form in the UI and saves, there is an error preventing save that comes from docroot/modules/contrib/webform/src/WebformEntityElementsValidator.php

This error prevents saving due to casing errors.

The element key contact_Name on line 1 must contain only lowercase letters, numbers, and underscores.

I have tried

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $forms_array = ['webform_ui_element_form', 'webform_source_form'];
  if (in_array($form_id, $forms_array)) {
    $form['actions']['submit']['#limit_validation_errors'] = [];
    $form['actions']['submit']['#_validate_form'] = FALSE;
  }

}

However it seems that for some reason this prevents saving a new element.

Any help is appreciated.

I was able to achieve this, thanks to some guidance in the comments, by overriding a service.

This involved work in two custom module files.  The first was modules/custom/mymodule/src/MymoduleFormParserServiceProvider.php

Within that file I used ::alter to alter which class is called for a particular service.

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * Replace Webform validator service.
 */
class MymoduleServiceProvider extends ServiceProviderBase implements ServiceProviderInterface {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('webform.elements_validator');
    $definition->setClass('Drupal\mymodule\MymoduleWebformElementsValidator');
  }

}

What this does is tell Drupal that when the webform.elements_validator service is called, use the MymoduleWebformElementsValidator class instead.

The second piece of the puzzle was to create that class.  I did that by extending the original class WebformEntityElementsValidator with my own MymoduleWebformElementsValidator class and doing the logic there.  That way I was able to keep most of the validation from the original, but make the changes to the validate method that were needed.

I was able to find many of the answers after googling override service thanks to the comment on the question by @jrockowitz


hook_preprocess_views_view not loading view when records are empty I am trying to add some css and js files using the hook_preprocess_views_view_unformatted Hook in template.php

Here is my code :

function mytheme_preprocess_views_view_unformatted(&$vars) {
$view = $vars['view'];
if ($view->name == "my_view_name"){

        drupal_add_css(drupal_get_path('theme', 'mytheme') .'/css/sample.css', array());
        drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/sample.js');

}}

My problem is that when the view is empty or when does not have any records the view is not loaded and thus I am unable to get the $view->name and neither are the css,js files being applied for the page.

It is working fine when the view displays a few records. So is there any other hook or method to fetch the view name or get it loaded when the records are empty ?

I found out the solution to add files to specific 'View Pages'. Need to use hook_preprocess_page in template.php and check the view_name. Here is the code that worked for me.

function mytheme_preprocess_page(&$variables){
if($variables['page']['#views_contextual_links_info']['views_ui']['view_name'] == 'my_view_name'){
    drupal_add_css(drupal_get_path('theme', 'mytheme') .'/css/sample.css', array());
    drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/sample.js');}


Features and CMI Together We are developing a single Drupal 8 site with a set of different features (content types, etc).  The CMI approach is great for sharing config through git and importing/exporting on local, dev, stage, and prod environments.

But... I also really like the organizational aspects of the Features module.  It is appealing to have config grouped in meaningful buckets rather than a single global sync folder.  Individual modules also provide a nice place to hang default content and hook_update_N functions.

I've read that these two can play nicely together, but I'm having trouble determining the practical logistics of it all.  When I develop a feature, I usually do a drush cex and commit the changes -- so with Features, do I also export a feature and commit that?  Now the config lives in two places -- should I be concerned?  Will it cause conflicts?

Am I just complicating things by trying to use both?  If forced to choose, I will use only CMI because I want to be sure to control all config (not just the bits I've grouped into Features) -- and we want consistent and predictable deployments between local, dev, stage, and prod.

In my opinion Features isn't really useful for just one site. It is useful for extracting and packaging functionality to use on multiple sites. Using both at the same time is probably counter productive and prone to errors, as they both try to enforce features via configuration and manage them as well.

If you had a site and wanted to copy/clone the article functionality or product catalog functionality from it to another (different) site, then, yes. You would need Features to do this, because core CMI does not work when you want to take pieces and import to a totally different site.

On the other end of the spectrum, you could ignore the core config management and use Features to do this for your entire site, but it is more for you to manage, and as stated, if you are not extracting it out for use in other sites, it is just busy work.


View add a new field it can't find the fields "All disappeared " Something strange happened to my website and suddenly all the fields disappeared from view.

I tried to create new view with content type building. the building content type has the following fields Title, photos,address,building ready,price,description and logo.

at the time of creating the view I can find all the above fields and can add them without any problem  but after few minutes the fields disappears from view and going back to add field only few common fields are available

Going back to view i can see a message "This view has been automatically updated to fix missing relationships. While this View should continue to work, you should verify that the automatic updates are correct and save this view."

During creating the view all the field are available

creating new view configuration screen

I tried to update Drupal noting changed

I tired to update Views noting changed

I tired Registry Rebuild noting changed

After spending two nights I finally manage to make it work for me by Always show the master display from /admin/structure/views/settings and enabling.

However this is a major bug in view and to be honest pain in the bottom !

Hope next release of view will consider looking into this bug.


Creating a view that excludes entity referenced nodes Say I have a Content type of Fruit. I have an Entity Reference on the User Profile to Fruit nodes. I want to create a view that shows all Fruit nodes that are NOT referenced by the Entity Reference on the current user profile.

(More details: I can create a view that includes Fruit nodes on the current user profile, by creating a view of Fruit nodes with a Relationship to the Entity Reference on the User Profile. Alternatively, by creating a View of users, filtering by current users, and then using the entity reference to show the data from the Fruit nodes. However, I haven't found a way to create a view of Fruit nodes that are NOT referenced on the current User Profile.

Views Reference Filter might help you:

  This module provides the feature missing in Views module - subquery filter for IN (NOT IN) condition, such as (quite informal):

  SELECT n.title FROM node n WHERE n.nid [IN | NOT IN] (SELECT n2.nid FROM node n2 WHERE ...)

  or

  SELECT n.title FROM node n WHERE n.node_reference_field [IN | NOT IN] (SELECT n2.nid FROM node n2 WHERE ...)


Custom Module Configuration not working I have the following file.

  modules/custom/test_module/config/install/test_module.settings.yml

test_module.settings:
    message: 'Hello'
    langcode: 'en'

But I am not able to get the following value.

$config = \Drupal::config('test_module.settings');
print $config->get('message');

I have referred this link.

UPDATE:

Removing test_module.settings: line solved the issue.

test_module.settings:
    message: 'Hello'
    langcode: 'en'

Is that really content of your file? It should only contain:

message: 'Hello'
langcode: 'en'

Also, Configuration on config/install is only imported when a module is installed. If it is an existing module, you need to re-install it or write an update function to initialize the configuration.

You can always use something like print_r($config->get()) to see everything in your config file.


Is there a way to inherit a Drupal installation profile? I want to create a Drupal installation profile based on an existing one. Is there a way to inherit the parent profile so I don't need to duplicate modules, dependencies, libraries definitions ?

Doing some research and testing I found a way to inherit Drupal installation profiles, using drush make (works in Drupal 7).

1) Apply Drupal patch #47 submitted in this topic

projects[drupal][type] = core
projects[drupal][version] = 7.32
projects[drupal][patch][] = https://www.drupal.org/files/issues/drupal-inheritable-profiles-2067229-47.patch

2) Set Drupal "base profile" in your profile.info file. My installation profile will be based in Guardr

name = MyProfile
description = MyProfile
version = 7.x-1.0
core = 7.x
base profile = guardr

3) Execute with Drush the make file of your base profile. Add it to your profile.make:

projects[guardr][type] = profile
projects[guardr][download][type] = git
projects[guardr][download][url] = "git://git.drupal.org/project/guardr.git"
projects[guardr][download][branch] = "7.x-1.14"

drush will download it and then recursively run the make file of the base profile

I found the reference in this blog post


Make feeds importer to replace instead rename file path I am using commerce_feeds module to import products. It works well except the image fields url gets renamed by adding _0, _0_5, etc at the end of the image paths. How to turn this off? I would like to have path the same at all times no matter if the file is present with the particular path or not. Thank you for any help you can give in this regards.

The problem was on the server. It was not supporting image GD extension that prevented for generating images with a new path.


Redirect to login page if login fails from a login block? I have a login form block, when a user fail to login to the site I want to redirect him to the user/login page with the usual error message

You can do this by form_alter

function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block':
      $form['#validate'][] = 'my_custom_login_val';
      break;
    default:
      break;
  }
}

function my_custom_login_val($form, &$form_state) {
  $form = form_get_error($form['name']) . form_get_error($form['pass']);
  if($form != '') {
    $_GET['destination'] = 'user/login';
    drupal_goto('user/login');
  }
}

If you need like after the correct login redirect to a page use Login Destination


Correct Syntax for $conf to populate Varnish Control Terminal This may be more a php question, but pertains to Drupal, so here goes: I'm trying to configure Varnish Control Terminal to use multiple hosts using settings.php. I have:

$conf['varnish_control_terminal'] = array ('11.22.33.44:6082','22.33.44.55:6082');

but I keep getting this error (1 set for each host in the array) at http://localhost/admin/config/development/varnish:

Warning: explode() expects parameter 2 to be string, array given in _varnish_terminal_run() (line 192 of /app/aegir/platforms/cms-1.0/sites/all/modules/contrib/varnish/varnish.module).
Warning: Invalid argument supplied for foreach() in _varnish_terminal_run() (line 196 of /app/aegir/platforms/cms-1.0/sites/all/modules/contrib/varnish/varnish.module).

I've also tried these (one by one):

$conf['varnish_control_terminal'] = array ('11.22.33.44:6082 22.33.44.55:6082');
$conf['varnish_control_terminal'] = array (11.22.33.44:6082 22.33.44.55:6082);
$conf['varnish_control_terminal'] = array ('11.22.33.44:6082');

with the same result. I think my array syntax is incorrect, but I am not sure what the correct syntax would is ... any ideas ... ? I looked at php's array documentation as well.

EDIT: This also causes the varnish status at http://localhost/admin/reports/varnish to go blank, so I am not sure if Varnish caching for Drupal is functioning properly or not at all.

Many thanks!

PS: I also posted a note in the Varnish project's issue queue on Nov 30th and haven't heard anything.

So, turns out, the list of hosts is not an array; this works:

$conf['varnish_control_terminal'] = '11.22.33.44:6082 22.33.44.55:6082';

Hopefully, it helps someone else.


How can I hook into entityforms being submitted? I've installed entity forms. I have made a form. I would like to fire some code when a user fills out and submits the form I have created. I do not know how to do this. I don't know which hook to use, nor entirely understand how hooks work.

I've done my best to learn php and read the documentation, but I don't understand. I understand that this is likely a very simple question, I have never had any formal computer training, so even the simplest concepts allude me.

Entityforms are - as the name suggests - stored as entities. So you can hook into hook_entity_insert(), or hook_ENTITY_TYPE_insert(), having the inserted data as parameter (the entity will be an object):

/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert($entity, $type) {
  if ($type == 'entityform') {
    // Do your stuff here.
  }
}

or

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MYMODULE_entityform_insert($entityform) {
  // Do your stuff here.
}

You could also utilize rules to define custom actions on submission, as the entityform submission triggers the entityform_submission rule.


How does the views page style options work? I have recently discovered the power of Views. I am using the Unformatted list Format and an Entity Reference bringing two content types that I created (myprojects and mytasks) together such that if there are any tasks associated with a given project they are listed below the related project. This works pretty well.

I know very little about HTML and really don't want to have to get into it. I want a simple indentation on each output task row displayed so that the report is easier to read. It would also be nice if it was double spaced.

The theme I'm using in my site is Outreach. What happens is each project is h3 and each row is inside div and underlined with a smaller font.

This list of projects and tasks becomes an agenda for meetings when copied into Word.

How can I use Settings for Unformatted list and/or Settings for Fields in the view to indent the rows of tasks?

It is a CSS question, not Drupal.

I understand that using the Open Outreach theme you probably run a non-profit organization of some kind, so I'll try to help you.

You already said that you don't want to learn HTML/CSS in other questions so I will try to be straightforward: you can't.

What you might do is change from Unformatted List to HTML List and hope that the basic CSS don't change it. And yes, the preview will be different from the final view because templates. The closed admin part uses a template different than the open part.


Is there a way to load content of each tab in the view using AJAX? I've created View to display my content and I'm using Quicktabs module https://drupal.org/project/quicktabs to format the output of this view into the tabs.

Is there a way to load content of each tab in the view using AJAX? I can't see any option.

I had a similar problem. The following code worked perfectly for me.

jQuery(".quicktabs-wrapper ul a").click(function(e) {
    e.preventDefault();
    jQuery(this).parents('.quicktabs-wrapper').find('.quicktabs_main  .quicktabs-tabpage').addClass('quicktabs-hide');
    showId = jQuery(this).attr('id').replace("-tab-", "-tabpage-");
    jQuery('#' + showId).removeClass('quicktabs-hide');
    jQuery(this).parent().siblings('li').removeClass('active');
    jQuery(this).parent().addClass('active');
  });


Safe to delete cache_form table while site is in maintenance mode? My site has a very large database of 100MB, most of this is in a table called cache_form.

I've tried clearing the cache. When I try and run the cron I just get a white screen.

My site is in maintenance mode, is it safe to delete the contents of this table in PhpMyAdmin? There are clearly some other issues that I need to look into but is it safe to do this as a short term measure to get the site back on its feet? I've had to put it in maintenance mode as aspects of content creation have stopped working properly.

First off, cache_form is not really a cache table, but a temporary table used to contain data necessary to verify the form being submitted to Drupal is not forged.
If you were to empty that table, users would encounter validation errors for the data they submitted from the form they were using. Since the site is in maintenance mode, that should impact the only users who are allowed to access the site when it is in maintenance mode, which includes you. You just reload the page containing the form, and fill it again; it's not a permanent error.


Custom basic .js from theme dir prevents Splashify module from working I am using latest Drupal 7 with latest Splashify version. Splashify (Splash in D6) is a simple module that uses jStorage js (from libraries/ dir) to add a splash/intro page for your Drupal site. So i.e. user enters my site and it gives him some intro splash page with like links to Enter site or Leave and etc. And that page is any node who's path/alias is chosen as a splash page. More about Splashify drupal.org/project/splashify

Now I found out that this module is not working because of some basic js my theme has. I tried on default Bartik and the module works just fine.

The problem is I am not js developer and don't know what's the problem. So I only managed to track down the problem.

There's the code, maybe someone knows what might be the issue, it's jQuery:

(function ($) {
  /* Slideshow */
  Drupal.behaviors.MYSITE = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
      });

      /* Rollover info */
      $(".block1").hover(function(){
        $(this).find("span.info").stop(false, true).fadeIn("fast");
      }, function(){
        $(this).find("span.info").stop(false, true).fadeOut("fast");
      });

      // Class for every 3rd row.
      $(".view-flavor-listings .views-row:nth-child(3n-3)").addClass("diff-margin");
      $(".view-content-inner .views-row:nth-child(5n-4)").addClass("diff-mrg");

      /* slidePager */
      $('.pages').slidePager({
        last:6,
        borders:1,
        change:function(n){
          var els=$('.thumbs li').removeClass('mrk')
          els.eq(n).addClass('mrk')
          els.eq(n+1).addClass('mrk')
          els.eq(n+2).addClass('mrk')
          $('.thumbs li').css('opacity',1)
          $('.thumbs li:not(.mrk)').css('opacity',1)
        }
      })
    }};

    // Make Plupload default.
    $('.filefield-sources-list').each(function() {
      $('a.filefield-source-plupload', this).trigger('click');
      $(this).hide();
    });
  })(jQuery);

To be exact it's that part:

/* slidePager */
$('.pages').slidePager({
  last:6,
  borders:1,
  change:function(n){
    var els=$('.thumbs li').removeClass('mrk')
    els.eq(n).addClass('mrk')
    els.eq(n+1).addClass('mrk')
    els.eq(n+2).addClass('mrk')
    $('.thumbs li').css('opacity',1)
    $('.thumbs li:not(.mrk)').css('opacity',1)
  }
})

Maybe its missing some () or {} or something like that. I remember I built that .js from surfing Google throughout.

Looks like simple syntax error :

(function ($) {
  /* Slideshow */
  Drupal.behaviors.MYSITE = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
      });

      /* Rollover info */
      $(".block1").hover(function(){
        $(this).find("span.info").stop(false, true).fadeIn("fast");
      }, function(){
        $(this).find("span.info").stop(false, true).fadeOut("fast");
      });

      // Class for every 3rd row.
      $(".view-flavor-listings .views-row:nth-child(3n-3)").addClass("diff-margin");
      $(".view-content-inner .views-row:nth-child(5n-4)").addClass("diff-mrg");

      /* slidePager */
      $('.pages').slidePager({
        last:6,
        borders:1,
        change:function(n){
          var els=$('.thumbs li').removeClass('mrk');
          els.eq(n).addClass('mrk');
          els.eq(n+1).addClass('mrk');
          els.eq(n+2).addClass('mrk');
          $('.thumbs li').css('opacity',1);
          $('.thumbs li:not(.mrk)').css('opacity',1);
        }
      });

      // Make Plupload default.
      $('.filefield-sources-list').each(function() {
        $('a.filefield-source-plupload', this).trigger('click');
        $(this).hide();
      });
    } // attach
  } // behavior
})(jQuery);


How to modify comment-wrapper.tpl.php to change the comment form layout? I am trying to change the layout of my comment form. Unfortunately, when I print only fields that I need and the submit button, I can't use the button, nothing happens when I press on it.

I used following code in comment-wrapper.tpl.php:

    <?php print render($content['comment_form']['field_cuisine']); ?>
    <?php print render($content['comment_form']['field_service']); ?>
    <?php print render($content['comment_form']['field_ambiance']); ?>
    <?php print render($content['comment_form']['field_accueil']); ?>
    <?php print render($content['comment_form']['field_qualit_']); ?>

    <?php print render($content['comment_form']['field_nom']); ?>
    <?php print render($content['comment_form']['field_n_de_carte']); ?>
    <?php print render($content['comment_form']['field_e_mail']); ?>
    <?php print render($content['comment_form']['field_t_l_phone_']); ?>
    <?php print render($content['comment_form']['comment_body']); ?>

  <?php print render($content['comment_form']['actions']); ?>

Everything is displayed as expected, but i can't submit the form.

I also tried something like:

    <?php print render($content['comment_form']['field_cuisine']); ?>
    <?php print render($content['comment_form']['field_service']); ?>
    <?php print render($content['comment_form']['field_ambiance']); ?>
    <?php print render($content['comment_form']['field_accueil']); ?>
    <?php print render($content['comment_form']['field_qualit_']); ?>

    <?php print render($content['comment_form']['field_nom']); ?>
    <?php print render($content['comment_form']['field_n_de_carte']); ?>
    <?php print render($content['comment_form']['field_e_mail']); ?>
    <?php print render($content['comment_form']['field_t_l_phone_']); ?>
    <?php print render($content['comment_form']['comment_body']); ?>

  <?php print render($content['comment_form']); ?>

Like that I can submit the form by pressing on button, but the content of fields are not taken in consideration.

The best solution:

This is the default comment-wrapper.tpl.php:

  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

    <?php print render($content['comment_form']); ?>
  <?php endif; ?>

If you want to modify the form elements by overriding the template file, here is the best known way:

  <?php if ($content['comment_form']): ?>

<?php print t('Add new comment'); ?>

    <?php
    // 1. Create a custom markup
    $form_custom_markup = '';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($content['comment_form']['author']);
    $form_custom_markup .= '
';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($content['comment_form']['comment_body']);
    $form_custom_markup .= '
';

    // 2. Attach the custom markup to the form
    $content['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
    ?>

    <?php print render($content['comment_form']); ?>
  <?php endif; ?>

In this example we make the Author field appear in red background and the comment body in blue background!

You could simply modify the sample above to re-arrange any form element in your form.

Why the normal way didn't work?

To understand this solution and other solutions first we need to understand why forms behave differently than other render arrays.

To start let us have a look at the function that renders a form:

<?php
// form.inc

function theme_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  // Anonymous DIV to satisfy XHTML compliance.
  return '<form' . drupal_attributes($element['#attributes']) . '>
' . $element['#children'] . '
</form>';
}

As you see, when you render($form) it wraps it with ''. It means that any elements that have been rendered before will be out of <form>. That was why when you render render($form['actions']) before render($form) even buttons stop working, because they are out of the <form> element!

What are other solutions?

Using HOOK_preprocess_hook()

As you could see we modified $content['comment_form']. You could do the same thing by using the template preprocess function:

/**
 * Implements HOOK_preprocess_hook()
 * Preprocess variables for comment-wrapper.tpl.php
 */
function THEME_preprocess_comment_wrapper(&$vars) {
  if ($vars['node']->type == 'article') {

    $form_custom_markup = '';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($vars['content']['comment_form']['author']);
    $form_custom_markup .= '
';
    $form_custom_markup .= '
';
    $form_custom_markup .= render($vars['content']['comment_form']['comment_body']);
    $form_custom_markup .= '
';

    // Attach the custom markup to the form
    $vars['content']['comment_form']['custom_markup'] = array(
      '#type' => 'markup',
      '#markup' => $form_custom_markup
    );
  }
}

This example overrides form elements of comment form on article pages.

Tip: You should replace THEME with your theme name and put this function in template.php in you theme folder.

Using HOOK_preprocess_hook()

If you trace where the element is actually generated you will get to this lines in comment.module:

$build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));
$additions['comment_form'] = $build;

We can see this is a form with the form_id of comment_node_NODE_TYPE_form. So we could use hook_form_alter to alter form elements:

/**
 * Implements hook_form_alter()
 */
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'comment_node_article_form') {
    // Play around with $form
  }
}

In this example we are altering the comment form for article nodes.

Tip: Generally using form_alter to change the display of the form is not recommended because it also affects the form_submit() and form_validate() and may cause unwanted issues in future or conflict with other modules.


I can´t publish the title of my contact form I´m  starting to build a site using my own theme, the problem is that I can´t see the title of my contact I start to build my own theme, the problem is that I can´t see the title of my form contact or the title of any views that I was used. Just when change my theme for bartik the title appear.
the site was implemented with Drupal8
my site: www.anep.edu.uy/observatorio2
Thanks in advance

The page title is in a block, you most likely just need to add that to one of your theme's regions (or create a new region for it).

You can place the block through the settings link visiting Admin -> Structure -> Block Layout.

If you need to add a region, define it in your theme's .info.yml file:

regions:
  ...
  page_title: 'Page title'
  ...

And add it to your theme's page.html.twig template wherever you'd like it to render:

{{ page.page_title }}

Flush the cache, and visit the Block layout page again to place the block in your new region.


How can i remove required field validation on click submit button? I have some radio buttons such as draft, need review, etc. I want to remove (omit) the required fields when draft is selected, and click on the submission button.
I tried with below code but it is not working.

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
 if($form_id =='catalog_node_form')
 {
  $form['#validate'][] ='remove_required_field';
 }
}

function remove_required_field($element)
{
 foreach (element_children($element) as $name)
 {
  $element[$name]['#required'] = FALSE;
 }
 return $element;
}

In the form_alter function you can use the limit_validation_errors property.

'#limit_validation_errors' => array(),

The above code will not perform any field validations. You can then add the individual fields that you need to validate here using the below code.

$form['actions']['next']['#limit_validation_errors'][] = array($field_key);

Where next is the action that I am using.


How do I programatically create and display a one-off view? I am programmatically generating views based on an entity with varying fields  and saving them with $view->save().  Just to be clear, I have to do this because my entities have x-amount of fields, and the view needs to display all the fields.

I am thinking that creating all these views in the database might not be a good long term plan, especially when I go into the Views UI, and see a billion views there.

Can I create a one-off view (e.g. typical Views export code producing a block), and print its block to a page without saving it?

I figured it out myself in the end - by looking at how Views does it itself in views_block_view().

function page_callback($my_entity) {
  //create view
  $view = new view();

   ... //Do all the views creation stuff e.g. code in export view

  $display_id = 'block_1';
  $view->new_display('block', 'Block', $display_id);

  if ($view->access($display_id)) {
    $output = $view->execute_display($display_id);
    views_add_block_contextual_links($output, $view, $display_id);
    $view->destroy();
    return $output;
  }
$view->destroy();
}

The above code renders a view that is created from scratch and never saved to a database.  If you wanted to do a page you could look at the code in views_page().


How do I show a list of nodes referenced by a field? I created two content types: News Agency and News.
The News content type has the Headline, Title, Body, and News agency name (a reference to a News Agency node) fields. The News agency content type has the News agency name and Publisher fields.

I need to show the news related to particular news agency. I am trying to set a relationship, but it still doesn't show result.

The "Entity reference" field has a few options about how to display the referenced entities (Label, entire node, Node ID).

But you're referencing News agencies from News nodes, not the other way around. So you're able to choose how News agencies are listed on News pages through the "Manage display" settings in Content type.

If you want to list nodes on the News agency pages you need to use Views to create "backwards" Relationship:

Create Views listing News, Block display
Add a Contextual filter for the Entity reference field relating to the News agency and configure it
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Related? News agency

Test the configuration by entering one of your News Agency NIDs into the Views Preview field. You should see News nodes that relate to that agency in the view results.
If everything is working as expected place the Block into a region in your theme and configure it to only appear on the News Agency pages, and configure the filter option for the reference.

Now when you visit News Agency pages you'll see a list of all News that relate to that agency.


Drush cannot connect to mysql I have a problem with Drush to enable or disable module. But downloading modules works perfect! However I want to use Drush in its full range.

Yesterday, I saw my Drush would not succeed in connecting to the database. I already tried to update the path in .bash_profile to the AMPPS path. But after that, my bash cannot find the database any more. I already deleted the line but bash don't find mysql.

Anybody has an idea about what to do to resolve this?

Below are the various messages I received:

  Sams-MacBook-Pro:demo Sam$ drush en views -d

  Starting Drush preflight. [0.01 sec, 1.82 MB]                        [preflight]

  Cache HIT cid:                                                         [debug]

  7.0-dev-commandfiles-0-9942ce60ec4ba1e3ca6f94d08d021773 [0.01 sec,
  1.88 MB] Bootstrap to phase 0. [0.09 sec, 5.75 MB]                   [bootstrap]

  Bootstrap to phase 6. [0.09 sec, 5.76 MB]                            [bootstrap]

  Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.09 sec,    [bootstrap]
  5.76 MB]

  Initialized Drupal 7.34 root directory at                              [notice]

  /Applications/AMPPS/www/demo [0.1 sec, 6.09 MB]

  Cache HIT cid:                                                         [debug]
  7.0-dev-commandfiles-1-68c4337f6c538cdf6d3ca715c4afb7a3 [0.1 sec,
  4.17 MB]

  Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.1 sec, 4.18[bootstrap] MB]

  Initialized Drupal site default at sites/default [0.1 sec, 4.18 MB]    [notice]

  Cache HIT cid:                                                         [debug]
  7.0-dev-commandfiles-2-9518eda12b48158193bd617384d95a7d [0.11 sec,
  4.18 MB]

  Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.11[bootstrap] sec, 4.18 MB]

  sql-query: SELECT 1; [0.11 sec, 4.3 MB]                              [status]

  Executing: mysql --defaults-extra-file=/private/tmp/drush_9NOj8N
  --database=demoDB --host=127.0.0.1 --silent  < /private/tmp/drush_gIJn4w

  sh: mysql: command not found

  Bootstrap to phase 5. [0.12 sec, 4.3 MB]                             [bootstrap]

  Command pm-enable needs a higher bootstrap level to run - you will   [error]

  need to invoke drush from a more functional Drupal environment to run
  this command. [0.12 sec, 4.3 MB]

  The drush command 'en views' could not be executed. [0.12 sec, 4.3   [error] MB]

  Drush was not able to start (bootstrap) the Drupal database.         [error]

  Hint: This may occur when Drush is trying to:

  bootstrap a site that
  has not been installed or does not have a configured database. In this
  case you can select another site with a working database setup by
  specifying the URI to use with the --uri parameter on the command
  line. See drush topic docs-aliases for details.
  connect the
  database through a socket. The socket file may be wrong or the php-cli
  may have no access to it in a jailed shell. See
  http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:

  Drupal version         :  7.34
  Site URI               :  http://default
  Database driver        :  mysql
  Database hostname      :  127.0.0.1
  Database port          :
  Database username      :  demoDB
  Database name          :  demoDB
  PHP executable         :  /usr/bin/php
  PHP configuration      :
  PHP OS                 :  Darwin
  Drush version          :  7.0-dev
  Drush temp directory   :  /tmp
  Drush configuration    :
  Drush alias files      :
  Drupal root            :  /Applications/AMPPS/www/demo
  Site path              :  sites/default

  [0.17 sec, 6.42 MB]   Sams-MacBook-Pro:demo Sam$

Ok i solved that problem my own. I have deleted the Drush Version 7.x and installed the 6.x Version. it works like a charm.


show PDF absolute URL in Views table I've got a column of links to files in a table. They're displayed via file-fields with  'Output this field as a link" enabled in Rewrite Results. It's works great with fx images but width pdf's the table only shows the filename, not the path to it.

Any ideas on how to always show the complete path to a file no matter the file type?

In views Change the Formatter  of the field from Generic file
to URL to file.
Go to REWRITE RESULTS and check 'Output this field as link' and
use replacement pattern of the file field.
check Use absolute path to get absolute path link of the file

That's it you will get complete path of the file instead of file name at output.


Adding Drupal field "subtitle" to page template I have created a Content Type called "Happy Days". I have created a field in that called "subtitle".

In my template "page--happy-days.tpl.php", I want the field "subtitle" to show wrapped in an  tag. I attempted:

<?php print render($content['field_subtitle']); ?>

but no luck. Any help would be appreciated.

I assume you cleared the cache. Your issue is page--content-type.tpl.php override not working. Try to suggest theme hook in THEME_preprocess_node.

Furthermore you need to theme nodes of Happy Day content type, so you must use node--CONTENT_TYPE.tpl.php. For more information visit Theming nodes by content type page.


How to get all filters and functions available in Twig templates? I have an option to create and edit twig templates via UI but I need to display what filters and functions are available to the user but I don't know how to get them.

From procedural code:

\Drupal::service('twig')->getFilters();
\Drupal::service('twig')->getFunctions();

Unless the Twig service is overridden this is calling the methods on the vendor Twig_Environment class.

For OO code you should inject the Twig service into your class. https://drupal.org/node/2133171 and https://drupal.org/node/2203931 have some documentation and examples on how to do that.


How to set the default page of my site? I want set the default frontpage of both my local and production site site.

In my local environment I created a content it has node id (/node/20) and it has URL alias of /homepage.
In the Basic site settings I set my default frontpage to /homepage

In the production environment I also create a content it has node id (/node/33) and it has URL alias of /homepage.
In the Basic site settings I set my default frontpage to /homepage.

Whenever I deploy something to the production environment, I export the configuration of my local environment (in the Drupal CMS) and I will import to the production environment.
But whenever I import my configuration to the production my default frontpage is setting my homepage to /node/33, why is drupal doing this? I specifically set the default page to /homepage.

I'm using drupal 8 by the way.

Drupal core expects only internal URL (node/123) in the page.front setting. See \Drupal\Core\Path\PathMatcher::isFrontPage.

To be able to set page alias in the front page settings, I have created
a workaround. I made a replacement of the path.matcher using an alias fallback:

mymodule/src/MymoduleServiceProvider.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the path matcher service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Override the path matcher for the alias fallback.
    $definition = $container->getDefinition('path.matcher');
    $definition->setClass('Drupal\mymodule\AliasFallbackPathMatcher')
      ->addArgument(new Reference('path.alias_manager'));
  }
}

mymodule/src/AliasFallbackPathMatcher.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Path\PathMatcher;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * The path matcher with alias fallback implementation.
 */
class AliasFallbackPathMatcher extends PathMatcher {

  /**
   * The alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Creates a new PathMatcher.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The alias manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RouteMatchInterface $route_match, AliasManagerInterface $alias_manager) {
    parent::__construct($config_factory, $route_match);
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   *
   * Support path alias for the front page path.
   */
  protected function getFrontPagePath() {
    if (!isset($this->frontPage)) {
      $path = parent::getFrontPagePath();
      $this->frontPage = $this->aliasManager->getPathByAlias($path);
    }
    return $this->frontPage;
  }

}


User account and Commerce addressfield bug I found out that when I enter a "Full name" in the commerce shipping and billing address information, the [user:name] value will be changed to the "Full name" entered.

As you can see the user name in the first picture is different from the value of the [user:name] token.

However, when I enter a different "Full name" for subsequent orders, or change the username it doesn't modify the value of the [user:name] token.

Is there a way to stop the commerce shipping and billing to modify the [user:name] token or to change the value of the token manually?

Thank you for your help.

I modified the user.tokens.inc file by changing $user['name'] to $user['login-name'] and commented out a line and this seemed to fix the problem of the tokens, as the token isn't modified by the username value in $account.

case 'login-name':
//$name = format_username($account);
$replacements[$original] = $sanitize ? check_plain($name) : $name;
break;

However, as you can see, I still haven't solved the problem of the the username field in $account is being modified by commerce shipping and billing. The result is the same whether I set the field to "Full name" or "First name" and "Last name". Inspecting the addressfield module, I can't find the part where it modifies the $account username.


Pass NID to contact form I have a website with a lot of furniture products.
Each node page has a link to "ask for more info" that opens the sitewide contact form. When I receive the e-mail message, I need to know to which product (node) the request refers to, because many people forget to say it. So I need to pass node url, title or nid to the form in order to insert it automatically in the sent contact e-mail.

Thank you very much

this link "ask for more info" needs the nid appended as query string. and then in the form this can be used.


How to use Git with Drupal 8 when using composer I am working on an OpenSocial project and its installed via composer. I am having a folder structure as below:

 - composer.json
 - composer.lock
 - html
  (Drupal Installation.)
 - vendor
  (Dependencies)

When creating, should I add the all files including composer.json and vendor to git or just add the content of html directory?

Note In some cases, for example in a normal D8 installation the composer
 files and vendor directories are in the same directory as Drupal installation.

Short answer: no, you do not need to commit the vendor folder, because the contents are built using composer.lock and composer.json (both should be committed) when running composer install. Some people have to commit vendor due to their hosting constraints and/or having no build process (where the application is built for deployment).

IMO management via Composer with vanilla D8 tarball is very difficult as it lacks the structure to facilitate solid version control, project management and patching workflow that others like Drupal Project or Acquia BLT offer.


Content API - parameter to find link url of a Link field I have a custom content type called Link, which has a Link field. I'm using services and Content API to query the list of Links, and I want to show the data for a Link node where the Link is equal to a parameter passed into the URL.

Eg, I would like to do something like the following:

[Drupal root]/api/content?field_link=http://www.google.com

The Content API is a tricky thing to get the hang of, but try to do the following:

As long as your Rest Server endpoint path is "api" and the resource is "content" what you have above should technically work.  Make sure you also enabled the Link content type in the Content API configuration.

When you do query with /api/content?field_link=http://www.google.com you will only get the base fields returned, even if you filtered by http://www.google.com it won't show in the response you get.  You then have to send another request to /api/content/ and that will return every field for that given node.

Hopefully this helps a little bit, if anyone can fill in my holes I would appreciate it, I'm by no means an expert, just played around with the Content API and got it to work a little.

I did respond to your email with some private links to prove that it is possible.


How to use different fields for different content types in a view I want to construct a view which will include nodes from several content types.

For each different content type, I want to display different fields (say an image for a type, a video for another, some different text for others)

Let me show you the example I want to achieve:

row 1 is "image", row 2 is "video", row 3 is "event" content type. So,

John shared a new image:
IMAGE
Jane is watching a video now:
VIDEO
Jack is thinking "this day is sunny".

Have you tried anything so far?

Try creating your view and select unformatted list as your style.
Add your fields as you would normally.
Under format, select settings and make sure that "Hide empty fields" is clicked.

If you fetch lets say the first five nodes from content types Images, Videos, Statuses then each row of the view should look like this:

==row 1==
John shared a new image: IMAGE
John is watching a video now: VIDEO
John is thinking "this day is sunny".

==row 2==
Jane shared a new image: IMAGE
Jane is watching a video now: VIDEO
Jane is thinking "this day is sunny".

==row 3==
...

but if row 1 is a result from the Video content type then the fields image and status should be empty and will be hidden since you clicked that format option before.
Try it and see if it works for you.


Field Type: Text vs. Long text What are the differences between 'Text' and 'Long text' in Drupal 7?

If it is simply database character length, is it better to be cautious and default to using Long text in situations where the domain of possible entered values is not precisely known?

The differences are laid out in text.module.

text fields are stored as varchar with a maxlength of 255 characters, and their default widget is a simple text input.
long text fields are stored as longtext, with a maximum length of 4 GiB (maximum characters depending on the encoding), and their default widget is a textarea
text with summary fields are like long text fields, except that text processing is enabled by default. That is, summary text can be included along with the main text, and the content will be processed through input filters. The default widget is a "textarea with summary"

Generally, long text and text with summary fields are used for, well, long text— anything longer than a few words or a few dozen characters: body text, lengthy embedding code, data tables, and so on. Ordinary text is better suited to short snippets of text: a personal name, a company tagline, a favorite color.

I think it would be rare that your data would be suitable to either type. If you're storing a biography for a user profile, for example, you would have a clear idea as to whether it is expected to be a narrative of several paragraphs or simply a short personal motto.


How can I filter an index view using REST? I have a custom content type called 'Regions', which simply has a title field. Example values are: Asia, North America, Ocenia, etc.

I've set up a view for this list and a REST export for it, so /regions gives me a simple list:

[{"title":"Asia"},{"title":"North America"},{"title":"South America"},{"title":"Ocenia"}]

I want to filter the results, so I added a contextual filter on the title field, making /regions/Asia show only Asia:

[{"title":"Asia"}]

How do I implement a wildcard search? Something like as should match Asia and amer should match both North America and South America. I'd like to do something like /regions?title=Asia

I referred to this guide on setting up contextual filters, but the following doesn't seem to work for me:

  This query works as a SQL LIKE statement so you can send just a piece of the name and Views will try to find all records LIKE that argument, example, I have a brand called Land Rover but if I just send Land as an argument it will work http://dev-cars-api.pantheonsite.io/api/cars/Land

The URL in the quote is no longer online, so I can't check if it actually works. For me, only entering a full, matching item title works. I can't even specify a title with spaces, so /regions/North+America is also blank for me.

My Drupal version is 8.4, running on PHP 7.1.

The solution is to add a search filter to the view.

In the view settings, under Filter Criteria, you'll see Content: Published (= Yes) and Content: Content type (= Regions) (or whatever your view is for).

Click add. In that box that shows all the fields you can add, type Search: Search Keywords.
Tick Expose this filter to visitors, to allow them to change it.
(optional) Rename the Filter Identifier from keys to query or terms or whatever you see fit.
Save the view.

You'll then be able to make a GET http://example.com/api/regions/?_format=json&keys=my+search+string!


Unable to change the widget for a webform coponent When editing a webform component (7.x-4.23) selecting a different widget type (e.g. from email to hidden) has no effect.

Disabling module Hide Submit Button (7.x-2.4) restored the webform functionality.


How can I add a tab to the admin/content page I'm new to drupal, so sorry if this is a stupid question.

While developing a module, is it possible to add a tab to the /admin/content page (where by default there is content, comments, files)

Currently using 8.0.6

Similar to Drupal 7, tabs are called "local tasks". Your module should implement a local task and a route.

The complexity in this is that /admin/content is a views-generated route with a system module fallback in case the view is disabled (as explained by @Berdir below), and the base route should be system.admin_content.

mymodule.mytask:
  title: 'My Task'
  route_name: 'mymodule.mytask.route'
  base_route: 'system.admin_content'
  weight: 1

If the view itself isn't altered, then the route is view.ID.page_NUMBER. I've done this latter thing working on an entity example module in my sandbox (Shift).


Change the size of the form element for content title I could have sworn that when we created our content type, we could select the size of the textfield for the title. I am unable to find that now as I'm in "Manage Fields" and the edit link that's available for other fields is not there for the title field. It says only in field type "Node module element". I even tried looking through our database to see if there was a place where this was set and I couldn't find anything. Am I missing something simple?

You don't have the options of choosing your title field lengths in standard D7.
However, there is a module that lets you change that:

https://drupal.org/project/title_field_ui

The only problem is, that the module is only in alpha and not widely used. On the other hand, the module author is very reputable, so I'd give it a try.

Other solutions have been discussed before:
Change / Increase the node title length


add class to form element function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
   $form['fbuser'] = array(
      '#type' => 'item',
      '#markup' => 'You have a facebook account?',
      '#weight' => -10,
    );
   $form['login_link'] = array(
      '#type' => 'item',
      '#markup' => '
',
      '#weight' => -6,
    );
   }

How can I add a class to this div's?

You might be looking for the #attributes property that you can add to forms and form elements. See example below

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
   $form['fbuser'] = array(
      '#type' => 'item',
      '#markup' => 'You have a facebook account?',
      '#weight' => -10,
      '#attributes' => array('class' => array('my-class-1')),
    );
   $form['login_link'] = array(
      '#type' => 'item',
      '#markup' => '
',
      '#weight' => -6,
      '#attributes' => array('class' => array('my-class-2')),
    );
   }


How to loop through comments using the Rules module? I have created a rule (using the Rules module) using Rules Event "After updating existing comment" and some comment fields must be changed.

Loop node:comments is used but nothing happens when component is used to change a field (list_item is considered as Any entity (parameter) to use it in the component). node:comments doesn't work in that case. What can be done?

How to loop through comments using Rules

Have a look at this rule (in Rules export format, you should be able to import it in your own site if you have the Rules UI enabled):

{ "rules_change_a_comment_field" : {
    "LABEL" : "Change a comment field",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_update" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "An update to some comment has been discovered ... Some more details about this updated comment:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment body (before) = [comment-unchanged:comment-body:value]\u003Cbr \/\u003E\r\nComment body (after) = [comment:comment-body:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment author (before) = [comment-unchanged:author]\u003Cbr \/\u003E\r\nComment author (after) = [comment:author]\u003Cbr \/\u003E\r\n" } },
      { "LOOP" : {
          "USING" : { "list" : [ "comment-unchanged:node:comments" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "drupal_message" : { "message" : "Now processing comment with cid=[list-item:cid] and body = [list-item:comment-body:value] ..." } },
            { "entity_fetch" : {
                "USING" : { "type" : "comment", "id" : [ "list-item:cid" ] },
                "PROVIDE" : { "entity_fetched" : { "comment_fetched" : "Fetched comment" } }
              }
            },
            { "data_set" : {
                "data" : [ "comment-fetched:author" ],
                "value" : [ "site:current-user" ]
              }
            },
            { "entity_save" : { "data" : [ "comment-fetched" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

In this rule, for the sake of simplicity, I intentionally did not use a Rules Component (I just included my entire Rules logic in a single rule). Here is a summary of what the above rule does:

Rules Event: After updating an existing comment.
Rules Actions: Loop over each of the comments, and perform these actions for each of them:

Show a message on the site (just for demo purpose, to know what the rule is processing).
Fetch entity by id, to retrieve all data about the comment entity being processed in the loop.
Set a data value, to change the author of the comment being processed to the current user (this may seem a bit bizarre, I know, but consider it as just a demo sample, to illustrate you can update EACH comment processed in the loop).
Save entity, for the comment entity being processed in the loop. If you don't perform this action, then I'm pretty sure the updated value won't have been saved in the end (which is probably also what you experienced in your nothing happens).

Disclaimer: there may be more refined (optimized) solutions to get such rule to work, but using the above Rules actions (and meaningful variables ...) should help to understand what's happening if you're not experienced enough with Rules (yet).

Attention: be careful if you import the above rule (and leave it active) ... because this rule really works (and will change all comment authors to the last user who updated any comment).

Plan B

If what's above doesn't help, then something that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).

Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 variations.


Add nodes in grid style I need to add nodes in grid style i.e inline adding of the nodes should be done there only. i.e use can add any number of nodes at a time.

You can use the Views module plus Slickgrid to do that.

The module:

  defines a slickgrid view style, so all data can be output as an editable grid.

And can also be used for data entry/manipulation directly within the grid itself.