texts: Which implementation is better for custom breadcrumb and why?

texts:
As per answers received here, we can implement custom breadcrumb either via module or via HOOK_preprocess_breadcrumb.

Via module:

In custom_breadcrumb.module file

<?php

namespace Drupal\custom_breadcrumb;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class Breadcrumbs.
 *
 * @package Drupal\custom_breadcrumb
 */
class Breadcrumbs implements BreadcrumbBuilderInterface {
  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.node.canonical' && $route_match->getParameter('node') instanceof NodeInterface;
  }

  /**
   * {@inheritDoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $node = $route_match->getParameter('node');
    $breadcrumb = new Breadcrumb();

    // By setting a "cache context" to the "url", each requested URL gets it's
    // own cache. This way a single breadcrumb isn't cached for all pages on the
    // site.
    $breadcrumb->addCacheContexts(["url"]);

    // By adding "cache tags" for this specific node, the cache is invalidated
    // when the node is edited.
    $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

    // Add "Home" breadcrumb link.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    // Given we have a taxonomy term reference field named "field_tags" and that
    // field has data, add that term as a breadcrumb link.
    if (!empty($node->field_tags->entity)) {
      $breadcrumb->addLink($node->field_tags->entity->toLink());
    }
    return $breadcrumb;
  }

}

and then in custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumbs:
    class: Drupal\custom_breadcrumb\Breadcrumbs
    tags:
      - { name: breadcrumb_builder, priority: 100 }

Via HOOK_preprocess_breadcrumb, as mentioned in the answer here

Both the ways are achievable, but the question is which one should be followed and why as a best practice?


texts:
I'm trying to build a single global website that houses multiple countries, each with their own set of language translations. There is also a global overview site that also has its own language options. The global site will live on global.domain.com and function the same as a country site, and the countries will be at domain.com/langcode-countrycode/ (domain.com/en-us/). From anywhere on any site, the user will have a menu to navigate to another country/language. There will only be a dozen countries or so. There will also be company sites, but they are identical to the country sites. Each country/company will have its own management team that should only be able to edit their section. Each also needs the option to swap the logo and maybe some colors, but that's it.

From what I've found, Domain Access and Organic Groups, coupled with i18n, seems like the best option, but I just can't seem to get it set up in the right way. Is there a better approach to that?

Some countries want to be able to use another domain to access their country site, which I'm guessing would just be an alias to the main domain in Domain Access.

I can mostly picture how I would build this in WordPress, or even from scratch, but I'm new to Drupal, so I might be missing something obvious...


texts:
I need to add cache manifest file just like below in my static markup:

<html manifest="my.manifest">

Is there any module to add this or custom way?


texts: Drupal base_url incorrectly writing extra subdomain

texts:
We have a basic drupal multi-site installation on a RHEL (RedHat) server.
For some reason when viewing the site, the asset URLs (CSS/JS) all point to the wrong subdomain.

Our site URL: http://drupal.sandbox.domain.com the drupal index page loads up with asset URLs being written as: http://drupal.sandbox.sandbox.domain.com.
Why would drupal add in the extra .sandbox subdomain?

The .htaccess file has been left as the default, also attempted to set RewriteBase to /, but there was no change. The sites/default/settings.php file has the base_url set to: $base_url = 'http://drupal.sandbox.domain.com' but Drupal is overwriting this somewhere. Setting the $base_url to the IP of the server causes the assets to be linked to the correct location (using the IP rather than the actual domain), but this is not ideal.

I've tested using the same configuration on an Ubuntu Server without any problems. I'm not sure exactly how to track down the cause of this problem.

How would I go about debugging this and discovering what is causing the overwritten URLs?


texts:
What I want to try and achieve.

An authenticated user creates a node of type 'listing' (this node obviously belongs to this user via his uid). On this node will be a link to create a new node of a different content type 'booking-request' (this link the author can't control).

Now an anonymous user can view this created 'listing' node and then they can click on the link and create a 'booking-request' node. So obviously the 'booking-request' node will belong to the anonymous user.

My question is. How can I assign this 'booking-request' node to the author of the 'listing' node after the anonymous user saves it?

Can I do this with a module or will this need custom php or both and how will I do this?


texts:
I am in need to theme webform in D7.

How can I do that ?

In the search I've come to know that by using web-form-nid.tpl.php we are able to theme a drupal individual form.

Could any one guide me in this case to theme a webform.


texts:
I experimented for a few hours with drupal (tried contextual filters) and searched across the internet, but couldn't find a solution for my problem. (I'm not a "drupal engineer", so maybe it's very easy to solve this problem, but I couldn't).

I have view that I want to use on multiple pages on our drupal site.
If the user browses to http://www.mywebsite.com/######, is it possible to display that view, but showing only nodes that contain "######" in a specific field in the content type displayed by that view?

edit: when ####### isn't found in that field (if 'ts available in the content type), of course it should not show the view. When ######### isn't provided (http://www.mywebsite.com/), it should display the view without te filter....


texts:
I tested my profile2 image field at upload moment and the file upload successfully and unexpectedly after save changes the image fid appears like 0 but the image don't show.

What I do?

Thanks!


texts:
I'm using Drupal Commerce Kickstart to create an E-commerce website.
How can customers cancel their own order if they accidentally ordered some wrong product?


texts: Find Menu Link Title given URL alias, to replace node Title in breadcrumbs

texts:
In Drupal 8, how can one determine the Menu Link Title of a node, given its URL and other information like its route & parameters?

This is to modify the core path-based breadcrumbs (PathBasedBreadcrumbBuilder.php) to use the Menu Link Title of a node, as breadcrumb link text, rather than the node's Title field.  This would have to be a common requirement, since the default D8 breadcrumbs would be very long in deep menus with wordy titles.  For example, we would need:

  Home > Design > Drupal

instead of the D8 default:

  Home > Introduction to Our Design Services > Drupal 8: The Best CMS for Everything

for all nodes in the "Drupal" sub-menu.

The default breadcrumb service method PathBasedBreadcrumbBuilder::build uses a bunch of injected services to look up & check routes to each ancestor pathname of the node URL, then ultimately TitleResolver::getTitle to get the titles for those routes.  We would just need a way of looking up the corresponding MenuLinkContent instead so we could then get the menu title via MenuLinkContent::getTitle.

I have tried to outline the problem for the Drupal Module Development forum (change Breadcrumbs from Node Title to Menu Link Title) but got no response when asking how to simply bridge the gap between the space of URLs/routes and the space of menu link content.  Maybe this means it's not possible without a traversal of the menu: if so I would deeply appreciate some idea of where to start with that approach.


texts: How to expose filters with dynamic values coming from another view?

texts: I have a page on which I supposed to have content of a content type(view 1) and on its sidebar there will be listing of node titles of same content type(view 2). I am passing node id on click of node titles in view 2 and this is set as contextual filter in view 1. Is there any workaround to use ajax for refreshing content for view 1?


texts:
I'm beginning to learn about writing tests for Drupal 8 via PHPUnit and am unclear on how the will() method actually serves to test anything.

Given this code (derived from examples and tutorials on the Internet):

$this->myClass = $this
  ->getMockBuilder(MyClass::class)
  ->getMock();

$this->myClass
  ->expects($this->any())
  ->method('getTestValue')
  ->will($this->returnValue('abc'));

$this->assertEquals('abc', $this->myClass->getTestValue());

If I'm just telling it to return value 'abc' and then, unsurprisingly, I get the same value back, then what am I testing? As far as I can tell, the getTestValue method of MyClass doesn't even get called. I verified this by coding MyClass->getTestValue to return a test-breaking value (i.e. 'def'), but it still passes.

How does this test the MyClass class?

Admittedly, I also don't understand the usage of expects() and method(), but these seem ancillary to the actual question. Please correct me if I'm wrong.


texts: What is controlling the layout of customer view orders?

texts:
On the page located at user/%user/orders/%commerce_order, I am having a hard time figuring out what .tpl.php is dictating its layout.

Namely, I have tried editing commerce_backoffice/theme/commerce-order--backoffice.tpl.php and clearing the cache, but I see no change.

I know very little about theming and am not sure what I am doing wrong.


texts: strtotime() doesn't return unix timestamp in custom view when $row->field_date is an English date

texts:
I'm confused. I'm using a Global: PHP field inside a view to tweak the output of the row based on the date value of a certain field.

print (strtotime((string)$row->field_date));

Doesn't seem to return anything.

print $row->field_date;

Returns "Tuesday, December 1, 2015"

print strtotime('Tuesday, December 1, 2015');

Returns 1448956800

I've tried converting the $row object to an array just for fun with get_object_vars($row) but that didn't work either.

In my case I expect that print (strtotime((string)$row->field_date)); returns the value (unix timestamp) 1448956800.


texts: How to configure boost for multisite configuration

texts:
I installed the Boost module in my site. The site is running on multisite configuration having subdomains like

http://site1.example.com

http://site2.example.com

http://site3.example.com

http://site4.example.com

After enabling the Boost module in all subdomains. And also edited the .htaccess rule generated for a subdomain.

in the document root www.example.com/public_html/cache/normal i can see 4 directories and relevant  cached pages for each sub domains inside these directories
site1.example.com
site2.example.com
site3.example.com
site4.example.com

But cannot see the boost comment at the end of page in any subdomain. In short I would say "Boost module is not working". Am I doing right boost configuration for multisite configuration. Actually I don't know what extra stuffs is needed for boost to work in multisite configuration

here is my .htaccess generated rule for each subdomain placed in .htaccess file in root folder

  ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=3]

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###


texts: Data export import failed to import into Drupal 7

texts:
I using "Data Export Import" module to export all articles from site Drupal 6 and import it to site Drupal 7.

I export all taxonomy terms in site Drupal 6 and import the dataset into site Drupal 7.

The error messages:

  There is a mismatch between the vocabularies in the dataset file and
  the current vocabularies - vocabulary name: News The Taxonomy Terms
  dataset file 20150824_113732_taxonomy_terms.dataset was not imported.

How should I correct the error?


texts: Dependent exposed filters and taxonomy level Drupal 7

texts: I have an exposed filter in a View. There you must select Brand of car. The taxonomy vocabulary is Cars, and has all brands as parents and all models of car at the second level under its mother term. When I try to make a expose filter linked to the first level of taxonomy, I don't know how to do it, and less to use the selected result to filter the second exposed filter, which will just render the second level taxonomy term (model).


texts: Is there a way to remove tabs inside panels?

texts:
This is a simple question, i know that there are many modules who can alter tab like tab tamer.

But i would like to avoid to install another module in my site because he's already slow and my server he's limited, it's why i'm asking this question.

I alter the user template profile, so i just want to remove the tabs : view and edit, i didn't find any setting to do that but maybe i missed something?


texts: Control Webform's date field (datepicker) from JS

texts:
I have to change number of months that's shown in datepicker of my date field in Webform, on desktop I need 2 months, but on mobile just 1.

I'm not able to control that using JS, so I created patch for Webform module to change that and show 2 months.

Is there some solution for this, how I can change stuff like this using JS even I initialized it through field settings in Webform module?


texts: Drush syntax error, unexpected T_FUNCTION in webform.module

texts:
When I try to run drush right now I get this error:

-bash-4.1$ drush pm-list
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected T_FUNCTION in
<site location>/sites/all/modules/webform/webform.module,
line 4654

Here is the function where the error occurs:

/**
 * Get a list of all available component definitions.
 */
function webform_components($include_disabled = FALSE, $reset = FALSE) {
  static $components, $enabled;

  if (!isset($components) || $reset) {
    $components = array();
    $disabled = array_flip(webform_variable_get('webform_disabled_components'));
    foreach (module_implements('webform_component_info') as $module) {
      $module_components = module_invoke($module, 'webform_component_info');
      foreach ($module_components as $type => $info) {
        $module_components[$type]['module'] = $module;
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
      }
      $components += $module_components;
    }
    drupal_alter('webform_component_info', $components);
    uasort($components, function($a, $b) {
      return strnatcasecmp($a['label'], $b['label']);
    });
    $enabled = array_diff_key($components, $disabled);
  }

  return $include_disabled ? $components : $enabled;
}

Line 4654 is the one that starts with "uasort" (near the bottom). I'm using

PHP 5.6.15
Drupal 7.41
Webform 7.x-4.12

Drush was working for the whole project (up till now) and webform was installed near the start of the project.


texts: How to display messages "properly" when using ajax submit?

texts:
Here is a simple form:
  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $form['some_text'] = [
      '#type'  => 'textfield',
      '#title' => $this->t('TextValue'),
    ];
    $form['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->getValue('some_text') != 'Awesome') {
      $form_state->setErrorByName('some_text', $this->t('Please enter "Awesome"'));
    }
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    drupal_set_message($this->t('The form was submitted'));
    $form_state->setRedirectUrl(Url::fromRoute('<front>'));
  }

And it works as expected:
Case 1A: Submit with no entry gives this (error message in default message location):

Case 1B: Submit with "Awesome" in TextValue gives this (completion message  in default message location and back to the front page of the site):

Now, I add some ajax on the submit button:
$form['submit'] = [
  '#type'  => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax'  => [
    'wrapper'  => 'default_form_wrapper',
    'callback' => '::ajaxCallback',
    'progress' => [
      'type'    => 'throbber',
      'message' => $this->t('Be patient'),
    ],
  ],
];
$form['#prefix'] = '
';
$form['#suffix'] = '
';

and the corresponding callback:
  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->hasAnyErrors()) {
      return $form;
    }
  }

And it works more or less as expected:
Case 2A: Submit with no entry gives this (almost OK, wrong location of the message):

Case 2B: Submit with "Awesome" in TextValue gives nothing (KO, no message and form is still displayed instead of front page).
And if I refresh the page in the browser, I get this:

As you can see, the location of the message area in case 2A is above form in default_form_wrapper
(to be compared to the default message area location, a div with class="region region-highlighted"):

How can I make it work as I expect?

Have the message in the "default" area?
Have my submitForm work after all?


texts:
Problem

I'm trying to theme the menu local tasks that Drupal places without any unique css classes. How would I do this?

(Specifically I'm looking to hide certain links on certain pages by giving each one a unique css class).

Links Sample HTML

Which is generated by this line in page.tpl.php.

<?php if ($primary_local_tasks): ?>
<?php print render($primary_local_tasks) ?>
<?php endif; ?>

So Far

To do that I'm trying to use theme_menu_local_tasks however I can't get it to work. I've put this snippet in my template file but it doesn't print anything or show me any variables.

function tefltheme_menu_local_tasks (&$variables) {
  dpm($variables);
  print("hello");
  return theme_menu_local_tasks($variables);
}

I'm using Tao sub-theme which means it splits menu local tasks into primary and secondary.

function tao_preprocess_page(&$vars) {
  // Split primary and secondary local tasks
  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();

Could this be affecting anything?


texts: Adding Profile2 fields to user registration

texts:
I have a custom module that overrides the /user/register page so that in addtion to username and email it also asks for about 10 or so Profile2 pieces of information.

The code I have so far:

    $form['hi'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
      '#title' => t('Additional Info'),
    );

    $form['hi']['l'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
    );

    $form['hi']['r'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',

    );

    $form['hi']['l']['h_ph'] = $form['profile_memberlist']['field_home_phone']['und'][0];

The form renders a space for username, email and Home Phone.  I fill out the form, and submit, and I get the following:

  Thank you for applying for an account. Your account is currently pending approval by the site administrator.
  In the meantime, a welcome message with further instructions has been sent to your e-mail >address.

Error message

Notice: Undefined index: profile_memberlist in profile2_form_submit_build_profile() (line 471 of /var/www/html/example/sites/all/modules/profile2/profile2.module).
Warning: array_merge(): Argument #1 is not an array in field_default_extract_form_values() (line 36 of /var/www/html/example/modules/field/field.default.inc).
Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be an array, null given, called in /var/www/html/example/modules/field/field.default.inc on line 38 and defined in drupal_array_get_nested_value() (line 6608 of /var/www/html/example/includes/common.inc).

I've double checked and the memberlist is the name ( machine name) of the profile2 I am trying to get populated.


texts: href link assigning callback action - ajax

texts:
I have a situation where I would like to define a href link and when it is clicked, for it to trigger an ajax response such as sending back some information which can then be shown on the page...

Part 1. Creating the link... So I've created the link via:

    $url = Url::fromUserInput('#');

    $nxt_button=Link::fromTextAndUrl('Submit Application',$url);
    $nxt_button=$nxt_button->toRenderable();

    $nxt_button['#attributes'] = [

    ];

    $output['link1']=array(
        "the_link"=>$nxt_button,
    );

Now in the '#attributes' I assume i could put something like 'callback' => 'name of function to be run' ... but, if the function to be run resides in another object say 'ajax_test_script.php' how would I do that?

Part 2. Say the server side responding code, was in a different class called 'ajax_test_scirpt' and the function to call is 'start' ... If I was sending back information via:

$response=new AjaxResponse();
$response->addCommand(<<what goes here>>);
return $response;

And these lines of code were inside the function 'start'... What would I put as the input parameter for addCommand, if I wanted the response to behave such that it could call the javascript function outlined below, which would be attached to the page (e.g call readMessage passing in the parameters needed by the readMessage function):

(function($, Drupal) {
/**
 * Add new command for reading a message.
 */
Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
    // Place content in current-msg div.
    $('#current-msg h2').html(response.subject);
    $('#current-msg p').html(response.content);
    // Remove from unread list.
    $('#msg-' + response.mid).remove();
    // Add message to read list.
    $('#read-msgs').append('<li>' + response.subject + '</li>');
}

})(jQuery, Drupal);

Any help is appreciated.


texts: How do I create a module that uses composer to manage a 3rd party library?

texts:
I maintain a module on Drupal.org, the jQuery Colorpicker module, which has a requirement on a 3rd party library. I created a composer.json file in the module root. When I originally installed it, I navigated to the module root and ran composer update, which created vendor folder in my module directory, and loaded the library to this vendor directory. I then released a beta version of the module.

One user who downloaded the library ran composer drupal-update from core, which installed the library to the DRUPAL_ROOT/vendor folder. I'm thinking this is the correct way to go.

So I deleted the vendor folder from my module folder, as well as the composer.lock folder from my module folder.

However, when I run composer drupal-update in my drupal root, it does not install the library to my vendor folder.

I'm not really sure where to go with this - do I need to add something to my module, or is there a required command that needs to be run somewhere for Drupal to install the library when running composer drupal-update? I haven't worked a lot with composer, so I'm trying to find the proper way to do this so my users can use the module in the standard Drupal way.


texts:
I've been made module that shows related articles and based on taxonomy tags. My problem is that, it listed related articles where is no comments too.

So I want that shows only these articles where is comments.. At least one comment, but I can't get that working. Thank you

My code:

function related_articles($cat, $limit = 10) {

 //$nid = $variables['node']->nid;
 //$variables['num_comments'] = db_result(db_query('SELECT COUNT(cid) AS count FROM {comments} WHERE nid = %d', $nid));

$limit = isset($limit)?  " LIMIT $limit " : ' ';
$row = db_query('
    SELECT nid \'id\',title \'name\', field_category_tid
    FROM {node} n
    LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
    WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat order by title asc
    '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

return ($row)? $row: array();
}


texts: Problem with Add to Cart form in views containing the Add to cart form

texts:
Possible Duplicate:
  Commerce - Views - Taxonomy - add to cart issue

I am creating a product discount based on a discount field present in product display following some real assistance from guys at IRC and Bojan Zivanovic. Refer to this question

The add to cart form on the product node display works fine as expected but if I use add to cart form present in Views, products are added to the cart but no discounts are applied because discounts are based on initial display_path present on the node display pages. I tried this but couldn't figure out comment from rszrama.

My question is how will I make views know about the node context i.e display_path?


texts:
I'm running D7.  I'm trying to figure out how to a) tag users with a location (ZIP, address, city, state, etc.) when they register an account, and b) set up a search where the visitor inputs their location (via ZIP, address, etc.), and it returns a list of every registered user sorted by their proximity to the inputted location in the search.  I'm more interested in an answer to part b) since it seems more complicated, but honestly any help at this point would be very appreciated.  I've been stuck for a few weeks now.

Thanks,
Edward Sapp


texts: Create a log of create/delete users in Drupal 7

texts:
I'm creating a log with several actions in drupal.

I register similar actions with hook_watchdog.

/**
* Implements hook_watchdog().
*/
function MYMODULE_log_watchdog(array $log_entry) {

  if($log_entry['message']=='Login attempt failed for %user.'){
    my_log_function();
  }
}

But I do not know how to detect that is created or deleted a user, and record this information in my custom log.

I'm new in drupal development and I Appreciate any guidance to investigate. Thanks :)


texts:
I would like to add some custom validation to a node form.
But for some reason the validate function is skipped, the submit function does gets called.

/*
 * Custom Form settings
 */
function frontpage_banners_form_promo_banner_node_form_alter(&$form, &$form_state, $form_id) {

  $form['#validate'][] = 'frontpage_banners_form_promo_banner_node_form_validate';
  $form['#submit'][] = 'frontpage_banners_form_promo_banner_node_form_submit';

  dpm($form_id);
  dpm($form);

}

function frontpage_banners_form_promo_banner_node_form_validate(&$form, &$form_state) {

  drupal_set_message('error');

  form_set_error('', t('Email must be valid format if entered.'));
}

function frontpage_banners_form_promo_banner_node_form_submit(&$form, &$form_state) {
  drupal_set_message('submit');
}

I tried several function names but nothing seems the work.

From the $form array:

#validate (Array, 2 elements)
0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 54 characters ) frontpage_banners_form_promo_banner_node_form_v... |


texts:
I just started using Drupal 8 and i am already experiencing problems. In my info.yml file I've added library/ies and in my libraries.yml are those files included. And when I clear cache in Admin, the css is not showing in source code. I've even clear cache in Drush, if that would be the problem but it's not.

Here is my libraries.yml file

global-styling:
version: 1.x
 css:
  theme:
   css/style.min.css: {}

global-js:
 js:
  js/app.min.js: {}
 dependencies:
  - core/jquery

And here is my info.yml file:

name: MyTheme
description: MyTheme template for Drupal 8
type: theme
package: Custom
core: 8.x
screenshot: mytheme.jpg
libraries:
 -mytheme/global-styling

regions:
 header: Header
 content: Content
 footer: Footer
 sidebar: 'Footer2'

What am I doing wrong?


texts: Taxonomy terms not localized in view with enabled aggregation

texts:
On a view on content, I added a field "All taxonomy terms" (Display all taxonomy terms associated with a node from specified vocabularies) and enabled aggregation, see screenshot of view attached. This view is listing exclusively terms that are actually used in content.
While the view is working for the standard language of the site, the terms are not translated into the other languages despite the vocabulary is translatable.
Once I disable the aggregation, the translation of terms is working again.

So how can I make the translation of terms work?


texts: Tag autocompletion fails for anonymous users?

texts:
On a site, anonymous can create content. The content type has a term reference field, which works fine for logged in users.

However, for anonymous, the fields JS is "dead", no autocompletion happens, and I can't even see an http request going off.

Obviously I assumed is has to be a permissions issue as it only affects anonymous, but I can't seem to figure out what permission that would be, and if it was, then it seems like the http request would go off.


texts: Why do I get an "can't add field due to unmet dependency" error?

texts:
In order not to manually duplicate a field from the staging environment to  production, I'd like to programmatically create some user fields.
I've tried with drush generate field, which basically gave me a folder with WidgetType, Formatter, etc, but I can't figure out what it is for.
Then, I created the field via UI and exported it.
langcode: fr
status: true
dependencies:
  config:
    - field.storage.user.field_fonction
  module:
    - user
id: user.user.field_fonction
field_name: field_fonction
entity_type: user
bundle: user
label: fonction
description: ''
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string

I put it in /modules/custom/mymodule_import/config/install, but when I try to reinstall my module, I get an "can't add field due to unmet dependency" error.
What am I doing wrong? Is there any easy way to create a user field?


texts: Is --overrides an accepted option in drush 8.x?

texts:
I'm creating a build script and would like to include the --overrides flag as describe in the documentation. I'm using Drupal 8.0.0 and Drush 8.0.1 and I get the following:

drush make build.make.yml ~/Sites/built --prepare-install --overrides=dev.make --no-cache -y -vvv
Unknown option: --overrides.  See 'drush help make' for available options. To suppress this error, add the option --strict=0.

Am I missing something? Is this functionality not built yet?


texts: Easy way to get this custom module to work with multiple Nodes (NID's)

texts:
Topsitemaker hooked me up with this custom module that works great with one node when I enable it.  My issue is I need it to work across multiple nid's.  The field name and cid on all the nid's will stay the same, the only thing that will change will be the nid.  I have been trying without success to get this to work.  In this example it works for nid 4, but if the module is enabled, it will return the error for the same field on other nid's.  Is there an easy way to get this module to work with several nid's?

'<?php

/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'application_name_director_name_manager_name';
  $cid = 10;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('YOU HAVE ALREADY SUBMITTED FOR THAT APPLICATION, PLEASE SELECT A NEW APPLICATION.'));
  }
}

/**
 * Implements hook_form_alter().
 */
function sample_form_alter2(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}


texts: How to have a language switcher that allows you to select the country and then the langauge within the country?

texts:
We are looking to have a menu at the top right that allows users to select the country they want to view and then once the country is selected, we want them to pick a language that they can view the site in. How is it possible and what are the recommended modules?

Example:


texts:
On my websites I have forums that mirror the structure of og-based groups. I am using advanced forums, OG Forum D7 and a decent amount of custom code.

My problem is to restrict access/visibility to forums based on the og role. While I know how to do it with forum topics which are stored as nodes, I have problems with forums which under a hood are taxonomy terms.

I am looking for a place where I can hook the code restricting visibility of a taxonomy term.

function mymodule_taxonomy_access($taxonomyterm, $op, $account) {
    if( $op == 'view' )
        $gid = get_grop_from_term($taxonomyterm);
        if( user_has_forum_access($gid, $account))
                return ACCESS_ALLOW;
        //else
        return ACCESS_DENY;
    }
}

I have no idea in which module I should look for the right hook: taxonomy, forum, forum_access, core (I think that taxonomy terms are entities)?

Taxonomy Access Control while being very powerful, provides no connection with organic groups.

UPDATE
I have found that TCL Lite is using the hook_query_TAG_alter to hide taxonomy terms.
The hook is editing all queries made to the database and is effectively filtering the taxonomy_terms that any query can see.
This looks like an awfully heavy solution.

Can anyone suggest a better approach?


texts: how can i specify certain block for specific content type to get in there?

texts:
In Drupal 7 every content type gets in the "Main page content" block,
so I want every node with "Product" content type to sits in some other block.
How could I?


texts: jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module

texts:
i have a script for dealing with node images hover

(function ($) {
    $(function(){

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

});
})(jQuery);

when clicking on a node filter set by 'better_exposed_filters' using ajax,
the POST drupal/views/ajax?field_tags_tid_1=4 is loaded and filter out nodes fine but the JQuery behaviour is working nomore.

Ajax breaks jquery

Any help?


texts:
I'm having trouble figuring out how to have a registration in different phases. This is what I would like to do:

A user registers with a name and an email or register with facebook.
He will receive an email to set his password.
The user can now bookmark nodes. But when he would like to create a node of content type Proposal he needs to complete a full registration (I'm using Multi-step registration module). An email will be send to the administrator who needs to check the data and give the user a new role.

For now I have the second step. A user register with a complete form. But how can I add the facebook register or name/email register before it?


texts:
Drupal 8 Twig
I have a content, which have entity reference field field_field_data_provider_ref, referencing another content, which itself contains a field field buisness_property_type (single taxonomy term)

 {{ node.field_field_data_provider_ref.entity.buisness_property_type.value }}

 {{ node.field_field_data_provider_ref.entity.buisness_property_type|views }}

doesn't work for me


texts:
I had this piece of code in a module developed for some previous version of Drupal 8.

protected function getOutput() {
    $content = $this->buildContent();
    //print_r($content);
    $page = array(
      '#theme' => 'html',
      '#page_object' => new Html(render($content)),
    );
    $rendered_page = render($page);
    return $rendered_page;
}

Now, in the present beta release, it shows this error:

  Fatal error: Class 'Drupal\hardcopy\Plugin\Html' not found in C:\xampp\htdocs\drupalbeta7\modules\custom\hardcopy\src\Plugin\HardcopyFormatBase.php on line 175

Can someone tell me how to pass the HTML of the whole page in the response object?


texts: Kernel base test for media view displays is failing with: LogicException: Missing bundle entity, entity type media_type, entity id image

texts:
I am trying to test media view displays via a test, which is based on the KernelTestBase class. I have also tried to inherit from Drupal\Tests\media\Kernel\MediaKernelTestBase, but got the same error from bellow:

  LogicException: Missing bundle entity, entity type media_type, entity
  id image.

My test class looks like this:

<?php

namespace Drupal\Tests\degov_image_and_crop_styles\Kernel;

use Drupal\Core\Extension\ModuleHandler;
use Drupal\KernelTests\KernelTestBase;

class ModuleInstallationTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'user',
    'migrate',
    'migrate_drupal',
    'system',
    'node',
    'taxonomy',
    'field',
    'file',
    'image',
    'media',
    'media_test_source',
    'text',
    'filter',
    'language',
    'content_translation',
    'image_widget_crop',
    'crop',
    'lightning_core',
    'responsive_image',
    'breakpoint',
    'degov_image_and_crop_styles',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installEntitySchema('node');
    $this->installEntitySchema('file');
    $this->installEntitySchema('media');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('taxonomy_vocabulary');
    $this->installEntitySchema('user');
    $this->installSchema('system', ['sequences']);
    $this->installSchema('user', 'users_data');
    $this->installSchema('file', 'file_usage');
    $this->installSchema('node', ['node_access']);
    $this->installConfig(self::$modules);
  }

  public function testSetup(): void {
    /**
     * @var ModuleHandler $moduleHandler
     */
    $moduleHandler = \Drupal::service('module_handler');
    self::assertTrue($moduleHandler->moduleExists('degov_image_and_crop_styles'));
    self::assertTrue($moduleHandler->getModule('degov_image_and_crop_styles'));
  }

}

Does anyone know, what I am missing here?


texts: Drupal 8, don't automatically execute the view after the first load of the view page

texts:
I created a view page from the admin interface. Then when I go to the view page url with my browser, the view is displayed and show automatically some results.

Now, I want force the user to click on the execute view button for display results. I mean, the user go to the view page url, only exposed filters are displayed, he must click on the view submit button for display results of the view.

It's possible to configure that from the view interface configuration (I didn't find..) or I must use a custom module ? (and how?)

Thanks you :)


texts:
I have a template for a view in which I load a node. Is there a way to get the value of all fields from that node? Like, if I add another field in CCK it will appear automatically in the template.

Something like:

foreach $node->field
     print $value

Thanks!


texts: I have three better exposed filter in views.when apply any filter it takes 4 to 5 secs to give a result.


texts:
I have made a single tiny change to a core module. I copied it into my site modules directory. I am curious as to whther I can simply override it's hook_menu() method in my copy so as not to carry over all the additional code which the core version provides?

Similar to theme inheritance, do modules support anything similar?


texts: How to list nodes posted in current month?

texts:
I try to list nodes posted in current month, with Views.

I tried to add a Contextual filter: Created: month, but no node appears.

I tried a Filter criteria: Content: post date / Is equal to / An offset ... / "-1 month", but no node appears.

Do you know how can it be done?


texts: Display any discounts only at cart / checkout stage

texts:
I am selling furniture, I also sell furniture accessories.

Both of these have their own Product Types.

I use 'Commerce Discount', 'Commerce Discount Extra' and a 'Workflow Rule' to offer a 20% discount on the accessories, but only when an item of furniture exists in the cart.

This rule composes of:

EVENT: Calculating the sell price of a product.
CONDITIONS:

Product Types: Furniture Accessories   AND
Order Contains Products: [a list of SKUs of every furniture item I sell]

ACTIONS: [The name of the discount I set up in 'Commerce Discount'] (which applies the 20% discount on any 'Furniture Accessory' products)

My problem is:

As soon as I add a piece of furniture to my cart, any furniture accessory product display price is discounted across the site.  I'd like the prices to remain at full price when viewing the product display node, but only discounted once viewing the cart or the checkout process is underway.

It feels like their should be another Event, perhaps "Starting the checkout process" or "Viewing the cart"


texts: Getting 443 Forbidden Error on my custom module

texts:
I am learning drupal 8 and creating my own custom module. I have a clean localhost installation and was following some tutorials online to create a very basic "hello" for my first attempt.

The issue I am running into is when I attempt to go to my routing area, I get the following error:

Forbidden
You don't have permission to access /tag on this server.

Here is my code. Can someone tell me why this isn't working? If I followed the online tutorials right, I should have access.

tagnbag.info.yml file:

name: Tag N Bag
description: 'Create a custom grocery list.'
type: module
package: Custom
version: 1.0
core: 8.x

tagnbag.routing.yml:

tagnbag:
  path: '/tag'
  defaults:
    _controller: 'Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
    requirements:
      _permission: 'TRUE'

TagBagController.php:

<?php
/**
 * @file
 * Contains \Drupal\tagnbag\Controller\TagBagController.
 */

namespace Drupal\tagnbag\Controller;
use Drupal\Core\Controller\ControllerBase;

class TagBagController extends ControllerBase {
    public function welcome() {
        return array(
            '#type' => 'markup',
            '#markup' => 'Content for Tag N Bag.'
        );
    }
}


texts: Why drush fails with undefined function conf_path() error?

texts:
Here's a weird one: I've got two nearly identical server setups, both running Drush 5.9. Both have been happy for a while. Went to use one today, and got the error:

Drush 5.9 does not support Drupal . Use Drush 4 instead.
PHP Fatal error: Call to undefined function conf_path() in /var/opt/drush/includes/bootstrap.inc, line 786

The other site runs Drush 5.9 just fine.  Any ideas?


texts: Theme specific form field for custom content type

texts:
I have created a custom content type and added some fields to it. I want to theme one of the fields which I added from the "Manage Fields" section.

I want to remove the div wrappers when the form field is rendered.

Is there any form field specific theme function which I can override in template.php and make my changes?


texts:
I read this interesting article on Drupal caching, but I'm not sure which caching method I should be using.

My code is implementing a menu callback, and returning a renderable array.
What is the difference between method #1 and method #2?

Please see the question embedded as a comment in method#2

// Method #1.
function my_module_menucallback() {
  $render_array = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $render_array = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $render_array
      // with the correct stuff..
      cache_set('my_module_data', $render_array, 'cache');
    }
  }
  return $render_array;
}

// Method #2.
function my_module_menucallback() {
  // ** Do the calculations and population of $render_array that would occur here
  // get called repeatedly if this method of caching is used??? **

  $render_array ['my_content'] = array(
    '#cache' => array(
      'cid' => 'my_module_data',
      'bin' => 'cache',
      'expire' => time() + 360,
      ),
    // Other element properties go here...
    );
  return $render_array;
}

Please ignore the time specified, as this is just sample code.


texts: Installed a feature, getting warnings on cache clear and view content not loading

texts:
The Feature included a menu link, main menu, 2 views, and a custom content type. Now I am getting a warning on cache clearing on my local and dev site. Never saw it before when clearing cache, and one of the views is not loading the content items.

They do load for admin. I have tried setting the view permission to none, to role anonymous, removed sorting by published content, and returning NODE_ACCESS_ALLOW in the module's hook_node_access().

The full drush warning is

class_exists() expects parameter 1 to be string, array given handlers.inc:34

and the watchdog output that corresponds seems to be

Warning: strnatcmp() expects parameter 2 to be string, array given in token_asort_tokens() (line 575 of /home/example/public_html/sites/all/modules/token/token.module).

I'm at a loss for how all these components interact, or if they are even related.

Edit: module.info file

name = Example
description = Example description
core = 7.x
package = Features
version = 7.x-1.0
dependencies[] = course
dependencies[] = menu
dependencies[] = references
dependencies[] = text
dependencies[] = views
features[ctools][] = views:views_default:3.0
features[features_api][] = api:2
features[field_base][] = field_example_key
features[field_base][] = field_example_passcode
features[field_instance][] = node-example-body
features[field_instance][] = node-example-field_example_key
features[field_instance][] = node-example-field_example_passcode
features[menu_custom][] = main-menu
features[node][] = example
features[views_view][] = example_sessions
features[views_view][] = examples
features_exclude[dependencies][ctools] = ctools
features_exclude[dependencies][features] = features
features_exclude[menu_links][main-menu_examples:examples] = main-menu_examples:examples


texts:
How to show images uploaded only on "read more?"

drupal is so confusing...


texts: How do I redirect a taxonomy menu item to another path?

texts: I have a taxonomy menu, and I want to redirect the page request from taxonomy/term/% to a custom path using a page callback function.  How can I use a function to cause the redirect?


texts: 403 forbidden for all css files located in /modules

texts:
My multi site Drupal 7 installation is suddenly unable to load any CSS file located in the /modules folder and subfolders (for example http://example.com/modules/system/system.base.css). I get "Failed to load resource: the server responded with a status of 403 (Forbidden)" in the browser console.

All CSS files for installed custom modules and all custom theme CSS files (inside /sites/all/modules and /sites/all/themes) are loading just fine.

Even more strange: the /modules/ CSS files load fine if I enable "Aggregate and compress CSS files." in Configuration > Development > Performance. When I disable "Aggregate..." I get the 403.

I realize that aggregating CSS is recommended in production sites, but I need to figure out what is going on and why the CSS files are not loading (they were loading fine earlier today). I did some changes in permissions earlier today, but I reverted those, with no success.

Any ideas?

PS: I noticed that Drupal adds "?obkukf" after .css - what is this, and does this have anything to do with the problem?


texts: Apply the timezone offset to my date field

texts:
I use the Date Module. My contenttype event dates are stored like

field_date['de'][0]['value'] = 2011-12-09T10:40:00 (String, 19 characters )
field_date['de'][0]['value2'] 2011-12-09T13:10:00 (String, 19 characters )
field_date['de'][0]['timezone'] Europe/Berlin (String, 13 characters )
field_date['de'][0]['timezone_db'] UTC (String, 3 characters )
field_date['de'][0]['date_type'] (String, 4 characters ) date | (Callback) date();

How to apply my timezones to the values? When I edit the date on my field_date and also when my dates are displayed, everything is fine. But I have to work with the raw DB values and need to apply the timezone. Doing it by hand with php +1h should work, but then it's summertime again....


texts: Failed opening required" symfony/class-loader/ApcClassLoader.php on line 110

texts:
I get this error after installing a module in modules/contrib and then uninstalling and moving it to a different directory. I accidentally installed the module in the wrong place.

This is in a local BLT/Drupal-VM environment. I've tried drush cr and rebuilding the drupal core directory as well as nuking the vendor folder that composer installs.

Seems that the paths to the installed modules gets stored in PHP memory some how and after the move php is not picking up the changes.

Restarting apache doesn't do anything either.


texts:
I am trying to import a rule for facebook autopost in Configuration>Workflow>Rules, but after I click import button, I receive the error message below. I don't know which php module I have to install. I have searched on drupal site but I don't figure out which module I have to install.

Regards,


texts: Getting "Fatal error: Class not found" by bootstrapping external script and executing user_save function

texts:
I have a problem i've struggled with for a long time, and it's starting to really piss me off, so i hope you can help me.

The thing is i'm writing a custom script (not a module) that needs access to the drupal user object, and it's profile2 fields, so i found out i could use the bootstrapper for this purpose.

Loading fields from the users profile works just fine, but when i try to make changes programmatically (user_save function for example), it fails with the following error, which makes absolutely no sense to me:

Fatal error: Class 'Drupal\gmap\GmapDefaults' not found in (root directory)\sites\all\modules\gmap\gmap.module on line 32

A function that would return this error could be something like this:

function custom_add_role_to_user($user, $role_name) {
              // For convenience, we'll allow user ids as well as full user objects.

              // If the user doesn't already have the role, add the role to that user.
              $key = array_search($role_name, $user->roles);
              if ($key == FALSE) {
                // Get the rid from the roles table.
                $roles = user_roles(TRUE);
                $rid = array_search($role_name, $roles);
                if ($rid != FALSE) {
                  $new_role[$rid] = $role_name;
                  $all_roles = $user->roles + $new_role; // Add new role to existing roles.
                  user_save($user, array('roles' => $all_roles)); // <---- This function throws the above error...
                }
              }
            }

If i don't call user_save(), everything works just fine, and until now i have been doing fine with direct sql queries, but i need to know why this doesn't work.

I've tried navigating to the GMap class to see what's actually going on at line 32
(Still not knowing why my simple script keeps referring to some random Google Map Module..?)

Here it is:

function gmap_defaults() {
 include_once(drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');
 return GmapDefaults::getInstance()->getDefaults();
}

So why is the bootstrapper calling this random module, and what is wrong with the module first of all???

It seems like it doesn't get to create the namespace required correctly. But i don't see where it goes wrong?

drupal_get_path returns the right path... I've tried to put a static path instead, to see if that made any difference... It didn't...

Thanks in advance for your help.


texts:
I have used custom code. I want to remove duplicate value using distinct, how can I do this? My code is like this.

$media_query = db_select('node','n');
    $media_query->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
    $media_query->fields('n',array('nid'));
    $media_query->fields('mtype',array('field_media_room_type_tid'));
    $media_query->condition('n.type','media_room_page','=');
    $media_query->condition('mtype.field_media_room_type_tid',$media_id,'=');
    $media_res = $media_query->execute();
    while($media_fetch = $media_res->fetchObject()){
     $media_year = '';
        if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
            $media_year = $media_node->field_year['und'][0]['value'];
        }
      echo'<pre>';print_r($media_year);
    }

Output like this:

2011

2011

2011

2011

2011

2011

2012

2012

2013

I want to remove duplicate values so how can I remove it?


texts: Is it possible to extend an existing contributed module?

texts:
There's a new Drupal module that I'm interested in integrating in our websites, the Media Entity File Replace module. I've already installed it via composer and created an update hook to enable it across our different profiles, but the problem is exporting its yml configuration file.
Step 3 of the module's Usage Instructions says you have to enable it in the Form Display settings of the media type you wish to use it on. In our case, we just want it on Documents media type.
I looked for the yml configuration under Entity Form Display and found that it updates this particular file:
core.entity_form_display.media.document.default.yml
I run a search in my local Drupal branch and found that that file only exists in the Acquia Lightning Media contributed module (docroot/modules/contrib/lightning_media/modules/lighnting_media_document/config/install/)
How would I safely utilize the Media Entity File Replace Module without breaking a contributed module?


texts: Not all content showing up after uploading to live server

texts:
I have been working on a site for a client and I have ran into a bit of an issue. I built the site locally and then pushed it to a staging server to show the client and everything is running fine. When we got to the point of launching the site, we did what our team normally does and everything seems to be working fine until you look at the page content... It only shows the first sentence.

Here is an example of what's going on:

staging server:

live server:

My head is hurting from trying to figure this one out. I am using a custom theme and using  to display the data on the left hand side like we always do, so that shouldn't be the problem. I am just at a loss, any little help would be awesome!


texts: How can I get exposed filter for content type from the view programmatically?

texts:
I want to customize an exposed filter for content types, how can I get the exposed filter for a view in the code? And to know exactly which content types need to be dispalyed?

$route = explode('.', \Drupal::routeMatch()->getRouteName());
if (!empty($route) && $route[0] == 'view') {

  if ($view = Views::getView($route[1])) {
       $filters = $view->getHandlers('filter');

  }
}


texts: How to form_alter fields attached to an unlimited field collection?

texts:
Here are 2 unsuccessful experiments I've done:

<?php

/**
 * My first attempt with implementing hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          // None of these work:
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#default_value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#default_value'] = 'test';

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#value'] = 'test';

        }
      }
  }
}

/**
 * My second attempt implementing hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {
    // These don't work either:
    $element['field_SOMEFIELD']['#value'] = 'test';
    $element['field_SOMEFIELD']['#default_value'] = 'test';

    $element['field_SOMEFIELD']['und']['#value'] = 'test';
    $element['field_SOMEFIELD']['und']['#default_value'] = 'test';
  }
}

How can I alter the form API elements on fields attached to a field collection?

PS: The hook functions are running fine. The issue is that the form API values I set do not make any change on the loaded form.


texts: How to trick feeds into re-importing nodes?

texts:
I have a content type in a feature. I am using feeds to import actual nodes from one site to another. I added new fields to the content type, and re-exported it into the features module. However, the feed ran before I updated the feature on the downstream site, and now it's not pulling the new field data. I know this will work, because it's worked before when I added new fields. However this time it's grabbed the data before it knew about the new fields.

How can I trick feeds into thinking it needs to update all the nodes? I tried setting the changed value on the nodes in the database to the current timestamp, but that didn't work. What criteria is feeds using to decide if the node data has changed?


texts: Filter by postal code as location within user defined radius

texts:
I have to make a filter in which user will add postal code and select a radius.
Suppose, user entered postal code = 12345 (which results into city 'XYZ') and the radius of 200 miles. So all nodes containing the location within the radius of 200 miles of the city 'XYZ' will be the output.

Can anyone suggest some solutions?


texts: Fetching field values only if they exist and applying them automatically as entity labels

texts:
I have a content type with these fields, among others:

field_address – required
field_entrance – not required
field_apartment_number – not required (or actually required if a previous field meets a certain criteria, otherwise not shown at all)

With the Automatic Entity Label modul I can use tokens to save the node title using this pattern:

[node:field_address] [node:field_entrence] [node:field_apartment_number]

If any of the non required fields are left blank there's no value from those fields saved to the node title. However, the whitespace between the tokens is still saved, and I don't want that. I'm not good at PHP but this I what I have, copy-pasted from various sources:

<?php

$address = field_get_items('node', $node, 'field_address');
$entrance = field_get_items('node', $node, 'field_entrence');
$apartment_number = field_get_items('node', $node, 'field_apartment_number');

print $address['value'];

if ($entrance) {
   print ' ' . $entrance['value'];
}

if ($apartment_number) {
   print ' ' . $apartment_number['value'];
}

?>

But it doesn't work. Instead, no title is saved at all. How do I correct my code?


texts:
I have a page/node that contains 15 view blocks, each view block has many fields and all of this causes the page to load really slow.

How do I load the view block only when I need it? for example I would click a button/div (venue) then the view block venue will load instead of invoking all of the view blocks on the template and letting it load all at once.

UPDATE:
I tried using ajax but it's not working even though I turned the ajax on the view block.

This the code I used:

JS:

$(document).ready(function(){
$("#getvenue").click(function(){
    $.ajax(
    Drupal.settings.basePath + 'views/ajax',
    {

    view_name: 'custom_package_form',view_display_id: 'block_56'
    },

    function(response)
    {
        if (response[1] !== undefined)
        {
            var viewHtml = response[1].data;
            $("#output-venue").html(viewHtml);

            Drupal.attachBehaviors();
        }
        else {
            $("#output-venue").html("NONE");
        }

    });
    });
 });

Node Venue TPL:

<button id="getvenue"> GET VENUE </button>

Nothing happens, I tried alerting the var viewHtml to see if it has something, the alert only shows null.

What's wrong with the JS? Can someone point me to the right direction?

Thank you in advance!


texts:
I'm planning a new project that will require a great deal of custom code that must remain proprietary to my client. I found the licensing FAQ http://drupal.org/licensing/faq to be unclear.  I know this is primarily a coder as opposed to legal Q&A forum, but hopefully some experienced Drupal developers can shed more light on this issue.

What constitutes distribution?  For example, if the code is used on two unique domains owned by the same client, is that considered distribution?  Page 533, Chapter 24 of The Definitive Guide to Drupal 7 states "Modules built for ourselves or a single client are not considered distributed", but that isn't very clear.
If a module has been distributed and you have a copy, are you obligated to give me a copy, or is it up to you?  (In other words, could I demand a copy from you?)
If custom javascript is called from a Drupal javascript object (such as Drupal.behaviors), is it considered GPL'd and distributed?  The licensing FAQ Answer #7 states "Drupal's JavaScript, including the copy of jQuery that is included with Drupal, is itself under the GPL as well, so any Javascript that interacts with Drupal's JavaScript in the browser must also be under the GPL or a GPL compatible license."  That's a major non-starter for this particular project.  The client obviously doesn't want competitors walking off with highly specialized javascript that took months to develop with no legal recourse.
What is the legal status of modules that are not for distribution?  Are they license-free, or are they automatically GPL'd even if not intended for distribution?  For practical purposes, in a module that is not for distribution, would the following language have any legal effect:  "This module is copyright Company XXX and is not intended for distribution.  This software is not licensed and you may not use this module for your own purposes."

Apologies if these questions aren't as precise as they could be; I'm obviously not a lawyer.  I really want to use Drupal for this project, but if I can't offer an assurance to the client that the custom code (module code and javascript) will remain proprietary it's a non-starter.


texts: How to bulk delete empty taxonomy terms?

texts:
The website has thousands of unused (empty) taxonomy terms and I want to bulk delete them.

With views all empty terms can be listed but it's not possible to delete them via Views (VBO etc).

I saw that taxonomy terms should be cleaned with taxonomy_term_delete() in this question: How to delete true orphaned taxonomy terms. But I don't know where to use it? Should I create a block and put the code inside it or a custom module or anything else?

(I also tried the Delete Orphaned Terms module but couldn't be sure if it's working properly. I tried it on a dev. site but couldn't check the results.)


texts:
I need a funtionality for search tags from a textarea (drupal form), I make it from sql, then, mysql have this function:
https://dev.mysql.com/doc/refman/5.0/en/string-functions.html
I believe that oracle/pql does have same function.

select * from cms_tags ct
 where instr('Americana Abstract Art Art Antique Jewelry Antique Jewelry Jewelry', ct.name);

How can I use that query in drupal way? using db_select() or something else.


texts: Is it possible to join dynamic tables (subqueries) using db_select()?

texts:
I've got a complex query I'm trying to convert to db_select().

SELECT c.cid, c.pid, c.thread, count.replies, SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) as torder
FROM comment c
JOIN(
    SELECT count(*) as replies, SUBSTRING_INDEX(LEFT(thread, LENGTH(thread) -1 ), '.', 1) as torder
    FROM comment
    WHERE nid = 1
    GROUP BY torder
) as count
ON SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), '.', 1) = count.torder
WHERE c.nid = 1 ORDER BY count.replies DESC, torder ASC;

I'm not sure how join through a select statement, if it is possible, or if there is another alternative.

I don't need to return anything from the join (count.replies is only there for show) so maybe there is another option other than join.

I'm trying to select order by the top-level comment with the highest number of replies and it's children.

The result prints this for my test data:

+-----+-----+-----------------+---------+----------------+
| cid | pid | thread          | replies | torder         |
+-----+-----+-----------------+---------+----------------+
| 262 |   0 | 03/             |      11 | 03             |
| 269 | 262 | 03.00/          |      11 | 03.00          |
| 272 | 269 | 03.00.00/       |      11 | 03.00.00       |
| 270 | 262 | 03.01/          |      11 | 03.01          |
| 273 | 270 | 03.01.00/       |      11 | 03.01.00       |
| 275 | 273 | 03.01.00.00/    |      11 | 03.01.00.00    |
| 276 | 275 | 03.01.00.00.00/ |      11 | 03.01.00.00.00 |
| 280 | 275 | 03.01.00.00.01/ |      11 | 03.01.00.00.01 |
| 277 | 270 | 03.01.01/       |      11 | 03.01.01       |
| 278 | 270 | 03.01.02/       |      11 | 03.01.02       |
| 271 | 262 | 03.02/          |      11 | 03.02          |
| 264 |   0 | 04/             |       3 | 04             |
| 281 | 264 | 04.00/          |       3 | 04.00          |
| 282 | 264 | 04.01/          |       3 | 04.01          |
| 260 |   0 | 01/             |       2 | 01             |
| 279 | 260 | 01.00/          |       2 | 01.00          |
| 261 |   0 | 02/             |       2 | 02             |
| 274 | 261 | 02.00/          |       2 | 02.00          |
| 283 |   0 | 05/             |       1 | 05             |
+-----+-----+-----------------+---------+----------------+

The 'replies' number includes the top level comment which is OK because I'm only using this for ordering and includes all of the comments in a thread for each comment which is by design because I want to group all of the comments first by how many comments are in their group.

The SELECT in the join returns the number of replies for each top level comment:

+---------+----------+
| replies | torder   |
+---------+----------+
|       2 | 01       |
|       2 | 02       |
|      11 | 03       |
|       3 | 04       |
|       1 | 05       |
+---------+----------+

I can't to this using db_query because I'm trying to overwrite the query in comment_get_thread() using hook_query_TAG_alter().

I've tried using $query->join() but don't see where it is possible to put in an argument.

EDIT:

Thanks so much for your answers. Here is the db_select translation of the sql query above if anyone is having trouble with this in the future:

$subquery = db_select('comment', 'c')
  ->fields('c', array('thread'))
  ->condition('c.nid', '1134');
$subquery->addExpression('COUNT(*)', 'replies');
$subquery->addExpression('SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), \'.\', 1)', 'toporder');
$subquery->groupBy('toporder');
$query = db_select('comment', 'c')
  ->fields('c', array('cid', 'pid'))
  ->condition('c.nid', '1134');
$query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
$query->addJoin('', $subquery, 'count', 'SUBSTRING_INDEX(LEFT(c.thread, LENGTH(c.thread) -1 ), \'.\', 1) = count.toporder ');
$query->orderBy('count.replies', 'DESC');
$query->orderBy('torder', 'ASC');
$results = $query->execute()->fetchAll();


texts:
I'm  listing nodes in a block view which is located in a panel managed by page_manager.

I need for these nodes somes custom opérations in contextual links, so i implmented hook_contextual_links_alter() to add some operations.

All works.

Problem : my custom contextual links are appearing in new nodes of this list (or modified nodes) but not in old ones. To make them appear, i need to flush my browser's cache (i'm also using memcache).
Editing all these nodes or clearing browser's cache are the only ways i currently found to get contextual links working for old nodes.

I need to achieve this during the update of my app with hook_update of my module without editing all these nodes or asking users to clear their cache.

PS : i tryed to clear all cache with & without drush -individually or not-, by all ways, all modules are last stable version, drupal 8.5.2


texts:
I was trying to find contributed module for Drupal 8 to track practically everything users do on site.

I was able to find some good modules like Events Log Track but it only works for entities (Users/Nodes/Taxonomies).

What I would like to do is to be able to track any change with permissions. I know I can track those changes through configuration but I want some additional data like: who changed what and when.

Do you know if there is a contributed module for this?

Should I go custom way? - As I imagine I could hook into any form and track changes from there but I am not sure if it is a right way to do it.

Thanks


texts: Can we make template for contextual filter?

texts:
Can we make template for contextual filter, because while I am writing php code in it, it is not supplying true values.
I am writing these code in php code of contextual filter:

<?php
   $children = array_keys(taxonomy_get_children($handler->argument, $vid=1));
   if(!empty($children)) $handler->argument .= '+' .implode('+', $children);
?>

I need to apply these code in template file so that get satisfactory result over there and can apply some custom code too.


texts: Hook into node operation from theme template.php?

texts:
I have made a new content type in Drupal 7 in Drupal Admin (not via module). What I want to do is to add a Hook on the insert and update operation. How can this be done when my node type is not created by a module?

Can this be done at all?


texts: Core Workflow: How to add Save as Draft button in form actions?

texts:
On we create article we have 'Save' & 'Preview' button.

I would like to add 'Save as draft' button.

I found https://www.drupal.org/project/save_draft  But it's not for Drupal 8

Found this URL : https://sites.google.com/site/learnandmake/how-to-created-button-for-each-state-of-workflow-in-drupal-7

I tried with this

function custom_module_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['actions']['draft'] = array(
    '#type' => 'submit',
    '#class' => 'form-submit',
    '#name' => 'btn-draft',
    '#value' => t('Save as draft'),
    '#weight' => '-10',
    '#submit' => ['custom_module_node_form_submit']
  );
}

In the function

function custom_module_node_form_submit(&$form, FormStateInterface $form_state) {

  $button_clicked = $form_state->getTriggeringElement()['#name'];

  if ($button_clicked == 'btn-draft') {
    if ($entity = $form_state->getFormObject()->getEntity()) {
      $entity->set('moderation_state', 'draft');
      $entity->save();
    }
  }
}

Using workflow module.

So have state (Draft/Publish/Archive)

Once it save not able to alternative function for node_form_submit($form, $form_state); Currently it's giving error 'title` is missing in DB Query

Error

  The website encountered an unexpected error. Please try again
  later.Drupal\Core\Entity\EntityStorageException:
  SQLSTATE[23000]: Integrity constraint violation: 1048 Column
  'title' cannot be null: INSERT INTO {node_field_data} (nid,
  vid, type, langcode, status, title, uid, created, changed, promote,
  sticky, default_langcode, revision_translation_affected, weight,
  publish_on, unpublish_on, publish_state, unpublish_state) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6, :db_insert_placeholder_7,
  :db_insert_placeholder_8, :db_insert_placeholder_9,
  :db_insert_placeholder_10, :db_insert_placeholder_11,
  :db_insert_placeholder_12, :db_insert_placeholder_13,
  :db_insert_placeholder_14, :db_insert_placeholder_15,
  :db_insert_placeholder_16, :db_insert_placeholder_17);


texts: Field Collection fields not showing field values in edit form

texts: After creating content in Drupal 7, when i open edit form, field collection fields are shown as empty , but on the node view page, values are shown.


texts: how to enable comments only to subscribed users

texts:
I'm creating a site for events where people can subscribe themselves to a single one.
Now, I'm using Node Registration module to allow users to subscribe. I would like to know if it is possible to enable comments of a particular event only to users who are members of it. Is there a module to do this? I tried with rules module but i couldn't...


texts:
Is it possible to create a slideshow using( slideshow module or views slideshow module or anything else) external image url's  instead of downloading the images, then uploading in the image field?

Also I'm looking for a functionality where there are some image fields( containing uploaded images) and some external image links but all need to be shown in single slideshow.

I've googled this but could not find anything useful ..


texts: Can I have a views field handler with an exposed form, or a filter handler with pre_query?

texts:
It's basically in the title, but here's the question:

I'm trying to create a way to allow the user looking at a view to control which columns are visible. This isn't very hard, provided I can get called in the right place. Specifically, I need to be called in three places:

in some kind of configuration pane
in the exposed form
in the pre_render function

Both field handlers and filter handlers get a configuration pane. But only filter handlers get to affect the exposed form, and only field handlers get access to the pre_render function.

Although I might be able to get something working by combining a handler with various hooks, I would prefer everything to be together.

Does anyone know how to convince Views to either call a field handler when rendering the exposed form, or to call a filter handler for the pre_render function?


texts:
I'm using a view grid template and a views-view-fields--view-machine-name.html.twig template file in order to render some pictures in grid format. I want to assign dynamic CSS classes to every picture that is being rendered, for example, using the following markup.

{{ fields.field_picture.content }}

I have set a variable in Twig with the following code, but since there is no loop, it doesn't get incremented.

{% set id = 0 %}

So for every picture I have the same CSS classes (profile-pic pic0).

I want to get the following.

Picture 1
profile-pic pic0
Picture 2
profile-pic pic1
Picture 3
profile-pic pic2
Picture 4
profile-pic pic3

If I use the following code, the same imagine is rendered instead of the pictures I have.

{% for field in fields -%}

{{ fields.field_picture.content }}

{%- endfor %}

How do I get the counter to be increased, and all the images to be rendered?


texts: Is there a way to make a body field automatically become the first comment on a node?

texts: Im on d7, I want my body field (or any textfield attached to a content  type really) to automatically become the first comment on its node. Any suggestions?


texts: Boost and expire not working after update

texts:
big problem here. I have a website up from 2 years and working with combo of boost cache system and expire to handle clear cache on insert/modify or delete Node.

Two days ago I did upgrade of this two modules (first tested locally properly to see if generated errors). I did not realize that there is an issue when the nodes were inserted expire cache was not working. Ergo now every time the editor of the site inserted nodes must clear the cache manually.

Drupal not write error or warning in log. Does anyone have this problem? Any idea about? Thanks a lot guys.
More info:

Drupal 7.36
Boost 7.x-1.0
Expire 7.x-2.0-rc4


texts: What is wrong with my JQuery UI datepicker option code?

texts:
I have an AJAX view using Views 3 and Better Exposed Filters (and therefore jQuery UI datepicker).  One of the exposed filters is dates between [post-date] (core).

The form works fine, but when dates are entered and submitted (via AJAX) the visible entries in the input fields disappear.

Before:

After:

It doesn't happen to other text fields, only date fields, and it stops happening when I change the Exposed Form type to 'Basic'.  I'm sure it's BEF causing the issue but what's really puzzling is that the input values are there in the HTML after submit:

<input ... value="2015-05-01" ...>

Why isn't it showing in the input field?

[edit:] I tried to reproduce this on a blank site and couldn't.  No longer certain the root cause is in BEF.

Additional information:

I've tracked the problem down to some custom JQuery code to add options to the datepicker post-render.  The options are added no worries, I just can't figure out why it breaks the inputs.

(function ($) {
Drupal.behaviors.myPageFilters = {
  attach: function (context, settings) {

    $("label[for='edit-post-date-max']", context).once('changeBetweenText', function(){
        $(this).text("to");
    });

    // This is the culprit, commenting out this block stops the weird behaviour
    $(".bef-datepicker", context).once('changeDatePickerFormat', function(){
        $(this).datepicker("option", "changeYear", true).datepicker("option", "changeMonth", true);
        $(this).datepicker("option", "dateFormat", "yy-mm-dd").datepicker("option", "showButtonPanel", true);
        $(this).datepicker("option", "buttonImage", "/sites/all/themes/mytheme/images/exposed-filter-calendar.png").datepicker("option", "showOn", "both");
    });

    $(".bef-secondary-options", context).once('createSecondarySubmit', function(){
        $(this).append('<input type="submit" id="bef-secondary-submit" value="Apply" class="form-submit">');
    });

  }
};
}(jQuery));

It's this:

$(this).datepicker("option", "dateFormat", "yy-mm-dd");

I placed it there to change the date format away from the US format provided in BEF code (AUS site).

I just discovered the jQuery UI Datepicker option field in BEF. /facepalm

I'll leave this question here in case anyone ends up with the same issue.


texts:
I had a site where the developer set up an screen that you went to directly upon logging in. it was a custom view, within a template that displayed all the content. The view was a block and displayed only to editors.  I set this all up but the blocks are not displaying. Am I missing a step here

this is all i have in my page.tpl.php file

  <div id="content" class="clearfix">
    <?php print $content; ?>
  </div>


texts:
I'm using Drupal 7 with views 3.

I have used an exposed filter for a date field and I want to provide option to choose date from datepopup for date filter? How can I do this?


texts: my page.tpl.php overrides path of page display of views

texts:
I created a view and a page display of it. I set a path for it. this is its path

http://localhost/myProject/library

but when I copy and paste this url in address bar, it just displays my page.tpl.php what I have created for front page. why?


texts: Can I work with hook_user_login() directly within user.api.php?

texts:
Somewhat new to Drupal... this is probably a softball for all you Drupal pros out there.

I need to update a custom table in the database each time a user logs into Drupal.  I thought I'd be able to do this within user.api.php and specifically within hook_user_login but it's as if none of the code I've put in there works.  To debug I added the following 2 lines to try to email myself details about $account and I never get that either.

$o = print_r($account, true);
mail("art@geigel.com", "Login Output", $o, "FROM: no-reply@geigel.com");

I've also gone into the Drupal admin area and saved the settings page for the modules thinking it was a Drupal caching issue related to its hooks.  That didn't do it either.

Can someone tell me what I'm missing?  I'd prefer to just take care of the database stuff here instead of creating an entirely new module and implementing the hook there.

Thanks in advance.

AG3


texts: When creating content: Force the checkbox "Provide a menu link" to be checked by default

texts:
When creating content, I would like to force the checkbox "Provide a menu link" to be checked by default.

What I'm really trying to do:

I created a new content type
I used node_add to get the form associated to my content type and render it into my template.
In my module I used the hook_form_alter to hide some fields of my form.

But when the user submit the form and the node is created, there is no menu link created by default.


texts:
I am trying to install Drupal 8 on my PC running Windows 7.
I am using XAMP; MySQL is installed and running properly. Drupal only provides the option for SQLite.


texts: How do I stop a module from installing optional configuration, or make sure it's installed by the time I want to remove it myself?

texts:
I don't want the "Frontpage" view to be installed along with my installation profile.

I tried adding a hook_install to a module which does this:

\Drupal::entityTypeManager()->getStorage('view')
  ->load('frontpage')
  ->setStatus(FALSE)
  ->save();

But during installation that tells me that the frontpage view doesn't exist when my module is being installed. Fair enough, so I added the module that owns the frontpage view config (core node) to my dependencies:

dependencies:
  ...
  - drupal:node

Still didn't work. Then I realised it's optional config; maybe the module responsible for processing that config (core views) also needs to be a dependency. It would make sense, so my dependencies became:

dependencies:
  ...
  - drupal:node
  - drupal:views

Still didn't work, same problem - the View simply doesn't exist yet, so it can't be deleted.

So two halves of the same question:

How do I stop this config from ever having been installed in the first place (or installed but initially disabled)?
If that's not possible, what dependencies do I need to provide to ensure that the View in question is installed by the time my own hook_install is executed, so I can remove/disable it myself?


texts:
I'm not sure how to frame this question, so I'm sorry if the answer already exists.

Basically, I want to know how to modify the way arguments are fed into views. For example, say I'm presenting a income statement and balancesheet, it seems like its formatting the links as www.example.com/balancesheet/ibm and www.example.com/incomestatement/ibm

Is there a way to make it www.example.com/ibm/balancesheet or www.example.com/ibm/incomestatement, so I can create views and have them grouped this way?

My problem is instead of grouping content by views, I want to try to group views by content so if someone searches for IBM they basically get all the views that apply.  I'm open to any suggestions anyone has.


texts: Conditionally output by content type using Twig

texts:
I want to theme the display of a Views based on the Content type. In my attempts to do that, I’ve created the views showing All Content Types. I’ve added all the fields I need, and also included a Content: Type field. It is this field that I am trying to use for conditionally formatting the output (if it’s a Blog content type use this html and for all other content types use a different html).

This is what I have tried so far but that condition is not triggering at all

I have created a views-view-fields--myexample.html.twig

{% if fields.type.content == 'blog' %}

{% else %}

   {{ fields.title.content}}
   {{ fields.field_image.content }}

{% endif %}


texts: Show translated content in view listing page when accessing translated site

texts:
I have a view that filters for a specific content type (accommodation) and shows a paginated list for the user.

The site has a second language (Welsh) and a few of the content nodes have Welsh translations.

In theory, I should be able to visit the accommodation view, and if I was on the Welsh site (http://www.example.com/welsh/accommodation) I should see the Welsh nodes listed.

Sadly, this is not the case exactly.

My view is able to filter the Welsh translated nodes, but the view is spitting out the English text (title, URL, description etc) and not the Welsh versions.

This makes it pretty pointless, especially the fact that the URLs are rendered as the 'normal' English URLs and do not point to the Welsh site.

I've tried a tons of various view options but cannot fathom how to render the translated information.


texts: How to theme views using Taxonomy Terms?

texts:
The site on which I'm working has a variety of views for multiple sections of the website. These different sections, which are defined by Taxonomy terms, use different themes. So, for example, sections 'X' and 'Y' each have views which we want to be displayed in themes 'X' and 'Y.'

Is there a way in Views to assign the page created by Views a taxonomy term, so that, using ThemeKey, it can be assigned a theme by it's taxonomy term, like the other nodes with that taxonomy term?

I'd really like to do this without using templates, so that it can be easily managed within Drupal's UI.


texts:
I would like to have a heading over my comments that only appears after a comment has been left... I tried the code below but it doesn't seem to be the answer:

<?php if ($comment): ?>

Comments

<?php endif; ?>


texts: Fatal Error after creating Custom Display Suite layout

texts:
I am using Display Suite and I created a custom layout called ds_6row when I Flush Cache I get the following error

Call to undefined function ds_ds_6row() in /Users/myname/Sites/sitename/sites/all/modules/contrib/ds/includes/ds.registry.inc on line 570

I followed the method to create the layout here

My structure looks like this:

mytheme
--ds_layouts
---ds_6row
----ds_6row.css
----ds_6row.inc
----ds_6row.png
----ds-6row.tpl.php

The code for ds_6row.inc is:

<?php
function ds_6row() {
  return array(
    'label' => t('6 Row Layout'),
    'regions' => array(
    'info_data' => t('Info_data')
  ),
// Add this line if there is a default css file.
'css' => TRUE,
// Add this line if you're using DS 2.x for icon preview
'image' => TRUE,
);
}

The code for ds-6row.tpl.php is:

    <?php

/**
 * @file
 * Display Suite 6 row template.
 */
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-6row <?php print $classes;?> clearfix">

  <?php if (isset($title_suffix['contextual_links'])): ?>
  <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

  <<?php print $first_wrapper ?> class="group-first<?php print $first_classes; ?>">
    <?php print $first; ?>
  </<?php print $first_wrapper ?>>

  <<?php print $second_wrapper ?> class="group-second<?php print $second_classes; ?>">
    <?php print $second; ?>
  </<?php print $second_wrapper ?>>

  <<?php print $third_wrapper ?> class="group-third<?php print $third_classes; ?>">
    <?php print $third; ?>
  </<?php print $third_wrapper ?>>

  <<?php print $fourth_wrapper ?> class="group-fourth<?php print $fourth_classes; ?>">
    <?php print $fourth; ?>
  </<?php print $fourth_wrapper ?>>

  <<?php print $fifth_wrapper ?> class="group-fifth<?php print $fifth_classes; ?>">
    <?php print $fifth; ?>
  </<?php print $fifth_wrapper ?>>

  <<?php print $sixth_wrapper ?> class="group-sixth<?php print $sixth_classes; ?>">
    <?php print $sixth; ?>
  </<?php print $sixth_wrapper ?>>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>


texts:
I created a content type called successful story; in this content type, there is a title field and a text field.

I have two types of users, Role1 and Role2; Role2 can only create or delete a successful story.

For example, The user called Michael is a Role2 user and can create its successful story

But how can I make this relation works between a content type and an user?


texts:
In Drupal 7 this was done with the l() command and setting the html option to true. I have found the Link::fromTextAndUrl() method in Drupal 8 but no mention of something similar to the html option.

[EDIT]
I think i was not clear with my original question. This is not for an image field; i was simply asking how to wrap a link around:

<img src="path_to_my_img">


texts:
As I have multiple Drupal sites on my server,  I am attempting to enable clean urls via the httpd.conf file.

I am using the following code:

<Directory /var/www>
   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

However, when I visit check the Enable clean URLs box and click the save button, my website just reloads as my index.php file showing the phpinfo() data.

Can anyone tell me where I'm going wrong, please?


texts: How to choose to which group new content will be visible?

texts:
I have a content type: Event. I put instances of Event inside the Calendar(everything works great). I also have Organic Groups installed and set up(I have a group called: employees).

Now, the problem is that when I create an Event I can't find dropdown list where I can choose to whom this content will be visible(to which group).

How to make it show up?

This is Drupal 7.


texts: Setting up Multiple Databases on a current site

texts:
I'm having issues with my current shared hosting provider due to my core database exploding upwards of 1GB due to cache_form. I've been looking at trying to offload the cache and revisions databases into different databases entirely and set them away in order to hold down the load. I think my understanding of how is ok but I want to be sure as this is a current live site.

I declare the default database then declare where each table is explicitly in the prefix array. If this is accurate then I will just do it that way, if not then I'd like to know where I'm going wrong. Do I need to explicitly declare ALL my databases first in settings.php or do I need to declare just my default and let it work that way?


texts: Making a username/password syncronization scheme - D7

texts:
I need to register my users to a 3rd party service upon registration in Drupal. I have toyed around a bit with hooks, and tried to catch the password upon registration so I can insert it into another database, but to no avail. The 3rd party DB encrypts the password in a different way, so I need to get the users password in clear text, crypt it and then save it to the database.

Can anyone give me some pointers to where I should look? hook_user_insert (&$edit, $account, $category), both $edit and $account contains the users encrypted drupal passwords.


texts:
I've got a TwitterBlock on my website. It works fine but all texts are in english.
Even if I change t('') function with my language (french) desired, it's still in english.

ex:ln422 twitter_block.module

'#title' => t('Tweets by @username', array('@username' => $config['username'])),

to

'#title' => 'Tweets par @me',

It still display 'Tweets by @username' in my page.
The language input seems to be ignored to in admin/structure/block/manage/twitter_block/1 when I wrote 'fr' in it.

I hope that my problem is a minor oversight on my part. All tips are good (even the simplest).

Thanks in advance.

PS: when I try to do a dsm($block) in twitter_block.module or dsm($content) in my override block I get all my values in french.


texts: Preprocess function for node.tpl.php file

texts:
I've watched a million videos and read a million tutorials trying to figure out how to create a new variable for use in a version of a node.tpl.php file by utilizing preprocessing functions, but can't figure out what I'm doing wrong.

First, I copied the node.tpl.php file, renamed it node--nameofnodetype.tpl.php, and saved it in my theme folder. Then, I edited the template.php file, trying different variations of the following code.

function theme_preprocess_nodename(&$variables, $hook) {
  $variables['link_name'] = 'link content';
}

I flushed the cache, and when I tried printing the new variable in the new node file, I got nothing. Can anyone tell me what I'm doing wrong?


texts: How to store replacement patterns in a field and get them to be replaced in a view?

texts:
I have two product types: Online Store and Product. The Online Store content type contains information such as name, URL, etc along with a Product URL template text field. What I mean by that is the link to the Products of the store all using the same URL except for the product id number. For example, I store a product link template to the website in a field on the Online Store content type like this:
"http://www.onlinestorename.com/items/product.php?id=[field_product_id_value]"

For Products content type, I have an entity reference field to a specific Online Store. I also have a product ID field (field_product_id_value).

When I create a table based view of Products in Drupal 7, I use entity reference so that I can also display the name of the Online Store, the URL, and the product link template. For each product row, I want to use the product link template pulled from the Online Store and replace the [field_product_id_value] with the product ID.

My problem is that I can't figure out a method to get the [field_product_id_value] replacement pattern to be replaced in product link template that is being pulled from the Online Store content type.

Basically, I am creating the link to the products on the fly instead of storing the links in the Product content type. Storing the product link in a field takes up a lot of database space hence the reason to create the link on the fly and have the pages cached.

Any thoughts?


texts: Entity reference form in views below node

texts:
I have a machine content type (clients have machines) and i would like to display all their machines in a view (done) and have a webform/entity form display below the node so that the client can submit issues to the machine. Therefore my end result should look something like this;

Johnny's machines;

Machine 1 - Model Number 234567

Form exposed

Sumbit form button

Machine 2 - Model Number 876543

Form exposed

Sumbit form

Etc.

Any ideas how I might be able to pull this off?

Thanks


texts: How to make content work with and without javascript

texts:
I have some content that I currently use a javascript dialog box to display. This works great when javascript is enabled but not so good when javascript isn't (it shows the dialog components on the screen along with original content). I would like to fix this so that dialog contents display on a separate screen when javascript is not enabled. I thought I saw some documentation somewhere on how to do this but for the life of me I can't find it by googling it again. Can someone point me to the proper online documentation on how to do this?

Additional Info:
The page has a button on it that allows the user to create a new item. With JavaScript enabled, the add button displays a dialog box in which the user can enter information about the new item. Currently the text/input fields for that dialog box is on the same page the add button is on but hidden by Javascript using special divs (hence why it is visible when JavaScript is disabled). This is code I inherited from someone else and now would like to fix.


texts:
Basically, I'm setting up a website for someone who is going to post one thing per day. I want to provide a way of accessing these articles by week and naming the week:

i.e. if a node is published on the 30th November, I would like the website to know that it is the first week of Advent and to be able to display that/sort by it.

The current way I was trying to do it was:

  Article Published using Scheduler --> Rules then tags according to
  date published

I just don't know if that's achievable, or indeed if there's a simpler way?

Thanks


texts:
My website is running on Windows and it sits on drive C:/, however I'd like to keep all my files on drive D:/.
How can I do it?
I know that I can move the whole site to drive D:/ but I was wondering if it's achievable at all.


texts: Odd log entries: is it indicative of an attack?, is there anything other than IP blocking that I should do?

texts:
So I've been getting some odd log entries in my Drupal 7 install:
Here's two:

As far as I can see they haven't done anything and I've blocked the IP addresses but they keep coming with different IP addresses so I'm wonder what they actually mean? Like if they were for manager/html I'd know they were (probably automated) attack testing for Apache Tomcat apps to hack. But these with a location that isn't even my site I'm confused by.
Also wondering why the message starts with ttp:// instead of http:// or something normal.