form with taxonomy autocomplete widget throws error upon submit: Invalid argument supplied for foreach() I have a custom form with this field in it:

$form['first']['field_city'] = array(
    '#title' => t('Woonplaats'),
    '#type' => 'textfield',
    '#size' => 25,
    '#autocomplete_path' => 'taxonomy/autocomplete/field_city',
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#required' => TRUE,
);

I'm trying to use the autocomplete tagging widget to use with an existing taxonomy vocabulary on this form.
It works fine tags are loaded when I start typing but if I submit the form I get the following Warning:

Warning: Invalid argument supplied for foreach() in taxonomy_autocomplete_validate()

resulting in this error and the wsod (white screen of death)

   PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2:
SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, v.machine_name AS vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.name LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (base.vid IN ()) ; Array ( [:db_condition_placeholder_0] => Amsterdam )

I think I'm missing something in the form decleration or made a mistake somewhere.
So what's wrong with it? Thanks!

some suggestion is that the machine_name of the field might be wrong. ( the machine name is actually stad when I look in the taxonomy in the admin UI).

I'm pretty sure this error will be coming from the following loop in taxonomy_autocomplete_validate()

 // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);
    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }

which is collecting the vocabularies allowed for the field, check:

Field is set to be a term reference
Field has at least one allowed vocabulary set
field_city is the correct machine name of the field in question


Find the origin of a redirection I work on a Drupal project in business and we are facing a problem. We have a webform node with an alias ..../contact. We also have a page view .../news listing a specific type of content. Recently, when we want to go on / contact, we are redirected to the page /news. By enabling dlevel, it displays: "The user is being white Redirected to /en/news."

We have the "Pathauto" and "Global redirect" modules, but we never had a problem with these two.

We have no idea from where this redirection can come ... :(

You can see what page is the referer by using

$_SERVER['HTTP_REFERER'];


Can I safely delete auto-created Postgres Indexes? Running Drupal 7.X with a Postgres 9.3 database.

When adding new fields, 8 database indexes appear to be created for each new field. Running the query "select * from pg_stat_all_indexes;" shows that only 2-3 out of the 8 indexes are actually getting used ... primarily field_data_field_XXXXX_entity_id_idx and field_data_field_XXXXX_pkey. All the other indexes (e.g., ...bundle_idx, ... deleted_idx, ... language_idx, etc.) show 0 for idx_scan, idx_tup_read, and idx_tup_fetch.

Is it safe to delete those indexes that show 0? Once deleted, is there an easy way to recreate the indexes if needed?

The reason for wanting to delete those indexes is that hard drive space is limited. Deleting those indexes would recover significant amounts of hard drive space.

I used the following PSQL query to identify all the indexes not being used and to sort by biggest first:

SELECT nspname || '.' || C.relname AS "relation",
  pg_relation_size(C.oid) AS "size",
  idx_scan,
  idx_tup_read,
  idx_tup_fetch
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
LEFT JOIN pg_stat_all_indexes stat ON C.relname = stat.indexrelname
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_relation_size(C.oid) DESC

I deleted several dozen indexes. So far, no issues. It seems performance may be improved as I am noticing less CPU resources needed. Likely because there are fewer indexes to be updated.


Output view field as link I need to output a field in a view as a field, how can I make part of the path the value of a CCK field?

For example if for a given item, my CCK value = '19' how can I make my path automatically be website.com/directory/19?

I think that you can use, in respective field settings of your view, the option Rewrite the output of this field. please see this example (in image) with a field title. you must replace [title] with the respective field tag, according the indication in Replacement patterns > Fields.


How do you render a Node's Last Saved date in a Region Footer (ie, inside a Block on every page)? I'm new to Drupal (8) and have no PHP experience, but I've managed to get this interesting CMS doing just about everything I need by playing with Twigs.

I cannot for the life of me figure out how to get a Page's "Last Saved" date to render in the footer block though.

In the Node twig I can add this, and it works perfectly:

{{ node.changed.value|date("d/m/Y H:i") }}

But in the region--footer.html.twig (which is an included block at the base of every page on the site, and where I wish to render this information) all I get back, from every combination I try, is the current date/time of when the page loads in the browser. Actually, i think it is the current server time.

Obviously there's something I just don't get about how Drupal works!

Can anyone offer a newbie some help in language I might understand?

Cheers,
mrEdge

I think you can add to the yourtheme.theme file next thinks;

function yourtheme_preprocess_region(&$vars) {
  $vars['node'] = \Drupal::routeMatch()->getParameter('node');
}

and afterwards in your twig template each region will have available variable node.

{% if node %}
  {{ node.changed.value|date("d/m/Y H:i") }}
{% endif %}

Don't forget to clear cache.


Contact form to notify the author of the node i am building a real estate website where authorized users will be able to add some properties. I need in the property details page(node) to have a contact form with spesific fields and when that form submitted, the author of the node will be notified by email. Is that possible and how can i do this?

I am not a programmer so i would prefer a solution with existing modules.

You may try the Privatemsg module.

  Privatemsg allows your site's visitors to send private messages to each other. Perfect for community oriented sites, such as forums and social networking sites. Many additional features are available as separate modules.

  Current features

  send and receive private messages on a site (between multiple recipients)
  threaded conversations (make it easier to keep track of messages and replies)
  search private messages
  tagging and filtering (helps organise conversations)
  user blocking
  e-mail notifications of new messages


Posting the main url of drupal site on facebook wall When pasting the URL of the Drupal site in question as a facebook message, the message, title and image that are being fetched from that drupal site are not the ones that are supposed to come up.
From what I gather, Facebook module and OpenGraph stuff seems needed in order to figure this out which seems overkill for this problem...

The homepage of the Drupal site is a view with some blocks in the sidebars. When you paste the URL of the site (www.mysite.com) in a facebook message, it fetches some text out of a block, and an image from some other node. Instead, I want to be able to choose which text it fetches from the site.

The answer to this question How to change facebook og:image to post image link? seems to come close and is telling me I need to use the metatag module. It doesn't explain how to go about it, but I installed the module and changed some of the values in the configuration, but didn't have any effect. Also flushed caches many times.

Also installed the fb module, I read the README.txt from the fbmodule from the beginning until the end (as asked).

I have a feeling like I don't necessarily have to get a degree in the the huge Facebook API/Opengraph rabbithole in order to get this sorted, do I?
I mean, there has to be one place where you can just determine when the text, image and title should be on the wall without too much of a huge construction around, no?

You have a two part question here.

One, the best way to deal with OG info on your site is with the Metatag module:

  The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about a website. In the context of search
  engine optimization, when people refer to meta tags they are usually
  referring to the meta description tag and the meta keywords tag that
  may help improve the rankings and display of a site in search engine
  results. In addition, the module provides support for meta tags (Open
  Graph Protocol from Facebook, Twitter Cards from Twitter) that allow
  control of how content appears when shared on social networks.

When you install and enable this, you can customize what OG info appears where, and it has full token support for dynamically creating the meta elements pages on a page's content.  You can also hardcode values for specific cases, like the home page.

The second part of your question has to with the fact that FB heavily caches page contents.  The provide a debug tool for dealing with this:

https://developers.facebook.com/tools/debug/

In addition to seeing exactly what OG info it is pulling in about a URL you provide, it has the side effect of clearing the cache for that particular URL.


Hide the Drupal /user/register form from spam, but leave open registration to Commerce/Ubercart Commerce/Ubercart require account creation to buy product.  That's fine - I want that.

But I do not want user/register open to the public.  Efforts to use Honeypot/Captcha/Mollom are still letting in lots of spam user registration.

What is a hook_form_alter I could use in a module to entirely remove the user/register form and make user/register page blank, without disabling open registration for Ubercart/Commerce?  I would then add a block to this page instructing humans to buy a product to create an account.

Make sense?  Please advise on the code.  THANKS!

Basically you can keep user registration functionality, notification emails etc.. and prevent access to the user register page by either altering the registration form, or better yet, the page callback for the entire page.

e.g:

/**
 * Implements hook_menu_alter
 **/
function MODULE_menu_alter(&$items) {
  // Deny all access to the user/register page.
  // Administrators can still create user accounts via admin > people
  // Notification emails etc.. are still operational
  // and Commerce / Ubercart can create user accounts following checkout etc..
  $items['user/register'] = array(
    'access callback' => FALSE,
  );
}


which page/code renders admin/config in drupal 7 I have a very basic question. In my drupal 7 installation when I go to admin/config the page does not render and all I get is a 1 printed out. I am sure someone die a die() on this page. But I am not sure which page is loaded when admin/config is rendered. Can anyone point me which possible page/code I should be looking at?

The page that normally come up when the path is admin/config is inserted into the site by the core system module's implementation of hook_menu().

The callback function that actually produces the page is system_admin_config_page().

However, unless you (or somebody else) has hacked core (and we don't that, right?) these functions are not the cause of the problem.

Here's a link to the SOP for debugging Blank pages or "white screen of death" (WSOD).


How do you override the add or edit node for a particular content type I want to format the editing or adding form for the article content type. i.e. node/add/article path and editing the same article.
I copied over the node-edit-form.html.twig template from core/modules/node/template and renamed it node-edit-form--article.html.twig.
I also tried node--article-edit-form.html.twig and some other flavors.
I can override the node.html.twig file by simply copying it to my themes template folder.
But since I couldn't get the edit file to work I also tried overriding the form alter function by adding this in my theme file.

use Drupal\Core\Form\FormStateInterface;

function newsass_form_node_form_alter(&$form, FormStateInterface
$form_state) {
  $form['#theme'] = ['node_edit_form'];
}

This code is from here-
How to override node add template for custom content type?

I added some text on top of the code, but I still can't get the article 'edit' or article 'add' page to display the text.

Drupal 8.6.1, and have debugging enabled. Full explanation of requirement: I have a user entity reference field in the article content type with a list of users that the article can be assigned to. For the most part they have an 'article' role. But if the person leaves, their role will be changed to 'Away'. The article can/will still be assigned to them but I need to indicate that they are no longer with the company or 'Away'.
Within views entity reference I am able to re-write the user with the users role but this information doesn't get back to the entity reference field in the editing node.
I thought of editing the article node and adding a hook to call the assigned users role..... Which I still need to figure out how to do.
With debugging I tried suggested template page--node--add--article.html.twig but I still couldn't get the content revealed and yes I cleared cache. Using page level though doesn't allow granularity for each field.

QUESTION: By mytype is that the machine name of the entity reference field in the content type? I am also not quite understanding this function, where is the call to query the roles? I enabled kint and added this to the function.

kint($elements); die();

but get nothing returned. How do I check if this function is actually being called.
I tried something else also. I have users in the entity reference and in the entity reference views for users I added the roles, made them hidden and rewrote the users to include the roles. I works nicely in the views preview, but the roles detail doesn't get carried back to the content type add/edit pages.

Depending on where exactly you want to indicate that "away" status, I think you should rather alter the entity reference field widget for that specific field to add this "away" status rather than trying to achieve this via templates.

Sounds like you want to try implementing this hook:

function hook_field_widget_multivalue_WIDGET_TYPE_form_alter(array &$elements, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $elements['#attributes']['class'][] = 'myclass';
  }
}


Adding custom field while migrating I am trying to merging content types while migrating to drupal 8 from drupal 7 and at the same time differentiating them with the taxonomy terms in D8.
E.g. The content types from D7 i.e. Article, Page, Blog will merge to a content types called "Media" in D8.
But in D8 "Media" content type, there will be a vocabulary "Type of content" with terms as Article, Page and Blog, so that while migrating from D7, the content of Article will be tagged to "Article" term in "Media" content type and same for others.

I am able to merge them to single content type in D8, by giving destination plugin for each content type as -

destination:
  plugin: 'entity:node'
  default_bundle: media

but not able to figure out how to tagged with "Type of content" vocabulary. This is additional field which is present in D8 but not in D7.

I tried to add

$row->setSourceProperty('field_type_of_content', $type_of_content);
$row->setDestinationProperty('field_type_of_content', $type_of_content);

code in hook_migrate_prepare_row() but not working...

Any suggestion. Thanks in Advance.

Regards
Sunil Singh

field_type_of_content is presumably a term reference field, so the value to set for it would be a term ID, not a term name. If you know the IDs for the destination terms, you can map them directly:

source:
  plugin: d7_node
  node_type: article
process:
  field_type_of_content:
    plugin: default_value
    default_value: 5   # Known D8 ID for the "Article" term

More robustly, you can use migrate_plus's entity_lookup plugin to translate the term name to a term ID:

source:
  plugin: d7_node
  node_type: article
  constants:
    term_name: Article
process:
  field_type_of_content:
    plugin: entity_lookup
    source: constants/term_name
    value_key: name
    entity_type: taxonomy_term
    bundle: type_of_content
    bundle_key: vid


Boost - Ignore url variables but still cache the page It seems like I'm not the only one with this problem but none of the other issues presented a clear solution.

I have a url variable called "?slide=X" which is only controlling which slide opens on the javascript slideshow when the page loads. Obviously I don't need 10 different Boost caches for each of the slides since they're all loading the same html.

All the .htaccess rules above don't really do it for me. Anybody had any luck on this?

examples.com/node/10?slide=3 needs to call the cache/normal/examplecom/node/10_.html file instead the cache/normal/examplecom/node/10_slide=3.html

Is this at all possible?

It would be great to have a general option on the settings page to ignore all url parameters or maybe ignore specific ones but still cache the pages. I think boos for D6 had this.

Thanks in advance

i just saw you in this issue :D

have you tried:

2 options to solve this. Create a rewrite rule at the server level to strip userID=1234 or in setting.php strip it out & use hook_boot to add it back in.

  A more interesting solution proposed in this thread by mikeytown
  (maintainer of several high performance Drupal modules like Boost and
  Advagg), is to remove specific query parameter at the server level or
  in settings.php, thereby tricking Drupal into getting and setting the
  page cache using a cleaner URL string.  This will almost certainly
  have unintended consequences, however, and should be implemented with
  extreme caution.

Found here: http://www.asmallwebfirm.net/blogs/2012/07/page-cache-vs-landing-page-performance


Add Encryption to Images Is there a way to add encryption to images once they are uploaded on the website and stored on the server?

Encrypted Files module sounds like exactly what you're looking for. From the project page:

  Say you want users of your site to be able to upload and download documents, but you also want these documents to be protected in case someone breaks into your server. This module allows Drupal to encrypt files that users upload and decrypt files for download, keeping the unencrypted versions of files from ever being stored on disk. It does this by creating a custom file stream wrapper that Drupal can read from and write to and a new download method that sits alongside the regular public and private methods. So you can make Encrypted Files the default download method, or only use it as the download method for specific file-type fields.


How do I get total webform submission count of multiple webforms? I am able to get the webform submission count total for single webforms, but when I filter for multiple webforms (using the OR operator) it only shows the total count for 1 of the webforms. How can I have Views add the counts for all of the webforms I filter?

I found a solution to my problem - albeit not using Views - to accomplish what I wanted to do.

My goal was to have a counter on a page where it showed how many submissions for certain forms have been submitted. I needed to show a combined total of 2 or more webforms but could not accomplish this with Views.

I did find this code that led me to my solution:

First, need to include webform_submissions:

module_load_include('inc', 'webform', 'includes/webform.submissions');

Then added this line:

webform_get_submission_count($nid, $uid = NULL)

I took out the $uid as I did not need to filter by user and made multiple calls for the different webforms I needed:

$a = webform_get_submission_count($node->nid = '6');
$b = webform_get_submission_count($node->nid = '7');

I then put the following line to add the 2 variables to get me the total that I can then use on my page:

$c = $a + $b;

This solutions was actually better for me because with Views I could never get the No Results Behavior to show 0 when there were no submissions.


Insert form fields into form i have a form inside an .inc file. That form i'm calling it inside a new form i'm making, using form_load_include, so far is working but its rendering the external form outside the new form. this is the code that does that:

<?php
// start form to create projects
function project_creator_form($form, &$form_state) {
    global $user;
    $uuid = $user->uid;

  form_load_include($form_state, 'inc', 'lc_core', 'location'); //here i call the form
  $renderable = drupal_get_form('location_form', $form_state);
  $location = render($renderable);
  print $location; //here i print the included form

  $form['u_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Identificador de Usuario'),
    '#size' => '6',
    '#attributes' => array('readonly' => 'readonly'),
    '#default_value' => $uuid,
    '#description' => "Este es su identificador de usuario, (no se puede modificar)",
    );

    $form['p_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Nombre de Proyecto'),
    '#required' => TRUE,
    '#description' => "Introduzca el nombre del proyecto.",
    );

    $form['p_type'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione tipo de proyecto'),
    '#options' => array(
      'Obra Nueva' => t('Obra Nueva'),
      'Adecuación' => t('Adecuación'),
      'Remodelacion' => t('Remodelación'),
      'Ampliación' => t('Ampliación'),
      'Refuerzo estructural' => t('Refuerzo estructural'),
      'Mantenimientos' => t('Mantenimientos'),
  ),
    '#required' => TRUE,
    '#description' => t('Seleccione el tipo de intervención a relizar.'),
    );

    $form['p_area'] = array(
    '#type' => 'textfield',
    '#title' => t('Area del proyecto (m2)'),
    '#required' => TRUE,
    '#description' => "Ingrese la cantidad de metros cuadrados (m2) del proyecto.",
    '#size' => '6',
    );

  $form['p_desc'] = array(
    '#type' => 'textarea',
    '#title' => t('Descripción'),
    '#description' => "Describa de que se trata el proyecto a ejecutar, puede especificar algunos detalles e información que considere necesaria.",
    '#rows' =>4,
    '#resizable' => FALSE,
    '#required' => TRUE,
    );

    $form['buttons'] = array(
    '#type' => 'submit',
    '#value' => t('Guardar proyecto'),
    );
  return $form;

}

function project_creator_form_submit($form, &$form_state) {

    db_set_active('civilproconstru'); //OPEN alter DATABASE.
    db_insert('project_info')
        ->fields(array(
        'u_id' => $form_state['values']['u_id'],
        'p_name' => $form_state['values']['p_name'],
        'p_type' => $form_state['values']['p_type'],
        'p_area' => $form_state['values']['p_area'],
        'p_ctry' => $form_state['values']['p_ctry'],
        'p_dept' => $form_state['values']['p_dept'],
        'p_city' => $form_state['values']['p_city'],
        'p_desc' => $form_state['values']['p_desc'],

        ))->execute();
$p_name=$form_state['values']['p_name'];
$loglink = l("Ver Proyectos", 'admin/lista_de_proyectos');
$msg= "El proyecto $p_name ha sido indexado, continue ingresando información del proyecto en $loglink o puede seguir indexando nuevos proyectos.";
drupal_set_message($msg);

db_set_active(); //CLOSE alter DATABASE.
}

And this is the output i'm getting:

Despite i'm printing inside the function that is creating the form drupal it's rendering outside of it...

HOW CAN I FIX THIS???? thanks for the help!...

Instead of printing the form when you load it, create a new form item of type markup and add your subform there as markup.

$form['subform'] = array(
  '#type' => 'markup',
  '#markup' => $location,
);

This would fix the display order but your submit handler will need to handle the extra items.


Chosen module/jquery plugin not accessible on mobile devices? I have installed the Chosen Module and was surprised to find out when viewing the page on an actual mobile device or on a desktop mobile device simulator that the Chosen menu is totally missing from the html markup and the menu items are not being displayed on the device.

Anyone know by any chance what I may be missing here? Is it possible the module only works for desktop or tablet devices?

I just found on the Chosen jQuery documentation in the FAQ section towards the bottom they say that they have disabled the Chosen module for mobile devices by default as there are bugs with the Menu working properly on those devices. Here is a GitHub discussion about the issue.


How to use Rules to perform a monthtly reset of a field for all users accounts? Once a month I would like to reset a field on all users accounts to 0.

At the moment I have a horrible way of doing it. Each time a user logs in the data is scheduled to be changed only for that user. This is done through a rule (using the Rules module) which whenever a user logs in runs 'Schedule component evaluation' with a data selector of site:current-user and a date of the first of the month. The component that the rule calls 'set a data value' of 0. This is obviously not an efficient way of handling this. However it does work.

Ideally I would like to have a rule that runs occasionally, I could use when cron is run. This rule would schedule setting the data value for all users of the site. The problem is that I don't seem to have a data selector of 'all users' to pass to the component.

Am I missing something really obvious here?

You can make a small module for this to write some code using hook_cron().

Inside hook function you can write query to collect all the user ID & update one field value in loop.

Then use Elsia Cron to schedule your made cron function.


Views: Create a block with terms marked (reference field) by the term viewing I am having two vocabularies, for example, styles and artists.
Each of the artists term has a term reference field to styles voc.

When one of the styles term page is open i want to show all terms from artists vocabulary marked with this term.

Can't figure out why my contextual filter with term id doesn't work. Could you please help me to achieve it?

2 steps are needed to achieve this with Views:

Relationship:

Add a relationship
1st screen on the popup: Choose Taxonomy term: Styles
2nd Screen on the popup: Choose Require this relationship
Apply

Contextual Filter:

Add a contextual filter
1st screen on the popup: Choose Taxonomy term: Term ID
On the Relationship dropdown choose the relationship you configured above
Choose When the filter value is not available -> Provide default value -> Type dropdown = Taxonomy term ID from URL
Apply

And you're done.


How to active payment pane in Commerce Kickstart? I am using Commerce Kickstart and I am trying to configure the checkout process.

But control is not going in payment module. Instead it's going in last step directly.

Can anybody help me find out what is wrong?

I think you are looking for Commerce Checkout Pane Payment or Commerce Checkout Pages.

Commerce Checkout Pane Payment Module Feature:

This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout. This is a contrib module for Drupal Commerce.
Drupal Commerce Contrib. This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout.

Commerce Checkout Pages Module Feature:

Commerce Checkout Paages gives site administrators the ability to create additional pages for the checkout process through the admin user interface.


Custom user profile fields, not editable by user I've created some custom user profile fields but I don't want to let the user change those fields when he is editing his profile. These fields should only be changed by the site admin.

How can I do that? Thanks

You could try looking at the Field Permissions module.  Simply don't allow editing of your specific fields for the role that the registering/registered user has.


Show url attibuts in twig I have this in my routing page

function_adh_apport.adh_apport:
  path: '/collecte/apports/{date}'
  defaults:
    _controller: '\Drupal\function_adh_apport\Controller\RapportsController::filtrer'
    date: ''
  requirements:
    _permission: 'access content'
    date: \d+

I got this url : ../web/collecte/apports/2016

but now, i'm trying to show in twig the value of {date}

So i do this in twig :

{{ path('function_adh_apport.adh_apport', { 'date': apports.date}) }}

but it return "../web/collecte/apports" and not just "2016"

I have do a preprocess function in my file ".module" like this

/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['date'] = \Drupal\Component\Utility\XSS::filter($_GET['date']);
}

but not sure that correct


Ordering Users for use in view I have a view that displays data for each user. Now I would like to be able to order the users.

One solution would be to add a new field called something like field_weight to the user content type and then use this field to sort the view, but preferably I would like to do this through drag and drop from the admin/people configuration page.

I installed the weight module, but it doesn't seem to support setting the weight for a user.

Is there a module that can do this?

If I haven't misunderstood your question and you're using Views, you could simply sort the view by your weight_field and then just assign the right weight parameter to the user.

If you prefer some kind of drag and drop functionality (which in my opinion is easier to manage than weight) you could use Draggable Views, this module will allow you to have a view where you can order your users display, a good tutorial I used as a first timer is this.


Version scheduling for nodes I'm looking for a way (simple) for my editor to save a draft version of an already published node to a later date.

So in other word a way to publish changes on a later date!

Having the possibility to have more than one version on bank would be nice.

Thanks!

You can keep your versions of nodes using  Revisioning module.In addition to it you can use Diff Moudule to compare between two versions of nodes.

And you can use Scheduler Module. to schedule the node publish.


Menu link Translation I'm using i18n and submodules to translate an English Language site to Spanish. I'm also using Automatic path aliases.

The issue is that menu links are directly to the node: node/42. When in the Spanish part of the site, /es/ the links take me to es/node/42, not to the aliased url.

The best answer I've seen is this "Afterwards, you can arrange your menu links as you need them. I use parent/child URL aliases based on menu hierarchy, so I make a mirror menu tree." I don't know what he means, but it sounds like what I'm trying to do.

Your problem might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


Drupal Node only with Title and Body? Using Drupal I need to recreated node that only display title and body.

Why ? I want to used my theme as e-mail template without re-creating a website manually. So I have to remove any menu, block, header, footer that is display it. Every time a new article is done they can export the page using their drupal theme but only showing the title and body to be send in an e-mail.

Any idea how to do this ?

Use the Print module that has an "email the content" functionality where you can control the look of that email including displaying only the page title and a body.


How to create a flyout menu with Views? I am trying to achieve the following output- id like a view with two images- each displaying a corresponding menu on hover- I've looked at using rewrite result for an image field in views for this- but I don't think I am using it properly. I would be tremendously grateful if anybody could take the time to give me some tips or tutorials on how to do this?

Note: I am a drupal-newbie.

Views maybe isn't the best solution to your problem. Drupal has a built in way to create menus. When you created your two menus and maybe placed them on your site with Menu Block, you then may apply the flyout functionality with CSS or jQuery or have a look at Superfish maybe.


Multiple Field Values on Separate Page I have multiple values for a field in a node, and am displaying only the top 5 using CSS, however, I would like to display the full list of values on a separate page with a, 'View More' link to that page.

My initial reaction would be to create a views page, but how would I associate that view page with a specific node, and then how would I link to that views page from the original node?

The example:

The main node would be a content type for, 'Author'
Another content type that get's referenced from Author are, 'Publication'
The Author's node will display the top 5 Publications and then have a View More link to the full list of publication.

Is there any better way to accomplish this? All thoughts will be much appreciated.

Using Views would be the most common way to do this. I will show you a Display Suite method though.

Install these modules:

Display Suite (or any model that can give you extra view modes such as Entity view modes

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

View Mode Page

  Create separate pages for different view modes for a given content
  type.

  On the manage display page for a given content type, you can assign
  patterns for view modes so that they will become a page at the given
  path. For instance, if you want to show the teaser at a specific URL,
  you could do node/%/teaser. If you also use Display Suite or other
  modules that allow you to create new view modes, you can use these
  modes to display one or more fields from a node at a separate URL.

Field multiple limit

  This is a simple module that provides settings to limit the number of
  values to display on fields with multiple values.

Token

  Provides additional tokens not supported by core (most notably
  fields), as well as a UI for browsing tokens.

Default View Mode:

On your content type's default view mode activate One Column Display Suite layout and click on the gear next to your multi value field and set it to show the first 5 of the multi value field. Use Display Suite to create a Code Field on entities node, with Field code:

Show all.

Tick Token. Back on the manage display for the default view mode you will now see that field: Show all. Drag it to where you want it displayed

Show all View Mode:

Use Display Suite to create an additional View mode. Go to Manage display for the new View mode and set the 'View mode pages' URL pattern to node/%/all. Make sure you set the multi value field to show all values.


Taxonomy view resulting content fields I have a view that lists a set of taxonomy terms. When the user clicks on one of the taxonomy terms  in the view it sends them to a results page showing a list of all the content types that have this taxonomy term. The problem is views made this results page without any options for me to change it. Right now it only shows the title field and a read more link. I would like to add more of the content types fields to the result. For example the content type has images One thing i would like to do is add the image field to that results page so each result has an image. How do you add fields to the views results page that is after the user clicks the term on the taxonomy view.

Current view shows a list of taxonomy terms. When user clicks on one of the taxonomy terms in the view it will send them to a page showing a list of content that are associated with that taxonomy term. I want to edit the list of content that is associated with the selection, not the list of taxonomy terms.

By default the output at taxonomy/term/% (with % being the term ID) is a collection of teasers for nodes to which the term ID is assigned.

You can alter the teaser display for each content type by going to Structure > Content types > [type] > Manage Display > Teaser. This is the simplest method, but note that this will alter the teaser display for the content type site-wide, not just on the taxonomy term results page.

If you want to alter the overall display of the results and you don't want to alter the teaser output everywhere else, @ShawnCohen's answer is your best bet. Views provides some powerful options for customizing a result set, including Relationships (mentioned by @Screenack in the comments).


Views 3, 2 different node types, filtered by the same contextual filter I have two node types. Node A and Node B, both node types can have a reference to to a taxonomy term.

Now I am trying to construct a view which shows a list of both Node A and Node B, filtered by the taxonomy.

So Node A and Node B have different names for the the taxonomy field (field_nodea_taxonomy, field_nodeb_taxonomy). If add both of these fields as contextual filters and then try to filter on taxonomy term with id 10, by writing "10/10", i get only contents for the first filter.

How can i make it so to that it will show both content types, but filtered?

If field_nodea_taxonomy and field_nodeb_taxonomy use the same taxonomy vocabulary, this problem can be addressed differently with a shared field.

I generally define a single shared field for each taxonomy vocabulary, and use it in every content type where it's needed (e.g., nodea and nodeb). If your requirements permit you to use this approach, your problem goes away, since a term filter on that single field will work for all content types.


Resetting outputted HTML markup to default? I am trying to fix a site, which I did not build nor 'break'.

On a clean install of Drupal, the markup for a node's textfield, set to display inline, looks like this:

Foo:&nbsp;

Bar

On my problem site it looks liike this:

Foo:

Bar

I have turned off the custom theme and I have disabled the Display Suite module, cleared all caches - no change.

Are there any other obvious places I could look to find what is changing the outputted markup?

There are 250 modules enabled, so turning things off one by one is not really an option.

Thanks.

Yes, it was the configuration of the fences module. I needed to cancel the override in the first section. Navigate to Fences configuration to change the settings.


drupal theme not show in appearance My new drupal theme zeropiont isnt showing up in drupal 7.
I placed zeropint drupal theme in the /sites/all/themes or sites/default/themes directories.
It is not showing into appearance.

Make sure your theme contains a zeropint.info file. This makes Drupal see it at admin/appearance
Clear the Drupal cache

Now your theme should be listed


User configured VIEW fields Curious, is there a module or technique I can use to easily allow my clients (who log in with a limited role) to manage fields visible in any given view?

Actually there are two specific content types and two specific page views -- which I would love to give them the capability to customize to their liking.

Sounds like something you can do with Views Dynamic Fields. Unfortunately there's only a D6 release atm, but perhaps you can port the module to D7 when it seems to fit your needs.


Where can I change this value? I'm trying to change the phone number displayed in sidebar window with the chinese lady in it. However I'm trying to find out where it's content is coming from.

This is how the HTML looks

    <?php print variable_get('yingyang_online_title1');?>
    <?php print variable_get('yingyang_online_title2');?>
    <?php print variable_get('yingyang_online_phone');?>

    <a class="onlineConsultation yyModChatLink" href="<?php print url('customer-contact-request') . '?width=790' ?>">

and the thing I need to change in particular is <?php print variable_get('yingyang_online_phone');?> but I can't find where yingtang_online_phone is set.

do you guys have any ideas where to look?

variable_get() is used to store and retrieve systemic variables , you can found them in system table in DB, or you can change them using variable_set()


Entity Reference View Widget problem with add selective I am using a content type which uses a field as "Views" Entity Reference View Widget. When I click "add selective" or "add .. and close" in form of this widget, it's just redirect to http://localhost/denwer.

How do I solve this problem?

Thank you for answer, kiamlaluno.

details of question:
1. I create a view with type display "Entity Reference View Widget" as table of taxonomy term
(after create view in this view besides display name of views "Entity Reference View Widget" no more information that it use "Entity Reference View Widget" - in Format just show that it's table (grid etc..)
2. Create content type
in content type create field:
- type filed "Entity Reference"
- widget "view"

after create field in description of module "Entit.. widget" says that "on the next page select your View from the dropdown" but there is no dropdown in which can choose my view (picture below)

if just click "save" created view chosen
(picture below)

then i use default settings and save settings of field.

Next step  - Add node of created type and here is problem:
- i see field with widget, can click add item
- then i see "widget form with created view"
But if click on buttom "add selected item" - it's just go to page "/localhost /denwer"
and of cause nothing add in "node add"

I solved a very similar issue by changing the display type to "Entity Reference" (not "Entity Reference View Widget") and using using the ER Widget only for the view checkbox selection field.

Here is a detailed step-by-step guide to a solution which worked for me using the latest Drupal 7 dev version of the ER Widget module.


How to get a field value and multiply it to get price in a PriceResolver Getting my feet wet with price resolvers, and I have figured out how to set a new price for all entities that have field_discount_percentage. I am then getting the price and multiplying it for the sake of this example by .95 to get a 5% discount.
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {
    return $entity->getPrice()->multiply('0.95');
  }
}

What I trying to do, is to use ->getValue or  ->getString for the field_dicount_percentage so that I can set the percentage value in the field from the front end.
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && $entity->hasField('field_discount_percentage')) {

    //here is where i would like to create a variable for the number value of the field, but I get lost...
    $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];

    // I have also tried this
    $discount = $entity->get('field_discount_percentage')->getString();

    return $entity->getPrice()->multiply($discount);
  }
}

I am getting empty quotes back from $discount = $entity->get('field_discount_percentage')->getString(); which is making me wonder if I cannot use a variable to a numerical field value.

InvalidArgumentException: The provided value "" is not a numeric
value. in Drupal\commerce_price\Calculator::assertNumberFormat() (line
261 of
MY-Site\web\modules\contrib\commerce\modules\price\src\Calculator.php).

So what is the best way to do this in a Drupal commerce context?
Any help would be appreciated.
:)

I was able to get this to work by checking that field_discount_percentage is not empty, rather than just checking if the entity has field_discount_percentage. The error must have been from all the other entities that were returning empty fields as a non-numerical value of ""
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && !$entity->get('field_discount_percentage')->isEmpty()) {
     $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];
     return $entity->getPrice()->multiply($discount);
  }
}


Adding a region to the Omega template I am trying to add a new region to the Omega Hero template. I have duplicated the Hero template calling it SuperHero and this is working okay. ( I have created a sub-theme ).

In the tpl file I have added the new bottom_sidebar region:

<?php print render($page['sidebar_first']); ?>
<?php print render($page['sidebar_second']); ?>
<?php print render($page['sidebar_bottom']); ?>

In the .inc file I have added the region here:

regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[sidebar_bottom] = Bottom sidebar
regions[footer]         = Footer

I have create new stylesheets and they are working okay but the new sidebar isn't appearing in the HTML.

Any ideas on what I might be doing wrong?

I finally found out from this post here drupal.stackexchange.com/questions/100102/… that I was overlooking the theme.info file in the themes root directory:

regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[sidebar_bottom] = Bottom sidebar
regions[footer]         = Footer

Works perfectly now. There are three steps to adding a region to the Omega template.


else condition does not work in my code in twig template In the code given below

content.field_image_link[0]['#url']
is empty but it still enters the if condition and adds html
what is incorrect in the below code due to which it enters the if condition whereas it should enter the second if condition given below

{% if content.field_image_link[0]['#url'] %}

{% block paragraph %}

    {% block content %}

{% if content.field_image_link[0]['#url'] %}

{{ content.field_image_2 }}

{{ content.field_image_link[0]['#title'] }}

{% endif %}
{% if content.field_image_link[0]['#url'] == '' %}
{{ content.field_image_2 }}

{{ content.field_image_link[0]['#title'] }}

{% endif %}
    {% endblock %}

{% endblock paragraph %}

You need to check if variable is defined (defined in twig) and additionally also check the length of variable in twig.

{% if content.field_image_link[0]['#url'] is defined and content.field_image_link[0]['#url'] | length > 0 %}
    //do stuff
{% else %}
    //do another stuff
{% endif %}


Why is the index.php file missing? I installed Drupal via the following command.
composer create-project drupal-composer/drupal-project:8.x-dev
projectfolder --stability dev --no-interaction

As a result I'm getting this structure.

../projectfolder/vendor/drupal
../projectfolder/vendor/bin/drush
../projectfolder/web/
etc. ...

Perfect structure, but what I'm missing the index.php file. Also, the common files like sites/default/settings.php are not part of my install or perfectly hidden.
How can I get those files? What I'm doing wrong? I tried to use Drush for an standard site-install, but it failed also.

That's exactly what drupal-project does. Your index.php should be at projectfolder/web/index.php.

Personally, I like this approach because it provides one directory level above your site root. This makes a good, secure place for files (settings, private file system) that should never be served directly by your web server.

The drupal-project composer template uses this level above your  site root to install composer dependencies and tools like Drush and DrupalConsole. That's nice because when you bundle these tools with the project (instead of using a globally installed Drush for instance), you can always be sure that your colleagues are using the exact same version.


In Commerece 2.x can address be selected in the country's official language? Upon setting up the address book, how can the select list of Country/Province/City etc. be displayed in the country's local language rather than in English?  e.g  廣東省　instead of Guangdong Sheng if China is selected as the Country?

Country and subdivision translations are selected based on the current language. If your site language is "zh" you should be seeing the local labels.

For non-native languages the latin script alternative is shown for readability. If this is not working as I described, you can open an issue in the address issue queue.


Centering block view Hello Drupal community!

I have a questions about displaying content with views. Is it possible to center the content within the block, in-browser?

Right now I have two entities next to each other, both left-aligned. I am trying to get them both centered in the block, and centered on the page.

Any ideas?

You need to right click and inspect the elements and find the div class or id that belongs to those blocks or fields.

Then with CSS you can center them. See CENTERING THINGS. So just add the css to your theme's style.css file, located in /sites/all/themes/yourtheme/ folder.

Then remember to flush the cache to see the changes.

If you want to do it within Views using REWRITE RESULTS

put <center>[title]</center>


using EntityFieldQuery, how to order results based on a node reference field title and/or field collection item field, says name I have a node which references another, I want to order the results based on the title of the referenced field title.

I'm using

function listAll(){
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
                    ->entityCondition('bundle', 'building')
                    ->fieldOrderBy('field_reference_area', 'title', 'ASC')
                    ->execute();

  $nodes = entity_load('node', array_keys($entities['node']));

  foreach($nodes as $key => $fac){
      dsm($fac);
  }
}

I'm afraid this won't be possible using EntityFieldQuery. You could build your own query using db_select() and have full control over it.

You can refer to this post and try to adapt it to fit your needs.


Video file upload errors with Cloud FIles I'm using the CloudFiles module to host my uploaded files on Rackspace Cloud Files. This is working very well for all of the photos I'm uploading, but it seems to be failing when I upload videos.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'rcf://videos' for key 'PRIMARY': INSERT INTO {cloud_files} (uri, filemime, filesize)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2);
Array ( [:db_insert_placeholder_0] => rcf://videos [:db_insert_placeholder_1] =>
application/directory [:db_insert_placeholder_2] => 1 ) in drupal_write_record()
(line 7013 of /var/www/vhosts/mydomain.com/includes/common.inc).

I'm not sure, but it appears that when the process finally gets to the CloudFiles module and the CF module is trying to insert that into the database, the filename appears to only be "rcf://videos" when it should be something more like "rcf://videos/original/my_test_video.mp4" (I'm guessing).

But perhaps this is the wrong understanding of what I'm seeing. It appears that there is a directory entry in the cloud_files db table, so perhaps the module is trying to insert entries for the intervening directories and it's accidentally trying to insert it twice or something... I don't know. I'm confused.

I'm not a drupal wizard (yet!) so I'm having real problems tracing this error down to its source. I'm assuming the issue is in the Video module since the CloudFiles module is working for image uploads.

Can you help me track down where the filename is set and/or converted?

Found the issue, it was with the Cloud Files module (I'm using a dev version) and I've submitted a fix to the author.

The Cloud Files code was creating directory entries in the db for all of the intervening directories when mkdir() was called. The mkdir() code in the file stream wrapper was always trying to insert a row into the cloud_files table. My guess is that it was assumed other modules would check for the existence of a directory before creating it, so he didn't want to do a redundant check. However, I think that other code would usually just blindly call mkdir() because if the directory already existed and it failed there wasn't any real downside to it.


Drupal 8 Hide Title If Front Page In drupal 8 how can I hide title on front page ? The title is rendered through page-title.html.twig through the code below

{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

I want to wrap it in if not front page condition but don't know the syntax.

The title is displayed in a block. Go to the block layout (/admin/structure/block), look for the block "Page Title", click on "Configure" and set the visibility on "Pages" to hide for <front>:


Prevent clicking on view tab when editing a node I was wondering anyone knew of a module that would warn people when clicking on the view tab if they have made changes to a node, but didn't save it. For example, I've seen a few times where people would click on the edit tab to edit the node, then when finished, click on the view tab at the top next to it. This doesn't save the page, and they loose everything they just worked on.

Any thoughts on how to warn people to click "save" first before navigating away?

See the content lock module:

  Features

  Concurrent editing:The user gets notified when he tries to
  edit a node, which is edited by someone else. He cant enter the edit
  mode.
  By node type: Configure content_lock to lock only specific
  nodes.
  By format: Configure content_lock to lock only specific input
  formats.
  No losing content by accident: User gets notified, if he
  wants to leave a edit form by abnormal conditions (close
  browser/window/link click). If the user confirms to leave, the edit
  lock gets automatically removed by an ajax call. You can disable this
  behavior in the admin menu.
  No forgotten locks: The user gets notified
  when he forgets to unlock a node. He/she will be asked to click on a
  link to unlock this node.
  Views integration: Show all open locks using
  any filters, as you have a views integration.


How to fetch all the details of a marketplace organization's page on Drupal.org I am new to Drupal.
I am trying to fetch all the details of a marketplace organisation's page, which are visible on drupal.org.

I am using the node id to access "https://www.drupal.org/api-d7/node/xxxxxxx.json" (where "xxxxxxx" is the node id).

I am not getting all the data in the response.

Is there any way to fetch all the data of a particular page in json?

You can check with GET method with your URL.

GET https://www.drupal.org/api-d7/node/782.json


Get users by term id In user profiles, I have added a term reference field. In my module, I want to get users that have a term id. Is there a function like taxonomy_select_nodes but for users to select users having a taxonomy term?

There isn't, but since users are entities, and taxonomy term references are fields, you can use an EntityFieldQuery to get this data. You could even wrap it in a function to make your life very easy:

function taxonomy_select_users($term_id) {
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'user')
    ->fieldCondition('field_taxonomy_term_field', 'tid', $term_id);

  $results = $query->execute();

  if (isset($results['user'])) {
    return user_load_multiple(array_keys($results['user']));
  }

  return FALSE;
}


Multi site installation with cPanel showing Warning: symlink() [function.symlink]: File exists in I want create multi site with drupal 7.I just started with below link http://drupal.org/node/960934 After setup show an warining

Warning: symlink() [function.symlink]: File exists in /home/ioss/mydomain/index.php on line 5

The PHP Code is symlik is given below

symlink( '/home/ioss/ashokks/', '/home/ioss/ashokks/test1/' );

in the above code snip drupal installed under the directory "ashokks" and test1 is the multi-site subdomain.

Thanks in advance

(1) You need to ensure if test1 does not exists there as directory to sub-domain. You will have to remove it and symbolic link will replace it and will point to main site directory.

Or alternatively....

(2) You can edit your sub-domain settings (from sub-domain manager in C Panel) and replace the file system path to /home/ioss/ashokks/ so that subdomain can point directly on main site without involving symbolic link as Options FollowSymLinks can be disabled in some server configurations.


Is there a one-click solution that builds a private organic group (OG) and invites another specified user to that group? I'm looking to let users initiate the creation a private organic group and invite another user to that group? I'd love to be able to craft a link (in a view of users perhaps) that adds a path like /request/new/og/{uid} to the routing table.

The idea is to match tutors to users needing help in a subject area.

I starting from a View based on User Accounts that presents a table as follows.

User       |  Tutoring Availability    | Request Tutor Group
-----------+---------------------------+---------------------
Abe        |  T/H Afternoons           | [ Request ]
Brian      |  M/W Mornings             | [ Booked ]
Courtney   |  Wknds Anytime            | [ Request ]
David      |  F All day                | [ Request ]
Mozzarella |  M All Day                | [ Request ]

In the request link above, I like to

Create new private OG (of content type 'group')
Make the Logged in user the group manager
Invite (not automatically subscribe) the other user (potential tutor)

I'd like to not have the user see any node creation from as these private groups will have non-creative names such as "Tutoring Session for Rob and Jim on Organic Chemistry." Users will communicate via another content type that helps to track tutoring benchmarks.

Update: I'd also be happy if someone can point me to a working code example of OG's API to create an organic group using functions from the og api.

Bounty reward may require some screen shots to create a good reference point for the community.

I would use Page Manager (part of ctools).

You can add an action or a tab to just about any page so you could have your view of users with a tab or link at the top (depending on your theme/styling) that requests a new organic group.

The URL would be based on the user view.  For instance if your user view was at /people/users you could add a path at /people/users/addgroup which redirects to the OG group creation page.

Alternatively you can create whatever URL you want like /request/new/org/id and give people the link for it... then use that URL to redirect to the OG group creation page.

In order to hide the user being added to the form you should be able to use a parameter in the URL like request/%tutor, then pick up the argument in Page Manager and auto-populate the user as a member.

As for automatically filling out the form?  Well, Automatic Nodetitles has worked well for me, you can build titles out of available tokens which is pretty neat.  And you could probably run some javascript to click the submit button on page load but that's a kludge.

If you don't want them to see the node creation screen then yes, the API is the way to go.  I haven't used OG so I'm not familiar with it, but most contrib modules have a .api file which gives an explanation of the available hooks.  But you probably want to use one of their functions, just look through the code until you find one called og_create_group or something like that, figure out what to send it as parameters and you're off!


Add field to display in views using a custom table I joined a custom table in an existing Views (using hook_views_query_alter) and now I'd like to display fields from this table.

Any idea how to do it ?

Thank you

For your custom table you need to add custom field handler for views.
Check out below link for example code.

https://gist.github.com/juampynr/5816530

Hope this will help.


Debugging panels visibility rule with custom access check plugin I created a ctools access plugin for use with visibility rules in panels. When I click to add the rule, my rule "Site Installation Profile" shows in the list. I click it and click continue and my form for input of the profile name shows. I enter the name and click save only to get an AJAX error message that says the service is unavailable. If I cancel and try to edit the content of the panel, I get an error page. The error page simply says "Error" with no stack trace information. I've put in break points in my access plugin to try to debug with xdebug but it's not catching anywhere where the error is occurring and I'm not sure where to look.
Here is the plugin:

$plugin = array(
  'title' => t('Site Installation Profile'),
  'description' => t('Installation profile value check'),
  'callback' => 'llnl_form_alterations_site_profile_ctools_access_check',
  'default' => array(
    'profile' => '',
    'negate' => 0,
  ),
  'settings form' => 'llnl_form_alterations_site_profile_ctools_access_settings',
  'summary' => 'llnl_form_alterations_site_profile_ctools_access_summary',
  'all contexts' => TRUE,
);

/**
 * Actual access check.
 */
function llnl_form_alterations_site_profile_ctools_access_check($conf, $context) {
  $profile_ck = $conf['profile'];
  $profile = drupal_get_profile();
  if ($profile == $profile_ck) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a config form.
 */
function llnl_form_alterations_site_profile_ctools_access_settings($form, &$form_state, $conf) {
  $form['settings']['profile'] = array(
    '#type' => 'textfield',
    '#title' => t('Installation Profile'),
    '#default_value' => $conf['profile'],
    '#required' => TRUE,
  );
  return $form;
}

/**
 * Provide a summary description.
 */
function llnl_form_alterations_site_profile_ctools_access_summary($conf, $context) {
  $profile = $conf['profile'];
  return t('Show if "@profile" is site installation profile', $profile);
}

I found it within a few minutes of posting this question. The issue was in my summary function and my use of placeholder values. Once that was fixed, it was working fine.


how can I change digits from latin to persian digits I am using Drupal with localization module,
 in persian language,
I want in persian show persian digits instead latina digits?

You can use persiantools module, it change digits from latina to persian and some another features.....

persiantools


Get current URL arguments inside ajax callback? I have created custom module called 'mymodule'.

In this URL localhost/es/mymodule/name/1/2/3, I have this field:

$form['name'] = array(
  '#title' => t('Enter name'),
  ...
  '#ajax' => array(
    'event' => 'blur',
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'my-wrapper',
    'method' => 'replace',
  ),
  ...
);

My ajax callback is successfully called:

function mymodule_ajax_callback($form, &$form_state) {
  ...
  return ...
}

However, inside 'mymodule_ajax_callback', I need to get the current URL arguments of the page such that arg(1) = 'name', arg(2) = 1, arg(3) = 2, and so on.

By nature, Drupal uses the URL system/ajax so calling arg(N) does not work as I need it to be.

How to get the current URL arguments using arg() inside the ajax callback?

EDIT 1:

I thought of using $_SESSION[...] = arg(1); $_SESSION[...] = arg(2); ... on my form and calling the session variables on my ajax callback. But I am looking for a better way without using session but only using drupal methods if available.

The arguments passed to the page callback are saved in $form_state['build_info']['args'], with the exception of the form ID.

If you use the following definition for the menu item, you would get them there. (Replace 'form ID' with the form builder ID.)

$item['name/%/%/%'] = array(
  // …

  'page callback' => 'drupal_get_form',
  'page arguments' => array('form ID', 1, 2, 3),

  // …
);

References

drupal_get_form()
drupal_build_form()


How do I create menu programmatically? I read through the Drupal 8 menu_api documentation in drupal.org. The example guide lists an option to create menu links and insert them into an existing menu. How does one create menu itself first and insert the menu links afterwords?

I used the entitytype manager based on the other answer in stackexchange, but going yml way is recommended. Any pointers?

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

\Drupal::entityTypeManager()
->getStorage('menu')
->create([
 'id' => 'test',
 'label' => 'test menu',
'description' => 'test test',
 ])
 ->save();

Using routes below to create the links:

 test.home:
 title: 'Home'
 url: 'test.url'
 menu_name: test
 weight: 1

If you have a feature where you need to create a menu whenever something happens, using the code should be just fine.

I prefer using the static create method on the entity object \Drupal\menu\Entity\Menu::create, but the manager is fine as well.

If you are creating menu's on your development environment as part of setting up your drupal site, I would advice using config export/import. If you use drush, you can make it part of the deployment to import configuration so production always reflect the configuration you have saved. I prefer to do things like this, but for small sites it might be a bit overkill.


How can I dynamically disable a single required field from validation in a form? This is an extension of this question:

Need help with AJAX callback function for text field validation in form_alter

I have a form with a Username autocomplete field (txn_user). The editors want to be able to enter a UID (txn_userid) as an alternative way of specifying the User for the form. They want to be able to enter the UID and skip the Username field altogether.

So in my form validation function, I want to be able to disable the required property (and all other validation) of the Username field during a Submit IF the editor typed in a UID field. In other words: the UID field should 'short-circuit' the Username field.

This is what I have so far (which doesn't work, obviously). Or do I need to do this via AJAX or straight JS?

function _validate_add_userpoints_userid(&$form, &$form_state) {
    $values = $form_state['values'];
    if( $values['txn_userid'] ) {
        $newuser = user_load($values['txn_userid']);
        if( ! $newuser) {
          form_set_error('txn_userid', 'You have entered an invalid UID. Either leave this blank and select a Username or enter a valid UID');
    }
    else {
        // this part works... the User Name is properly assigned.
        $form['txn_user']['#value'] = $newuser->name;
        $form_state['values']['txn_user'] = $newuser;
        $form_state['input']['txn_user'] = $newuser->name;

        // this part doesn't work... the User Name field is still required on submit.
        $form['txn_user']['#disabled'] = TRUE;
        $form['txn_user']['#ajax_processed'] = TRUE;
        $form['txn_user']['#required'] = FALSE;
        $form['txn_user']['#needs_validation'] = FALSE;
        unset($form['txn_user']['#process']);
    }
}

}

Why dont you use conditional field module?

https://www.drupal.org/project/conditional_fields

By this module you can disable the requirement of fields when something happens to another field. you can also implement your form as a content type so its node/add page will be your form. Then by using the different hooks you can add autocomplete field or do any thing else


Several variants in a page Is it possible to use several variants in a page?
In the page I made only one variant is shown.

The first variant that "passes" will be the one that is shown.

So if the first (top) variant does not have any conditions limiting when it is displayed, it will always be the one that is shown.


How do I dynamically include ouput from an external file? How do I dynamically include output from another web page?

This is the result of a CGI link along the lines of: http://www.example.com/name.cgi?Arg=argument  I would like to include everything within the html tags that it generates as HTML on my page.

(I own both web pages!)

There are a couple of modules that can help with this:

Web widgets (http://drupal.org/project/web_widgets): Embed any other web site content in a widget with a simple widget API.

Iframe_filter (http://drupal.org/project/iframe_filter): you just need to add this filter to an input format and the content you create using that format will be displayed inside an iframe created dynamically.

And other iframe projects: http://drupal.org/project/insertFrame, http://drupal.org/project/iframe_page (only dev version available right now for d7).


Theming Print PDF module output when used on non-content page (views) I have a View that has an enabled PDF version feature provided by the Print module (http://drupal.org/project/print). Its ok, but I'd like to tweak the output table with theming. According to the module documentation pdf output can be altered using these files:

- To modify the template of printer friendly pages, simply edit the
print.tpl.php or the css/print.css files.

- It is possible to set per-content-type and/or theme-specific templates
  which are searched for in the following order:
   1. print_[format].node-[type].tpl.php in the theme directory
   2. print_[format].node-[type].tpl.php in the module directory
   3. print_[format].tpl.php in the theme directory
   4. print_[format].tpl.php in the module directory
   5. print.node-[type].tpl.php in the theme directory
   6. print.node-[type].tpl.php in the module directory
   7. print.tpl.php in the theme directory
   8. print.tpl.php in the module directory (supplied by the module)

  format is either html, mail or pdf, and type is Drupal's node type (e.g.
  page, story, etc.)

My question is how to do the same when I use this module not on a specific node type but on a view? The views module's theming information table is unaware of the Print module so the possible theming *.tpl.php files are not shown there.

Supposing that the name of my view is foobar, what tpl.php file should I use?

(Views PDF module is not an option for me as it fails on my special characters..)

The .tpl file for a View with machine name "myview" would be views-view--myview--page.tpl.php. Following that convention and what the print module reports, I would try creating a .tpl called print.views-view--myview--page.tpl.php. Include <?php print $content; ?> in this file, clear Drupal's cache, visit the View's print page, and see if it registers.

Edit: Try and throw something like this in your theme's template.php file:

function mythemename_preprocess_node(&$vars) {
  // Something to make sure they're on your View.
  if (arg(0) == 'my_view' && arg(1) == 'print') {
    // Add a new template suggestion...
    $vars['theme_hook_suggestion'] = 'print__view_page'; // and then make a print--view-page.tpl.php file.
  }
}


How to get a drupal path in a modal form? I would like to have a specific path in a modal form. I tried several things but cannot get i work.

Modal_form

I installed the module, clear cached and added into a body tekst the example of the module:

Link to click

When I click on this link I will get ajax error 200.

Colorbox and Colorbox Node

Maybe it is working with this module...installed module. After installation I Enabled the Colorbox load option and clear cache.Put the below link in a body text.

colorbox test

After clicking the link I will see node/2 in the browser but not in a modal form.
The filters in the editor is full html

Ctools automodal module

Installed the module. Put node/2 into the extra modal links box. Pushed the submit button but it is not saved

So probable I do something not good but what? Any suggestion?
Using chrome.

Console errors: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ with jquery

Any investigation says that this is a ajax call but I'n not sure.

set jquery update to 1.9 for front end. But no luck :-(

Any suggestion?

you want to display node on popup I guess. The modal form itself does not provide node to display on popup. You need create custom module for it and set its template page.

If you are using colorbox there is one module colorbox node which provides you built in setting to display node on popup.

only need to set class="colorbox-node".


Creating Select Fields in a module with Drupal 7 I am trying to write my own module to add a content type with the help of node_example and this page. I made small tweaks and got it to work, yet I cannot find any example to create a select box as a field, and I failed in my each attempt. I have also checked the official documentation for field_create_field, still no clues.

Is there any documentation or sample you can guide me?

Something like this should work:

// Create field definition
$field = field_info_field('field_my_select_field');
if (empty($field)) {
  $field = array(
    'active' => '1',
    'cardinality' => '1',
    'deleted' => '0',
    'entity_types' => array(),
    'field_name' => 'field_my_select_field',
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(
        'Yes' => 'Yes',
        'No' => 'No',
      ),
      'allowed_values_function' => '',
    ),
    'translatable' => '0',
    'type' => 'list_text',
  );

  $field = field_create_field($field);
  drupal_set_message('Created field_my_select_field');
}

// Create field instance on entity bundle
if(!field_info_instance('node', 'field_my_select_field', 'my_node_type')){
  $instance = array(
    'bundle' => 'terms',
    'default_value' => array(
      0 => array(
        'value' => 'Yes',
      ),
    ),
    'deleted' => '0',
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'module' => 'list',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => '4',
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_my_select_field',
    'label' => 'My field label',
    'required' => 0,
    'settings' => array(),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '3',
    ),
  );
  field_create_instance($instance);
  drupal_set_message("Added field_my_select_field field to node");
}


Is there an event before and after form is submitted via ajax? Currently if a form is submitted via ajax is will show the throbber and "please wait" message(which can be configured on the ajaxified button that submits the form.

I would like to perform some additional actions before and after the form is submitted via ajax so I am looking for events that are being triggered and on which elements they are being triggered.

When you look in ajax.js you find several prototype functions, that can be used like hooks in drupal:

core/misc/ajax.js:

 /**
   * Modify form values prior to form submission.
   *
   * @param {object} form_values
   * @param {HTMLElement} element
   * @param {object} options
   */
  Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
    // This function is left empty to make it simple to override for modules
    // that wish to add functionality here.
  };

You can override this prototype-functions in your own js-file:

(function($) {
   var ajaxBeforeSubmitOriginal = Drupal.Ajax.prototype.beforeSubmit;
   Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) {

      // your code

      // call original function since it can be already overridden
      ajaxBeforeSubmitOriginal.call(this, form_values, element, options);
   }
})(jQuery);

This is the most basic version. More info: https://www.drupal.org/node/1372840


Multilevel Menu but all in the same drop down? How would you create a menu in Drupal where you had multiple levels, but they were all displayed in the same dropdown but with the child menu items indented.

e.g.

Parent 1
 Child 1
 Child 2
 Child 3
Parent 2
Parent 3

Bootstrap has recently removed the sub-menu features from version 3.x, so it won’t support the multi-level menu anymore. But drupal 8 has multi-level menu structure. I am going to show you how to get back the sub menu features in bootstrap and how to render multi-level menu in the drupal 8. Just copy and paste the following css in your custom css, its has been taken from the bootstrap version 2.x with some custom changes, The following article would help to create multi-level menu in drupal 8


Add custom classes to node links How can I add custom classes to node links in Drupal 8?

I want to add some classes to the Read more and Add new comment links in article teasers.

In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:

/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if (isset($variables['links']['node-readmore'])) {
    $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
  }

  if (isset($variables['links']['comment-add'])) {
    $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
  }

}

Update:

Code above will add css class to any readmore link, to add for article only you can add preprocess and check type is article.

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function bartik_preprocess_node(&$variables) {
  ...

  if ($variables['teaser'] && $variables['node']->getType() == 'article') {
    $node_type_is_article = &drupal_static('node_type_is_article');
    $node_type_is_article = TRUE;
  }
}

/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if ($node_type_is_article = &drupal_static('node_type_is_article')) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
    }

    if (isset($variables['links']['comment-add'])) {
      $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
    }
  }
}

Clear all cache and see result. Here is my result:


Taxonomy term view - show node fields in the view? Ive enabled the default view 'Taxonomy term' which overrides taxonomy term pages. How can I add fields for my nodes? Currently it says 'The selected style or row format does not utilize fields.' Thanks

Right above "Fields" that you can't change is "Format".  It's set to "Show: Content" by default.  Change that to "Show: Fields".


Remove Side Menus on certain pages in Drupal 7 I realize that this question might be the result of a fundamental misunderstanding of how things work.  So I apologize in advance if this is just me being a dope.

I am creating a webpage for a festival.  On each page there is a left side menu bar with about 6 menus in it.  I want that there most of the time, so that is good.

I've now created the ability for users to add events to the festival so others can see what's going on.  I've created a content type called Event, added the fields I want to it and exposed it to registered users.  I then create a table view and calendar view with all the events broken down by date/time with a few filters.

All that is working fine.  The part I'm now struggling with is, I want all the menus on the left to go away, any time I am working with the events. Which means when I'm adding, editing, viewing the content, and when I'm viewing the Event views I want access to the entire width of the site, except for a small menu on the right with Add Event, View Events, View Calendar.

I thought a sub-theme would get me what I want, so I created a subtheme with the menus the way I want it and the page the way I want it.  But I can't for the life of me figure out how to get the content to show in the sub-theme.

Any help would be appreciated.  Please keep in mind I am very new to drupal so as much detail as you can go into would be appreciated.

Thanks,

PJ

Did you added the menu on the left side menu bar using blocks or printing directly from the template?

On the first case you can hide the blocks on specific pages in many ways. The easiest is to configure the visibility from the blocks configuration (Administration > structure > blocks). On every block settings you can specify in which pages hide or show the block.

If you're printing the menus from the template you've to use some php in order to select when print them, like "if current page is x, then print" or something similar.

:-)


Put node url in href to all img tags with jquery I have a drupal site and i want to put all nodes url to all img tags! With bellow code can do this but all img linked to the same post url in the main pages, because take the link of the final post and put to all img. The Code i added to node.tpl.php file.

<script>
      jQuery(document).ready(function($) {
      $(document).ready(function() {
      $('img').wrap("<a href='<?php print $node_url; ?>' </a>");
    });
    });
</script>

Thank you

There is no reason to wrap document.ready inside another call to document.ready. If it's ready, then it's already ready!
The reason your code does not work is because it is assigning the same link to all images on the page. You want your code to link to the node that contains the image.
I would not use jQuery for this at all. Views+Imagecache were designed to do this sort of thing and they do it well. Use views to create the page, and use when displaying the image use the "Image linked to node" option.
If you really really don't want to do it that way, then change your code to be this to give it proper scope (right now it is affecting images outside the target node and causing your page to get images wrapped in 20 different  tags!):

Or better yet, don't add it via php and put this in a js file included by your theme instead:

  jQuery(document).ready(function($) {
    $('article img').each(function() {
      var url = $(this).closest('article').find('h1.node-title a').attr('href');
      $(this).wrap('');
    });
  });


Insert block content into the $content variable to be indexed by search I have a block that is generated by a view.  It brings in the author's name and other information for the specific node that is being viewed. The problem is that the block data is not indexed by drupal since it is not in the "content" of the page.  How can I get around this?  I tried moving the region to the node.tpl.php but that didn't help. Any suggestions would be great.

You can use Nodeblock or one of it's competitors:

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page.

Side effect of managing blocks' content like that is exactly what you want: they can be indexed in search, as they are, in fact, nodes.

If you have dynamically created blocks, you could try to use API provided by Bean module - it works the other way around, exposes blocks as entities, instead of entities as blocks. And if it will not work, well, at least you could use it as an example code for entity <-> block mapping.


Automatic Nodetitles IF php statement in between other tokens in title I have an automatically generated title of an address with an if empty statement in the middle of the other tokens:

[node:field_street], [node:field_number],
<?php
$floor= '[node:field_floor]';
$ground = '[node:field_ground_floor]';
if (empty($floor)) { return $ground; }
else
{ return ' Floor '.$floor; };
?>,
[node:field_location_address:postal_code], [node:field_location_address:city]

but the token after the php statement is not displayed. If I put the php statement at the end after all other tokens, everything is displayed. What am I doing wrong?

I tried your snippet and could reproduce the problem.
What worked for me was printing/echoing instead of returning.

My code that reproduced the error:

[current-user:name]
,
<?php
$floor= '[node:nid]';
$ground = '[node:created]';
if (empty($floor)) { return $ground; }
else { return " Floor floor"; }
?>,
[current-page:url]

produced the title "admin, Floor 228".

My updated code (echo instead of return) worked:

[current-user:name]
,
<?php
$floor= '[node:nid]';
$ground = '[node:created]';
if (empty($floor)) { echo $ground; }
else { echo " Floor $floor"; }
?>,
[current-page:url]

and produced the  title "admin, Floor 228,http://localhost/drupal/node/228/edit"

Verdict: I believe this is expected behaviour following from the use of return; it exits the current code block, and therefore the rest of the code is never executed.

Hope this helps!


Responsive Sticky Headers I had previously created a front facing page with a table that has a sticky header using Drupal's built in sticker header js.

Now, we are in the process of making that site responsive. To handle the tables we have set an overflow: scroll on the table container to create a horizontal scrollbar for the table.

However, the sticky header (because it is position fixed) does not scroll.

How can I implement Drupal's sticky header in a responsive site.

Code that generates the table:

$block['content'] = theme_table(
  array(
    'header' => $table_headers,
    'rows' => $table_rows,
    'attributes' => array(),
    'caption' => '',
    'empty' => '',
    'colgroups' => array(),
    'sticky' => TRUE,
  )
);

You may need to attach some additional custom JavaScript to do this. Take a look at the "correct" answer to a similar question.

EDIT:
I've put together a working version of this page - which contains a working modification of the tableheader.js to solve the problem of sticky headers not working when scrolling horizontally.

I've created a module with a new theming function that can be used as an alternative to Drupal's table_theme to allow for scrolling sticky headers.I also created an example module. It's working great, but may need some tweaking for your case. The modules are not documented (I'll do that later) but you can look at the example. It's self explanatory. It's on GitHub, here.

I hope this is useful.


How to control the display of a user account connected via entity reference My searches have turned up nothing, I'm sure it is something simple but I can't figure it out.

To give a simple version of my set up:  I have a content type for publications, that publication has a paragraph field for authors.  That paragraph field accepts either a user linked by entity reference, or a non-user author (a set of text fields).  My end goal is to display them in proper order like so:

Authors: Staff Author 1, Non-Staff Author 1, Non-Staff Author 2, Staff Author 2, Staff Author 3

Replacing the text there with actual author names.  The order needs to be the order in which they were entered, which is the reason I am using paragraphs (I can mix types and keep the order)

Unfortunately the view options for the entity reference that work for the Users seem to be: Entity ID or Rendered Entity.  Entity ID just gives me a number (which I'm sure I could then use in a preprocess function to load the user info and display it as desired -- if that is the best approach, please give me some guidance on where to start), Rendered Entity gives me a User Account full display including photo.  I only want the name linked.

In How can I change a rendered user display to a combination of fields linking to the user? I got the answer about how to change user links, but how can I get this reference to show as a user link?

how can I get this reference to show as a user link?

Go to your paragraph bundle and click on manage display. Find your entity reference field and click on the gear icon.

Note:

The label on the left it's the actual field label.
The label on the right, refers to the fields contents

Check-mark Link label to referenced entity.


An AJAX HTTP error occurred. HTTP Result Code: 500 Everytime I try to edit content on one of my panels I get the following error message.

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /panels/ajax/editor/edit-pane/panel_context%3Apage-   sign_up_page%3A%3Apage_sign_up_page_panel_context%3A%3A%3A%3A/417
StatusText: Internal Server Error
ResponseText:

I am using Panels 7.x-3.5.  Anyone have any idea how to go about fixing this?

You guys were right and it was a problem with CKEditor and Media not working well together.  I fixed it using a patch found here: https://www.drupal.org/node/2455391


How do I export the list of URL alias into an excel or csv? I am beginner and have recently started to work on Drupal website that has been implemented at my work place.

I would like to export the list of URL alias to an excel or csv file so that we can look at the various url aliases that we have set and eliminate or update those that aren't required.

How can I achieve this?

This is easy with a query:

select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

If you are good with mysql, you can run this directly from mysql with your drupal database selected.

If you are using drush you can run the query this way from the command line when in your site's root directory:

drush sqlq "select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';"

If you have the developer module installed, you can run this with db_query in /devel/php:

db_query("select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';");

You can also run the above code anywhere in the code base that runs on page execution, and then remove it once you have gotten your csv.


how to change views output I need to create a block with eg the latest comments on the site.
when using views, concegui select the data I wanted, but the problem is that I need to edit the output of view (specify the html). I tried to make a tpl, but the fields when they get to this, are already formatted ([#markup]). also tried to make a block programmatically by accessing the fields of view, via $comments = views_get_view('last_opinions');, but so the fields do not bring content, but for example, ids (for referrals), or integers (in the case of dates), ....

basically, how to change views output?

Views out but can be changed at every stage of the process upto the field level.

You can check the theme information in the other section towards the bottom of the right vertical tabs. There you would see the list of theme templates you can use. The last one is where the fields get themed. and moving upwards each of the wrapping themes such as the row theme the entire page theme etc. The name suggestion are also there in the same place.

You can make the template as specific as you want.


Updating without Composer I've previously used Drush to update my Drupal-installations. They are installed without using Composer, and currently on version 8.7.3. However, when I try to use Drush (drush v8.1.15, using drush up) to install the currently newest version the update fails when untarring the new core. When googling I see conflicting answers about what to do - among suggestions are Drush9, updating using composer (which I tested - does not work since the page is not installed using Composer) and others. What would be the simplest, least likely way to destroy the page while being able to update (with regards to security updates)?

The latest releases of Drupal 8 are "supported but not recommended" on Drush 8. Drush 8 is still necessary if you are not using Composer to build your site. Composer is recommended for all Drupal 8 sites because sooner or later you are likely to need a module that requires Composer. If your site does not yet need such a module, though, then it is possible to continue to use Drush 8 and the pm-update command.

A few months back drupal.org changed all of the URLs used to download Drupal images; in order to continue to use Drush 8, you need the latest version, which has been updated to use the new URL scheme. Please update to Drush 8.3.0, and you should be fine.


Drupal combine nodes and comments in view I have a view with nodes of the type 'Note' (custom CT). I have A view with comments that are associated with those nodes. How can I combine these views into one view so that I can filter them individually on the date ?

Add 'Comment' as a node type to display in the view but keep your 'Note' content type filter. You should get both the nodes and the comments associated with any of those nodes, which you can then add an exposed filter to for date.


Remove password field from user registration form I don't want the password field to be a required user registration field. How can I remove the password field? Is this done by changes in user.module file?

You can use Generate Password module to achieve this goal.
This module makes the password field optional (or hidden) on the add new user page (admin & registration). If the password field is not set during registration, the system will generate a password. You can optionally display this password at the time it's created.

For more info go through the documentation of this module.


Show user based on subdomain Im using Domains Access to create a subdomain and already created all the virtualhosts, so that one is working.

Is it possible to show a user based on domain name?

Im creating a view, and i need to show for example:

lucas.site.com and show user lucas.

I have tried by adding contextual filter: User ID context on route.
But it doesn't take effect, it looks in lucas.site.com/lucas maybe im missing something?

Reply to my self:

I have created a custom Controller that get the user from db based on the domain, i get the subdomain using this:

$subdomain = substr_count($_SERVER['HTTP_HOST'], '.') > 1 ? substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], '.')) : '';

Not sure if its the best.

Then i compare to the user on db:

$result = \Drupal::database()->select('user_data', 'n')
            ->fields('n', array('id', 'user_domain', 'user_email'))
            ->condition('n.user_domain', $subdomain)
            ->execute()->fetchAllAssoc('id');

First you need to create a install schema with the domain created so you can fetch this.

Then loading by user email:

$user = user_load_by_mail($userEmail);

and pass the variable to the Twig.
Not sure if its the best way.


Removing username from personal contact form On the personal contact form, when someone cc themselves, the username of the user they are emailing is exposed. Many users actually type their full name as username, so for them to remain anonymous, I don't want username to be exposed to others.

You can customize the email with hook_mail_alter(&$message).


I can't find product types UI I'm trying to add a new product type, but I can't find the tab for the product types.

In Manage product structure, it is very clear where that tab is, but I cannot find it.

I'm using Drupal 7.59 and Commerce Kickstart 2 with demo.

https://docs.drupalcommerce.org/commerce2/user-guide/products/manage-product-structure contains documentation for Commerce 2.x, which is based on Drupal 8.

You're using Drupal 7, which is Commerce 1.x, so you need to find and follow the Drupal 7 documentation. That should be as simple as clicking "Commerce 1.x" in the left-hand navigation panel.


httpd.conf clean urls issue 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?

It is hard to tell what your exact problem is, but the default .htaccess does more than just redirect requests to index.php.  It

Protects certain directories and files from being accessed
Set up safe PHP defaults for those with old configurations
Sets up some baseline cache rules
Redirects directory/file not found to index.php

In addition, the catch-all rules that you are using is not the correct one for Drupal 7.

Unless you really know what you are doing, you should keep the .htaccess in each Drupal site's DOCROOT, and then configure your server to support multiple sites using the normal methods.  You really shouldn't have to do any configuration specifically for Drupal, other than potentially needing AllowOverride All.  Personally, I use virtual hosts on all of my servers.  The Apache config for each site essentially looks like:

<VirtualHost *:80>
  ServerName www.example.com
  ServerAlias example.com *.example.com

  DocumentRoot /var/www/example/docroot

  <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
  </IfModule>

  <Directory /var/www/example/docroot>
    AllowOverride All
  </Directory>
</VirtualHost>

That could run just about any site on the planet, Drupal, PHP, or otherwise.

On high volume sites, it sometimes makes sense to avoid .hatccess files (they are scanned every request), and place everything in your apache config (where it will be parsed/stored upon startup).