Drupal gives `Notice: Undefined index: highlighted in include ..` error during theme creation So, I have a fresh instal of Drupal 7.34 and decide to create a simple theme.

I created a folder in /sites/all/themes/samayo and in it, I placed a screenshot.png, style.css, samayo.info inside samayo.info I pasted these settings.

name = samayo
description = samayo theme
version = 0.2.1
core = 7.x
engine = phptemplate

screenshot = screenshot.png

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
regions[footer_content_1] = Footer Content 1
regions[footer_content_2] = Footer Content 2
regions[footer_content_3] = Footer Content 3

stylesheets[all][] = style.css

Went to drupa and chose this them as default, and I am getting this error for the past 2 hours.

Notice: Undefined index: highlighted in include() (line 126 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_first in include() (line 138 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Notice: Undefined index: sidebar_second in include() (line 144 of /var/www/public/dev.samayo/modules/system/page.tpl.php).
Warning: include_once(/var/www/public/dev.samayo): failed to open stream: No such file or directory in _drupal_theme_initialize() (line 209 of /var/www/public/dev.samayo/includes/theme.inc).
Warning: include_once(): Failed opening '/var/www/public/dev.samayo/' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in _drupal_theme_initialize() (line 209 of /var/www/public/dev.samayo/includes/theme.inc).

All the answer I checked do not seem to affect anything, including this which suggested placing

regions[highlighted] = Highlighted

in the samayo.info file, but even this could not change anything.

this is probably stemming from the default page.tpl.php which is expecting to find a region highlighted.  The best approach IMHO would be to create a custom page tpl that excludes the regions you don't use, and includes the regions you do.

You can find the default page.tpl.php under modules/system - just copy the file to your theme directory (or sub folder templates) make the changes you want, and then clear the cache


Creating static pages on production from a local module This question could have multiple types of answers, so I'll take anything you guys have to offer.

I have to transform an XML feed into a set of Pages (content-wise).  Currently, I have a module I'm developing locally using PHP and SimpleXML in order to dynamically simulate these pages (so, each page being rendered is a completely dynamic thing controlled by the module).

I need to take this output and create a set of static pages on a production server.  One painful thought I had was to render each page, copy the generated HTML, and physically create a new node.  As there are a lot of pages being generated, this would be a long and drawn out process.

What would be nice is for some method to render all these pages in one go, and then somehow push them to my production Drupal installation.

A caveat, which would be more in the nice to have category is that it is possible for the XML feed to change.  So, it'd be nice to, for instance, mark the changed text in a different color, or produce a new revision, or something along those lines.

I am using Drupal 6 (with no plans to upgrade).

I'll add an extra specific on this question.  At present, I am using SimpleXML to walk through my feed, and using PHP to dynamically create an HTML tags I need.  Essentially, I'm building up a string of HTML that gets returned from the module (in a _module_generate() function), which is then displayed by Drupal.  If there is an easy way to take this, perhaps turn it into a Cron job, and have it produce some kind of output for the Feeds module (thanks @Clive), then that may be the easiest thing for me to do.

Method I ended up using:

Procedurally create nodes on local environment, parsing XML feed with SimpleXML
Hardlink to production server when crosslinking nodes
Use Node Export to export/import nodes from local to production server
Use pathauto on production to create node aliases


How can you create a list of referenced nodes in a view? I have a content type on my Drupal 7 site which has a field called field_related, with a type of Node reference (I've installed References). This allows me to select nodes that are related to the one I am editing. I'd like to then display these in a view, but am coming unstuck with the setting up of the view.

I've set up a single document with some related nodes for testing. If I set a relationship up in my view as "Content: Related Nodes (field_related) - reverse", I see a list of the related nodes I defined. But I see these same related nodes on every single page - not just the page they are defined for. ("Require this relationship" is ticked.)

If I set up the relationship as "Content: Related Nodes", nothing appears. I've tried a variety of filters, contextual filters and relationships, but that hasn't helped much.

I'm sure I'm missing something obvious ... can anyone enlighten me?

Some screenshots of the current setup, so you can see what I've got so far:

View

Contextual filter

Relationship

Got there in the end, thanks to a combination of the (very nice and helpful) Baysaa and keva. This was the method that got there in the end:

Contextual Filter: Content: Nid (set to "do not use a relationship"; default value of "content ID from URL")
Relationship: Content: Related Nodes (with "require this field")
Then, I went to Format and changed Show: Content to anything else. Then I changed it back to Show: Content - this allowed me to select the relationship I defined above (I couldn't define the relationship here without changing Show: Content to something else first).


How to handle password field for externally authenticated users (Oauth2)? I'm working on an Oauth2 authentication implementation where I need to provide content access to external users authenticated against an Oauth2 server which provides me with user info. From my understanding of Drupal's user system, this requires me to create a local user populated with the information provided via the API. I've been looking at the user_external_login_register function and it looks like one of the expected user fields is a password. In my case, since the users are authenticating against an external server, the only validation info I have for them is the auth token, and it would actually defeat the purpose for me to have their password. So, should I provide a dummy password?

It depends on how you want Oauth integration to work.

If the Oauth integration is a supplement, then you should let users define a password themselves, so they can either login with username/password or Oauth. If you don't want users to login directly on the Drupal site with credentials but only use Oauth, you can use user_external_login_register. This willassign a random password to the user, since the password property is required, a random password is generated on the fly:

...
$userinfo = array(
  'name' => $name,
  'pass' => user_password(),
  'init' => $name,
  'status' => 1,
  'access' => REQUEST_TIME,
);
$account = user_save(drupal_anonymous_user(), $userinfo);
...


Translating a site where default is in two languages Drupal is written in English. We have created some custom modules where the strings in the module are written in French. These are passed through the t() so can be translated.

I am a little confused how I can show my site in both French and English when the default site language English is in both language. Please could you point me in the correct direction?

When you pass string through t() without specifying a langcode, then it will default back to English.
So, if string is a French word, it will be handled as an English word.

Two options:

Always use English words in t() and use the translate interface to
translate it to French.
As per https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7
set the langcode as such t($string, $args = array(), $options =
array('langcode' => 'fr'))


Unable to install ... already exist in active configuration On Drupal 8.1 I keep running in those kind of messages when I try to activate a custom module or a custom feature that makes some modification to the basic page. (add fields).

It is really annoying...

Steps:

Clear database entirely
go to /install.php and choose Standard profile
Now that the site is running go to Extend
Select Feature - Basic page

Result:

Unable to install Feature - Basic Page, core.base_field_override.node.page.promote, core.entity_form_display.node.page.default, core.entity_view_display.node.page.default, core.entity_view_display.node.page.teaser, field.field.node.page.body, node.type.page already exist in active configuration.

Well yeah... that is what I want to do: Change those default settings!

Expexted:

Be able to install my feature that makes some modifications to the basic page.

My Feature

Here is my Feature create with the Features module

It basically adds two fields, banner_image and background_image to the basic page

Files:

config
    install
        core.base_field_override.node.page.changed.yml
        core.base_field_override.node.page.created.yml
        core.base_field_override.node.page.promote.yml
        core.base_field_override.node.page.status.yml
        core.base_field_override.node.page.sticky.yml
        core.base_field_override.node.page.title.yml
        core.base_field_override.node.page.uid.yml
        core.entity_form_display.node.page.default.yml
        core.entity_view_display.node.page.default.yml
        core.entity_view_display.node.page.teaser.yml
        field.field.node.page.body.yml
        field.field.node.page.field_banner_image.yml
        field.field.node.page.field_image.yml
        field.storage.node.field_banner_image.yml
        language.content_settings.node.page.yml
        node.type.page.yml
feature_basic_page.features.yml
feature_basic_page.info.yml

Why this simple thing is not supported? Is it a bug? What should I do to be able to use my feature?

With Drush, you can run drush config-delete module_name.settings to delete the configuration causing the error.


How to modify comment reply form? I've installed the Ajax comments module.

I am not able to modify comment form. I want to modify the comment form which one is coming when click reply link.

Note: When I click add new comment the form will show subject, name, comment field. In reply option also showing same form. But I don't want subject and name in reply comment form.

First of all the reply form and the comment form are the same forms (form_id: comment_node_NODE_TYPE_form), you shouldn't think they are different forms.

Second, you would need some custom coding in your own module, that would look like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function yourmodule_form_comment_form_alter(&$form, &$form_state, $form_id) {

OR, even more specific to comments on article nodes (you can replace article with page, blog, YOUR_CUSTOM_CONTENT_TYPE)

function yourmodule_form_comment_node_article_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['comment'])) {
    $comment = $form_state['comment'];
    // if this is a reply, hide the two fields
    if($comment->pid > 0) {
      $form['subject']['#access'] = FALSE;
      $form['author']['#access'] = FALSE;
    }
  }
}

Good luck!


Is there a way of completely replacing the SQL of a View with my own custom string? Recently I completed a rather complicated View, with plenty of relationships, filters, etc. I needed the View for its elegant page system. Is there a way, after seeing the SQL string, that I complete my string in MySQL, and with minimal change, use it in db_query standard format to replace the SQL string of the View? I know about hook_query_alter and hook_view_query_alter but it is too much abstract than a simple SQL-string, mainly if I already have the string almost complete from the Views UI.

Don't do that. You've got two options: either use Views or don't.

Option 1: Use a custom block/page handler

You can build your own query and theme it any way you want it. Just build it as a block or a custom page and do it the "old-fashioned" way. It will be much cleaner than trying to use views.

Option 2: Use Views

If you want views, then you should build any additional plugins, handlers, or add any alters you need and do it right (that includes using the DB abstraction layer). This isn't hard and there is plenty of documentation floating around that can help you with this.

If you circumvent the systems you have (e.g. Views), you will end up producing code that isn't maintainable by someone else or could unknowingly introduce problems. Please don't look for shortcuts, do it well and do it right.


How can I tell if module_load_include() is working? I'm getting errors such as

Fatal error: Call to undefined function webform_expand_select_ids()

and so I'm trying to include all the includes in /sites/all/modules/webform/components.

I'm not even sure if that's going to help, but to help figure that out I was hoping that I could at least check and see whether module_load_include() is successfully including files?

  if ($form['#form_id'] == 'quiz_answer_key_node_form'){
    $url = "./sites/all/modules/webform/components/*.inc";
    $filenames = glob("$url");
    $type = 'inc';
    $module = 'webform';
    foreach ($filenames as $filename)
    {
       dsm(module_load_include($type, $module, $filename));
    }
}

module_load_include() returns FALSE if it can't find the file, and the full path to the file included if it can find the file, and it was successfully included. In addition to that, it uses require_once which will throw a fatal E_COMPILE_ERROR error if the file is not found.

An easy way to debug would be to use code like this in your loop:

$file_path = module_load_include($type, $module, $filename);

if ($file_path === FALSE) {
  dpm('Failed to include: ' . $filename);
}
else {
  dpm('Successfully included: ' . $file_path);
}

That will give you a pretty solid answer as to whether or not the files are being included. If you get no debug messages, you know that the glob() isn't returning the list of files that it should be.


Feed items field from Feed node I'm looking for a way to make Feed items inherit a field value from its parent Feed importer node during the import. The idea is to later use this field value in views filter. In my case this field contains the nid value of referenced node that should be the same for Feed importer node and all of its feed items, and different for other importers and their feed items.

What I have found a quiet similar issue:
http://www.zivtech.com/blog/feed-feeds-importing-referenced-rss-data

but unfortunately I'm not very good at coding and cant find out the reason why this solution doesnt work in my case. Maybe there is a way to do this through views relationships or any other module like Rules or Node Hierarchy?

I also found an module for Drupal 6 that might do this kind of stuff but it wont work for Drupal 7 and Feeds module: FeedAPI Field Inherit

If some one has an advice for this issue please help. Thanks!

The node ID of the parent feed node should be attached to each child feed-item node. Using this in either the template file, or within Views, you can get to the data you require.

For example :

In a Views listing. Add a relationship to the parent feed.
Add a new field for content title - but attach it to the relationship - this gives the parent title. Same applies for any other fields you may have added to the parent.

In template.php -- do a node_load($node->PARENT URL REFERENCE GOES HERE) this will give you access to all the variables on the parent node. If this sounds alien to you then you probably don't need it.

Hope that helps :)


colorbox gallery with media field I am looking for a way (in D8) to create a colorbox gallery for a node field with multiple images but I am facing the following problems:

colorbox only works as an image field formatter (no media field formatter).
I would prefer media field since its nice to have entity browser to reuse some of the images.
Trying to create an image field that collects image using entity browser did not work for me. I was getting the error "The entity must be of type file" and none of the solutions seemed to work either. I even created a new entity browser but it did not succeed.
Media gallery and other related modules are not yet ported to Drupal 8

Is there any alternative?

I have finally managed to find a workaround which involves creating a view that displays the media field images based on contextual information from the node.  The field formatter can be changed to a view using views_field_formatter module

Here is in a little more detail

lets assume the content type that we want to have media gallery is named "gallery" and it contains a media field "field_media" and assume colorbox and views_field_formatter modules are installed and enabled

prepare a view that displays nodes of content type "gallery" (a block view is enough)
add relationship that exposes the field_media and call it "media"
add contextual filter "Content ID" based on "media" relationship
add appropriate image field to display (based on the "media"
relationship) and use colorbox formatter (since this field is an
image colorbox will be available)
go to the gallery content type display settings and configure the media field  to use the view prepared above passing as first parameter the node id


Render array value empty for Datetime field I'm using hook_form_alter to modify an admin edit node screen. The form has a datetime field which I'm unable to get the value for in the render array. textfields value usually appears in value->#default_value.

xxx_form_alter(&$form, &$form_state, $form_id) {
  print(json_encode($form['field_date_test']['widget']));
}

When the page loads, the value is in the input field but I can't find where I can get hold of the value before the page loads.

The solution was $item['value']['#default_value']->render(). This outputs the value in the following format Y-m-d H:i:s e.

Alternatively, calling format('Y-m-d') or any other format string will update accordingly

because '#default_value' was of type DrupalDateTime which must not implement jsonSerialize this is why I was getting and empty object for a value when dumping out as JSON.


Add CKEditor widget (footnotes) from external addon I want to add CKEditor footnotes addon to a Drupal 8 toolbar.

The plugin seems to load as I can add the button when configuring the input format  and I see CKEDITOR.plugins.externals.footnotes is defined and pointing to my plugin file. However the button does not show in the toolbar. No errors or warnings in the console.

This is my /modules/custom/ckeditorfootnotes/src/Plugin/CKEditorPlugin/CKEditorFootnotes.php

class CKEditorFootnotes extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile() {
    return drupal_get_path('module', 'ckeditorfootnotes') . '/js/footnotes/plugin.js';
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginButtonsInterface::getButtons().
   */
  function getButtons() {
    return array(
      'CKEditorFootnotes' => array(
        'label' => t('Footnotes'),
        'image' => drupal_get_path('module', 'ckeditorfootnotes') . '/js/footnotes/icons/footnotes.png'
      )
    );
  }

This is  filter.format.basic_html

    uuid: b47ec9da-02dc-420c-8100-c2127d8e5012
    langcode: ca
    status: true
    dependencies:
      module:
        - editor
    name: 'HTML bàsic'
    format: basic_html
    weight: 0
    filters:
      filter_html:
        id: filter_html
        provider: filter
        status: false
        weight: -10
        settings:
          allowed_html: '<a href hreflang target> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <p> <br> <span> <img src alt height width data-entity-type data-entity-uuid data-align data-caption> <s> <table> <caption> <tbody> <thead> <tfoot> <th> <td> <tr> <sub> <sup> <section>'
          filter_html_help: false
          filter_html_nofollow: false
      filter_align:
        id: filter_align
        provider: filter
        status: true
        weight: 7
        settings: {  }
      filter_caption:
        id: filter_caption
        provider: filter
        status: true
        weight: 8
        settings: {  }
      filter_html_image_secure:
        id: filter_html_image_secure
        provider: filter
        status: true
        weight: 9
        settings: {  }
      editor_file_reference:
        id: editor_file_reference
        provider: editor
        status: true
        weight: 11
        settings: {  }

And finally editor.editor.basic_html

uuid: 175d53b1-06a9-4aca-9755-85595f23633b
langcode: ca
status: true
dependencies:
  config:
    - filter.format.basic_html
  module:
    - ckeditor
    - editor_file
third_party_settings:
  editor_file:
    status: true
    scheme: public
    directory: inline-files
    extensions: txt
format: basic_html
editor: ckeditor
settings:
  toolbar:
    rows:
      -
        -
          [... several groups ...]
        -
          name: Media
          items:
            - CKEditorFootnotes
            - DrupalFile
            - Blockquote
            - DrupalImage
            - Table
        -
          [... more groups ...]
  plugins:
    stylescombo:
      styles: ''
image_upload:
  status: true
  scheme: public
  directory: inline-images
  max_size: ''
  max_dimensions:
    width: null
    height: null

It turns out you need to call editor.ui.addButton() to get the buttons to show.

It seems to me that it is not usually needed in vanilla CKEditor development, because it is not included neither in the tutorials nor in the ckeditorfootnotes plugin. However, most of the current Drupal 8 CKEditor modules do include it in the plugin source.

For the simplebox plugin it would read like this, here command is the name of the defined widget.

editor.ui.addButton('SimpleBox', {
    label: Drupal.t('SimpleBox'),
    command: 'simplebox',
    icon: this.path + 'icons/simplebox.png'
});


User and Content tracking and analytics I have a fairly active Drupal 7 environment and I would like to track and log certain things about my users and their behaviour.

What are some of the approaches people tend to take to this? Ideally I'd love to graph some kpi's for reporting etc.

For example I if wanted to track (and log for comparison) things like:

Number of new users this day/week/month
Number of new nodes of 'content type' created this day/week/month
Number of new comments this day/week/month
Most active users (not just in terms of content created but also number of logins, number of comments etc...)

On a per user basis I love to know things everything I can reasonably find about behaviour.

Danny.

For most part, you can achieve this using contrib modules. Here are some of them:

Views will allow you to fetch most of the information in your database and create pages, blocks and subpages.
Administration Views will override default admin pages (e.g. /admin/content/node and /admin/people) and even more importantly, allow you to change the output of those pages.
Views Data Export allows you to export information from Views to a variety of formats, from txt to csv.
Google Analytics with custom
Messages module. I've used Messages module many times when I needed to track an action of a user somewhere. It integrates with Views and Rules, and in combination with the two you can log most actions on the site.
Total Control gives you a central administrative page from where you can manage different sections. It's also coming with certain panes that you might find useful.
Panels will allow you to create more complex pages that contain blocks and information in a different layout than what is provided by default in your admin theme (e.g. 3 columns and multiple different rows).
Forena reports module allows you to create custom reports from the database.

For additional information, see this response by Pierre Vriens.

Lastly, I just realized that this question might not be really suited for this website as it's opinion based and asks for module suggestions. If that's the case, I guess mods will remove both the question and answer.


Count content types which have taxonomy term I have a content type where a taxonomy term is associated to it . I would like to know how could i count the number of content types by taxonomy term ?

You can use the following snippet, to get count of nodes by passing the term id

<?php
  $tids = array(1); //An array of term IDs to match.
  $nodes = taxonomy_select_nodes($tids);
  echo count($nodes) ;
?>

Edit:

You can use views to achieve this, check this similar question . It explains an example


Override node title validation I have a pretty specific case where I want to fill in the node title myself if the user fills a checkbox above the title field.

For this reason, I can't use autonodetitle (because the title is only automatic if the checkbox is selected).

I have added my own validation callback using array_unshift() in a hook_form_alter to make sure its the first one but when its called the form already has an error (title field is required)

Is there any way I hook into the validation process earlier or even just remove the error for this field?

Thanks!

You can easily hook into the validation process by implementing hook_form_alter(&$form, &$form_state, $form_id) or it's cousin hook_form_FORM_ID_alter(). There you can inspect the $form variable, find out where the array of validation functions is, and perform array_unshift() on it.

You could also use the form alter hooks to modify the #required property of your title field, therefore preventing further validation errors down the line.

Don't forget that in order for your array_unshift() operation to be successful, the form needs to be passed by reference to your hook, or else you would only be modifying a local copy of the form variable. It's very easy to forget adding the ampersand & in front of $form in the hook implementation. i.e. ...& $form...


What is the difference between $variables['elements']['#node'] and $variables['node']? Just wonder what is the difference between $variables['elements']['#node'] and $variables['node'] in hook_preprocess_node(). Are the same instance of the same node?

See the code executed in template_preprocess_node(), the function called before the preprocess functions implemented by modules for a node.

$variables['node'] = $variables['elements']['#node'];

So, yes, $variables['node'] and $variables['elements']['#node'] contain the same value.


How do I create a merge request for a project? I'd like to create a merge request for a drupal.org project. I found a page on drupal.org titled Issue forks & merge requests which seems to address this but I'm not really getting anywhere. The page says:

On an issue page, make sure the fork is created and you have access.

If the fork has not been created yet, click “Fork {project}”
If you do not have push access yet, click “Get push access”
If you see “✓ You have push access,” you’re all set!

The only place I could find a "Fork" button was on https://git.drupalcode.org/project/project_name/-/forks. But when I click on that I see just see a namespace with my name, and a greyed out "select" button, which, if I hover over it, displays "You have reached your project limit". But I think I'm in the wrong place anyway.
The instructions start with "...on the issue page" so I created an issue on drupal.org for the project, on the issue page there are no links that mention "fork" anywhere to be seen.
What am I doing wrong?

As said in Issue forks & merge requests drupal.org only implements (so far) issue forks and merge requests related to those issue forks. Issue forks are still in development and enabled only on those projects that opted-in, a list of which is available in Opt-in core issues into the Drupal.org Issue Forks and Merge Requests Beta: The list doesn't include the projects maintained from the Drupal Association, for which issue forks have been directly enabled from a Drupal Association employee.
The plan is making them available on all projects on November 10, 2020.
When issue forks are enabled, an issue opened for that project contains a button as in the following screenshot, taken from Show commit activity for issue fork branches without merge requests.

When an issue fork has been created, there will be a different button, as in the following screenshot.

I didn't watch at the code used on drupal.org, but I expect the code checks users have the Git user role on drupal.org, which is given to the users who accepts the Git access agreement, or a Git account on Drupal.org, before allowing them to create an issue fork or obtain push access on an issue fork.

Merge requests aren't tested on DrupalCI, until Test merge requests made in GitLab with DrupalCI is marked as fixed. That could happen before, or after, issue forks are enabled on every project.
As for today, December 24, 2020, issue forks and merge requests have been enabled on every project hosted on drupal.org. Merge requests are tested by the DrupalCI instance running for drupal.org.


Blog with subscription option to send emails on new blog entry I'm working with Drupal 7. How do I setup 'Subscription' option for my blog so that upon every New Entry of the blog, an email is sent out to the subscribers?

Another way is to use the MailChimp module but requires the extra step of registering on MailChimp.com.

  This module provides integration with the MailChimp email delivery
  service. While tools for sending email from your own server, like
  SimpleNews, are great, they lack the sophistication and ease of use of
  dedicated email providers like MailChimp. Other players in this field
  are Constant Contact and Campaign Monitor.


How to exclude a field when a search is done? I just enable the Search Form (provide by the search module) block to allow the visitor to make searches.

When a search is done the entered word is searched in all field of the nodes.

Can I exclude a field?

Let's say the content type has the fields: title, body and provider.

Then when a search is done I need to exclude the field provider from the search.

I have the custom_search module enabled but I see no way to exclude fields.

Default Search is not customizable. Consider using one of more advanced solutions:

Search API with client module that will suit your needs.
Finder with proper views configuration.


Creating a custom page I am new to drupal 8 however, I have experience in MVC pattern and used Django earlier. I want to create a page that points to localhost/home where I would like to show a slideshow from view slideshow module as well as some static contents like images, links, etc. If I were on django, I would simple redirect the parameters to display directly on template i.e something like HttpResponse(template.render(context, request)).

How do I do such thing is drupal 8? I have looked at lots of places and still cannot find anything. The solution that I have found till now is to create separate module for each page i.e home, about-us, etc. and route a Controller function. Is this the only approach? Please help. Thanks.

Pages in Drupal are largely composed of content types with fields attached to them, and sometimes, blocks (which can be created from Views).

You do not need to create custom routes and controllers for them, the core Node module takes care of this for you.

The core Path module will allow for custom aliases, and Pathauto will let you create automatic aliasing rules.

It would be a fairly rare thing to need to implement a route and controller just to display basic content in Drupal. 99% of the time it can be achieved with content types, Views, or panels.

You will probably want to review some of the material on Drupalize.me to learn Drupal content management.


Looking to make an opaque image/image caption in a teaser I am interesting in making a teaser that just shows an image, which an opaque caption over it it saying blahblahblah READMORE and then a link to the page.

how would i do this?  i'm not even sure where to start.  i am using this with views kwick slider.

I did this in CSS using the content title and the opacity feature of CSS. See below (modify for your purpose)

.view-id-programmes.view-display-id-block_1 .views-field-title {
margin-left: 10px;
position: absolute;
background-color:
white;
filter: alpha(opacity=68);
-khtml-opacity: 0.68;
-moz-opacity: 0.68;
opacity: 0.68;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-khtml-border-radius: 15px;
border-radius: 15px;
padding: 8px;
}


Where does Drupal store information after creating a rule? I'm wondering where Drupal stores information in the database when one creates a rule with an event A node has been flagged and an action Grant user points to a user.

Can you help me?

Rules are stored in the rules_rules table in D7. The table contains the rows of name (a machine readable name) and data (a data blob).

^ this is from D6, D7 has rules stored in rules_config, with rules_trigger holding the triggers and the ID of the rule and the trigger matching to each other.


How to split Commerce Order: Shipping Address and/or Billing Address into different lines in Views In a Views view that pulls out order information, I'm trying to put the Shipping and Billing addresses, but the addresses seem to be all joined up, and there's no way to split them into different lines. I'm grabbing a field called Commerce Order: Shipping information and Commerce Order: Billing Information

At the moment it looks like:

Name123 StreetSome RoadSome CitySome CountryPOSTCODE

I want it to look like:

Name
123 Street
Some Road
Some City
Some Country
POSTCODE

I'm outputting the result to a CSV export using the Views Data Export module. So I only need it to look readable when I open it with MS Excel.

Thanks to this question, and Stan Ascher's answer, I was able to find the correct tokens to use with Rules. I thought I would share it here:

[commerce-order:commerce-customer-billing:commerce-customer-address:name_line]
[commerce-order:commerce-customer-billing:commerce-customer-address:thoroughfare]
[commerce-order:commerce-customer-billing:commerce-customer-address:locality], [commerce-order:commerce-customer-billing:commerce-customer-address:administrative_area] [commerce-order:commerce-customer-billing:commerce-customer-address:postal_code]


Making content available to a user after certain amount of time I  want to restrict content access to subscribers over a period of time. Each user should be allowed to access the content in a sequential manner. So, after one week of membership, users would be able to access "Week 1" material; after 2 weeks users could access "Week 2" material.
Membership would just be a particular role.

Something similar has been done in Drupal 6, using PHP as reported in Release Content to Subscribers in a Sequence.

I am wondering if this is possible just using modules, like Rules and Rules scheduler.

I yes I think this is possible using Rules and Rules Scheduler

Unpublishing Content

You should check out this tutorial  (its also for Drupal 6)

Publish content exactly 24 hours after it was created

What you have to pay attention to is just do the opposite. So in the action you say Unpublish. And then of course you pick the dates.

Hope it helps


How to upload a file in Drupal 8? I'm a brand new Drupal user and I just installed and started configuring a Drupal 8 instance.  I've had no problem tweaking the theme, and creating text content, but I can't seem to find the button to upload a file.  I doesn't exist on admin/content/files where I would expect it, and Googling quickly points me to modules I could include.

I was hoping to upload a few images to use on some of my "basic page" content entries.

Is there not a simple "file upload" button in this CMS?

"Content entity" types like nodes (content) are field-able, so you can choose what data are attached to them.

The "basic page" content type only comes with a body field out of the box, but it's a cinch to add new ones:

Visit /admin/structure/types
Click "Manage fields" for the "basic page" type
You'll see a list of the fields currently attached to the content type. Click "Add field"
Select a field type; "Image" would probably make most sense for your needs
Follow the rest of the wizard and choose suitable values (should all make sense)

When you visit the node add/edit page for a "basic page", you'll see the new field, and you'll be able to upload your images.

Next you'll probably want to visit the "Manage display" tab to choose how the images are rendered, and the "Manage form display" tab to choose which widget is used.


Customize Drupal 6 Nice_Menus Output I had asked this exact question on StackOverflow, until I cam across this StackExchange site...makes much more sense to post this here!

I'm using nice_menus-6.x-2.1 with Drupal 6.22 and would like to know if there is any way to rewrite the menu output so that the end-result resembles the following:

Parent Link 1

        Parent Link 2

Child Link 2[Description]

Child Link 2[Description]

Parent Link 3

Basically, I only want the customization on the second tier of sub-menus onwards. The
 wrapper is there for styling purposes. The  within the link tag is supposed be the description that you usually get on mouse-over, but I want this to show a bit smaller below the link (but be part of the link itself, and therefore not outside the  tag).
I'm sure this is possible? I just don't know where to start.  I'm looking within nice_menus.module but can't seem to find the function for the children rewrite. I currently have this working in a mock using plain HTML markup and CSS, but I just can't work out how to customize the PHP function in Drupal.

Has anyone been through this and would care to share?

Thanks a million everybody!

Probably you would just want to implement your own version of theme_nice_menus_build(), and add all your required divs/spans right there.


How to make a user role expire after 1 year? I'm looking for a way to make a user role expire after 1 year. In Drupal 7 there is the Role Expire module. I found this post using the Rules module. But I can't seem to figure out how to do this in Drupal 8.

More specific, what I want is for a user to buy a Commerce product when payed, the user gets a user role to read articles behind a paywall. This role should be active for a year.

The only option I found is building a custom module but I want to try and find an other to do this first. Hope someone can help with a good suggestion or a push in the right way.

Below are the following ways to do this:

1.As same as role expire another module User expire is available User Expire.

2.By using Rules module you can expire the role after 1 Year.

Try these Modules hope this will help you.


Letting anonymous users vote in a poll when using Varnish I have a poll on my front page that I want users to be able to vote on, but anonymous users always just see the results and are never able to vote. I've been trying just about everything I can think of to fix this and nothing works.

I'll start by saying that I can access my web server directly through an alternate port. When I do this I see the poll when I'm not logged in; so I know that anonymous users can vote.

I've tried using ESI and the Drupal 7 ESI module. I got it set up and working so that the poll block is being loaded via an ESI tag (obviously accessing it directly through the alternate port stopped working when I did this since browsers don't parse ESI tags). No dice.

I tried using the AJAX Blocks module, I set a delay on loading the block just so I could visibly make sure the block was loading via AJAX, it was and it was still just displaying the results.

I tried voting from the same IP address using the alternate port, thinking that since someone has voted going through Varnish before the server wont allow it again, but I can vote twice from the same IP address through the alternate port.

I tried logging into the server via ssh and using Links to view the site, thinking that maybe it's the local IP address that is making the web server serve the results page for some other reason, but when I use Links I can see the voting form.

Clearly there's something that's causing Drupal to serve the results instead of the form when Varnish requests the page, but what is it?!?

https://drupal.org/project/pollanon
This lets anonymous users vote in a poll more than once, and here's an article on using ESI to allow parts of your page to remain cached while other parts remain dynamic.

Accepting votes from anonymous users on Drupal polls is complicated when you use caching. By using Edge Side Includes (ESI), you can dynamically load some parts of a Drupal page while caching the rest of it. The addition of the Poll Enhancements module allows multiple anonymous users to vote on polls by using cookies to track who has voted.

Edge Side Includes integration
The ESI module includes two Varnish VCL files (located in the docs directory of the module:

docs/esi_blocks.vcl - custom sub-routines to handle ESI-block integration.
Copy this file to the Varnish config directory, /usr/local/etc/varnish/
docs/default.vcl - example code showing how to include the ESI blocks VCL in your Varnish config. Portions of this should be added to appropriate places your Varnish config file. We'll do it by creating a copy, /usr/local/etc/varnish/default-esi.vcl, that has the portions we want:
include "/usr/local/etc/varnish/esi_blocks.vcl";
sub vcl_recv {
  call esi_block__recv;
}

sub vcl_hash {
  call esi_block__hash;
}

sub vcl_fetch {
  # don't ESI anything with a 3/4 letter extension
  # (e.g. don't try to ESI images, css, etc).
  if (! req.url ~ "\..{3,4}$") {
    esi;
  }

  call esi_block__fetch;
}

Then, edit /usr/local/etc/varnish/drupal.vcl and add a line near the beginning:

include "/usr/local/etc/varnish/default-esi.vcl";
Restart the Varnishcache:

svc -t /service/varnish
With the module enabled in your Drupal site, block configuration pages now have an ESI Settings section with two options: Enable ESI, and a TTL value.

Poll Enhancements
Installing this module allows anonymous users to vote on polls. By using cookies to track who has voted, multiple users who are behind a firewall will be able vote on polls. There's a threshold setting for how many votes from a single IP in a time period. The module also provides a Use AJAH option - I needed to enable this to have the ESI-enabled Poll block work properly.

Configure Varnish to ignore the poll cookie ( pa-[nid] ) by editing the vcl_recv section of /usr/local/etc/varnish/drupal.vcl and inserting a line to remove the cookie:

// Remove pollanon cookies.
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(pa(.*))=[^;]*", "");
Restart Varnish:

svc -t /service/varnish

Source: http://www.productionmonkeys.net/guides/drupal/performance/pressflow/varnish/varnishing-polls


Add cropping option to an image form I've the next form.

$form['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
    );

That generates something like this:

What I need is to give the user the option to see the image that he has upload, and resize the image. The functionality that I need, is the same that the ImageField_crop module gives.

I'm totally lost. I don't know how to add this functionality to the form.
It's totally necessary for the project to insert this form in a custom module, because I have a multistep form.

Does anybody know how to do this??

Thank you very much.

Better you can go with implementing the field with "imagefield_crop" module instead of doing customization further.


How can I print user field values in page.html.twig? I've created a couple of fields for the user in Drupal 8, example: first name. And i'm trying to print it in the home page (page.html.twig) but to no avail.
I tried the following:

{{ user.field_first_name.0['#context']['value'] }}
{{ user.field_first_name.0.value }}
{{ user.field_first_name }}

I even tried adding preprocess functions on mytheme.theme, and still it didn't work.

noting that the below works

{{ user.displayname }}

Appreciate any help given,

thanks

To print user fields on the page template create a Views block and place it in an existing region.

At best you first added a new view mode for User under https://example.com/admin/structure/display-modes/view and then on https://example.com/admin/config/people/accounts/display select the newly created view mode and place the fields you like to display.

Then create the view, have it display Users and in the very right under ADVANCED add a contextual filter for User ID. Select Provide default value and choose User ID from logged in user, save. Then in the very left under FORMAT > Show > User select the view mode you created earlier.

Don't print user values on the page template.

page.html.twig is for printing regions.
page.html.twig is cached per user role. Next user with the same role will get displayed initially cached values of another user.
The user object with all field values isn't fully loaded by default, you would need to preprocess the user first.
Templating should be done when you need to structurally change markup.


Invoke Mollom CAPTCHA directly I have a custom form within CTools form wizard that I would like to use Mollom on. Is there an API function I can use to place it in the Form API on that page?

I'd suggest you simply integrate with mollom to expose your form.

You just need to implement two simple hooks and you can also configure if it should be CAPTCHA only or analyse some fields.

Hook documentation:

hook_form_mollom_list()
hook_form_mollom_info()

As an example implementation, you can have a look at my patch against Privatemsg: http://drupal.org/node/720038#comment-3501758 or have a look at these: http://drupalcontrib.org/api/search/7/_mollom_form_.


Print Emvideo Field in node.tpl Hello im playing about with my node.tpl so as i can show the title of a video below the video ala youtube. Ive managed to sort that ok but my body field was showing above the title still so i rectified that with

<?php print $node->content['body']['#value'];?>

Now im going to remove the print content bit from my node.tpl but that will mean no video.

could anyone advise on how to display the video field?

Im presumming i need to add some code which shows the fields and then print out the field.

This is where i am stuck.

thanks

(drupal 6)

Instead of print_r try:

<?php print var_dump($node);?>

Look at your source, find the video field you've setup, then copy and paste the complete path the the CCK variable you've setup. The problem is your outputting the entire body field where as it sounds like you just need two fields "$node->title" and "$node->MyVideoField" but without knowing the complete variable path I can't really help.


Checkbox value incorrect in custom validation I have a custom form like this :

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

      $form['first_name'] = [
        '#type' => 'textfield',
        '#title' => t('First name'),
      ];

      $form['t_and_c_accepted'] =[
         '#type' => 'checkbox',
         '#title'=> t('I accept the terms and conditions'),
         '#return_value' => 1,
         '#default_value' => 0,
      ];
 }

public function validateForm(array &$form, FormStateInterface $form_state){

          $values = $form_state->getValues();
          if(empty($values['first_name'])){
             $form_state->setErrorByName('[first_name]', t('Fill in a first name'));
          }

          if($values['t_and_c_accepted'] !== 1){
             $form_state->setErrorByName('[t_and_c_accepted]', t('Accept the t&c's);
          }
    }

If I uncheck the checkbox and submit the form, it gives me an error about the unchecked checkbox, as expected.
If I check the checkbox, leave the first_name empty and submit the form, it gives me an error that my fist_name is empty, as expected.
But if I then fill in first_name, UNcheck the checkbox an submit. The validation passes! So not as expected.
If I then go back to the form (back from my landing page), I can reiterate this sequence

I have monitored the $form_state->getValue('t_and_c_accepted') value throughout my tests and it gives me indeed value=1 during the unexpected behavior. So it is consistent with what I see, but I have absolutely no idea what's going on.

So any help would be appreciated

Update:
When looking into the http headers I see that the browser does the POST request with form data t_and_c_accepted:1 while the checkbox is unchecked.

So Drupal's form api seems to handle the request correct, but why does the browser doesn't post the correct checkbox status value ?

ok, I've found the cause of the issue:
I rendered $form['t_and_c_accepted'] twice in the twig template which caused the browser to post a value that was different from the checkbox that was visible.

So it was my own mistake but I answer this question anyway in case anyone else would be wasting time solving the same issue


Responsive Images Not Scaled-Down Properly in Omega Theme just on Firefox I'm building a responsive site using the Omega theme, and Adaptive Image Styles. So, in my Firefox 16.0.2 (Mac) browser, images that are scaling down look very poor quality as they are scaled down. If I take the same image out of Drupal and scale it in the same browser, it looks fine; in any other browser, it looks fine. Images seem to be using proper CSS (max-width:; height:auto;).

Check out this snapshot. Is it a bug in my browser or where does the issue exist?

What kind of Mac are you using? For example, I have a Retina Mac. Firefox doesn't support Retina displays, so things generally look fuzzier in Firefox than say Chrome.

Also, if the responsiveness is aimed towards mobile devices, wouldn't it be better to test on those? You probably won't have a user with a desktop window of 600px wide. ;)


How to remove welcome to message? I changed the:

configuration: Site Name --> 'my site name'

But it shows in title bar like this:

  Welcome to 'my site name'

So, how can I remove the "Welcome to" in the title bar, so that the result would be just:

'my site name'

When I inspected the html I found like this:

Welcome to my stie name | my site name

But I wanted to be :

my site name

And I'm using zen base theme and zenophile sub-theme.

Try Page Title module and configure the Page title for Front Page.

Download & enable https://drupal.org/project/page_title module.
Configure Page Title from admin/config/search/page-title And change
the Frontpage.


No Emails sent on User Creation in D8 through Rest API I'm working in Drupal 8.2.4 currently and building a headless webapp using Rest Web Services module for the endpoints I need.
I'm using the endpoint /entity/user to create users, however the default welcome emails are not getting sent out by Drupal when I create the users.

I do have the emails set up to be sent properly and I know this because if I create a user like normal in Drupal with "Notify user of new account" checked, it does send the email. Is there some simple way that I am just missing to get this to work?

I have also tried using hook_ENTITY_TYPE_insert using _user_mail_notify to trigger the email to be sent, however this is not working either for what I want. My code is as follows:

/**
 * Implements hook_ENTITY_TYPE_insert().
 * When a new user is created, do things.
 */
function custom_rules_user_insert(Drupal\Core\Entity\EntityInterface $entity)
{
  _user_mail_notify('register_no_approval_required', $entity);
}

Am I doing something wrong, is there a simple way to get this to work or does this just not work at all yet in Drupal 8? I will also need to set up Pass Reset emails, so any feedback would be appreciated.

I've tested this and it seems like _user_mail_notify just isn't working currently in 8.2.4, however I did find a workaround using the hook_ENTITY_TYPE_insert() still, but using hook_mail and MailManager also.

/**
 * Implements hook_mail().
 */
function custom_rules_mail($key, &$message, $params) {
$options = array(
    'langcode' => $message['langcode'],
);
 switch ($key) {

   case 'create_user':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('Welcome to the site!', $options);
     $message['body'][] = $params['message'];
     break;
 }
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 * When a new user is created, do things.
 */
function custom_rules_user_insert(Drupal\Core\Entity\EntityInterface $entity)
{
  global $user;

//  _user_mail_notify('register_no_approval_required', $entity);

  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'custom_rules';
  $key = 'create_user';
  $to = $entity->getEmail();
  $params['message'] = "Welcome to our site! \r\nYour username is " . $entity->getUsername() . " " . "\r\nIf you would like to reset your password, you can at the following link: \r\n" . user_pass_reset_url($entity);
  $langcode = $entity->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] !== true) {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }
  else {
    drupal_set_message(t('Your message has been sent.'));
  }

}

The way I have this set up works. When a user is created (through drupal GUI or REST API), they are sent a welcome email that also includes a link to reset their password. To do this, you use the user_pass_reset_url function that is defined here. MailManager was pretty simple to use and figure out.

I followed this blog to figure out how to do this.


How to show contextual links buttons in templates with minimal markup? I want to get rid of the most markup in Drupal 8 templates, but still want to have working contextual links. How to do this?

In Drupal 8 the contextual links markup is still printed via the {{ title_suffix }} variable (D7: print render($title_suffix);).

block.html.twig (default):

{%
  set classes = [
    'block',
    'block-' ~ configuration.provider|clean_class,
  ]
%}

  {{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}

So a minimal version would still work:

{{ title_suffix }}
{{ content) }}

Printed result for user without the permission "Use contextual links"

BlaBlaBlaContent

Printed result for user with the permission "Use contextual links"

    <button type="button" class="trigger focusable visually-hidden" aria-pressed="false">Open configuration options</button>

Configure block

Edit

Delete

BlaBlaBlaContent

The default formatting will be destroyed because the outer class .contextual-region is missing and it's defined like this in contextual.theme.css:

.contextual-region .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li {...}
...

So you have to overwrite (https://www.drupal.org/node/1876600) this file or copy the definitions in one of your theme css files and change for example like:

.contextual-region .contextual .contextual-links, .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li, .contextual .contextual-links li {...}

Or you place manually in the template or via JS ".contextual-region" into an outer dom element or print {{ attributes }} there.

Printed result:

        <button type="button" class="trigger focusable" aria-pressed="false">Open configuration options</button>

Configure block

Edit

Delete

    BlaBlaBlaContent

Remark: Without the upper .contextual-region the mouseover visibility of the contextual links icon is not working ...

Note: Current version of Drupal 8 is Beta 6 - so things may still change!


How to allow for redirecting on same URL with different query strings? I'm using Drupal 7. I have about 120 urls with different query strings, and Drupal is not allowing me redirect on same url with different query strings/parameters.

For example:

I have to redirect from this url blog/its-time-occupy-it?page=1 to blog/its-time-occupy-it. See more example given below;

(from url) blog/about-author?page=1  -> (to url) blog/about-author
(from url) blog/about-author?page=2  -> (to url) blog/about-author
(from url) blog/about-author?page=3  -> (to url) blog/about-author

Any suggestions to give me solution to fix this issue?

Using the Rules module you can implement a rule that looks like so:
{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "blog\/about-author?page",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "blog\/about-author" } }
    ]
  }
}

It will redirect any path starting with blog\/about-author?page to a path named blog/about-author. So this will "redirect any such paths but with different query strings/parameters to the same url" (as in your question ...).
To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if you have the Rules UI enabled).
But wait, there is more ...
You could also check if page was specified as an URL argument. And make the actual value specified for such argument (like in your question: the 1, 2 or 3 after page=) available as a new variable to Rules. To do so, use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rules configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Can I access public:// from inside a module? I need to load an image that's uploaded to the public folder from within a module

In the module itself:

function mymodule_dashboard() {
   GLOBAL $user;
   $profile = profile2_load_by_user($user->uid, 'personal_information');
   $data['avatar'] = $profile->field_picture['und'][0]['uri'];

In my dashboard.tpl.php:

<img src="<?php echo $data['avatar']; ?>" />

The rendered content:

I can pull the image name and build the path myself, but I'm looking for a way to actually take advantage of this public folder business

You're looking for the file_create_url() function:

  Creates a web-accessible URL for a stream to an external or local file.

e.g.

$data['avatar'] = file_create_url($profile->field_picture['und'][0]['uri']);


db_update after a submit button is clicked I want to update  a "picture" field with a type of character varying, after a button is click. My customize module is already connected to it's database.

This is my form:

function myid_user_page_form(){

    $enrollment = array(
        'database' => 'enrollment',
        'username' => 'postgres',
        'password' => '',
        'host' => 'localhost',
        'driver' => 'pgsql',
    );

    Database::addConnectionInfo('myid', 'default', $enrollment);

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save',
        '#attributes' => array(
            'id' => 'myid_save',
        ),
        '#submit' => array('formsave_action'),
   );
   return $form;
}

function formsave_action($form,&$form_state) {
    db_set_active('enrollment');

    $num_updated = db_update('student')
        ->fields(array(
          'picture' => 'Yucks',
        ))
        ->condition('studid', '101-03043', '=')
        ->execute();

    if($num_updated) {
        drupal_set_message('Successfully Saved');
    }else{
        drupal_set_message('Save Failed');
    }
    db_set_active();
}

Unfortunately, nothing works. Nothing gets updated and displayed and an error saying:

My external database is SQL_ASCII compared to drupal's default database which is UTF8 encoded. Does it do something with my problem? Can someone point me to where I've been wrong? Thanks.

Although db_update should work with db_set_active in fact db_set_active is completely unnecessary in Drupal 7. Instead of db_update($table, $options) you can do Database::getConnection('default', 'enrollment')->update($table, $options); a bit more verbose but avoids changing the global state.


Commerce- Show a base price (MSRP) and a discount (the real price) I have a number of products for which I would like to display the MSRP (with a line through it) and then the discount price (my store's actual price).

I do not want to actually discount the products; the "discounted" price is the real price in the system.  Rather, I want to also show the MSRP (to show what a good deal my customers are getting).  This is similar to what Amazon.com does (they always have the original price with a line through it, and next to that is the Amazon.com price).

What is a sane way to do this?  Should I add another field of type price to products?  Should I add that field instead to my product display content type?  From the perspective of long-term maintenance, I'm not sure how to approach this.

Here's an example from Amazon:

Use the Commerce Price Savings Formatter module.

  This module is an extension of Drupal Commerce that provides a display
  formatter for the Commerce Price field which shows the amount of
  savings when a discount is applied.


How to hide content when first displaying the view (Views contextual filter) I am on drupal 7.56 and using Views to display some content based on a filter.

I am trying to not display content when the user opens the page for the first time. I want to make sure the user only displays values that will be related to the filter. My filter is on the Title and is a Search box.

I know that it is possible to reach that goal with contextual filter. I did it once, but can't do it again.

Can somebody help me make that views work like that ?

You can do this with an exposed filter and selecting the input required option. This option will appear in the Advanced section in the view configuration. You'll want to add an exposed filter for your title field first. I think that's in core.


How can I have device-specific block layouts? I'm fairly new to Drupal. In my current project, I'm using Drupal 8. The site is supposed to have a fairly different look depending on the device, in a way such that being responsive is not enough here.

So, within a single custom theme, I would like my site to have two different block layouts depending on the type of device (mobile / desktop) on which it is displayed. This can be achieved by showing / hiding blocks depending on the device. For performance reasons it is important for the hidden blocks to not be rendered at all in the HTML code (i.e. merely hiding with CSS won't do).

For this it seems that a combination of the Context module and its little brother Context Mobile Detect would do the trick. However, Context Mobile Detect is not yet available in Drupal 8, preventing me of using the Context module with the relevant condition.

Is this the right approach? Any other solutions for achieving what I'm trying to do here? This seems like a common enough problem to me and I'm expecting other developers to have found a way.
If it is: I'm tempted to write my own custom condition (wrapping the project Mobile Detect) so I can use it with the Context module. It seems Context uses the Drupal 8 Condition API, but I can't find any useful resource on how to write my own custom conditions in version 8 of Drupal. The official doc is sparse at best and I would rather avoid trying to reverse-engineer the thing. Any of you have a useful link/video/advice for this?

I followed the counsel of Berdir and Ash Upadhayay. Having a sub-domain dedicated to mobile devices is a sound advice as many important websites currently use this method. As they say, using the same domain for both version could cause problems with caching and referencing by indexation robots.

This however doesn't clash with my requirements, and I was able to fulfill them using the Drupal 8 version of the Domain Access module.

The Domain Access module allows to define specific sub-domains that Drupal 8 will be able to recognize. The module then makes possible to condition all manner of things depending on the current domain, including the block layout.

I installed the module itself and its contrib module (packaged with it) Domain Alias. This last module allows you to associate various patterns to a domain that works as an alternative way of detecting the domain. This allows to match the URLs of local installs of the project without changing the Domain configuration.

This is the perfect solution for me as I am now able to condition the display of blocks from a single page - the block layout page.

All that's left to do then is to redirect the user on the correct sub-domain depending on the device, using a module such as Mobile JS Redirect.


Why do I get a "page not found" error? I have a working page listing items in a block (created by the 'block_view' hook) which when displayed link to another set of pages where I want to list content types associated with them. The items are not standard drupal types so there is no relation between these two sets except through my DB table.

So say I have a link on the original page to mysite/speech/3, and I want to see all speeches associated with speech 3.
To do this I created a block, made it display on speech/* and all is good. I can see the content types associated with speech 3 in a nice table, except it also displays a 'Page not found error' along with the correct data.

Why?
I'm trying to use the Drupal structure as far as possible where I can. When I can't are there issues with using blocks extensively performance wise?

You don't have a piece of content at that URL mysite/speech/3, only a block. Don't use a block in this situation, just use a regular page.
Blocks are fine if you can cache them. Does the data change often? If not, set a very long cache and there should very little performance impact.


Why D7 Update Manager keeps sending emails? This is very weird,

http://example.com/admin/reports/updates/settings

keeps sending emails to my email while the owner of example.com has changed his website from Drupal 7 to weebly! I mean, the Drupal installation does not exist!

Update Manager is a module that exists and works inside your installation. This means that Drupal installation exists. Maybe it is no longer connected to domain, but it is there, up and running. Delete it and you'll be all right. Or, if you want to keep it for backup / rollback purposes, ask your sysadmin to delete it's CRON rule. Without system's cron and visitors, nothing will trigger update checks and mail sending.


Is there a distribution optimized for heavy data traffic? I am testing an Android app which sends minute-by-minute updates to my Drupal site which acts as a server.

I create a single node each day and all my app data is saved in CCK fields within that node.

I got the updates working yesterday and tested for half a day. When I try to edit the node, to see the CCK data uploaded, my site crashed and complained of lack of PHP memory.

In my .htaccess file, I had set PHP memory to 100M. I then increased it to 300M and then 500M with no improvements. Then I tried 1000M. It worked but it seems slow.

That's just for one user's half a day's worth of data. Eventually, I will have hundreds of users with 24hours data each.

Can anyone tell me if there is a Drupal distribution which handles heavy data traffic by design?

You should have a look at Pressflow.

  Pressflow is a distribution of Drupal with integrated performance, scalability, availability, and testing enhancements.


Link Mini Panel thumbnail formatter to node Working on a site that shows images and video with a Mini Panel formatter in a View withe File Entity and Media modules. The Mini Panel has a piece of content of file display that shows an Image display as well as Vimeo Video and YouTube. The Image display settings uses an Image style.

How do I link the media from the mini-panel to the referencing entity? (User clicks on the thumbnail in the view listing and is taken to the node's path).

If you go to the view display page and click on the field of your thumbnail, on the settings page scroll down and you should see a drop-down with title of Link image to. Choose content and save.


Impossible to html_entity_decode the button title in a render array Here is the code that reside in my extended class of the RegisterForm:

$title=$this->t("M'inscrire") // notice the apostrophe in French
// the $element variable is the action sub array of the form
$element['submit']['#value'] = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
dpm(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));

Unfortunately, my submit button is displayed like M&#039inscrire
And strangely, the dpm function print it as it should be

Edit to add, the following does not work:

$element['submit']['#value'] = $this->t("M'inscrire"); //NOT WORKING
$element['submit']['#value'] = "M'inscrire"; //NOT WORKING

As pointed out by Jaypan, it was due to a bug in the bootstrap_barrio theme.

I have posted a patch for it: https://www.drupal.org/project/bootstrap_barrio/issues/3083728#comment-13527917


AJAX append content via link on existing page I am trying to recreate the functionality of the ajax_link example in the Examples for Developers module.  Here is the code I have so far:

In animal_licence.module:

function animal_licence_menu() {
  $items['buy-animal-licence/animal'] = array(
    'page callback' => 'ajax_link_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'animal_licence.inc',
  );
  return $items;
}

In animal_licence.inc

function ajax_link_response($type = 'ajax') {
      if ($type == 'ajax') {
        $output = t("This is some content delivered via AJAX");
        $commands = array();
        $commands[] = ajax_command_append('#content', $output);
        $page = array('#type' => 'ajax', '#commands' => $commands);
        ajax_deliver($page);
      }
      else {
        $output = t("This is some content delivered via a page load.");
        return $output;
      }
    }

The ajax link on-page is:

Click here

When I visit /buy-animal-licence/animal/ and click the link I get the ajax spinner and it eventually times out with the following:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /buy-animal-licence/animal/ajax/
StatusText: OK
ResponseText:...

I'm not sure where to go from here, any suggestions would be much appreciated.

you need to add the nojs uri part in your menu item like:

$items['buy-animal-licence/animal/%ctools_js']

also, to make all more clear - your type argument in the callback should default to NULL

function ajax_link_response($type = NULL) {


Internal links no longer working. Getting MAMP virtual host info instead My local site is running Drupal 7.43 using MAMP on Mac OS X 10.10.5. The site was running fine until recently, when all of the links on the front page were no longer working correctly. Each link now opens the same page. Here is a screenshot of that page.

After much digging, I found out that turning off clean URLs allows me to access the rest of the site, which is a CiviCRM installation. I downloaded the files and database from a live site to verify the backup worked. It does work, but only if clean URLs are disabled. Why does it happen?

Since turning off Clean URLs seems to at least be a work around for your issue, it sounds that you have not correctly configured Clean URLs. To correctly enable/configure Clean URLs, refer to Configure Clean URLs in the installation guide.

If you're not familiar with Clean URLs yet, I suggest to review that documentation (for the version of Drupal that you're using) and make sure your server is correctly configured before proceeding.

Here is a summary of common steps/issues:

With Apache HTTPD as web-server, you have to enable mod_rewrite and configure the necessary rewrite rules in the .htaccess file.
Usually, theses rules are applied automatically, when mod_rewrite is enabled. But in some cases, the AllowOverride directive is too restrictive to allow this.


accessing block type in the theme_preprocess_node() I have a block which include a view which is based on node.tpl.php, and I want to change the mark up in the node.tpl.php file just for a specified block.

function theme_preprocess_node(&$variables) {
  $block = unknown_way_to_get_it();
  if ($block->region == "product_stream") {
    $variables['theme_hook_suggestions'][] = 'node__productstream';
  }
}

How do I get a block from the preprocess function?

You can't get access to a block object from a node preprocess hook; the context simply isn't passed down the chain.

As you're using a view, though, you can get hold of the View object, and test the name/display id. The basic idea would be:

function theme_preprocess_node(&$variables) {
  if (!empty($variables['view'])) {
    if ($variables['view']->name == 'some_view' && $variables['view']-> current_display == 'block_1') {
      $variables['theme_hook_suggestions'][] = 'node__productstream';
    }
  }
}


hook_ENTITY_TYPE_view() only fires once on cache rebuild? When implementing hook_ENTITY_TYPE_view() for nodes, I notice the following behaviour:

Cache rebuild
Navigate to node/1 // Message 'Node viewed!' displays
Navigate to node/2 // Message 'Node viewed!' displays
Navigate to node/1 // No message
Navigate to node/2 // No message
Cache rebuild
Navigate to node/1 // Message 'Node viewed!' displays

My code:

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function sitelog_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
    drupal_set_message(t('Test result: @result', array('@result' => 'Node viewed!')));
}

Is this the intended behaviour (it doesn't fire every time an entity is viewed) of hook_ENTITY_TYPE_view()?

Yes, it is. Entities are render cached. If your output is dynamic/depends on something, you need to provide the necessary cache contexts, use placeholders or something like that.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

If it's just about debugging locally, there is an example.settings.local.php file that has a example lines to disable those caches, but make sure you always test it with enabled caches before deploying.


How to know which name will have my view tpl file? Currently i have a view with the name:

name (String, 21 characters ) home_slideshow_mobile

At the same time this view content is displayed inside a block, which filename (tpl.php) should it have my template file to rewrite the content of this view?

Thanks a lot :)

https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

See the suggestion for views templates.

If You calling a view block in your custom tpl.php use
echo views_embed_view('view_machine_name', 'block_1');
You can find out the display name by clicking the tab and check its name in the address bar of your browser: "#views-tab-block_1" gives you "block_1'.


how to add #states property to an $element of the custom field? i develop a custom field and have some errors on property #states.

The method of using #states in $element is quiet different with the $form.

The code i write is below.

 function cellphonefield_field_widget_form(&$form,&$form_state,$field,$instance,$langcode,$items,$delta,$element)
    {
        $base=$element;

        $element['cellphone']=array(
         '#type' => 'textfield',
         '#title'=>t('Enter your Cell phone Number!'),
         '#description'=>t('System will send you a message '),
         '#default_value'=>isset($items[$delta]['cellphone'])?$items[$delta]['cellphone']:'test for this field',
         '#weight'=>0,
        )+$base;

      $element['send_sms']=array(
         '#type' => 'button',
         '#name'=>'send_sms',
         '#title' => t('validate your cellphone number'),
         '#weight'=>1,
         '#value'=>t('Send the validation code!'),
         '#ajax'=>array(
            'callback'=>'ajax_send_sms_callback_function',
            'wrapper'=>'replace_markup_to_textfield',
            'effect'=>'fade',
            'speed'=>'fast',
            'method'=>'replace',
         ),
         '#states'=>array(
            'disable'=>array(
              ':input[name="profile_main[field_cellphone][und][0][cellphone]"]'=>array('filled'=>TRUE),
            ),
         ),
        );

    $element['validation_fieldset']=array(
    '#type'=>'markup',
    '#weight'=>2,
    '#prefix'=>'
',
    '#suffix'=>'
',
  );

   return $element;
}

No matter what i replace the input name of the #states, it's still not working.

i checked the html form and the code blow

<input type="text" id="edit-profile-main-field-cellphone-und-0-cellphone" name="profile_main[field_cellphone][und][0][cellphone]" value="" size="60" maxlength="128" class="form-text" />

what could the problem be?

drupal_process_states() takes the parameter $elements and contains the example:

array(
  'visible' => array(
    ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  ),
)

Your example is very similar:

array(
  'disable'=>array(
    ':input[name="profile_main[field_cellphone][und][0][cellphone]"]'=>array('filled'=>TRUE),
   ),
 )

But I noticed that 'visible' is an adjective while 'disable' is a verb so I checked the list of available states on the drupal_process_states() documentation and found:

  The following states may be applied to an element:

  enabled
  disabled
  required
  optional
  visible
  invisible
  checked
  unchecked
  expanded
  collapsed

So it looks like your problem boils down to a missing letter 'd' on 'disabled'.


How to get replacement pattern for Search API's fulltext search in global text area header In Drupal 7, I'm currently using the default core search, and a view for node search results. I have a global text to pull in the replacement pattern for the term that were searched for. I get the token by adding the contextual filter Search: Search Terms I am using the replacement pattern %1 as seen in the picture:

Then I put You searched for:  %1  in my global text to display the keywords that were searched for:

This all works great for Drupal core search, but I am not finding a way to do this with the view in Search API? I am using Database Service, and a view built from the database index I created. I have tried to find a field such as keywords for the full text search, but since the view is based off of indexed content, I am not able to get those type of fields added, to make them available for tokens, even via relationships. Maybe there is a better way to build the view?

The problem I was having here is my view that I was trying to build for search API was using a full text search exposed filter rather than a contextual filter. The contextual filter provides the search term title and search term input tokens that are pictured above. The exposed filter will not produce them. Live and learn.
EDIT: There is a bit of a workaround I found but it was an implementation I would not recommend. I was using Drupal core search blocks with Search API view's contextual filters together. I was able to add the contextual filter, get the token, then remove the contextual filter. That somehow allowed the token to work in that context.


Drupal Commerce : Shipping Calculator for Shipping Service In my Product Add page, Seller can select Shipping service. I am using FedEx, USPS and UPS for my website.
Here there would be a link for shipping cost calculation.
By clicking on that link, it would open up a Shipping Calculator window from where Seller can add product dimensions and weight and select from available shipping services. By clicking on submit button, window would be closed and Selected Shipping Service and it's cost would be added into Textbox.

Is there any Shipping Cost calculator available in Drupal ?

I think you're looking for a module that do a very specific behavior, some shipping providers don't offer this option and if they do, maybe the drupal module doesn't implement it yet.

The basics of calculating shipping is knowing what the item measures and weights, for that you've got the modules Physical field and Commerce Physical product. With that you've got a field for dimensions and another one for weight, that would help you communicate with your shipping providers to get a quote before the user goes on with the checkout.

Commerce Fedex module seems to offer integration with the
physical modules mentioned above.
Commerce USPS also claims support for physical modules in the project description page
Commerce UPS also seems to provide physical module support.

Once you've got everything set up and your products have the information needed, you can start filtering out the shipping methods offered for every context and user. Depending on the visual requirement and behaviors you'll need to customize it further, but these collection of modules should provide a basic shipping calculation service.


Change "Passwords match" and "Password Strength" text on signup How do I change the "Password Strength:Weak" and "Passwords Match:no" text on the sign up page. Are there drupal settings for this?

The two sentences are set by Javascript (/modules/user/user.js) so for this you have to use JS too..

$(".password-strength-title").val("Test");

can replace the first one, but for the other it is more complicate. I have to look deeper.

EDIT

The info are here now I don't know if it is possible to do an alter

EDIT

Ok so for doing what you want 2 steps:

function your_module_element_info_alter(&$type){
  $type['password_confirm']['#process'][] = 'your_module_form_process_password_confirm';
}

Then alter the data:

function your_module_form_process_password_confirm($element){
  $element['#attached']['js'][1]['data']['password']['strengthTitle'] = t("Test Title");
  $element['#attached']['js'][1]['data']['password']['confirmTitle'] = t("Test confirm");

  return $element;
}


PHP code to add a link to the configured default home page The default home page of a site can be configured in Home » Administration » Configuration » System » Site information.

I have a node instance (with PHP code text format) and I need to insert a link to the default home page of my site, knowing that it can be reconfigured later. In other words, I can't put a static link, I need to fetch info from Drupal (if possible).

How can I create such a link with a PHP code snippet? Is this possible?

Solution

I got away with:

<?php
    $ttmp = variable_get('site_frontpage', url());
    echo 'Home';
?>

If you mean you want programmatically get the value in your Site Configuration, then this works for me: <?php print variable_get('site_frontpage', url()) ?> although I'm not sure this will work in multilingual environment.


Add field in hook_node_info(); Is it possible to add fields to a node type declared using hook_node_info? Do I have to add the fields separately? If so, what hook would I use for that?

You need to attach the fields separately, they can't be added through hook_node_info(). You would usually do this in a hook_install() function in your module's .install file.

A nice simple example from Drupal core is in the blog module's install file:

function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

The function simply rebuilds the node types (so the newly added type is available), then adds a body field to it using the node_add_body_field() function. This function in itself gives an excellent example of how to create a field, an instance of that field, and then attach it to a content type using the field_create_field() and field_create_instance() functions.

The code isn't that so long so I'll include it here as an example:

function node_add_body_field($type, $label = 'Body') {
  // Add or remove the body field, as needed.
  $field = field_info_field('body');
  $instance = field_info_instance('node', 'body', $type->type);
  if (empty($field)) {
    $field = array(
      'field_name' => 'body',
      'type' => 'text_with_summary',
      'entity_types' => array('node'),
    );
    $field = field_create_field($field);
  }
  if (empty($instance)) {
    $instance = array(
      'field_name' => 'body',
      'entity_type' => 'node',
      'bundle' => $type->type,
      'label' => $label,
      'widget' => array('type' => 'text_textarea_with_summary'),
      'settings' => array('display_summary' => TRUE),
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'text_default',
        ),
        'teaser' => array(
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ),
      ),
    );
    $instance = field_create_instance($instance);
  }
  return $instance;
}


Drag and drop builder This site comes with a nice drag and drop builder for webform. What modules are required to create a builder like this?

The main module to accomplish this is the Form Builder module, which integrates with Webform.  Acquia also uses a similar-but-different module for Drupal Gardens.


Drupal 7 Clean URLs and Image Upload I am currently having problems with uploading images and using clean urls on my website. File permissions are working correctly.

When I upload an image to an article page and then I click refresh to view the page, the image doesn't appear. I check for the image url and an example url would be:

http://example.com/sites/default/files/styles/large/public/field/image/01.jpg

but the image would appear if I modify the url on the address bar to:

http://example.com/?q=sites/default/files/styles/large/public/field/image/01.jpg

I have tried:

turning on and off clean urls (sometimes the images appear, but then they disappear again)
modifying rewrite rules in the the .htaccess file
folder permissions
This happened when I uploaded the site to a server and the url would change, but before uploading the site to the servers and testing it on my computer, the url doesn't change. I am currently thinking that it has something to do with some of the rewrite rules in the .htaccess file.

Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server.
    Server configuration for Clean URLs on a dedicated server, with httpd.conf


How can I translate config entity fields? The question is fairly straight forward. I have several config entities with various fields.

I haven't found a way to translate config entity fields in the Drupal 8 documentation(or maybe I haven't looked hard enough, both are a strong possibility).

You need a schema of the type config_entity.

See for example the one for the node type config entity:

/node/config/schema/node.schema.yml:

node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

Choose for fields you want to make translatable the types label and text. See also D8 How to create custom configurational form translatable?


How to implement just a 'Purchase Order' solution (without Drupal Commerce)? Here is the situation: I need create a content type 'Purchase Order' with just few fields: date, product to buy, quantity, price unit, price total, author. The goal is don't need be finding in the future the SKU of products which we bought before, and in the finish of the year see how many papers or PC we bought. We are small group and I don't believe a complete 'Drupal Commerce' solution will be necessary, just a content type, with views for some basic reports.

I though make some small content type 'Purchase Order' with a entity reference to the product(s) content type but I stuck in the quantity field (and price). The problem come when I referenced the product, add a field to that relationship for the quantity, and later see in a custom view how many times that product was bought (and link the orders). Also, take the price from the related products, multiply by quantity and count the total price.

Some idea for Drupal 7?

Below are 2 possible alternatives (options) for setting up a simple shopping cart without using Drupal Commerce (as in your question) (or Ubercart) modules.
Option 1: A lightweight e-shop
If you're only looking for a simple and lightweight e-commerce solution, then have a look at the Light Shop module. Here is a quote from its project page:

Session-stored basket.
Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
Orders history. For each order will be created a separate node.
There is no dependence on other modules.
Full support for working with anonymous users
Integration with Views.

Option 2: A simple shopping cart
If you're only looking for a shopping cart, then have a looking at the Basic Cart module. Here is a quote from its project page:

Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
Main difference from Ubercart and Commerce:
The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
Features:

The possibility of choosing the content types that can be added to the cart.
The possibility of sending, or not, an email to the customer once an order is placed.
Custom email messages for both the site administrator and the customer, along with the order details.
Order registration and listing in the administration area using Views module.
Integration with Rules module.
A block with the contents of your shopping cart.

Here is a screenshot of it (note the Checkout button also ...):


How to create a view with no data I have a content type with a number of fields, one of which is state (pending/active/complete). Users can also be assigned to a piece of content. Eg Frank is linked to content titled "Blah" with state "active".

I want to create a view that shows users who ARE NOT linked to any content with the state field "active".

So far, I figured I can show a list of users and then using relationships, I pull up and reference the content.

It is easy enough to show users linked to content that has the state field "active", but for the life of me, I cannot figure out how to show users who ARE NOT linked to content with state "active".

Any ideas?

Thank you all.

In the end I added a new field to the user as Jimajamma suggested, which counts the number of state (active) nodes that user has. I used Rules to add and subtract from the number to keep it current. Views then filters, only reporting on users with 0 state (active) nodes.


Provide support for embedding feature I am wondering how can I provide support for embedding feature. Actually in my application when user creates article/content, I need to take option from user that if his content can be embedded via embed code to some other web sites. For that he selects yes, then, system should display embed code in the article page, by using which, other people can embed this article.

Please suggest is their any module in drupal that helps me to achieve this or some tutorial helping me to achieve this will also be useful.

Thanks for your time.

For D6 there is Embed widgets

  Embed widgets allows content such as pages, blocks, views, and nodes
  from your Drupal site to be embedded in external sites (including
  non-Drupal ones).

If its D7 there is Embeddables

  Embeddable provide a method for embed thingies in content.It is a
  pluggable system that currently allows the embedding of nodes and
  blocks.

Found 136 results containing the words: Embed on drupal.org


Is there an error in Drupal with hook_views_post_execute? In D8 I would like to sum a field in a view within a custom module called nvgh.
I choose to use a hook for a start. I'm not sure this will be the good hook anyway.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_post_execute/8.6.x

function nvgh_views_post_execute(ViewExecutable $view) {

  if ($view->total_rows > 12) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

I directly get an error:

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to nvgh_views_post_execute() must be an
  instance of ViewExecutable, instance of Drupal\views\ViewExecutable
  given in nvgh_views_post_execute() (line 96 of
  modules\custom\nvgh\nvgh.module).

a) Is this a bug in Drupal 8?
b) Which hook is common to use for pseudo code like

for each row in view result

count a field
display a message

You have to define the statement of ViewExecutable like use \Drupal\views\ViewExecutable

use \Drupal\views\ViewExecutable;

function nvgh_views_post_execute(ViewExecutable $view) {
  if ($view->total_rows > 12) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}


How are contextual arguments specified explicitly in the URL? The examples in contextual arguments simply call for specifying them with slashes without specifying the name of the filter, but if you wish to apply the second or third filter in the contextual link, what syntax should be used?
eg if there are contextual filters, on field_1, field_2 and field_3 and you want to ignore field_1 and field_2 in the URL, how do you write the URL for field_3 only?

Even if you want to apply only the first filter, but specify it explicitly in the URL, what is the syntax for it?

PS. When contextual fields for different fields are applied are they combined with OR or AND? are they

Contextual filters always use AND operator between them. Unless you use a special module to change it Views Contextual Filters OR.

But there are conditions under which a Contextual filter will show all the results as if it hasn't been applied. This means that it could be seen as if the OR operator is applied.

Contextual filters have two major options in their configuration:

`When the filter value is NOT available`

and

`When the filter value IS available or a default is provided`

Under the former options there is always the Exceptions setting, where the default value is all (you can change it if you think it would be better for UX).

But this means that you can use that expression in the URL as a way to temporarily cancel that Contextual filter, so you can test the others if you have more than one.

field_1_value/all/all

or in your case to ignore the first and the second one:

all/all/field_3_value

To apply the first one only you can use:

field_1_value/all/all

but you could also use

field_1_value

if you have configured the last two Filters to use
Display all results for the specified field or
Provide default value.

There is also the setting Action to take if filter value does not validate under Specify validation criteria where you can choose the option Display all results for the specified field. So you can also use this in combination with other settings, if it makes sense in your specific case.

Setting up a Contextual filter isn't a trivial thing, there are different "paths" that can come out out of a single filter, and you'll get a different set of results.


Is it safe to use $vars['name_raw'] instead of $vars['name']? I ran into an issue with usernames being trimmed in articles. I found a thread here with a fix suggesting to use $vars['name_raw']: https://www.drupal.org/node/854762#comment-7614255. It works.

But I'm wondering if $vars['name_raw'] should be sanitized with check_plain or not before being displayed to the screen. I'm not sure what the difference is between $vars['name'] and $vars['name_raw'] ? I searched and found no clear answer.

For this particular instance you should be fine because usernames already are filtered to a limited set of characters.

Like you assumed *_raw is unfiltered input. So in almost any other circumstance, it should be sanitized in some way before use.