texts:
I have this function that I used in a similar situation (Drupal show all terms of different vocabulary) that prints the terms of a node with a corresponding parent (if applicable). In my template.php file:

function theme479_print_terms($node, $vid = NULL, $ordered_list = TRUE) {
     $vocabularies = taxonomy_get_vocabularies();
     if ($ordered_list) $output .= '
'; //checks to see if you want an ordered list
     if ($vid) { //checks to see if you've passed a number with vid, prints just that vid
        $output = '
';
        foreach($vocabularies as $vocabulary) {
         if ($vocabulary->vid == $vid) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= 'vid . '">';
             if ($ordered_list) $output .= '
vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = 'tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '
';
             $output .= '';
           }
         }
       }
     }
     else {
       $output = '
';
       foreach($vocabularies as $vocabulary) {
         if ($vocabularies) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= '
vid . '">';
             if ($ordered_list) $output .= '
vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = 'tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '
';
             $output .= '
';
           }
         }
       }
     }
     if ($ordered_list) $output .= '
';
     $output .= '
';
     return $output;
}

I have this vocabulary structure:

Foods

Fruits
Fruit_with_seeds

This function only shows:

Fruits

Fruit_with_seeds

Is it possible to show the entire hierarchy of a vocabulary?


texts: What is stopping my theme from using a file that uses a suggested file name?

texts:
I needed to modify a module's .tpl file and so copied it, renamed it to something suggested by Theme Debug's file suggestions.

Eg when I run drush theme_debug I see:

<!-- FILE NAME SUGGESTIONS:
   * image-resp-item--f6.tpl.php
   x image-resp-item.tpl.php
-->

So I rename my new file image-resp-item--f6.tpl.php and place it in my site's theme.

I clear cache and rebuild the theme registry but to no affect - the site still uses the original .tpl.

To experiment, I change my new .tpl's name to match the old one (remove --f6). This works - I see my new code appear on the site.

Why is my site (or theme?) not wanting to use the suggested file name?


texts:
I may be thinking about this the wrong way, but I would like to download a feature that is already created. I know how to create a feature and download it, but how do you download a feature that already exists so you can use it on another site? Preferably in Drush.

I'm using Drupal 7.50. Thanks!

Edit: I figured out that in the UI, if you create "recreate", you can download it from there. How can this be done in drush though?


texts: The default favicon shows up while the page is loading but it switches to my custom favicon after

texts: I have my custom favicon.ico set up in my themes custom folder and it renders correctly for every page on my site. However, in the process of it rendering, it flashes the default Drupal logo for a split second before showing my custom favicon. I have my Global Settings set to Use the favicon supplied by the theme, then both my Claro and custom theme set to the path of my custom favicon(the favicon used by Global Settings in my themes custom folder). Any ideas on whats causing this?


texts:
I have a content type with a field that has been set to inactive. This happened after I reverted my feature in an attempt to undo a change I made to the content type.

The error message given is the following:

  This content type has inactive fields. Inactive fields are not included in lists of available fields until their modules are enabled.

I've disabled and re-enabled the feature module, but the field is still inactive.

How can I activate my field?


texts: Importing blog articles from a WordPress site

texts: I am looking for a module to import any blog written on a WordPress site. Is there any module to do this?


texts: How to hide user profile(edit current password, email, picture, everything) based on role?

texts:
When user logged in with common shared username and password, I wanted to hide user profile for some of the user based on the given role.

So, I want a feature where user can just logged in and logged out with the given shared user name and password and, I don't want to allow them to change their password or I don't want to allow them to edit in their profile.

I have created separate role for this users.

I came to know that we can hide edit user profile with CSS:

display: none;

Is there any other way to hide user profile based on some roles?


texts: How to get last_comment_timestamp for a node

texts: Can someone tell me what table to look for to get the node's last_comment_timestamp?


texts: Passing variable from preprocess block to the block body

texts:
There is a block which its body is produced by PHP Code. I need to set a variable before loading the block and use it in it. This is my code

function THEME_preprocess_block(&$variables){
    $variables['var']="some text";
}

when I open the block configuration page and in its body I write

<?php print $var;?>

it prints nothing. How do I can pass variable from block template page in to the block body in the block configuration page?


texts: In Views, how can I show users with one role before all other users?

texts:
I have several views of users and I want to show all users with a certain role (example, "show_me_first") before all other users in all of these views.

I thought this would be easy, but apparently there is no "User: Role" as a sort criteria (I'm using Views 3.5 on Drupal 7.15).  I can filter by role, but I don't want to filter; I just want to show users with the role "show_me_first" before all other users.

How can I implement this?  Minimal view customization is best because I will have to repeat this for a lot of views.  If there is a way to do it without using roles, I would be open to that as well.


texts: Returning code in views search tpl but ONLY if user clicked 'search' button and results were returned

texts:
I have a Views-based search page on my site. I've created a views-view-search--tpl.php file to customize the order of elements on the page. I have a specific block I'd like to return but ONLY if a user has already clicked the search button and results were returned.

Here's the code I'd like to return based on that condition:

  <?php if ($feed_icon): ?>
   <div class="feed-icon">
    <?php print $feed_icon; ?>
   </div>
  <?php endif; ?>

I guess I probably need an 'if' statement or something before that block but I'm not sure how to reference if results and/or if user clicked the search button...

Anyone know how to do this?


texts: How do you save data that is in fields inserted via hook_form_alter?

texts: I created a module that just uses the hook_form_alter to add additional fields to an existing form. The problem now is when I enter in the information and submit none of the information inputed in the additional fields get saved when I go back to the form.


texts:
Is it of any advantage, in addition to using Global Redirect, to rewrite html links from /node/nid to /article/this-is-the-title, even though in both cases traffic is directed to /article/this-is-the-title (by Global Redirect).

Edit:

From this answer I gather that I should use Global Redirect so that aliases wouldn't cause "duplicate" content.

The same answer suggests a way to intercept links, passing them through functions to "convert from node/nid to article/title". However, I am green at coding Drupal, and have no clue as to go about it. Could some one advise on alternatives? Or ways of making this less cumbersome?

I am also adding this link to a related answer on avoiding disadvantages of 'same content/multiple URLs' for whoever's reference.


texts: Responsive design on a page using Accordions

texts: I've been wondering how to make the text on this page (http://confluencenter.arizona.edu/events) stop overflowing into the images. I have tried floating the text under the images, but it is reset by some module. I have some experience in CSS but am still very new to Drupal. I did not create this website.


texts: Add attributes to wrapped element in Display Suite field template

texts:
Is it possible with Display Suite to add an attribute to a field's html tag.

I want to add a class to the read more link. I've tried hook_ds_field_theme_functions_info(), but by that time the link has already been rendered. I was hoping to find a render array.


texts: How to use a hyphen instead of an underscore when using the content type as a Views argument? (Hackable URLs)

texts:
I have a classifieds site where I would like to list items at a URL structure like this:

classifieds/for-rent/apartments/title-of-my-ad.

That structure is broken down like this (views-page)/(content-type-argument)/(taxonomy-term-arg)/(node-title)

What I want to happen is this: If someone removes  then all nodes will be listed that are apartments, which were created with the 'for rent' content type; If someone remove apartments (the tax arg) then all 'for rent' items, regardless of taxonomy, are listed.

See what I am getting at?

My problem is that the content type argument has to be written with an underscore instead of a hyphen before it will work. I want to use a hyphen. It's not as ugly, plus Google specifically recommends hyphens in the url instead of an underscore, and I want to keep google happy.

so, given the above example,

classifieds/for_rent/etc/etc <= works fine.

classifieds/for-rent/etc/etc <= does not work.

How do I use the hypenated form as the argument? Is there a way to do this in views? Is there a way to write something in the .htaccess file so that when an argument is received with a hyphen the url is passed with an underscore behind the scenes?

Thanks!


texts: Is a DB transaction executed when it is committed?

texts:
cache_get() is not working as expected when called in a request initiated by drupal_http_request() on the same server.  Is it true that the cache_set() immediately before drupal_http_request() doesn't actually take place in the database until the first database transaction is committed?

Given the sequence:

cache_set($cid, $data)
cache_get($cid) // returns data
external request using drupal_http_request()

cache_get($cid) // same $cid, returns FALSE

cache_get($cid) // of course, returns data

To make the cached item available to the request initiated by drupal_http_request() I wrapped the cache_set call in a function like this, but it had no effect.

function cache_set_wrapper($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  $txn = db_transaction();
  return cache_set($cid, $data, $bin, $expire);
}

Why is there a discrepancy in the cache between the initial request on the second request?


texts: Route not registered (likely hook_menu() not called)

texts:
This question follows this one, where I was asking for help about an Ajax call resulting in 404.

I didn't received any answer solving my issue so I continued digging it, then I discovered that it's due to hook_menu() not registering my MENU_CALLBACK route in the menu_router table.

Here is my hook_menu() implementation:

function myModule_menu() {
  return [
    'myModule/ajax' => [
      'page callback'     => '_myModule_ajax_handle',
      'access arguments'  => ['access content'],
      'delivery callback' => '_myModule_ajax_delivery',
      'type'              => MENU_CALLBACK,
    ],
  ];
}

I can't see what might be wrong in it.

Then taking advantage of this that my site contains another module of my own, working fine from times, I modified it's hook_menu() including the exact same route, so it looks like this:

function otherModule_menu() {
  return [
    'myModule/ajax' => [
      'page callback'     => '_myModule_ajax_handle',
      'access arguments'  => ['access content'],
      'delivery callback' => '_myModule_ajax_delivery',
      'type'              => MENU_CALLBACK,
    ],
    //... already present routes for "otherModule"
  ];
}

This way, the myModule/ajax route appears in the menu_router table as expected (and so, quite ironically, my Ajax call gets successfull ;).

So the only assumption I can make now is that hook_menu() is not called in the context of myModule (while it is called when in otherModule).

Based on that I explored Drupal Answers (and more generally googled) without success: all posts I found either had different issues or obvious errors.

NOTE: indeed my module is active, indeed I'm clearing the cache at each try...


texts:
I use drupal 6 and ubercart 2. I need to pull cck field data from product nodes and display it on cart block along with products that are already in cart

I created a simple custom module using hook_cart_item

function instore_cart_item($op, &$item) {
  switch ($op) {
    case 'load':
   $node = node_load($item->nid);
   $item->instore = $node->field_instore[0]['value'];

And try to display the values using a template file for cart like this

print $item['instore']

So far I am getting no results. Can anybody help me with the code?


texts: How can I restore the security of an old site with a sql injection vulnerability which was probably exploited?

texts:
Edit: Sorry, the question was marked as unclear. In a nutshell, there are two questions:

Does the code below indeed create an sql injection vector? (It seems clear that the answer is yes, even though I was unable to craft a successful attack on my current server architecture.)
Assuming someone successfully exploited that sql injection vector on the old server, what would I have to do to make sure that there are no leftover attack vectors? Would it be sufficient, for example, if I took the following actions:

Move to a new server
Build a new Drupal codebase from scratch
Remove the insecure code from the theme
Block or delete all users except those that are recognized
Force password resets for the recognized users
Check the menu_router table for bad items
Check all node and comment titles, bodies and fields for  tags

...Or is the situation even more hopeless than that, and the site should simply be abandoned or rebuilt from scratch? For various reasons I don't think it is possible to restore from a backup, mostly because the attempted exploits go back 6 years.

=== Original post ===

I'm looking at an old D6 site that was done in a very non-standard way. What concerns me most are some .tpl.php files from the theme that use $_POST parameters to insert data into some tables, e.g.:

<?php
  $uid = $user->uid;
  $name = $user->name;
  $title=$_POST['title'];
  $comment=$_POST['comment'];
  $nid=$_POST['nid'];
  $cid=db_result(db_query("select  max(cid) from  comments"));
  $cid2=$cid+1;
  $timestamp=mktime();
  db_query("insert  into  comments  values($cid2, 0, $nid,$uid,'$title' , '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', null, null)");
 ?>

This seems like very straightforward sql injection vector, but I'm not really an expert at exploiting such things, and my relatively feeble attacks have been caught by the new server. However, there are 1000 entries in the database where the titles are pretty clear attempts to execute injection attacks, and worse yet are the 1000 more with empty titles which might represent attacks that were successful.

So how bad is this? Here is my scale:

37GB of spam! Ha ha ha! No problem!
Removing the insecure code and moving to a new server should be safe.
The site will not really be safe until you switch to a new server, remove all the insecure code, and run some automated tests on the database and/or file structure to check for residual attack vectors.
The site will not really be safe until you switch to a new server, remove all the insecure code, and then go through each file and each database row and manually check to make sure that it isn't an attack vector — in other words, it's probably easier to give up and start over, no matter the size of the site.


texts: Creating new Solr index when using Solr without Search API

texts:
I've previously worked with Solr with the Search API module, but currently I'm working on a client project which is hosted at Acquia, and since they seem to discourage using Search API in favor of the non-Search API Solr modules, I'm trying to see if I can accomplish my task without Search API.

I've hit a wall, however, in that I want to add a new "index," to use the Search API terminology. The site already has a single index for general site search, but I want to add one that will only index content of one type and have particular facets and such. With Search API it's very easy to create a new index, but I haven't yet been able to figure it out without it, and haven't been able to find an answer via search engine - maybe "index" isn't the terminology I need to use here…?


texts:
So I have this Drupal 8 site with its custom theme, some blocks, menus, content types, views and other more stuff. What I am required to do is create a site distribution of this site for drupal.org, but I have absolutely no idea of how to do it.

I created the profile folder in doctoot/profiles and created the info.yml with the profile basic information. I also have the .install and .profile files but they are empty. These files were created using drupal generate:profile

After that I exported the config YAML files using drush config:export, but they were created in config\sync in the profile folder, but I saw in another distributions that these files are located in config\install rather than sync,and I don't know if that makes a difference.

I don't have anything besides that and I don't know what to do after that to configure things in the distribution in terms of theme and configuration. I have the project page in drupal.org already with the git configuration. Hope you can help me with this issue.


texts:
How can I get an email notification when there is a new subscriber? I can't find this setting on the Simplenews module, but I do find "Send e-mail" in "Configuration > Actions".

Does Simplenews has this feature? Can Send e-mail actions make this work? if so, how?


texts: TB Mega Menu: The website encountered an unexpected error. Please try again later

texts:
I have installed drupal 8.0.2 on my hosting for testing purposes. I am using Zircon template and installed TB Mega Menu 8.x-1.0-alpha1. After installation, on page: admin/structure/tb-megamenu, when I click any of button, I get the following error:

The website encountered an unexpected error. Please try again later.

by searching google, I came accross with a solution: https://www.drupal.org/node/2623306

But as a new to drupal and environment, I do not know how to do it. I have never tried patching before and most importantly it is the solution for the case.

If patching is the solution, which program should I use, how can I accomplish this step by step?


texts: Errors when trying to send e-mail when using Ubercart

texts:
I am aware of the many other:

  Unable to send e-mail. Please contact the site administrator if the problem persists.

Questions that have been asked however, I believe my situation to be a bit different.

Situation:

I have been tasked to make some updates to my companies website. They are hosted and use cpanel for management. I have been working with the Drupal portion of the site and have been getting the Unable to send e-mail error when trying to do any of the following:

Create a user account
Retrieve lost password
Use any of the e-mail functions in Ubercart (order confirmation ect..)

Question:

Are there any settings that I should be looking to change or is this something that needs to be configured in a config file. I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart.

Things I have tried:

I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart. I have also set up the site e-mail (Home » Administration » Configuration » System).


texts: Filter View by Entity Reference Value From Current Node

texts:
I've been trying to figure this out for a while now, I believe that this should be easy but I still can't solve it. I'm a beginner at this. -_-

I have 3 Content types

Venue
Food
Package

I have a List of Venue that will be used as reference for the Food. So, The Food content type has an entity reference field -> field_venue

The Food will only be available to the venue it referenced.

The Package Content type has the entity reference Venue and Food. It shows the venue and the food available.

I use Entity Reference View Widget for the Entity reference on Package Content Type. The Venue is working well.

My Problem is the Food.

I need an Entity Reference View Widget (VIEW) that shows the available food for the Venue.

On the form, the user will only be able to answer the Venue field. After that the form will be saved and the entity reference field for Food will display on the page, that is the place where the user will answer that field.

On the entity reference view widget Food, I have the following:

Filter Criteria:
Content Type: Food

Relationship:
Entity Reference: Referenced Entity (field_venue) marked as required

The problem is that the view shows all the food even if the chosen venue is not available for that food. I don't know where to put that condition. Either on contextual filter or Filter Criteria. I'm not sure. I just need the view to get the Answer of the Venue from that same form/node so that the Food will filter automatically.

Is there anyone that will be able to help?

Thank you very much!!!


texts:
Drupal 8, When we go to URL aliases section, there is no URL pattern option like Drupal 7.

Do I need to install any other modules to have this feature available?

Edit

Added screenshot

Drupal 8

Drupal 7


texts: Unable to install the Cloudinary Integration module

texts:
I downloaded the Cloudinary Integration module and installed it.

The module appears in the module list, but I cannot enable it. The modules page shows this message after the description of the module.

  Requires: Cloudinary Stream Wrapper (disabled), Cloudinary SDK (disabled), Libraries (missing)


texts: Override html.tpl.php per node type does not work

texts:
I saw that this was asked few times before, and I tried the answers, and I tried modifying the answers, yet nothing.

Case:
I have Advanced Forum installed, and I am using HTML5 Application Cache (appcache) (don't you dear to run away now!).

Obviously I need to turn appcache off when surffing forums, and I managed to make custom html.tpl.html for /forum and /forums, so when I am looking forum list and topic list I won't get cached.

But then:
When I am looking at forum topic, it is a post ofc, and post type (machine type is forum) and I have defined in template.php:

$node = menu_get_object();

if ($node && $node->nid) {
    $vars['theme_hook_suggestion'][] = 'html__' . $node->type;
}

and it won't make change.

So I am able to change html.tpl.php for path but not for node type.

Help me please and correct my knowledge for making such things.

Thanks for all!!!
(btw i dont need a lesson of appcache, sincerely if you have manifest = x.appcache" in your html tag it will cache it, even if it's in network section)


texts: How to create content / entity via ajax on a view?

texts: I have a view listing some content and I want to have an "Add new" button, which should load the node form via ajax (either modal or into a div). After I save the form, it should still stay on the page. Updating the view would also be nice, but for the first thing I'm trying to load the node form via ajax. How can I do that?


texts:
I've searched and found variations of this question but I've never found an answer that seemed to work. I need to add a class to the
 elements, currently the main menu is rendered like this:

print theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
        'id' => 'slidemenu',
        'class' => array(
            'links',
            'inline',
            'clearfix'
        )
    ),
    'heading' => t('')
));

As far as I can tell, this only sets up the
 element of the main menu, so I was wondering if there's a way to edit the attributes of the 'links' part.

---EDIT---

Alright, I think I solved it. Apparently you can use theme_links__system_main_menu in templates to override the whole thing. I ended up doing this:

function mytheme_links__system_main_menu($variables) {
    $html = '
';
    $html .= '
';

    static $linkClass = 1;

    foreach ($variables['links'] as $link) {
        $html .= '
' . l($link['title'], $link['href'], $link) . '
';
        ++$linkClass;
    }

    $html .= '
';
    $html .= '
';

    return $html;
}

Not entirely sure if this is correct Drupal, though it did solve my issue!


texts:
I currently have a project with the requirement to edit templates for content like content, i.e. we will have a template content type which will be used as template for another content type.

I've looked for projects and best practices on the matter but didn't find anything. Does someone have experiences with a similar setup?

Should I use Twig and inline_template or should I write my own template system with tokens? Other ideas?

Any help is greatly appreciated!


texts: A shop and marketplace for selling/buying currencies

texts:
I'm trying to find a way to do a shop for currencies. That means people can sell one currency and buy the other in return.
In fact this is an online version of an exchange agent.
So far I looked at currency as a product that users can post their own currency to sell using the commerce marketplace.
So if the default currency is USD, then they can sell GBP and get USD which is ok.
But if they want to buy GBP and sell USD (default currency) then the default currency for that product need to be GBP, as they need to collect GBP which I don't know if such thing is possible!!

The second solution that I though can be possible:
If users in the marketplace be able to post a product to buy, and other users can see this product but with "sell" button instead of "buy", so they can sell their own product if they have it!

Do you have any suggestion for doing such shop or do you have any solution for these 2 scenario that I have in mind?

Hope this make sense and you can help.

Thanks in advance for any help.


texts: Ajax webform: refresh page on a successful submission

texts:
I am using the ajax webform, because I don't want the page to be reloaded when the user doesn't enter everything correctly because my form slides in and reloading just causes it to disappear and you would have to navigate back there. When I have ajax-mode enabled, the redirect part works differently, and since the site has only 1 page, it doesn't really do anything, the form doesn't close.

What I want to do it actually refresh the page when the form is submitted with ajax-mode on.


texts: Values don't get saved to the database when fields are wrapped in a container

texts:
When I wrap a field in a container, the field value doesn't get saved to the database. But if it lives in root, it works properly.

public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

    $item =& $items[$delta];
    $element += array(
      #type' => 'fieldset',
    );

    /** a bunch of fields **/

    $element['concelhocontainer'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'concelhocontainer']
    ];

    /** works properly **/
    $element['concelho'] = [
      '#type' => 'select',
      '#title' => t('County'),
      '#default_value' => isset($item->concelho) ? $item->concelho : '',
      '#options' => $this->getConcelhoList()
    ];

  /** does not work
  $element['concelhocontainer']['concelho'] = [
    '#type' => 'select',
    '#title' => t('County'),
    '#default_value' => isset($item->concelho) ? $item->concelho : '',
    '#options' => $this->getConcelhoList()
  ];
  */
  return $element;
}

The problem is that the value of the second input is not saved to the database (I've confirmed it in the database).


texts: How to favor exact matches in entity reference autocomplete?

texts:
Right now if you use entity reference autocomplete for short titles of a node type or entity type, and you have many items, due to the fact that by default they are ordered by entity id (nid), less relevant entries show up before exact matches.

For example, if you create a content type for stock symbols, and you have tens of thousands of them, and you want to search for "EA" or "DIS", longer strings that contain these substrings show up before exact matches.

How can you change the behavior so exact matches show up before other matches with lower entity ids?


texts: How to add a class to vertical tabs created using Form API?

texts:
Form API element vertical_tabs does not have #attributes property.

I have two kinds of tabs. The first one is language dependent. The second one has language independent values, just shows a preview in the selected template. I want them to be visibly different on first glance.

How can I mark them, possibly without adding dummy containers that makes the form tree more complicated than form logic requires?


texts: how to display the uploaded zip file content in drupal?

texts:
i created a cck file field and i uploaded zip file in that content type. Now i want to display the content of zip files after uploading the zip files. i don't know how to implement it?. can you tell me how to implement it?

thanks in advance.


texts: Flat Shipping price per product using Drupal Commerce

texts:
I've been beating my head against a wall trying to configure shipping in Drupal Commerce for a week now and so here I am! I have a Select or Other field in the product entity with a couple of choices:

Free Shipping
Call for Details
Other (and the admin enters a flat price)

Again, this is entered on a per product basis, on the Commerce Product entity (not the node). My question is how do I update the shipping price based on this value? It should work as follows:

Item 1 (shipping: $1.00)
Item 2 (shipping: $4.00)
Item 3 (shipping: Free)
Item 4 (shipping: Call for Details)
Item 5 (shipping: $1.00)
Total Shipping: $6.00

Perhaps I'm doing this wrong. Any direction would be awesome. Thanks!

This is the final working code:

class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      if ($line_item_wrapper->commerce_product->field_shipping_price_other->value() > 1) {
          $price += ($line_item_wrapper->commerce_product->field_shipping_price_other->value()*100)*$line_item_wrapper->quantity->value();
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom Shipping label'),
      'quantity' => 1,
    ));
  }
}


texts:
I'm working on a headless website based on Drupal 8; I installed the CORS module and in CORS domain set *|*. Client side can read my view rest endpoint, but when client side try to load a file url returned by views rest result, I am faced with CORS error:

  XMLHttpRequest cannot load http://domain.com/sites/default/files/home-slider-slide3-audio/2016-11/tr_SaidNursi.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xx.domain.com' is therefore not allowed access.

How can I resolve this problem?

The webserver is Nginx.


texts: How to use jquery accordian in side bar first

texts: I am using facets search filter. I want to use accordion in facest search filter.


texts: how to know this query related to which block

texts:
I have a website with a very large number of blocks, some of them have been created using Views module. now i am seeing in slow query log some queries generated by Views like

SELECT DISTINCT(node.nid) AS nid,
  node.type AS node_type,
node.vid AS node_vid,
node.title AS node_title,
node.language AS node_language,
node.created AS node_created
FROM node node
LEFT JOIN term_node term_node ON node.vid = term_node.vid AND term_node.tid = 193
LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid AND term_node2.tid = 194
LEFT JOIN term_node term_node3 ON node.vid = term_node3.vid AND term_node3.tid != 194
WHERE (node.type in ('article')) AND (node.status = 1) AND (node.language in ('ar')) AND (term_node.tid IS NULL) AND (term_node2.tid IS NULL) AND (term_node3.tid = 0) GROUP BY nid ORDER BY node_created DESC ;

Now, is there any way to know this query related to which block? i couldn't figure it out by checking in preview query of views!!


texts: Add the view mode to the CSS classes used for the body

texts:
Is it possible to add the view mode used for a display into the body class?

At the moment, the view mode is being inserted into one of the region classes, but I would like to add it also to the body class. This would allow me to change the page to full width depending on the view mode.

I am using the Bootstrap theme.


texts: For my application with several different voters, I want the caching table (votingapi_cache) to never be populated. Is there a hook or a configuration I can implement so that no caching happens at all?


texts: How to resolve composer autoloader not found error?

texts: So, I'm running a D7 site with composer manager. I have successfully run the composer install command from inside the /sites/default/files/composer directory. The libraries appear to be successfully installed, but my watchdog is loaded with RuntimeException: Autoloader not found: /var/www/html/psrlivetoupdate/sites/all/vendor/autoload.php in composer_manager_register_autoloader() (line 173 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).  and there's also a notice in the site's status report that composer's dependencies haven't been installed. Any idea what's going on and or how to address it?


texts: Updating drupal/core using composer: "[RuntimeException] Could not delete web/core" (using Lando)

texts:
Trying to update Drupal 8 core.
composer require drupal/core:~8.9.2 --no-update

This works fine.
composer -vvv update

It fails with the following:
  - Updating drupal/core (8.8.5 => 8.9.2):     Update failed (Could not delete web/core: )
Would you like to try reinstalling the package instead [yes]? yes
  - Removing drupal/core (8.8.5)

[RuntimeException]
Could not delete web/core:

What's the easiest and/or correct way to resolve this?
(This has happened to me before but can't remember what I did to fix it)


texts: Problem with enabling the Optimizing js files

texts:
I have installed the events and signup modules. The events appears in a calender. All were working fine. But when I enabled the optimizing JS files on the performance page Now the events does not display for the anonymous and authentication user. Now they are only available for the administrator.
I again the disabled the optimizing JS files on performance page but still events are not displaying.

Can someone tell me what is the problem?
I am using drupal 6.


texts: "Preview before submitting" based on user role

texts:
So, you can make "Preview before submitting" optional or required for a node type.
I would like to make it optional based on the user who is creating the node.

So, for example, a authenticated user has to view the preview of a node before he can save it, whereas a administrator user can save the node without previewing it beforehand.

Is there a module for that?

I tried it myself, hiding the submit button in hook_form_alter, depending on the current user's role:

$form['actions']['submit']['#access'] = false;

But i can't let the submit button appear again in hook_node_validate by doing:

$form_state['complete form']['actions']['submit']['#access'] = true;

Any help would be appreciated!


texts: Why are these file errors show up on the site - I have "none" selected in admin

texts:
I'm getting errors like these show up on the site with setting "Error messages to display" set to "none":

File temporary://fileGhQKBK could not be copied, because the destination directory public://css is not configured correctly.

Why do they still show up on the site?


texts: How to prevent certain users from adding (for example, a Node) to bookmarks with Flag Module

texts:
Flag Module >>> https://www.drupal.org/project/flag

How to disable/prevent some Users (NOT Roles) from adding (for example a Node) to bookmarks? Maybe showing a message after clicking on the Boomark button (You are not authorized to make this choice or something like that).


texts:
When I sign with admin user (or any other user), I can edit the contents, I can edit user, I can´t create user, I can`t Edit nodes, I can´t install upgrades, I can´t install modules, I can´t save anything.

Thanks.


texts:
So I have already read and followed everything I could find on that issue:

putting my_module_views_data_alter(array &$data) in my_module.views.inc file in the root directory of my_module,
disabling cache for my view,
clearing caches million times,

but still I can never stop at a breakpoint inside this hook, nor can I see any effects of the code I have put in it.

What am I missing?

EDIT: updating with some code

In my_module I have already created a computed field user_age, calculating user age from a custom user profile field with date of birth.

my_module/my_module.module

function my_module_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields = [];
    $fields['user_age'] = BaseFieldDefinition::create('user_age_field')
      ->setName('user_age')
      ->setLabel(t('User age'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\my_module\UserAgeIntegerItemList')
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'weight' => -5,
      ]);

    return $fields;
  }
}
function my_module_field_formatter_info_alter(array &$info) {
  $info['number_integer']['field_types'][] = 'user_age_field';
}

This field is working and is accessible in my user profile template.

Knowing that since Drupal 8.4

  Computed fields can now be displayed by Views

I wanted to use field user_age as an exposed filter in my search_users view:

my_module/my_module.views.inc

/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {
  if (isset($data['users_field_data'])) {
    $data['users_field_data']['user_age'] = [
      'title' => t('User age'),
      'field' => [
        'id' => 'my_module_view_user_age',
      ],
    ];
  }
}

my_module/src/Plugin/views/field/MyModuleViewUserAge.php

<?php

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\ResultRow;
use Drupal\views\Plugin\views\field\FieldPluginBase;

/**
 * A handler to provide proper displays for user user_age.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_module_view_user_age")
 */
class MyModuleViewUserAge extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    $relationship_entities = $values->_relationship_entities;
    $age = '';
    // First check the referenced entity.
    if (isset($relationship_entities['user'])) {
      $user = $relationship_entities['user'];
    }
    else {
      $user = $values->_entity;
    }

    $type = get_class($user);
    if ($type === 'Drupal\user\Entity\User') {
      $age = $user->get('user_age')->getvalue();
    }

    return $age;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // This function exists to override parent query function.
    // Do nothing.
  }
}

but my_module_views_data_alter() seems to never be executed and user_age field is not present in the filter criteria for my view.


texts: Why are most of my Timefields blank when editing a node?

texts:
I have a node with four timefields. When I want to edit the node, all the timefields, except the first one (that has a default value), are blank.

I found this issue still doesn't solved:
https://www.drupal.org/node/1970252

How can I solve this? I could populate the missing fields via javascript?

Altenatives of timefield module?


texts:
I have developed my own xmlrpc hook, which have certain functions.

Basically I need to call that functions outside Drupal. So I can't use xmlrpc() function.

What is most simple method to call that functions through Drupal's xmlrpc.php?


texts: How to resize  element within drupal block?

texts:
I created a custom block with Full HTML format selected using the following code:

<img src="myimage.jpg" atl="myimage" width="xx" height="yy" />

However, Drupal seems to always display the image at it's actual size. Is there a way to achieve this in a block?


texts: How do I add a specific class in a row of a table output depending on a field content?

texts:
I use the Views module to list the content of a custom entity, using the Table format.
I'd like to add the myClass CSS class to each row where a given field is equal to zero.

How can I achieve this?

Edit I found out that I could use 'Rewrite results' (Overriding the output of a field with custom text) with twig.
For example:

{% if nombreproduits == '0' %}
{{ '99/99/9999' }}
{% else %}
{{ datedistribution }}
{% endif %}

How could I use that to add a class to the corresponding row?


texts: How to exclude all blocks on a specific page?

texts:
I have a website that uses themekey to display a different theme for one page. I use the context module to display blocks across the site (*). I tried to exclude the page I don't wish to display blocks on using ~, but it didn't work.

Essentially I followed this answer for my path setup: Exclude a block from specific parts of the website with the Context module

So in my path setting I have

*
~my-page-to-exclude-all-blocks

That did not work as all the blocks listed in the context are still present.
I even went so far as to create a second context with no blocks added for the path in question, but that didn't work either.

Edit: I also tried ~/my-page-to-exclude-all-blocks, but that didn't work either.


texts:
We have a requirement that our standard CKEditor toolbar omit a specific button on only one content type. It seems silly to create a brand new text format just for this. I'm able to modify the toolbar via a hook, but the modification gets saved and applied everywhere.

How can I programmatically modify the toolbar for just that content type?


texts: Blank page when trying to add new content

texts:
I've to cope with something very odd: I can't add any type of content anymore. For example: when I go to Content > Add content > Article, I navigate correctly to the 'add acticle' page, but I simply get a white screen. I didn't have this before and I can't remember installing new modules. I already tried to flush all caches, but that didn't solve anything. Even when I add

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>

to my index.php or settings.php file, no erros are displayed. Please help!

Edit 1: going to the Configuration screen doesn't result in a WSOD. There's only a white screen when I try to add content.

Edit 2: I discovered that I also get a WSOD when I try to edit already existing content. Please help me! I really can't do anything anymore!


texts: How do I include JavaScript with assets (libraries.yml)?

texts:
This is my mytheme.libraries.yml file:

global-styling:
  css:
    theme:
      css/style.css: {}

  js:
      js/effect.js: {}
    dependencies:
    - core/jquery

This is my js/effect.js file:

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
      alert("Hello World");
  }
};
})(jQuery);

I created jquery.js in core folder of my site root.
Even if I remove the  dependency line from my libraries.yml and remove jquery syntax from my effect.js, I receive nothing on my site.


texts: How to create an external menu link with some arguments?

texts:
I`m trying to create Main menu item with external URL. This code is good for me

    $path = 'https://backend.supplysolver.com/startApp/' . $uid . '/' . $userKey . '/' . $currentLang;
  MenuLinkContent::create([
    'title'     => 'start Application',
    'link'      => ['uri' => $path],
    'menu_name' => 'main',
    'target'    => '_blank',
    'external'  => TRUE
  ])->save();

When I use this code in preprocess_page Menu item is duplicating. Please help


texts:
I need some advice.

My client has a website with loads of products.  Now the client want the ability to add products to a cart, and instead of buying, they want the products to be mailed.

How can I acheive this.  I took a look at the commerce module.  This module is amazing.  I did some research and found this article saying I can achieve  what I want with the rules module.

This is awesome.  But drupal commerce has its own set op products that you need to add inside the store.  I need to use products already created. As well as add options such as colors and sizes that also needs to be displayed in Select lists.

Is there a way that I can get this feature with existing products? Or just add the cart button to my nodes?

Thanks.


texts: programmatically attaching file to file media

texts:
I am trying to programmatically attach a file to a node, using the media module now included in core as of Drupal 8.5.0.

I wrote this drush script to stub out the creation of a new file media content piece.

<?php

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
use \Drupal\media\entity\Media;

$file = file_save_data(uniqid(), 'public://test' . uniqid() . '.txt');

$drupalMedia = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'file' => [
    'target_id' => $file->id(),
  ],
]);

$drupalMedia->setName(uniqid())
  ->setPublished(TRUE)
  ->save();

When I navigate to the site's media at admin/content/media, I see my media listed:

But when I edit the piece of media, my text file is not attached to it:

There are no error messages in watchdog.

What am I missing? What do I need to do to attach the file to the media?


texts: How to exchange variable values between contextual filters of the same view?

texts:
I have a view with two Global: NULL fields as contextual filters, which use php code in their default value.
The first global null value calculates and provides an order quantity, and the second global null calculates and provides the discount percentage. Both base their calculations on values in the URL.
I store the order quantity and the discount percentage as session variables (for use in the transaction).
The calculation of the discount value depends on the quantity.

Question: How can I use the quantity (calculated in global null field 1), in the php discount percentage calculated in global null field 2?
I tried using the session variable as set in the global null field 1, but that appears not to work?


texts: With a custom Drupal form, how can you attach WYSIWYG functionality to a textarea with the WYSIWYG module?


texts: How do I replace a comma with a line break using feeds tamper?

texts:
When trying to import a feed using Feeds and Feeds tamper, I want to insert a new line at the commas (for displaying address in a nice format).

The screenshot shows what I'm trying to achieve:

The result is \n appears in the output

Why is "\n" being inserted rather than a new line?


texts:
How can i ommit an condition in Entity Field Query if variable do not exist, for example

->fieldCondition('field_filter_color', 'tid', $filter_color)

Recieves in $filter_color one term id.
But there are situations where $filter_color is not present, so i would like to do:
if $filter_color is empty, ignore this condition.

Alternative is to present it as an array like

->fieldCondition('field_filter_color', 'tid', $filter_color, 'IN')

and prepopulate all values in $filter_color, and if $filter_color is chosen, create array with only one value, but i am not sure it is best way to do it.


texts: How to switch existing file field from public to private?

texts:
I have a Drupal 7 website with an existing file field set to store files in the public folder (i.e. sites/default/files).

I need to switch this one field so that it stores files in the private folder. Because the field has already been set to public and there are a number of existing files in place - the option to change the settings to private is not available in the user interface. I was wondering if anyone has a way to make this change manually in the database.


texts: How to switch view before render current view?

texts:
I am using Field Collection Views module which allowed to create field widget as a view.

My requirement is to allow content author to choose widget for output this field (Field Collection). I added select field to article type to choose widget from two Field Collection Views views.

Field Collection is using views_embed_view for rendering this field, so I am trying to use hook_views_pre_view to switch to different view if author choose other than default view (display formatter)

/*
 * Implements hook_views_pre_view()
 */
function wzp_gallery_views_pre_view(&$view, &$display_id, &$args) {
    $node = menu_get_object();
    if (! $node->type == 'article') {
        return;
    }
    $field_name = FIELD_GALLERY_VIEW_FIELD_NAME;
    if (! $node->$field_name) {
        return;
    }
    $value = array_shift($node->$field_name);
    $view_info = explode('#', $value[0]['value']);
    if (! $view_info) {
        return;
    }
    $name = $view_info[0];
    $id = $view_info[1];
    if ($view->name == $name && $display_id == $id) {
        return;
    }
    $display_id = $id;
    if ($view->name == $name) {
        return;
    }
    drupal_set_message('
' . print_r($name, 1) . '
');
    drupal_set_message('
' . print_r($id, 1) . '
');
    $view = views_get_view($name);
    $view->set_display($id);
    $view->preview = TRUE;
}

but I am end up always with default view rendered.

Code form Field Collection Views module:

/**
 * Implements hook_field_formatter_view().
 */
function field_collection_views_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'field_collection_views_view':
      //debug($items);
      $args = '';
      $i = 1;
      foreach ($items as $delta => $item) {
        if ($i == 1) {
          $args .= $item['value'];
        }
        else {
          $args .= '+' . $item['value'];
        }
        $i++;
      }
      $view_name = isset($settings['name']) ? $settings['name'] : 'field_collection_view';
      $display_id = isset($settings['display_id']) ? $settings['display_id'] : 'default';
      $content = views_embed_view($view_name, $display_id, $args);
      $element[0] = array(
        '#markup' => $content,
      );
      if (empty($items)) {
        field_collection_field_formatter_links($element, $entity_type, $entity, $field, $instance, $langcode, $items, $display);
      }
      break;
  }
  return $element;
}

Could someone give me any advice?


texts: How to set to Webform's fields a 'Number of values' setting like in default content types?

texts:
Yeah, so in content type fields like Article or any other when you add a field it has an option 'Number of values' and if you select Unlimited it adds a button 'Add another item' when creating a content.

So I was thinking is it possible to do that with Webform module's forms? Let's say a user is filling in the form, let's say he fills in his phone number into Phone number field and then maybe he has a another phone number, so he could click 'Add another item' and that would open up a second field of a Phone Number field.

To be exact, I need that Unlimited option to work on Webform fieldset fields. So if I have a fieldset of three fields, I can click 'add another item' and it opens up a 2nd fieldset.


texts: Removing all unapproved comments from database dump file

texts: I got thousends of spam comments on my drupal 7 site. The mysql database file is grown to 1.9GB and the site is broken. How can i delete all comments (or even better: all unapproved comments) from the database dump file?


texts: After adding some link to menu, on which Workbench Access has its hierarchy, I cannot immediately use this one, as a section. Tried rebuilding drupal menu (menu_rebuild()), but it's something inside Workbench. Does anyone has dealt with this? To solve this, after adding some link to menu, I need to go to Workbench Access configuration page and just save it. Then it's refreshed, and new items (new hierarchy positions) are available to be set as sections.


texts: GeoIP or browser language redirect on first visit: how can I achieve this?


texts: Why doesn't drupal.org/download give a link to the Drupal 7 version?

texts:
Friend asked how to get the latest d7 version. I said go to the Download link, eg under Build > Download and Extend, or under Try Drupal > Download.

He pointed out that it only has a button for d8 download at https://www.drupal.org/download.

Why?


texts:
Is there a way to update Drupal Core without reuploading files and following the UPDATE.php file?  Something similar to how you can update a Wordpress install with a click of a button?  I wasn't sure if there is a module that will allow this?

--edit--

I've attempted the "drush up" command per @Enxebre's suggestion.

I installed Drush to my shared host and it seems to be running correctly. The site is still not updating though. I checked for updates and its still at 7.22 instead of 7.23.

I also had to run an update on Drush.
Here are my results from the terminal command:

Drush self update:

drush self-update
X-Powered-By: PHP/5.2.17
Content-type: text/html

A newer version of drush, 7.x-5.x-dev (2013-Aug-06), is available.  Would you like to back up your current drush, version 4.3-dev, to /home1/munortap/drush-backups/drush/20130912205746 and replace it with the newer release? (y/n): y

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Drush up:

[~/public_html/misadventureinc]# drush up
X-Powered-By: PHP/5.2.17
Content-type: text/html

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in         /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34


texts: How do I get the delta value of a multifield in a View template? I need to get the delta value in the Row output View template.


texts: Translating Javascript files with Drupal.t() fails

texts:
I've attached Leaflet draw js library to my site.
I've modified that JavaScript file by wrapping UI texts in Drupal.t()

It took a while before these texts were available in translation interface (repeating drush rr, cc all etc.).

However, translated texts aren't shown in the UI (map page).
Now I'm wondering that should I just localize this script either by a create language file for each language or by adding translations into script itself(object)?

Basically there's no need for Drupal translation so this would do the trick since "The Drupal way" seems bit of a dead end.


texts: Adding local task tabs to node display for specific content type

texts:
I'm creating a custom module (it's called cil_meet) which adds two content types (organisation and room).  On an organisation node I want a local task tab (next to 'view' and 'edit') of 'add room', for administrators.  On a room node I want two tabs 'publish' and 'info'.

After some research, I've figured out a way to achieve this, but I want to know if there is a better way of doing this?

cil_meet.routing.yml:

cil_meet.addroom:
  requirements:
    _role: 'administrator'
cil_meet.roompublish:
#  path: '/meet/{organisation}/{room}/publish'
  requirements:
    _role: 'authenticated'
cil_meet.roominfo:
#  path: '/meet/{organisation}/{room}/info'
  requirements:
    _role: 'authenticated'

I've commented out the path for publish & info for now - I'll set up controllers, etc later.

cil_meet.links.task.yml:

cil_meet.addroom:
  route_name: 'node.add'
  title: 'Add Room'
  weight: 100
  route_parameters:
    node_type: 'room'
  base_route: entity.node.canonical
cil_meet.roompublish:
  route_name: 'cil_meet.roompublish'
  title: 'Publish'
  weight: 100
  base_route: entity.node.canonical
cil_meet.roominfo:
  route_name: 'cil_meet.roominfo'
  title: 'Info'
  weight: 101
  base_route: entity.node.canonical

This adds the tabs to all nodes.  So to remove the tabs from anything other than organisation or room nodes, I've got to add some code to the module.

cil_meet.module:

<?php
/**
 * Implements hook_local_tasks_alter().
 */
function cil_meet_menu_local_tasks_alter(&$local_tasks, $route_name) {
    $route_match = \Drupal::routeMatch();

    if ($route_match->getRouteName() == 'entity.node.canonical') {
        $node = $route_match->getParameter('node');
        if($node->bundle()!='organisation') {
            unset($local_tasks['tabs'][0]['cil_meet.addroom']);
        }

        if($node->bundle()!='room') {
            unset($local_tasks['tabs'][0]['cil_meet.roompublish']);
            unset($local_tasks['tabs'][0]['cil_meet.roominfo']);
        }
    }
}

All works as expected, the above may help others needing a similar solution.  Is there a better way of doing this?


texts: Openlayers views , center map to each geofield

texts:
I have setting geofield in profile for each user , and make a view that list the location of the current user post (" I'm here ") , but the map isn't centered well to show up the marker , and when you zoom out it shows the markers.

So how do I get my map centered for each user geofield ?


texts: How can I access location information via rules, to include the City of a node in an email?

texts:
I have a rule, which works like this:
After saving new content, Fetch users who have flagged a Taxonomy term, Loop, send email.
The emails get sent perfectly, to users who have flagged the specific term.

Now I would like to include the location, from the new content item which is saved, in the email.

If I look for the relevant Replacement Patterns [node:location] is available, but does not print anything when included in the email. I'm guessing this is because [node:location] is an array and I need to do something else to explode the array to get "City" out and print it in the email...

Does anyone know how I would do that? Or a better way to access the specifics (i.e. City) from a node location?

NB: The Location information for my content type is NOT added as "fields" but is added to the content type under "Locative information" (next to Comment Settings and Menu Settings in D7) I am only collecting City and Postcode (and forcing Country to the default)


texts: How to make table-responsive in drupal views

texts: I have created the views which renders table. I want to make table responsive without any contrib module. Is it possible?


texts: Foolproof way to prevent email sends from local/dev server

texts:
We have had a number of occasions when a new new developer starts working on a project, and when they have it installed the cron runs and sends out a load of emails to users. If the database is fairly old this could send out a lot of unwanted mails. What is the best way to prevent this?

We are currently using Reroute Email which works fine, but obviously this is needs to be enabled. We have set up the settings.php to override the config to enable this, but as it's not included in the GIT repo a new developer might not include this when setting up their local version.

Is there any way to lock this down so it can't happen?


texts: 7 picture doesn't generate images emidiatly

texts: I have a site with picture installed. When a user access the site with a device where image styles are not created yet the user has too refresh the site to see the image. How could I force the theme to preprocess the image styles when cronies runs?


texts: How to retrieve a file or image from a content type?

texts:
I'm using services module to get data from database, among those data there is an image.

All fields are loaded except the image, the uri seems to be wrong.

here's the postman response :

  "writer": "writer1", <==== ok
  "picture": "public://couverture_harry_0.jpg",<=== not ok(wrong path)
  "review": null, <====== ok
  "date": "2010-02-05",<===== ok

I've configured drupal to store on sites/default/files

the picture is there but the real path is :

drupal/sites/default/files/couverture_harry_0.jpg

(if I enter this path manually on postman it shows me the picture)
But by default the path services put is wrong.

How to "configure" services or drupal to get the good path ?

EDIT
This is my custom resource to retrieve a book (livre in french) :

function my_module_get_livre($entity_id) {
// check uid && entityID

$result = db_query("SELECT `field_title_value` as titre, `field_prix_value` as prix, `field_auteur_value` as auteur, `uri` as couverture, `field_resum__value` as resumé
    , `field_date_de_parution_value` as parution, `denomination_ed` as editeur,`field_nombre_de_pages_value` as pages FROM {field_data_field_titre_en_arabe} as t_ar
    inner join {field_data_field_prix} as pr on t_ar.entity_id = pr.entity_id
    inner join {field_data_field_auteur} as aut_ar on t_ar.entity_id = aut_ar.entity_id
    left join {field_data_field_photo_de_couverture} as ph_couv on t_ar.entity_id = ph_couv.entity_id
    left join {file_managed} as file on ph_couv.field_photo_de_couverture_fid = file.fid
    left join {field_data_field_resum_} as resu on t_ar.entity_id = resu.entity_id
    left join {field_data_field_date_de_parution} as d_paru on t_ar.entity_id= d_paru.entity_id
    left join {field_data_field_edit} as edi on t_ar.entity_id = edi.entity_id
    left join {editeur} as ed on edi.field_edit_target_id = ed.uid
    left join {field_data_field_nombre_de_pages} as pages on t_ar.entity_id = pages.entity_id
    WHERE t_ar.entity_id = $entity_id ")->fetchAll();

return array('code'=>'0', 'response'=>$result);
   }

 function my_module_livre_retrieve ($entity_id){
      return my_module_get_livre($entity_id);
    }

I've also tested this (it works) :

$fid ='2'; <=== i put it manually(but it would be set by select query
$file = file_load($fid);
$realURI = $file->uri_full = file_create_url($file->uri);
var_dump($realURI);<==== returns the real url (localhost/drupal/sites/...

I want to 'alter' or just put the $realURI value to every book(livre) in his field : "photo de couverture" (which is the pitcture i want)

Thank you


texts:
I am new to Drupal. I created a page and I want to embed charts in that page. I am trying to use chart.js and I have question regarding how to import the script of chart.js in the page i created?

is it like this

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>

or some other way to do it? I also dont understand how you add javascript code to a drupal page. Thank you.


texts: How to find all views that have "broken or missing handler"?

texts:
Is there an easy way to get a list of all views that have a "broken or missing handler" ? To make sure it is ok to disable a module that defines views plugins.

I think in D8 we have proper dependency management for this stuff. But in D7?


texts: How to show titles as plain text on rendered entity reference

texts:
By default the titles are showed as links to there node if you choose to display format rendred entity (full).

I want the titles as plain text and not links


texts: Nesting views with a node reference field

texts:
I am creating a Drupal site that is used as a task manager; each task node has the ability to reference another task node as a parent.
In the task list view, I would like to nest the same or similar view within each row, displaying that tasks children.

I've done something similar before by theming; however, I'm wondering if is there a standard, or emerging way of accomplishing this within the Views interface with a third-party module.


texts: Is it possible to combine contextual filters with regular filters?

texts:
I would like to take my standard taxonomy term view and add a "meta" category that would show up in addition to the term selected. The result should be that items in the meta category show up as well as those in the term being viwewed.

I tried adding the meta category as a regular filter or an additional contextual filter, but there's no way to add the "OR" logic needed between the contextual term filter and the specified meta term filter. In spite of using them for many many years, I still don't fully understand the all settings of contextual filters. Perhaps there is a right way to get it to do what I want?

Thanks for any leads or suggestions.


texts: how to know block id in class which extend from BlockBase

texts:
I am trying to get block id in my custom module  in build function of class which extends BlockBase.

How can i do this?

i want to use this block_id in another class controller to have configuration of that block so i think best place to get block id and send it to controller class is build function like below code

        class XController extends ControllerBase{
        ...
        $block = \Drupal\block\Entity\Block::load($block_id);
        if ($block) {
        ...

any other suggestion to do this is appreciated.


texts: How add additioanl field to message filter in private message module?

texts:
As you know private message module gives drupal users ability to send message to each other.

each user can see his/her messages in message page. Also table of messages can be filtered by subject or participant.

I want to know is there any way to add extra field to the filters ?

Also table of messages only includes these columns

Subject
Participants
Started
Messages
Last Updated

But I have added extra fields to message via "Manage Field"

I want to know how can I add extra field as columns to table of messages.


texts: How to print child fields from embedded view in a webform

texts:
I've got an embedded view (articles) in a webform with two child fields (article_title, article_body). I need to print/generate a PDF of the webform submission. The default template works, but looks messy in a table.

What is the right syntax to call the data from the child terms?

Here's my webform structure:

Using print ('<b>Report Name:</b> '.$renderable['report_name']['#value']); I can get the Report Name, but I can't seem to figure out how to get the the article_title and article_body fields. I'm not very familiar with coding and have been searching online for ages with no luck, except for this article which I can't seem to get working for my system either.

Any help would be appreciated.

Thanks


texts: Viewing Referenced Field Images in node template

texts:
I'm stuck with a probably simple problem, maybe someone can help?

I have a node (representing a route) which has a reference to other nodes (points of interestes)
Like this node.field_poi

Every field_poi has it's own images attached

from the node template I'm trying to get the images, but no way!

There are my attempts, where am I wrong?

{{content.field_poi.0.entity.field_image.0.entity.uri.value}}
{{kint(node.field_poi.0.entity.field_image.0.entity.uri.value)}}

If I try this, it breaks completely the page:
{{kint(node.field_poi.0.entity)}}


texts: Form API: #action is in conflict with #submit

texts:
I have custom form created with Form API.

<?php
function myform($form, &$form_state) {

//some form elements..
$form['#action'] = '/my-projects';
 $form['#submit'] = array('myform_submit');
return $form;
 }
?>

I have a problem, that my submit function is not called. I need to comment line with $form['#action'], and then my submit function works.
But problem is, that I need to set action manually. (My form is loaded with ajax on javascript event, and loaded form has set the  #action parameter by system according last called page URL.

In particular, I am rendering the form with jquery $.get method. $.get returns HTML output of the form. But the problem is, it returns form with action set to

<form action= "/my-ajax-path">

, where "my-ajax-path" is path used in $.get method to render the form, but I dont want Drupal to set this path IN rendered form. Thats why I am trying to set #action manually.

How can I let work #action and #submit parameter together?


texts: how it's possible to load nodes by taxonomy terms

texts:
Here im loading nodes by "type" article, i want to call nodes by another id , but this id is in another table, should i join tables , or it is some other way to do this

$type = "article";

          $build = array();
          if ($nodes = node_load_multiple(array(), array('type' => $type))); {
              $build['nodes'] = node_view_multiple($nodes, 'teaser');
          }


texts:
For some reasons I have too weird appearances in a node.

A "Read more" button appearing near to my "Tags" list (even though my display settings dictate only "Full page" appearance, and I've disabled any other option.
An RSS button, that appears there although I never installed the Aggregator module.

How can you explain these phenomena?


texts:
I am trying to export a date field as mm/dd/yyyy.  I keep getting the time 0:00:00 added on the end.  Can someone tell me how to format the output from within the view.
Formatter: choices are Date and time, Time ago, and plain.  I chose date and time.
Choose how users view dates and times:  we have one format which is called:
News item (04/17/2015) which is perfect except that the output includes the time.
What can I do from within the view to omit the time?
thanks


texts:
When I'm trying to save a node using batch processing, I'm getting this error:

  PDOException: in drupal_write_record() (line 7383 of C:\wamp64\www\drupal7\includes\common.inc).

Here is my complete code:

function custom_node_import_form_submit($form, &$form_state) {
  $csvFile = file_load($form_state['values']['csv_file']);
  $csvFilepath = drupal_realpath($csvFile->uri);
  $file = fopen($csvFilepath, "r");

  $batch = array(
    'operations' => array(),
    'finished' => 'node_import_finished',
    'title' => t('Node import'),
    'init_message' => t('Importing is starting...'),
    'progress_message' => t('Imported @current out of @total.'),
    'error_message' => t('Node importer has encountered an error.')
  );

  fgetcsv($file, 0, ",");
  while($line = fgetcsv($file)) {
    $batch['operations'][] = array('node_import_progress', array(array_map('base64_encode', $line)));
  }

  batch_set($batch);
  batch_process('admin/node/custom-node-import');
  fclose($file);
}

function node_import_progress($line, &$context) {
  $line = array_map('base64_decode', $line);
  saveNode($line);
  $context['message'] = t('Importing %title', array('%title' => $line[0]));
}

function node_import_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Node importing is complete!'));
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}
function saveNode($param = []) {
  global $user;

  $node = new stdClass();
  $node->title = $param[0];
  $node->type = "article";
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  $node->body[$node->language][]['value'] = $param[3];

  $node = node_submit($node);
  node_save($node);
}

I have debugged and found that the line which gives this error is the last line where the node is getting saved. i.e node_save($node);


texts: Multi-site setup outside public_html and add on domains

texts:
So I have a Drupal site http://experiment-resources.com running on HostGator dedicated server. It's document root is the default public_html directory.

Now I need to setup a multisite environment outside public_html because I dont want to mess with existing website's functionality.

I already added http://arkivtjenesten.no as an Add-On domain and pointed it to /home/myaccount/arkivtjenesten as its document root. All works fine.

Now I need to add another domain , http://assistertselvhjelp.no . I added this as an add on domain and pointed its doc root to /home/myaccount/arkivtjenesten , same as the previous site. I also added its own settings.php so that it will have its own database. The problem now is if I type in http://assistertselvhjelp.no in the browser it only shows the Apache page.

Please help!

Thanks!


texts: How to check in a Rules Condition if a specific value of a multi-value field is selected?

texts:
I have a "checkboxes" field that allows the user to select unlimited options.
How do I check if at least a specific value has been selected?

I am using the Rules module, and when it checks if the 'field has value' it combines all the options. Right now, if both the values "b" AND "c" are selected, then the action (which checks for the value "b") won't be executed.


texts: NotFoundHttpException after changing webiste hosting, sub-domain

texts:
After changing webiste hosting (Drupal 8) I got this very un-intuitive error message:

The website encountered an unexpected error. Please try again later.

Symfony\Component\HttpKernel\Exception\NotFoundHttpException: in Drupal\Core\PathProcessor\PathProcessorFront->processInbound() (line 43 of core/lib/Drupal/Core/PathProcessor/PathProcessorFront.php).

Drupal\Core\PathProcessor\PathProcessorManager->processInbound('/', Object) (Line: 157)
Drupal\Core\Routing\RouteProvider->getRouteCollectionForRequest(Object) (Line: 141)
Symfony\Cmf\Component\Routing\NestedMatcher\NestedMatcher->matchRequest(Object) (Line: 258)
Symfony\Cmf\Component\Routing\DynamicRouter->matchRequest(Object) (Line: 185)
Symfony\Cmf\Component\Routing\ChainRouter->doMatch('/', Object) (Line: 155)
Symfony\Cmf\Component\Routing\ChainRouter->matchRequest(Object) (Line: 84)
Drupal\Core\Routing\AccessAwareRouter->matchRequest(Object) (Line: 154)
Symfony\Component\HttpKernel\EventListener\RouterListener->onKernelRequest(Object, 'kernel.request', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.request', Object) (Line: 120)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

The files are all the same, other files on ftp/website (besides Drupal) are accessible and works fine.

I've cleared cache via Admin Panel before moving anything.

I've also tried remove it manually:

TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;

but I guess it's not the point.

The previous website was working on http://someurl1.com/site/ (sub-domain) and new one is under http://someurl.com/ (top domain). But even moving everthing on new hosting to /site/ doesn't change a thing.

When I changed database connection settings in settings.php to something wrong intentionally I get:

PDOException: SQLSTATE[HY000] [1044] Access denied for user...

So I guess it's not the database connection problem either.

Using http://.../core/rebuild.php also didn't help.


texts: How do I programmatically log in a user?

texts:
I am looking for the API that will let me login a user by passing it the username and password.
Does anyone have experience with this?
To clarify, I am trying to make an AJAX login box that appears as a popup on the home page, and do not refresh the page in case of wrong credentials, but only if the log in is correct. So here is what i have done so far:
Update
I now load the login form on my homepage, then on submission I launch an AJAX request that sends credential to this script:
function user_login_submit_try() {
  global $user;

  $uid = user_authenticate($_POST['name'],$_POST['pass']);
  $arr = array ('name'=>$_POST['name'],'pass'=>$_POST['pass']);
  if ($uid){
    $user = user_load($uid);
    user_login_finalize($arr);
  }

  echo drupal_json_encode($uid);
  exit;
};

So far it works, but my worries are (as mentioned by googletorp) security issues; it seems that none of the API I used in this script sanitized the data in anyway.
Would anyone see a better way to do so?


texts: Unable to upgrade from version 5.10.0 to version 8

texts:
I tried upgrading from Drush 5.10.0 to Drush 8 using sudo composer global require drush/drush:~8, but it doesn't update anything.

  Changed current directory to /home/lupiyardo/.composer
  Running composer as root/super user is highly discouraged as packages, plugins and scripts cannot always be trusted
  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update
  Generating autoload files

As confirmation Drush wasn't updated, the output of drush --version is Drush 5.10.0.

I looked at the composer.json file and it contains 'require': { }.

How can I upgrade Drush?


texts: how to show a view with one to many relations

texts:
I am using Entity Reference, what would be the best way to show the parent entity on the top (4 columns ) and then the children entities in horizontal rows below?
Can Display suite be used?


texts: How to configure annotator and annotation modules in Drupal 7?

texts:
I would like to provide an MS Word -like annotations (review comments) functionality in some text areas of my Drupal 7 website.

I have experimented with the co.ment and annotator - annotation Drupal 7 modules, and the second solution seems lighter and more appropriate for my requirements.

Unfortunately there is very poor documentation on the annotator and annotation modules and I cannot configure the storing of my annotations.

I have read the annotator library documentation but I do not know how to implement either the store or authentication and permissions plugins on my Drupal 7 website.

From the Annotator module page, what I understood is that by installing the Store plugin together with the Annotation module you use your own storing and not Annotateit.org service.

I have downloaded and installed the required libraries (annotator and Gettext) and from the Annotator configuration page I have enabled the Store plugin with the default Store url options. But my annotations do not get stored and I do not get any exceptions or other info, so that I can see what is going wrong.

Any suggestions please on what may be missing? I can provide more details where needed.


texts: Solution for preventing indexing of content types?

texts:
I have a custom content type that I simply want to not be indexed by the Drupal search engine.  Yes, I can hide it from the search results, but there are hundreds of thousands of these nodes and rebuilding the index takes days.  After much searching and trial/error, I came across this solution from ChrisPliakus.

You can see my query below in the update_index hook, where I exclude MY_CONTENT_TYPE from the query. I've tested the query manually and it seems to show nodes other than the one I want to ignore, which I think is the goal there.

However, when I run drush cron --verbose, I still see those nodes getting indexed :(

/**
 * Implements hook_module_implements_alter().
 */
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ('update_index' == $hook) {
    unset($implementations['node']);
  }
}

/**
 * Implements hook_update_index().
 *
 * @see node_update_index().
 */
function MYMODULE_update_index() {
  $limit = (int) variable_get('search_cron_limit', 100);

  $result = db_query_range("SELECT n.nid FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE (d.sid IS NULL OR d.reindex <> 0) AND n.type != 'MY_CONTENT_TYPE' ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));

  foreach ($result as $node) {
    _node_index_node($node);
  }
}

Any ideas?  Thanks in advance!


texts:
In my website, I'm creating a dynamic external link to open email from Outlook using outlook:{Entry ID} link. It should be like:

outlook:000000006CD8BD6F1761654D9AD70F841783C591070062F134BA8C073B4296C8467090C20CF200000089D837000010EBA743D9305C4891225FE3E347AE1800003B82DF840000

I tried to use:

"Rewrite the output of this field": open outlook

AND/OR

Output this field as a link, with link path: outlook:[guid] with options: "Use absolute path" and "External server URL" enabled.

The problem is no matter I use in Views field rewrite, the anchor's href outlook: replaced with http://localhost/ or http://localhost:8080/pms/outlook%3A

What do I need to do to generate the link correctly in format outlook:[guid]?


texts: How to create a filter in Views for filtering dates by day, month, or year?

texts:
I have a few thousand nodes with different dates as one of the fields. I am trying to create an exposed filter in views that allows the user to filter by day, month, or year.

For example, I would like someone to be able to enter "July" and get all the nodes associated with July, regardless of their day or year. I would also like users to be able to filter for "July 6" of any year or only "July 1973." Likewise, I would also like the user to have the ability of drilling right down to "July 6 1973" with the filter.

I have created a view with day granularity and an "equal to" operator. While this allows the user to select by day, month, and year ("July 6 1973"), any time only day, month, or year is put in, the form indicates that the other parts of the date need to be entered as well.

Does anyone have any suggestions?


texts: Booking events do not trigger an action and missing in module

texts:
Am using the Booking Time Slot module in my project.

I configured some booking related Rules and noticed that they were not triggered.

While trying to debug the rules configuration, I noticed that no information was logged in the System logs.

Also while going through the Booking Time Slot module, i could not find the Rules event in the module files.

My question is that in what files can the booking rules event be and how can i get the rules configuration to work.


texts: link to create a user relationship type in views

texts:
I have user relationship, statuses and views installed. I created a view which shows "users online". I need to add a link to the view, that would allow other users to "create a relationship" with other online users via the view.

The user relationship I created is a one way relationship and there is no need for approval.

Thank you.


texts: What's the advantage of using Git submodules for Drupal core and contrib?

texts:
I've seen a number of questions/blog posts about setting up a Git repository with Drupal Core and Contrib Modules as submodules, such as Setting up the ideal multiple repository Drupal Site version control with a DVCS.

What advantages do you get from this kind of repository set up?
Many people say things like "core and module updates are really easy," but what makes this approach easier/better than have a single repository containing everything for the site and using Drush to update Core and Contrib, then committing back to your repository?
I can see this being great for contributing to those projects since each module is a separate repository, but what benefits does to provide when focusing on building your own site?


texts:
I need to use an alternative function to replace drupal_goto().
The reason is that this function is causing me a problem to run cron.php. The code is:

    if(is_int($order_id)) {
$path = 'admin/commerce/orders/' . $order_id;
drupal_goto($path);
}
else {
  drupal_goto('admin/commerce/orders/');
}


texts:
I'm trying to follow this article to build my first entity using Entity API module. I'm unclear about the dependency between controller classes and include files. If it says:

'controller class' => 'ExampleTaskController',

does this mean the class has to be in a separate file named exactly as the class name (as it is in Views)?


texts:
I have a dilemma i just can't figure out, and i need your help. The thing is, I wish to display the ip address of the logged in user in my custom form. The problem i have is how do i make it based on the logged in user?

The following is the code i used:

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid =
  :uid LIMIT 1', array(':uid' =>33));

  echo "Hostname:" . $hostname . "";


texts:
I'm very amateur in theming. Using Basic theme for Drupal 6, I try to add an image to the very top of the page. (Something like repeating flags here)
However, when I add

<img src="images/flags.png"/>

to the upper side of page.tpl.php, the image has proper permissions but does not show up. No surprise though since the image is hyperlinked as

http:// 127.0.0.1/drupal6/content/images/flags.png

I have also tried defining a  div class="flags" at the top of page.tpl.php and then introduce the image as the div's background-image url('images/flags.png'). No success either.

Direct insertion of static images used to work on my other theme. So got really perplexed and appreciate your help.


texts: How to inject the database connection into a custom service?

texts:
I have a custom module that pulls data from several different external databases that have been defined as connections in settings.php. The current setup includes a series of controllers that have a service I have created called DataAccess injected into them. My DataAccess service has several methods that accept a $schema parameter and based on this I use the following each time:

$connection = Database::getConnection('default', $schema);

I can then query each database as needed with this setup. I thought about injecting Database into my service from the Drupal container, but I would then need a base class like ControllerBase's create method to get that service in the first place. What would be the correct way to do this as it isn't a controller - would I use a different base class here? I am new to Drupal 8 development and trying to ensure I am following the best practices, but at the same time I don't want to overcomplicate things.

Any advice?


texts: Views/Twig/token error when trying to enter a custom URL

texts:
I'm creating a view that shows a list of "articles" with a contextual filter, "organization", to be shown as a block in the organization detail page. I configured the filter so that it grabs the organization ID from the URL (URL being something like node/123). I want the block to show 3 articles, and a "more" link that points to a page I'll build in the future. For now, I want this URL to point to the organization page (i.e. to the same page, bear with me with this part).

Now, configuring the "more" link in the view, I selected Custom URL on the Link display setting. The modal box says this:

  The following tokens are available for this link. You may use Twig
  syntax in this field.

  {{ arguments.field_organization_target_id }} == Content: Organization (field_organization) title
  {{ raw_arguments.field_organization_target_id }} == Content: Organization (field_organization) input

Now, I assume I can use these tokens to build my URL. I tried both of them in the Custom URL text field, like so:

/node/{{ raw_arguments.field_organization_target_id }}

But when trying to open the page, it shows a massive error:

The website encountered an unexpected error. Please try again later.

AssertionError: Tokens need to be valid Twig variables. in Drupal\Component\Assertion\Handle::Drupal\Component\Assertion\{closure}() (line 373 of core/modules/views/src/Plugin/views/PluginBase.php).
assert('preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $token) === 1', 'Tokens need to be valid Twig variables.')
Drupal\views\Plugin\views\PluginBase->viewsTokenReplace('/node/{{ raw_arguments.field_organization_target_id }}', Array)
Drupal\views\Plugin\views\display\DisplayPluginBase->renderMoreLink()
...

The error goes on, but I think this first part shows what's relevant: this is related to Twig and the renderMoreLink method.

I also tried a simple URL like /node/2, but I get the same error (same thing without the first slash character). How can I make this work?


texts: Create a node Automatically when a commerce order is completed

texts:
In my site, I am using drupal commerce in order to run  a shop.

In my plan, a new node must be created when an order is completed. (paid)

Also in new node creation I want to use the order's field values. (for example order id, or username (and uid ) who ordered , entity values & etc )

Please help me. How can I setup this solution?
can I do this process via "Rules" or I have to create a module and use hook functions?

Thanks a lot for your guidance.


texts: How to programmatically embed iframe in a page

texts:
I am trying to render a page with iframe embedded in it. My code is as follow

public function giveHugs() {
  return [
    '#type' => 'inline_template',
    '#template' => '<iframe frameborder="0" style="border: none;" width="400" height="400" src="{{ url }}"></iframe>',
    '#context' => [
      'url' => 'yahoo.com'
    ]
  ];
}

Some how its not rendering the iframe , rather it is embedding the drupal site it self. How can i render iframe in a page?


texts: Allow users to Use tags while adding content, not Adding new tags

texts:
At the moment, users can add their own tags while tagging their content. However, I want them to only be able to use existing tags, not add new tags. Just like this website has when you ask a new question and add tags, you can't add your own (except for those with permission).

Thanks in advance.


texts:
New at Drupal. Trying to extract from MySql the list of the posts with body and user name. Apparently since Drupal 7, the content is stored in drupal_field_data_body. The problem is that it does not contain any user_id, so I have no clue how to join the two tables.
So far I am here:

SELECT *
FROM drupal_node node, drupal_node_revision revision, drupal_users users
WHERE 1=1 AND revision.vid=node.vid AND revision.nid=node.nid AND users.uid=node.uid

Need to JOIN drupal_field_data_body


texts: Form API: completely custom tableselect?

texts:
I need a table that'll have some rows tableselect and some not, also it I should be able to set properties on specific rows and cells, not just inputs. Row can have 1 or many values.

Is that possible with Form API? I've tried to just stuff self-generated HTML into markup, but that didn't work out (in submission I don't see values).

Any ideas how to do that?

UPD: An example of what I want: http://jsfiddle.net/rLwpW/1/


texts: How do I show Device Geolocation share location prompt only on specific pages?

texts: I am working with the Device Geolocation module packed with Smart IP. I got all the functionality working great, but I would prefer if the prompt to share your location wasn't given on every page of the website. The location service is only needed on two pages of the site, so I was wondering if there's any way to only load the Device Geolocation service on those pages, or somehow limit it to only ask to share location on one page and remember that (independent of browser settings).


texts: Commerce: Extra information per quantity bought

texts:
Is there any module or solution that allows extra information to be collected for each item bought? Example of what I mean below:

A user can buy any number of tickets, and for the amount of tickets purchased they have to complete details of the other guests (name, email address etc...). So if they buy 10 tickets they have to complete 9 lots of guest information in addition to their own.

Is there any module that can facilitate this? Additionally, the user should be able to log in and change the details of the guests before the event occurs. This part I'm almost certain will be a custom module, but I'm open to any ideas!


texts:
I'm using the Webform module for Drupal 8. The module confirmation settings for a form are the following:

Page (redirects to new page and displays the confirmation message)
Inline (reloads the current page and replaces the webform with the confirmation message.)
Message (reloads the current page/form and displays the confirmation message at the top of the page.)
URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page.)

But how am I able to submit a form via AJAX so that the page doesn't reload on submit, but a confirmation message still replaces the form? What did I do wrong?

EDIT:

Here is the solution which works:

First you have to hook the form alter function and set an AJAX callback (as in echo's answer):

use \Drupal\Core\Form\FormStateInterface;

function MYTHEME_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) && $form['#webform_id'] == 'MYWEBFORM' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' => '\Drupal\MYMODULE\Controller\DefaultController::processFormSubmission',
      'event' => 'click',
    );
  }
}

Then in the processFormSubmission function you can process the form (put use \Drupal\Core\Form\FormStateInterface; at the top of your file) like:

// Instantiate an AjaxResponse Object to return.
$ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

/* do sth */

// in the DOM: replace the form with the text 'form submitted'
$ajax_response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('#MYFORM', 'form submitted'));

return $ajax_response;


texts: How to pass a parameter/argument to webform using clean urls?

texts:
I've found a post which explains how to pass a parameter/argument/referer to webform.

It works fine, but I get an ugly URL.
Is there any way to do this using a clean URL? I mean without using GET parameters.


texts:
For some reason on my site, if a user logs in using the user login block it will send them to the /user/ page to login where they have to type in their details again and it will log them in. It will redirect them here whether the initial details are correct or not.

This is also happening with the slipjaq module (slide down login panel) so I think it might have something to do with clean URLs. Do you have any idea?


texts: Drupal 7 Form API, Checkboxes with key -> value from database

texts:
I'm working on a custom module and I'm adding a form that uses checkboxes.  All is fine with using code like:

$form['tags'] = array(
   '#type' => 'checkboxes',
    '#options' => array(
      88 => 'option1',
      100 => 'option 2',
      79 => 'etc'
    ),
   '#title' => t('Tag this project as...'),
  );

The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy).  I do not want to use an autocomplete, I want to use checkboxes.

Specifically, how do I get the results from the database and format into a proper array for the options array?  Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value?

All of the examples I've seen are extremely basic and never show how to do this from a database call.  Thanks for reading/answering