Custom VBO action fails silently / works with AJAX error in Views Admin Here is an action I need to use with VBO:

/*
 * Implements hook_action_info()
 */
function ams_action_info() {
  $action = array(
    'ams_archive_action' => array(
      'type' => 'ams_survey',
      'label' => t('Archive survey'),
      'configurable' => FALSE,
      'triggers' => array('any'),
//      'behavior' => array('changes_property')
    )
  );
  return $action;
}

/*
 * Implements a registered drupal action to set the archive bit on given survey
 */
function ams_archive_action(&$entity, $context = array()) {

  drupal_set_message(print_r($entity, TRUE));
  $entity->archive = 1;
  entity_save('ams_survey', $entity);
}

I selected the action in the list for a Bulk Operations field in a table view for my custom entities 'ams_survey'. The view and operations form look fine but executing the action just reloads the page. If I execute in the preview in view builder admin, I get an error popup starting with "An AJAX HTTP error occurred." but the action is successfully performed.

A block display for this view is being loaded and displayed inside a form callback which is being loaded in a page callback from hook_menu(). I have tried turning off AJAX and turning off views cache with the same result.

The malfunction was due to the VBO form appearing inside another form. I changed the page callback to be a regular function (not form builder) that loads the block view and actions are working.


Custom migrate source plugin, extends FieldableEntity class, has migrate status of [error] No migrations found. Why? I'm writing a migrate source plugin for migrating D7 entityform (entityform module) submissions. If anyone has done this or knows an existing plugin, please let me know.
I am trying to extend the FieldableEntity base class from Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity; because I want to use its getFields() and getFieldValues() methods when I override prepareRow() to include custom fields from my D7 entityform.
My problem is that when my source plugin extends FieldableEntity, drush reports [error]  No migrations found. for my migration. Importantly, however, if my source plugin instead uses the SqlBase class from Drupal\migrate\Plugin\migrate\source\SqlBase, then drush can import all of my entityforms from D7 into D9 contact forms no problem. So it would seem that I am missing something when I try to implement FieldableEntity preventing it from retrieving data for the migration.
Here is my plugin, which shows up fine in drush ms:
<?php

namespace Drupal\mymodule_migrate\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;

/**
 * The 'mymodule_migrate_entityform' source plugin.
 *
 * @MigrateSource(
 *   id = "mymodule_migrate_entityform",
 *   source_module = "mymodule_migrate"
 * )
 */
class Entityform extends FieldableEntity {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('entityform', 'e')
      ->fields('e', [
        'entityform_id',
        'type',
        'created',
        'changed',
        'uid'
      ]);
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return array(
      'entityform_id' => $this->t('The ID of the entityform submission.'),
      'type' => $this->t('The entityform type.'),
      'created' => $this->t('The time that the entityform was submitted.'),
      'changed' => $this->t('Last updated time.'),
      'uid' => $this->t('The {users}.uid who submitted the entityform. If set to 0, this entityform was submitted by an anonymous user.'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['entityform_id']['type'] = 'integer';
    $ids['entityform_id']['alias'] = 'e';
    return $ids;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $entityform_id = $row->getSourceProperty('entityform_id');
    // Get Field API field values.
    foreach ($this->getFields('entityform', 'BUNDLE_MACHINE_NAME') as $field_name => $field) {
      $row->setSourceProperty($field_name, $this->getFieldValues('entityform', $field_name, $entityform_id));
    }
    return parent::prepareRow($row);
  }

}

I use this yml migration definition. My migrate destination is D8/D9 contact_message entity.
id: mymodule_contact_message
label: D8 Contact message migration from D7 entityform submission
source:
  plugin: mymodule_migrate_entityform
process:
  id: entityform_id
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  created: created
  changed: changed
destination:
  plugin: entity:contact_message
  default_bundle: MY_DESTINATION_BUNDLE

As stated above, all of this works great when I use SqlBase in my plugin. But with FieldableEntity drush comes back with [error] No migrations found.

I resolved my problem when I identified a mistake in my @MigrateSource annotation on my plugin. I had included my own custom migration module in the source_module entry of the plugin annotation. Here is what I did wrong:
/**
 * The 'mymodule_migrate_entityform' source plugin.
 *
 * @MigrateSource(
 *   id = "mymodule_migrate_entityform",
 *   source_module = "mymodule_migrate"
 * )
 */

Well I looked at the api docs on source_module

Identifies the system providing the data the source plugin will read.

The source plugin itself determines how the value is used. For example, Migrate Drupal's source plugins expect source_module to be the name of a module that must be installed and enabled in the source database.

It didn't work because source_module was set to my D9 custom migration module, which is obviously not on the D7 source, so the migration just silently gets removed from the list of migrations.
So I simply deleted the annotation line. My working plugin annotation looks like this now, and the plugin extends FieldableEntity and works as I had hoped it would.
/**
 * The 'mymodule_migrate_entityform' source plugin.
 *
 * @MigrateSource(
 *   id = "mymodule_migrate_entityform"
 * )
 */

I hope my plugin here will prove useful to someone migrating from D7 entityform to D8/9 core contact module (with contact_storage contrib module). It works.


How do I get the product ID when I submit the form? How do I get the product ID when I submit the form?

I have http://localhost/drupalcart/product/7?v=7 as URL. I need to get that 7 when I click on Add to cart.

(The form doesn't come from a third-party, but it's something I made.)

Hi guys finally i got the solution to it, all that I need it was the following:

$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

then I got the product id of the product i am checking it


user can not view nodes of custom content type I have created a user with the rights to view, edit and delete nodes of all the content types including some custom content types. On admin / content page it shows the list of contents of all content types except one custom content type.

little edit Its showing the contents of that content type when I am adding the content from that user but not showing the contents of that content type posted as user1

When we try to filter the contents to banner content type it shows no results, when we filter the contents to other content types including some custom content types it shows the filtered list.

I checked the permission for that content type for the user role which was not defined earlier but even after granting the permissions its not showing up.

After defining the permissions I have also rebuild the permission but the result is still the same.

I assume that you just forgot to publish the content. Since the first user has access to every content, he can see unpublished content from the userX, but userX cant see unpublished content created by user1. To change this behavior you could give userX the permission "bypass node access".

For further explanation take a look at the official documentation:

http://api.drupal.org/api/drupal/modules!node!node.module/group/node_access/7

  In determining access rights for a node, node_access() first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. user 1 will always pass this check.

Edit: As mentioned in the comment, although this solution solves the initial answer, in most cases it isn´t good to give the "bypass node access" to a large number of users. In the case which is described in the comment, you should use a more sophisticated module for content pushblishing like the Workflow Module.


How to impose a global maximum limit on two webform number fields? I'm using a webform as an online reservation form.
Apart from the name, email and phone number fields, there are two number fields to ask how many adults and how many children will be attending an event.

The thing is we want to restrict the online reservation to 8 participants (adults and children combined)
For example : It can be 8 adults or 4 adults and 4 children or 6 adults and 2 children etc..

Is there a way to use some sort of rule to impose this ?
thanks

Install the Webform Validationmodule which allows you to easily set rules for fields. So in this case you could add a rule that the number can not go above 8.

You can also use hooks to add your own validation rules in code for more complex formulas like the child and adult combination.


Hidding a form element before printing I want to print only bits of a very big form, my first approach was as follow:

function THEME_preprocess_user_profile(&$variables) {
    global $user;
    $account = user_load($user ->uid);
    $variables['user_edit']  = drupal_get_form('user_profile_form', $account);
    $variables['user_edit']['field_about_me'] = 'invisible';
    .....
    $variables['user_edit']['field_some_filed'] = 'invisible';

}

This does work to hide certain element, the problem is that there is way more elements i want to hide than elements i want to show, so this process can be tedious..

Would anyone think of a better way to do so ?

UPDATE : Ideally i'd like to have a function similar to drupal_get_form, but that instead only return a targeted element.

Thanks a lot

if you want to hide elements the appropiate way is to set the #access attribute on each element to FALSE, using a hook_form_alter()

  '#access'

  Used by: All elements and forms

  Description: Whether the element is
  accessible or not; when FALSE, the
  element is not rendered and the user
  submitted value is not taken into
  consideration.

  Values: TRUE or FALSE.

Source: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#access


What would be the parameters for a services to receive a JSON file? This might be sound like a very foolish question ...

I want to expose a service to receive a JSON file from client side in GET or POST format through which I can send an email. What should be my initial algorithm?

I know I need to implement hook_services_resources() to create a resource for the services.

But I don't get what would be its parameters and what would be there in resource api [].

drupal_json_output($resultsarray);

you will get json data


Creating a view that shows multipule blocks containing content with filtered by differnt taxonomy terms Im looking to create some pages that contain blocks of content based on a separate taxonomy term for each block.

Right now i created a separate block view for each taxonomy term, and added each view into its own block on the block administration page. (http://cs.scottrlarson.com/services)
It works, but I want to have more control over the container of the set of blocks as a whole so I can style the blocks in a flexbox. I wondered if there was a way to create a view that had different blocks filtered by taxonomy terms for each block that way I could set a style name for the container of the blocks allowing me to use flexbox styles.

If anyone has a better way to do this please let me know. Thanks.

You could make a parent block view that has all of the subsequent views as attachment display type.  Or add the other views in the footer of your first view...


How to make sure that /taxonomy/term/24/WHATEVER gives 404? Google found up some weird links on my website and has started indexing stuff like /taxonomy/term/24/WHATEVER. I don't want that.

I also don't want to find all these URLs manually, ideally they will turn up in Google Webmaster's list of broken links and I can fix them using that list.

Unfortunately in the taxonomy term view at PAGE SETTINGS it just says Path: /taxonomy/term/%. Is there a good way to respond 404 on /taxonomy/term/24/WHATEVER addresses?

I've done something similar, but there might be some edge cases where this solution might not be suitable.

You can use hook_taxonomy_term_view() and within that check if the amount of arguments in the URL ($_GET['q']) is more than three.

/**
 * Implements hook_taxonomy_term_view().
 */
function custom_module_taxonomy_term_view($term, $view_mode, $langcode) {
  if (count(arg()) > 3) {
    // This will throw a 404.
    drupal_not_found();
  }
}


Using EntityFieldQuery with Address Field I have a custom content type with a postal_address field provided by the module addressfield. postal_address fields are one field in the custom content type. This one field is comprised of many subfields like: country, name_line, and postal_code.

How can the core function EntityFieldQuery be used to retrieve nodes of my custom content type based on their postal code value (a subfield of the postal_address field)?

Specifically, I do not know what to put in the code below instead of the text: what_goes_here:

$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
  ->propertyCondition( 'status', 1)
  ->propertyCondition( 'type', 'consumer_store' )
  ->fieldCondition( 'what_goes_here', 'value', $postal_codes )
  ->execute();

Although Addressfield can be extended, the standard columns like zip code are normal field columns and live in field storage (see addressfield_field_schema()).

In your case you want the postal_code column:

$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
  ->propertyCondition( 'status', 1)
  ->propertyCondition( 'type', 'consumer_store' )
  ->fieldCondition( 'field_postal_address', 'postal_code', $postal_codes )
  ->execute();


Need help with PHP: Show an image field when video field is empty I have been working with Drupal for some months now but I have not coded anything in it so I need help.

Situation: On my homepage there are 3 rows that contain blog teasers. On the first row the first video (youtube/vimeo) and the first image of the blog is shown. They are all styled responsively and it works fine. I use a view to do this.

What needs to change: When there is a video in the blog, I want to exclude the image.
So Video = No image, No video = Image, No video and No image = just the teaser text (which is always present).

What I have tried: Tried the Views Conditional module. Doesn't work since the replacement variable (example [photo]) does not contain the image itself.

Tried Views If Empty module. The logic works but messes up my CSS in a lot of ways and impossible to make it look like it should.

Solution?: I think that what I need is a PHP part in my View.
I have no experience at all with making this. What I have tried is visible below.
(messes up the homepage).

if (empty($fields[$row->field_alg_video_1]->last_render)) {
          $this->last_render = $fields[$row->field_alb_fotos]->last_render;
        }
        else {
          $this->last_render = '';
        }

I just threw some stuff together from the net. Can anyone help me out? :)

Trust on Views empty field settings :-)

Hide the image and the test field. Configure the video field empty setting telling that should show the image field: use the right token, something like this:

[field_image]

Then configure the image field empty setting with the text field.

So, if there's no vídeo Views will try to show the image field. When rednering the image field Vies will show the image if it's present, or the text field if image is also empty.


Why are all Drupal mails going to spam folder wheter it is reset password mail, account activation e-mail etc.? All the e-mails from my site are going but they are going to spam folder, whether its the Drupal system generated mails like reset password mail, account activation mail etc.
 How can I prevent that?

This is not a technical sure fire solution. There can't be a sure fire answer either, because spam detection algorithms are different, even if the recipient mail server had same software, per-account activity and a lot of factors can be used to decide whether the email is spam or not.

There are some steps I take for every site before going them live.
The obvious one is to not send spam content in first place, but other than the content itself, there are other ways to convince the recipient you are not spamming.

Setup SPF records for your domain. The spec is easy to understand, and there are tools to generate the record too. You need to make sure you only send emails from the correct IP addresses only.
Install MimeMail module. This is probably overlooked, but Drupal default mail class sends emails using php's mail() function directly. Mimemail does this too, but it adds extra headers and better mime information. All modules using drupal_mail to send emails will be instantly compatible with the module.
Think about going to a meeting with a basic dress vs a complete suit.

Mimemail trick is the most effective one I've tested.


How to call a CSV resource I have a decoupled Drupal website and I want to call a REST resource outputing CSV, using the CSV Serialization module. I have also configured REST UI to accept CSV in that particular resource.

I tried sending headers with Content-Type: application/csv, or Content-Type: text/csv, I'm sending _format=csv as a GET parameter, but the only response I'm getting is:

   "No route found that matches ""Content-Type: application/csv"""

What am I doing wrong?

I've found out I also have to send the Accept header:

Accept: text/csv

I'm also sending some parameters on POST and PUT, in JSON format (the resource also accepts JSON for input), so I also send:

Content-Type: application/json

and, on the query string, as mentioned, _format=csv


How to Integrate Non-Gregorian Calendars in Calendar Module? I plan to create a simple event calendar on Drupal 7 that uses the Arabic Calendar (Hijri) instead of Gregorian (western) calendar. Instead of developing a new module, I was wondering if I can use the capabilities of Calendar Module and make it use Hijri Calendar instead of Georgian calendar in views and in the calendar template. The mini-calendar should be Hijri Calendar. No need for Month or Year calendars.

There is a module called Calendar Systems that adds the support of Hijri Calendar to Drupal but I'm not sure how it can be integrated with the Calendar Module or Views.

What are my options?

You can use the latest development snapshot of the Calendar Systems module. It works fine.


Best practice for building modules using classes I'm looking to start building my modules as classes now that lazy/auto-load are in Drupal 7, and I'd love to look at some modules (contrib or core) that are doing a great job of it.

Is there a creative way for integrating a class as hooks? Do I implement each feature as a ctools plugin?

Any passers-by should note that D7 has new files[] declarations in module .info files for auto/lazy-loading classes/interfaces: Writing .info files (Drupal 7.x).

The following is a good read to get the motivations and the constitution (as it were) from the Drupal community Drupal programming from an object-oriented perspective.

A module is not a class by Crell is what you should read first.

The biggest OOP part in Drupal 7 is the new database abstraction layer (designed by the very same Crell and others). That implements many patterns which can and should be re-used.

For example:

Define interfaces for anything that could be switched out, only work against the interface internally. Example: SelectQueryInterface
A single class represents a single "thing". For example SelectQuery is a SELECT query, DatabaseConnection is a connection to the database and so on. See http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Use of inheritance to allow to overide a certain implementation. Most classes in DBTNG can have a driver specific subclass, which is automatically used and included if existing. For example SelectQuery_mysql. How that is done.
Extenders, which are an implementation of the Decorator pattern to add additional functionality to the SelectQuery Class. Extenders can have driver specific subclasses too.

Something that is still controversaly discussed is Information hiding. DBTNG implements that by making class properties protected and disallowing direct access. On the other hand, we have hook_query_alter() and they can be changed almost freely with various by reference getter methods.


How do I access the loaded comment object? I'm trying to access the comment field value in controller. With the following code I'm able to access the particular comment object.

$comment = \Drupal::entityManager()->getStorage('comment')->load($commentID);

When I try print_r for the $comment variable, I can see the fully loaded comment object.

I understand I cannot access the values by traversing the object since the values are protected. I tried $comment->get('subject')->value function, this time its looping and doesn't return any results.

How do I achieve retrieving the value of specific fields associated with comment entity?

It is better to use kint() function of the devel module for debugging entities because you will get also a list of available public methods.

You cannot get all comment fields values by looping them as different fields have different array result structure.

Using $comment = \Drupal::entityTypeManager()->getStorage('comment')->load($commentID) you get full comment object.

$comment->get('comment_body)->value you get comment body value as it uses some text format (eg. full html).

You also can covert comment object to array $comment = $comment->toArray().


Use a CURL to work with sites without api? I have this problem.
I need to programmatically submit forms on multiple sites and receive data
The sites do not use API
This task perfectly solves the CURL.
Is there a solution to this issue Drupal way?
Maybe https://www.drupal.org/project/services?

The Services module provides API endpoints, it doesn't help to make HTTP requests.

All Drupal has natively for making HTTP requests is drupal_http_request(). Personally I'd recommend using a library like Guzzle instead, it's much more pleasing to work with, and has support for submitting forms. Plus it's in core for Drupal 8 so you know it's got the seal of approval.

PHP's DOMDocument should be more than enough to help with processing the response.


switching display suite view modes based on context or user location, show/hide fields based on user location The Drupal 7 site i'm working with needs to have a services directory, each service needs to have a general description and a description for health professionals.

So I've created a new content type and called it service, and create 2 custom fields one for general description and one for the health description.

Now the the general services will create their own menu items (this part is fine), the healthcare ones will need to be available in a sortable list as pictured below

http://i.imgur.com/gPf19.png

Now here's the tricky part.

(I know I could just create 2 content types, one of general and one for healthcare but i'd like to reduce the double handling and maintenance as much as possible - so if there is
a way to have all the data entered in one content type that would be ideal)

Using display suite I can hide one of the fields, and using views I can create the directory listings but the directory listings created by views all just link back to the node.

So far I haven't been able to figure out a way to manipulate which fields are displayed (or even switch between display suite views) based on where the user is in the site.
This could be context, a link, or block on a page, i'm open to anything at this point.

Hopefully this is starting to make sense:

Services Content Type (takes all the data, field 1& field 2)

Viewing Content through general services (/services/service-name/service-item)

Display field 1

Viewing Content through health care (/services/health-care-professionals/service-item)

Hide Field 1

Display Field 2

I was hoping you could give me some pointers, I've looked into using the context module, rules module, even had a thought about having 2 content types and using rules to copy the data from

Content Type 1 Field 2, to Content Type 2 Field 2 upon saving..

I was able to do this using Display Suite Extras, I found this tutorial very useful.

Display Suite Extras has a switch view mode by URL option, if you add ?v=view_name to the end of the url it will render that view. So I created the needed view types and used views to rewrite the URL of the titles to include the url parameter.


I cannot access drupal.org I haven't been able to access drupal.org for the past few days. When using Chrome I get: 'This webpage is not available'.  I have no problems with accessing any other site.

Oddly enough when I use a proxy I have no problem. I've cleared my cache in both IE and chrome but still no luck. I don't believe my IP address has been blacklisted so beyond that I don't know. This is true when I try on my phone too so perhaps it is IP address related?

For what it is worth here is a link to Chromebook help for "This webpage is not available".

Assuming you've typed in the right URL, it looks like Chrome will give you this error message if it thinks the site takes too long to respond.  The help page also suggests:

Clear your cookies.
Adjust your proxy settings

You could also try to use another browser to access the site (both Firefox and MSIE work OK for me).


Best hook to use to save a new node when a node is saved I want programatically create a new node of type B (status message),
immediately after a node of type A (e.g. gallery post) is added (or updated).

Looking at this recipe, I see that I will have to add hook_node_insert inside my module and call node_save to save the new node. But on the comments to the hook_node_insert docs ndvo claims I can't call node_save in the middle of another node_save operation. So what is the best approach to use?

There is no hook which is called AFTER the node is saved. No POST-SAVE hook.

But calling node_save within hook_insert actually works. The warnings were false:

So I ended up with something like:

function MYMODULE_node_insert($node) {
  if ( $node->type == 'blog_post') {
    MYMODULE_insert_statuspost($node);
  }
}

function MYMODULE_insert_statuspost($n) {
  global $user;
  $node = new stdClass();
  $node->title = "New blog post $n->title";
  $node->type = "statuspost";
  node_object_prepare($node); /* Sets some defaults.
     Invokes hook_prepare() and hook_node_prepare(). */
  $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
  $node->body[$node->language][0]['value'] =
    "New blog post: " . l($n->title, "node/$n->nid") . " has been posted");
  $node->uid = $user->uid;
  $node->status = 1; //(1 or 0): published or not
  $node->promote = 0; //(1 or 0): promoted to front page
  $node->comment = 2; // 0 = comments disabled, 1 = read only, 2 = read/write
  $node = node_submit($node); // Prepare node for saving
  node_save($node);
  drupal_set_message( "Status post with nid " . $node->nid . " saved!\n");
}

Here is a full commented code to programatically create a node.


SQL query to count comments for node type I am looking for a SQL query to count all comments for a specific node type. What code should I use to achieve it?

You can use this helper function

function mymodule_get_comment_count_by_node_type($node_type) {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $node_type, '=')
      ->execute();
  $nids = array_keys($result['node']);

  $comments = db_select('comment', 'c')
      ->fields('c', array('cid'))
      ->condition('nid', $nids, 'IN')
      ->execute();
  $comments_count = $comments->rowCount();
  return $comments_count;
}


Set default menu link as default menu? I have sub menu of Main menu.
I need to set 2nd sub menu as default menu, so when user visit a site 2nd sub menu should open.

You can use the following modules

Context : It allows you to highlight a menu item if certain condition has been met.
Menu position : This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

Reference:

Menu Position


How do I remove a system CSS file in a theme? I am trying to remove Drupal CSS files (such as ajax-progress.module.css) from my custom theme YML. Here is what I tried:

name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - core/themes/stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      theme:
        css/components/ajax-progress.module.css: false

Drupal's documentation about that is scarce at best...

Update: another version that also does not work:

name: Mercante
type: theme
description: Tema para o site Mercante.co
core: 8.x
stylesheets-remove:
  - @stable/css/system/components/ajax-progress.module.css
libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false
        /core/themes/stable/css/system/components/autocomplete-loading.module.css: false

You can try with the unset method that drupal provides for css alter hook. Try the following code in your custom module

function hook_css_alter(&$css) {
unset($css[drupal_get_path('module','system').'/system.theme.css']);}


Custom access control in views I have Views page with list of enities. The URL is /admin/group/12/members

There is a route in mymodule.routing.yml:

  mymodule_members_list:
  path: '/admin/group/{id}/members'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\GroupController::access'

The Group entity has field contains group administrator email (field_admin_email)

What I need is to allow administrator to only access a view with group/{id} associated with his email.
(I have only problem with views access - it seems like views override my custom access method)

Solved!

Adding custom access to the Views is very easy:
Just create own views access plugin by extending Drupal\views\Plugin\views\access\AccessPluginBase class.

Then implement custom access logic in access method and new rule should appear in PAGE SETTINGS > Access popup window.


How to allow only certain users access to certain fields of a node? I have product information on my site. Only some users can view pricing for certain suppliers. So each product has a supplier field, which is a node entity reference to an instance of a "supplier" content type.

When User A logs in, who only has access to Products Offered by Supplier B, he must only see the "cost price" of items that he is linked to. This link is currently accomplished using a Profile Field, which is private and set by administrators.

What is the best way to now restricting users based on this relationship. The end result would be that certain users see the full node with the cost price, while others will see everything except the cost price.

How can I get this right?

Install Field Permission module. In this module you can set permission on every filed of content types for different roles.

You can also modify hook_field_display_alter  to check for the user and the field id and see if the user is allowed or not. you should copy this in to your template file.


How to combine several form objects into one? i'm working with Drupal 8 and i want to combine the user form and a node creation form into my custom form.

So i've created the form skeleton :

<?php

namespace Drupal\fritr_register_friterie\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class RegisterFriterieForm.
 *
 * @package Drupal\fritr_register_friterie\Form
 */
class RegisterFriterieForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'register_friterie_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form = [];

//        $form = \Drupal::formBuilder()->getForm();

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {

    }

}

But i don't know how to import the user_profile form and the node creation form of a custom content that i've created in the back office.

I know drupal_get_form('form_id') is replaced in drupal 8 by \Drupal::formBuilder()->getForm(class, parameter);

Maybe it's something like this : \Drupal::formBuilder()->getForm(Drupal\user\Form\UserForm::class);

But i have not find the documentation which show all the locations of form or examples.... And i have not find how to load a node creation form :/

Can you help me please ? Thanks :)

EDIT : i've found how to include my node creation form (but i don't know how to modify my fields... D8 So complex u_u) by :

$type = node_type_load('friterie');
        $node = \Drupal::entityManager()->getStorage('node')->create(array(
          'type' => $type->id(),
        ));

        // OPTIONAL - Set default values for node fields
        // $node->set('field_age', "32") ;
        $node_create_form = \Drupal::service('entity.form_builder')->getForm($node);
        $form['friterie'] = array(
            '#type' => 'markup',
            '#markup' => render($node_create_form),
        );
        return $form;

need to find how to load user_profile form ^^

I've created a working example of a combined form object.
Please read the comments below if you want to understand how it works and the workarounds that were applied.

The gist can be found here

Note: There may still be unforeseen issues with the solution below.

<?php

namespace Drupal\sandbox\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;

class ComboForm extends FormBase {

  /**
   * This constant is used as a key inside the main form state object to gather
   * all the inner form state objects.
   * @const
   * @see getInnerFormState()
   */
  const INNER_FORM_STATE_KEY = 'inner_form_state';

  const MAIN_SUBMIT_BUTTON = 'submit';

  /**
   * @var \Drupal\Core\Form\FormInterface[]
   */
  protected $innerForms = [];

  /**
   * The ComboForm constructor needs to initialize the inner form objects
   * that this form will later use.
   *
   * Because both the user and the node forms are entity forms then an entity
   * object needs to be assigned to them.
   *
   * Because the node entity has bundle, the bundle (type) must be defined
   * before the form is generated.
   *
   * @TODO If the node type is customizable then a custom controller is needed.
   *
   * @TODO should this form allow edits? If so then the form objects should
   *       be assigned with the edited entities.
   */
  public function __construct() {
    $this->innerForms['user'] = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity(User::create());

    $this->innerForms['node'] = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity(Node::create([
        'type' => 'article'
      ]));
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return implode('__', [
      'combo_form',
      $this->innerForms['user']->getFormId(),
      $this->innerForms['node']->getFormId()
    ]);
  }

  /**
   * The build form needs to take care of the following:
   *   - Creating a custom form state object for each inner form (and keep it
   *     inside the main form state.
   *   - Generating a render array for each inner form.
   *   - Handle compatibility issues such as #process array and action elements.
   *
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#process'] = \Drupal::service('element_info')->getInfoProperty('form', '#process', []);
    $form['#process'][] = '::processForm';

    foreach ($this->innerForms as $key => $inner_form_object) {
      $inner_form_state = static::createInnerFormState($form_state, $inner_form_object, $key);

      // By placing the actual inner form inside a container element (such as
      // details) we gain the freedom to alter the wrapper of the inner form
      // with little damage to the render element attributes of the inner form.
      $inner_form = ['#parents' => [$key]];
      $inner_form = $inner_form_object->buildForm($inner_form, $inner_form_state);
      $form[$key] = [
        '#type' => 'details',
        '#title' => $this->t('Inner form: %key', ['%key' => $key]),
        'form' => $inner_form
      ];

      $form[$key]['form']['#type'] = 'container';
      $form[$key]['form']['#theme_wrappers'] = \Drupal::service('element_info')->getInfoProperty('container', '#theme_wrappers', []);
      unset($form[$key]['form']['form_token']);

      // The process array is called from the FormBuilder::doBuildForm method
      // with the form_state object assigned to the this (ComboForm) object.
      // This results in a compatibility issues because these methods should
      // be called on the inner forms (with their assigned FormStates).
      // To resolve this we move the process array in the inner_form_state
      // object.
      if (!empty($form[$key]['form']['#process'])) {
        $inner_form_state->set('#process', $form[$key]['form']['#process']);
        unset($form[$key]['form']['#process']);
      }
      else {
        $inner_form_state->set('#process', []);
      }

      // The actions array causes a UX problem because there should only be a
      // single save button and not multiple.
      // The current solution is to move the #submit callbacks of the submit
      // element to the inner form element root.
      if (!empty($form[$key]['form']['actions'])) {
        if (isset($form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON])) {
          $form[$key]['form']['#submit'] = $form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON]['#submit'];
        }

        unset($form[$key]['form']['actions']);
      }
    }

    // Default action elements.
    $form['actions'] = [
      '#type' => 'actions',
      static::MAIN_SUBMIT_BUTTON => [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => ['::validateForm'],
        '#submit' => ['::submitForm']
      ]
    ];

    return $form;
  }

  /**
   * This method will be called from FormBuilder::doBuildForm during the process
   * stage.
   * In here we call the #process callbacks that were previously removed.
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param array $complete_form
   * @return array
   *   The altered form element.
   *
   * @see \Drupal\Core\Form\FormBuilder::doBuildForm()
   */
  public function processForm(array &$element, FormStateInterface &$form_state, array &$complete_form) {
    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);
      foreach ($inner_form_state->get('#process') as $callback) {
        // The callback format was copied from FormBuilder::doBuildForm().
        $element[$key]['form'] = call_user_func_array($inner_form_state->prepareCallback($callback), array(&$element[$key]['form'], &$inner_form_state, &$complete_form));
      }
    }

    return $element;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormValidatorInterface $form_validator */
    $form_validator = \Drupal::service('form_validator');
    foreach ($this->innerForms as $form_key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $form_key);

      // Pass through both the form elements validation and the form object
      // validation.
      $inner_form->validateForm($form[$form_key]['form'], $inner_form_state);
      $form_validator->validateForm($inner_form->getFormId(), $form[$form_key]['form'], $inner_form_state);

      foreach ($inner_form_state->getErrors() as $error_element_path => $error) {
        $form_state->setErrorByName($form_key . '][' . $error_element_path, $error);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormSubmitterInterface $form_submitter */
    $form_submitter = \Drupal::service('form_submitter');

    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);

      // The form state needs to be set as submitted before executing the
      // doSubmitForm method.
      $inner_form_state->setSubmitted();
      $form_submitter->doSubmitForm($form[$key]['form'], $inner_form_state);
    }
  }

  /**
   * Before returning the innerFormState object, we need to set the
   * complete_form, values and user_input properties from the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function getInnerFormState(FormStateInterface $form_state, $key) {
    /** @var \Drupal\Core\Form\FormStateInterface $inner_form_state */
    $inner_form_state = $form_state->get([static::INNER_FORM_STATE_KEY, $key]);
    $inner_form_state->setCompleteForm($form_state->getCompleteForm());
    $inner_form_state->setValues($form_state->getValues() ? : []);
    $inner_form_state->setUserInput($form_state->getUserInput() ? : []);
    return $inner_form_state;
  }

  /**
   * After the initialization of the inner form state, we need to assign it with
   * the inner form object and set it inside the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param \Drupal\Core\Form\FormInterface $form_object
   *   The inner form object
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function createInnerFormState(FormStateInterface $form_state, FormInterface $form_object, $key) {
    $inner_form_state = new FormState();
    $inner_form_state->setFormObject($form_object);
    $form_state->set([static::INNER_FORM_STATE_KEY, $key], $inner_form_state);
    return $inner_form_state;
  }

}


Imagefield_crop field in custom form? How can I add through the form API an image upload field with the cropping functionality implemented by this module?

http://drupal.org/project/imagefield_crop/

I'm using Drupal 7. I need to implement an image upload field with cropping functionality. If there's another module that does the same job as Image Crop and plays more nicely with the form API, that's fine.

I ended up getting this working by using a module called Form Block and just putting the block containing the node form in the content. For some reason I never figured out, just calling drupal_get_form on that node form just did not work, even with the right node module files included. So, hopefully someone else struggling with this will be able to learn from this question


Get select options for an entityreference field using another field as a contextual filter? I have a Course Offerings vocabulary where each taxonomy term is an educational course.
Users have a multivalued My Courses Entity Reference field referring to the terms of the courses they're enrolled in.
I have a custom content type (Entityform) with two more Entity Reference fields: a Course field and a Student field. The user must first select a course (a Course Offerings taxonomy term), and then select a student (a user).

Here's the kicker: I need to filter the Student select list options based on what the user selected in the Course field.

The Course field select options are generated by a view that returns the current user's My Courses field courses. After the user selects one of their courses, the Student field select options should be generated by a view that uses the course they chose as a contextual filter to return a list of only the users enrolled in that course.

I know how to build the view once I have the contextual filters, but I'm stumped as to how to pass the Course term to the view as a contextual filter. Is this possible?

EDIT FOR CLARIFICATION:

Both the Course and Student fields are Entity Reference fields.
Both use select-list widgets whose options are populated with views Entity Reference displays.
The Course field comes before the Student field on the eform. The intention is that the person filling out the form will first choose the course. Then they'll choose the student from a list of students enrolled in the course they just selected.

I've kept an eye out for a module that does this since the original post, but never came up with anything. I've been using a sort of "one off" solution to do this on a case-by-case basis instead:

In a custom module, implement hook_form_FORM_ID_alter() for the
form with your dynamic fields.
Add #ajax attributes to the first element to trigger and handle
changes to it with AJAX. This will specify the AJAX callback handler
and the HTML ID of the element to be replaced with the AJAX response.
In the ajax callback for that element, use the AJAX-submitted value
to dynamically get the appropriate values for the second value. For
me, this is usually a query of some sort with the submitted value as
a filter.
Update the second field's form element #options attribute with the
dynamic values and return the element.


How to Configure WebForm to Allow Users to Choose Which CiviCRM Campaign to Contribute to? Our non-profit currently has a basic donation page via a CiviCRM Contribution page. We would like to add the ability for the user to select which campaign the contribution is directed to.

The Webform CiviCRM Integration Module seems like a necessary component. When configuring a webform, you may direct the contribution to a pre-existing contribution page, but without the ability to expose this to the user. I also looked at apply the Webform Conditional module, but did not see anything that would lead to my desired outcome.

I appreciate any insights in how to create a donation page which provides the user the option to select CiviCRM campaigns.

You can actually do this without Webform-CiviCRM if you like:

Set up your campaigns in CiviCampaign
Create a new profile to add a field to (or from the Profiles page, click "Fields" beside an existing profile to add a new field there)
Add a new "Campaign" field to the profile you are working in (this will list all active campaigns in the profile)
Add the profile to the Contribution Page in question (note: if you added the field to an existing profile it may already be on the Contrib Page)


Is there a way to selectively export specific relevant configuration into custom modules? I'm learning D8 and gaining familiarity with the configuration management aspects of drush.

All my configuration is exported into my config/sync directory and I cherry picked the relevant files and moved them into a config/install under my custom modules.

However, I'm having trouble when I had to rebuild my site due to some vagrant issues and I came across the following type of errors:

  Unable to install Questions due to unmet dependencies: field.field.node.quiz.field_questions (node.type.quiz), views.view.quizes (node.type.quiz, rest, serialization)

Is there a way to selectively export specific relevant configuration into my custom modules directly?

I would use the awesome features module as a base to export complex configurations that contain multiple dependencies as a base of my new module and then start building my custom functionality. All major distributions are using features module as it saves a lot of time and it is very reliable.


Is it possible to import custom XML files with the Feed Import module? With the feed import module I see that you can import CSV files and RSS feeds. But what about custom XML files that follow our own defined format. Is it possible to tell the Feed Importer to import these files?

Yes it is. You need the Feeds Xpath Parser module


How to track and report which data is used or accessed the most for a site on an internal network? I have a Drupal site set up on Solaris 10.

I made custom PHP file to allow users to pass parameters in URL to retrieve feedback in xml format, and a couple of views to display data in table format.

Is there a way to track which data is used or accessed the most and display it in a report? So I can get rid of the data less frequent used.

Note: The site I built is for internal network, so the outside world doesn't have access to it (and therefor I cannot use Google Analytics).

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for, which also includes hits for paths corresponding to a view, such as the one with path charts/examples/views:

Top pages (table with columns Title, Path and nr of Hits). Here is an example of this report:

Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor). Here is an example of this report:

If you follow any of the "details" links in the example above, you'll get something that looks as in this example:

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. Any visits to a Views related path will be reported in the Recent hits module. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


Ubercart shipments are not entities So I am interested in logging signed, scanned copies of my Ubercart packing slips.  Cool right?  The problem is that Ubercart shipments are not fieldable entities.  Thus I cannot add a file field or even a checkbox to say that I received a signed packing slip.

My plan was to make an entity called 'Signed Packing Slip' with the file field and use entity reference to link it to at least uc_order (because, again I can't link up with Ubercart Shipments because they are not entities).

Can anyone think of a hack or workaround to make this work?  Is there any way to incorporate custom PHP code or database calls through ECK/EntityReference

Migrate to commerce. ;)

I think you'll have to do this the old manual way.

Create your own entity with an image field to store the data.
Hook_form_alter the relevant form to insert your own widget.
Handle form submission, and push the data to it's relevant entity, then hand over form submission to the original handler.


How to modify the existing field in a form? I wanted to modify the existing fields in a form. I tried using hook_form_FORM_ID_alter but I could only add new fields; I could not alter the properties of existing field. I wanted to add ajax properties to some existing fields.

I wanted to alter the content add form which is created by Content Type. I wanted to add an Ajax property to the content creation form. I couldn't figure out a way to add this while creating the content type. Could anyone please help on how to do this? It's very urgent.

This is the DPM for the field.

field_mstyle (Array, 6 elements)

#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 2 characters ) -3
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 18 elements)
    #entity_type (String, 4 characters ) node
    #bundle (String, 12 characters ) pz_main_menu
    #field_name (String, 12 characters ) field_mstyle
    #language (String, 3 characters ) und
    #field_parents (Array, 0 elements)
    #columns (Array, 1 element)
    #title (String, 10 characters ) Menu Style
    #description (String, 0 characters )
    #required (Boolean) FALSE
    #delta (Integer) 0
    #type (String, 6 characters ) select
    #default_value (Array, 1 element)
    #multiple (Boolean) FALSE
    #options (Array, 4 elements)
    #value_key (String, 5 characters ) value
    #element_validate (Array, 1 element)
    #properties (Array, 4 elements)
    #after_build (Array, 1 element)

You'll usually find the elements for fields buried in the form and you'd alter them like so:

$form['field_my_field']['und'][0]['value']['#ajax'] = array(
  // ajax settings
);

I strongly recommend installing the Devel module and using the dpm() function to perform debugging. You can use it to print any variable to the standard message area, and it allows you to inspect arrays and objects.

You could easily find out where abouts in the $form array the fields you're looking for are by including a line like this in your form alter function:

dpm($form);


Services custom resources issues - IIS, MSSQL This really is two issues, but possibly both are related.

Main issue:

I have a custom resource setup in Services, the endpoint seems to be "mostly" working.  The endpoint is api/ada/ and my resource is named "assessment", so when I go to mydomain/api/ada/assessment/retrieve, it works.  I have an arg setup which is the assessmentID to retrieve and I'm returning a json array with just that ID for my test.

When I set the arg source to array('path'=>'0') it works, but the ID value in the json aray is the word 'retrieve'. When I set the path to '1' and go to mydomain/api/ada/assessment/retrieve/1 I get a "Controller not found" error in my console (using Chrome).

Secondary, but possibly related:

I have my custom module info file setup with files[] = includes/my_module.inc  which doesn't seem to work, so my callback in the above has to be in the same file for it to work. When I try to require 'includes/my_module.inc' or do module_load_include(...) it's outputting the file contents onto the screen rather than including them.  I'm certain this is an IIS config issue, but you'd think other modules would be doing this, but it's not, I get no other errors (or this type of output) across the site, though I'm less certain of that.

Anyway, I've setup a work-around using the hook_menu() functionality and setting up an "api" of sorts so I can build out the functionality while I recover from bashing my head on the desk trying to figure this endpoint issue out, but I get the module_load_include(...) error in this method as well, so I'm thinking maybe it's not entirely an issue with the Services Module.

Any help is greatly appreciated!

Link to code

In your case the path should be 'path' => 0, because it is the first argument after the endpoint url. Currently you have 1 and it will look for undefined argument which will end up with an exception.

For more information read services oop to get a better understanding in an OOP way. https://github.com/hugowetterberg/services_oop


Assigning Organic Groups using Feeds We're using Feeds (https://drupal.org/project/feeds) and things are working fine. However, we use Drupal/Acquia Commons. How might we assign Organic Groups to each new node?

After studying up the Feeds module, I what I needed. The Feeds module, set up properly, mapped the organic group of the Feed node to the newly created [Blog] node.

Link: /admin/build/feeds


Custom entity datetime field in calendar I created an entity in a module, using code. I generated skeletons with drupal console generate:entity:content (without bundles), and then added a datetime field to my TestFieldEntityItem.php, in baseFieldDefinitions().

$fields['test_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Test date'))
  ->setDescription(t('Test.'))
  ->setRevisionable(TRUE)
  ->setSettings([
    'datetime_type' => 'date'
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'datetime_default',
    'settings' => [
      'format_type' => 'medium',
    ],
    'weight' => 14,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => 14,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I installed my module, cleared the cache, reinstalled calendar and calendar_datetime modules, but when I try to add a view from a template, like the calendar module suggests, I can't see any template matching my datetime field.

If I create a datetime field on this entity through the UI, it appears in view templates. What am I missing?

Inspecting the calendar code, I found the function that search datetime fields, in ViewsFieldTemplate.php.
This function finds my field, but the field_info does not match isDateField() because of the argument property.

isDateField() wants 'datetime' as argument ID.

protected function isDateField($field_info) {
  if (!empty($field_info['field']['id']) && $field_info['field']['id'] == 'field') {
    if (!empty($field_info['argument']['id']) && $field_info['argument']['id'] == 'date') {
      return TRUE;
    }
  }
  return FALSE;
}

My field_info argument is 'string'.

array (size=7)
  'title' => ...
  'help' => ...
  'field' =>
      'id' => string 'field' (length=5)
  'argument' =>
      'id' => string 'string' (length=6)
  'filter' =>
      'id' => string 'string' (length=6)
  'sort' =>
      'id' => string 'standard' (length=8)
  'entity field' => string 'test_date' (length=4)

So thanks to @4k4 answer, I tried to do the same as the working date field, and I created my own EntityViewsData (I tried hook_views_data_alter() first but the field was not present in input data)

namespace Drupal\kabukis_tests\Entity;
use Drupal\views\EntityViewsData;

class TestEntityViewsData extends EntityViewsData {
  public function getViewsData() {
    $additionalData = [
      'test_date' => [
        'title' => new TranslatableMarkup('Birth date'),
        'help' => new TranslatableMarkup('Birth date'),
        'field' => [ 'id' => 'field' ],
        'argument' => [ 'id' => 'date' ],
        'filter' => [ 'id' => 'date' ],
        'sort' => [ 'id' => 'date' ],
        'entity field' => 'test_date',
      ]
    ];
    $data['test_field_entity_field_data'] = array_merge($data['test_field_entity_field_data'], $additionalData);
    return $data;
  }
}

Now, the field appears in views template list ! However, the generated view is not working, I get the following error :

  \Drupal\calendar\Plugin\views\style\CalendarStyle: A calendar date argument is required when using the calendar style, but it is missing or is not using the default date.

EntityViewsData provides the information for views for entity types, so that they are included in views. For datetime basefields this is not working at the moment, because of this issue https://www.drupal.org/node/2489476. So you need to provide the data in a hook_views_data or by extending EntityViewsData. From the documentation:

  argument: Specifies a handler to make it available to Views as an   argument, or contextual filter as it is known in the UI.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_data/8.3.x

You've mentioned that you have a working example if you use a field configured in UI, so you could try to copy the views data.


Remove a code from core module without modifying it(using hooks?) Referring to my question about the removal of "Add new comment" link from the book page links area, is there a way to remove the code with the help of hooks. I am new to implementing hooks. I have found the solution to the problem, but I need a better way to implement it(maybe by hooks, idk).

Edit
I did face a similar problem when I had to comment out the print $tree from the core book module's book-navigation.tpl.php, as it was printing the tree at the bottom of every node, and I didn't want it that way. I used the tree navigation block in my sidebar to navigate through the tree structure. Is there a quick way to do this?

1) The suggested hook_link_alter() (in your linked question) does not exist in Drupal 7 so it doesn't work like you already found out. On the API page there's hook_node_view_alter() being mentioned which can be used instead. You can implement this specific hook both in a module and your theme's template.php file. To unset the comment link the following should work (updated based on the comment by Ajit):

function myThemeOrModule_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}

If it's not quite right you can try (in your development environment) finding out what to unset by adding the following line inside the function: drupal_set_message('<pre>'.var_export($build['links'], TRUE).'</pre>'); (until you have a better tool available).

2) Overriding template files is handled like paul-m already mentioned by creating a copy of the necessary tpl.php file inside your theme folder and doing all the changes there.

3) If you end up needing to override theme functions then you should create a copy of it inside your theme's template.php file where you can modify it.

Don't forget to clear the caches after adding a new function or template.


Two random blocks displaying different fields from the same node I have a content type with field_1 and field_2. I want to have two blocks displaying different fields from a one random node. I can easily create two random blocks via views module, but they wil not be synchronized. Any ideas?

Define helper function like _random_node_id() which stores generated id in the static variable.
Use this function as an argument in the view.

This function will return a random node id, but called twice on the same page it would return the same id (because it is static).


Nested AJAX calls to a site I've been making this cordova app against this casting agency website, and I've come across this nasty situation where I need to list each user's created nodes. For this purpose, I have created a view with the contextual filter uid and it's taking the uid from the logged user. I also have this fiddle where I am trying to list each user's nodes. However, it's returning empty (2nd ajax call). The weird thing is, it lists the nodes by the logged in user on this URL username is tolga and password is 111222.

The steps I have taken to debug:

Hardcode the username and password.
Hardcode the uid in the 2nd ajax call without deleting the 1st one.
Delete the 1st ajax call.
After deleting the 1st call, hardcode the uid in the 2nd call.
After deleting the 1st call, not pass the uid at all because I have configured the contextual filter to take the uid from the logged in user.

Nothing worked. Am I missing something? Do I need to use something like Services Views?

UPDATE: I tried using Services Views, and I ended up a whole lot of 404: Resource not found messages. Docs for the module and views say different things for path; docs say http://www.example.com/<endpoint-path>/views/<view-name> while the view says to put the path name after the endpoint path (in my case, services)

I found out the hard way that what was not working on jsfiddle.net was actually working on mobile. I wasted my own evening on this issue :S Thanks for all the comments though guys.


Change de default status: Published to Not Published in Publishing Options Is it possible to alter somehow the Publishing Options of the content type so that the default status of the article is Not Published?

I would like to do it in a preprocess function if possible. Thanks.

You can set the default status on /admin/structure/types/manage/YOURCONTENTTYPE in the publishing opitons. Just uncheck "Published".


In Drupal 7, Where is field settings data stored? (Not the field data) I'm trying to update my field's data tables structure manually via phpmyadmin as I cannot modify it via the fields settings page since i have data in them. The thing is, where do I update the "fields settings" to encompass these table structure changes?

Base field data is in field_config, and instance data is in field_config_instance. Rather than modifying them manually, though, you can always use the API:

$field = field_info_field('field_name');
$field['key'] = $new_value;
field_update_field($field);

Or for an instance

$instance = field_info_instance('node', 'field_name', 'article');
$instance['key'] = $new_value;
field_update_instance($instance);

Using the API will clear the appropriate caches, and it's just a better idea than editing the data manually.

Either way, make sure to backup the database first in case something goes horribly wrong :)


How do I enable the browser spell checker in WYSIWYG editor? I want to use the in-browser spell checker within the Drupal 7 WYSIWYG editor, which is currently disabled by default.

I found this post but the settings aren't availble in my Drupal module. When I go to Home » Administration » Configuration » Content authoring there doesn't seem to be a place to enable or turn off the disabled browser spell checker. Thanks for any help!

The Check Spelling plugin is only included with CKEditor Standard and Full by default.

For the CKEditor module spell checking is enabled via the profiles.

Go to Configuration > Content authoring > CKEditor and edit each profile you to to it display on. Then under Editor Appearance drag the appropriate buttons to the "Current toolbar"

If you are using the WYSIWYG module it is also enabled through the profiles.

Go to Configuration > Content authoring > Wysiwyg profiles and edit each profile you want it to display on and check the "Check Spelling" option.

With CKEditor 4 you must enable "Spell check as you type" since the buttons have been merged into one with WYSIWYG.


How to flag or unflag an entity with multiple flags at once? I have a large number of user Flags created. When a user performs certain actions on the website a Rule is triggered Flagging them (based on the action) which in turn provides that user with additional access and other privileges. When the user performs an exceptional action on the website the user is Flagged with several Flags all at once, providing them with multiple privileges all at once.

The reason I am using Flags instead of Roles is because there is quite a large number of actions that can be performed on the website; and trying to manage the permissions for such a huge amount or Roles is not only unwieldy but it takes up unnecessary database space, which Flags do not.

So the question then: Is there a way in Rules to Flag a user with multiple flags all at once? For example fetching a list of all Flags based on a Flag property, and then setting all of the flags in this list to "Flagged" for the specific user? At the moment I am setting a single Rules action for every single Flag that needs to Flag the user under certain conditions. This works but is very time consuming. If there is a better to way achieve this without Flags I am open to that as well.

Is there a way in Rules to Flag a user with multiple flags all at once? For example fetching a list of all Flags based on a Flag property, and then setting all of the flags in this list to "Flagged" for the specific user?

Yes there a way in Rules to Flag a user with multiple flags all at once (as in your question), and maybe even by some kind of fetching as you described. However, you can for sure use the Conditional Rules module to flag a user  with multiple flags all at once. Here is a sample rule to illustrate how such rule would look like:

{ "rules_flag_a_user_with_multiple_flags" : {
    "LABEL" : "Flag a user with multiple flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_superuser" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT flag_flagged_user" : {
                "flag" : "follow",
                "user" : [ "flagged-user" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_flaguser" : {
                  "flag" : "follow",
                  "user" : [ "flagged-user" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "NOT flag_flagged_user" : {
                "flag" : "friend",
                "user" : [ "flagged-user" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_flaguser" : {
                  "flag" : "friend",
                  "user" : [ "flagged-user" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Some details about the above rule, which uses flags with machine names superuser, follow and friend:

Rules Event: A user has been flagged, as "superuser".
Rules Actions:

If the flagged user is NOT flagged with flag "follow", by the flagging user, Then flag the flagged user, with flag "follow", by the flagging user.
If the flagged user is NOT flagged with flag "friend", by the flagging user, Then flag the flagged user, with flag "friend", by the flagging user.

If you adapt the machine names of the flags to fit your own flag names, you should be able to import it in your own site (provided the Conditional Rules module is enabled also).

So with that, a user that gets flagged with superuser, and which is not yet flagged with follow, will also be flagged with follow. And the similar for the friend flag.

BTW, even though this answer is about entities of type "user", you can use a similar technique for any entity.

Easy, no?

PS: I'm assuming this question is about D7 ...


Display last logon date on profile I have D7 with profile2 how can I display the user last active date (last login date) on the users profile so other users know that they are an active user. It doesn't have to the actual date it can say something like "Active within the last week"

You can implement template_preprocess_user_profile

In your theme's template.php file add:

function MYTHEMENAME_preprocess_user_profile(&$vars) {
  $vars['user_profile']['last_login'] = array(
      '#markup' => t('Last login') . ': ' . format_date($vars['user']->login, 'medium'), // prints the actual last login time using the medium date format
      '#weight' => 99, // defines location
  );
}

Clear the cache and check the user profile page (e.g. /user/1)


How to run cron more often than every hour? I'd like to run cron every 5 minutes, but the UI doesn't offer any increment of time smaller than an hour.  I'm assuming the solution is as simple as

creating a feature module for the setting, and changing the integer to 300 (60 seconds × 5), OR
cracking open the database and changing the value to 300.

Are there any hidden 'gotchas' with either of those approaches (or any reason they'll fail)?  Is there a better way?

You can get really fine-grained control over your cron runs with these modules:

Elyisa cron

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

Ultimate Cron

  The Ultimate Cron handling for Drupal.
  Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

(In no particular order) I've only used Elysia cron before, and only recently at that, but it works well.

Either module will let you use a standard cron rule to define it's frequency, which I think means you can get the granularity down as far as seconds if you need it.

I think the only gotcha is that the more often you run cron (if it has expensive tasks to perform), the more load there will be on your server. Testing and benchmarking are the only real way to solve that one :)


Drupal commerce and big cart I'm using drupal commerce for ecomerce project.  Shopping cart views with 100-200 line_items renders extremely slow - 5-10sec. How to fix it?

This is too vague to really answer well. A View may be slow for any number of reasons, but at a minimum, this View is loading 200 entities and potentially 400 if you're joining to products (or any other entity). You're going to need some pretty aggressive query caching, both at the database level and likely at the Views level, to perform at that scale of carts without having to change the way Drupal Commerce loads / manages cart orders.


How to programmatically create forum topics using entity api? I used this post and this post to get started but I was trying to use only the entity API.

Here is my code. So far the node creation works but I'm not able to save the node under the correct tid.

global $user;
$properties = array(
'type' => 'forum',
'uid' => $user->uid,
'status' => 0
);
$entity = entity_create('node', $properties);
$wrapper = entity_metadata_wrapper('node', $entity);
$wrapper->title = "My new forum topic";
$terms =  taxonomy_get_term_by_name ('General discussion','forums');

//$wrapper->taxonomy = $terms; //Doesnt work
//$wrapper->forum_tid = $terms->tid; //Doesnt work
//$wrapper->taxonomy_forums = $terms->tid; //Doesnt work

$wrapper->save();

$wrapper->taxonomy_forums = reset($terms)->tid; works!! taxonomy_get_term_by_name() returns an array of objects keyed with extra dimension (I think its keyed by the tid). The wrapper's save method will call forum_node_presave($node) but will look in the wrong dimension for the tid if you don't get rid of it.


Adding a webform to a different content type I have an "event" content type.  Now I want to add a Webform to it so that people can request purchasing and availability information.

I checked my event content type in admin/config/content/webform under Webform-enabled content types but how can I now add the form to my existing content?

Your webform is empty. You need add some fields to the webform.
You can add webform to any "event" node.
Try this: go to your_host/node/node_id/webform and you can see wizard for webform elements!


Different content in a block per page I'm using Drupal 8. I have a content type of “course”. Each course should have a “Banner” block in it that we can upload different background images to (per course).

I've created a “custom block type” of Banner and in this block type I have fields for “desktop image file”, “tablet image file” etc. I then created a “block” called Banner that uses this “custom block type" of Banner. Then, I added the block to the top of the “Content region” and set it to display for the course content type only. I can then see the block on the course pages. So far so good...

However, if I alter the text in the block, it changes the text on all pages... how do I configure it so that I can change the text and images I upload per course/page? Thanks in advance! (Hoping the answer doesn't involve installing extra modules).

The trouble with this approach is that there are block definitions and block instances.  A block definition is the code or custom block that defines the block's behavior.

A block instance is what you create when you place a block onto your theme and defined its settings (e.g. nodes to display it on, values for custom fields).

To have different banners for each class using this method you would need to create a different block instance for each class.  (and set the display rules appropriately).

To use a single block, you will need to define a location outside the block that has the needed information.  Probably on your course page.  Then you can use either a view block as mentioned in the comments or write a custom block to pull the info.  If it is only needed on the main course page, you could probably just use a custom content type twig file and add it when the page is rendered.

If you need the block on subpages, e.g. secondary pages of a course, you will probably have to write a custom block that knows how to relate the subpage to the main course page. E.g. get the course information from a course entity reference field on the subpage and then get the banner info from the main course page).

Note that with both views and custom blocks, you will need to define the cache tags appropriately so that the content is cached per page and not overall.


Content types accessible to a role I have a requirement to return a list of content types accessible to a user in JSON format using services module.

I have followed this approach:

Used Content Access Control module to set the access permission to a particular role to which the user belongs.
Set up a custom resource type for the services module to send the content list in JSON format.
Implemented oauth to authorize the request.
I could send all the content types present in the drupal setup using my custom resource for services module.

Now I want to check the permissions as declared by the Content access module for a role to access the content types.

I am a beginner with drupal and php programming. I am just trying to ready a module which communicates with my android client. Any help would be greatly appreciated.

EDIT:

I followed RajeevK's advice to get the list of permissions from the role_permission table (actually I accessed this using phpmyadmin inerface).

But the permissions declared by the content_access module such as view any <content-type> content are not listed in the role_access.

Since I have accepted the answer here, I will spawn a new thread and rephrase this question.

Good. I hope you are using D7.

So lets start with the finding the machine name of the permission which get saved with the user_role when you enable the permission for particular user type.

These are them -

administer services,
get any binary files,
get own binary files,
save file information,
get a system variable,
set a system variable,
perform unlimited index queries.

Get you RID from the table ROLE by searching your NAME.ROLE

Get the list of PERMISSION from table ROLE_PERMISSION by RID.ROLE_PERMISSION

List anywhere and do what you want...

Enjoy :)


"Broken pipe" between Nginx and PHP-FPM On 6th January, I updated my Drupal 8 development system (composer update). The following ls listing shows the modules that were updated.

drwxr-xr-x  7 drupal8 www-data 4096 Jan  6 02:36 checklistapi
drwxr-xr-x  7 drupal8 www-data 4096 Jan  6 02:36 ctools
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:36 quick_node_clone
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:36 workbench_access
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:36 file_checker
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:36 eva
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:36 social_post_linkedin
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:36 term_csv_tree_import
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:35 memcache
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:35 feeds
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:35 easy_breadcrumb
drwxr-xr-x  7 drupal8 www-data 4096 Jan  6 02:35 fontawesome
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:34 term_csv_export_import
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:34 leaflet_more_maps
drwxr-xr-x 11 drupal8 www-data 4096 Jan  6 02:34 devel
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:34 typed_data
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:34 externalauth
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:34 libraries
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:34 social_post_twitter
drwxr-xr-x  4 drupal8 www-data 4096 Jan  6 02:34 auto_entitylabel
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:33 contentimport
drwxr-xr-x 11 drupal8 www-data 4096 Jan  6 02:33 paragraphs
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:33 telephone_validation
drwxr-xr-x  9 drupal8 www-data 4096 Jan  6 02:32 leaflet
drwxr-xr-x  9 drupal8 www-data 4096 Jan  6 02:32 entity_browser
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:32 workflow
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:32 config_update
drwxr-xr-x  5 drupal8 www-data 4096 Jan  6 02:32 entity
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:32 workbench
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:32 unique_field
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:32 entity_reference_display
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:31 ledger
drwxr-xr-x  8 drupal8 www-data 4096 Jan  6 02:31 eu_cookie_compliance
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:31 social_api
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:31 permissions_filter
drwxr-xr-x  3 drupal8 www-data 4096 Jan  6 02:30 social_post
drwxr-xr-x  6 drupal8 www-data 4096 Jan  6 02:30 gdpr_compliance

I then went to bed and carried on working at around 14:20. Since that time I have regular errors of the following kind in my php7.2-fpm.log:

[06-Jan-2019 14:37:21] WARNING: [pool www] child 1263 said into stderr: "There was a problem sending 4325 bytes on socket 5: Broken pipe"
[06-Jan-2019 14:37:22] WARNING: [pool www] child 1263 said into stderr: "There was a problem sending 178 bytes on socket 5: Broken pipe"
[06-Jan-2019 14:40:23] WARNING: [pool www] child 1232 said into stderr: "There was a problem sending 178 bytes on socket 5: Broken pipe"
[06-Jan-2019 14:43:55] WARNING: [pool www] child 6461 said into stderr: "There was a problem sending 178 bytes on socket 5: Broken pipe"

I have only just noticed this now whilst in pursuit of another problem. Does anyone know what might be causing it?

I'm running Drupal 8.6 on Ubuntu 18.04 with Nginx 1.14.0 and PHP 7.2.10 with FPM. The database is Postgresql 10.6.

I thought originally it might be a hardware problem, but the the immediacy of the problem after the Drupal update seems too obvious to ignore.

An year and a half later ...
Looks like it's xdebug: https://bugs.xdebug.org/bug_view_page.php?bug_id=00001401
If you turn debugging on (so something is listening on port 9000), the error goes away.
(Found this while searching for the same problem, so I thought I'd share)


Drupal licensing/reselling I am sure this has been answered somewhere, and I did read the licensing faq but it wasn't 100% clear to me so I thought I'd ask.  I was curious as to the licensing/legal requirements of, well, using Drupal to make money.

Example 1:  You are a free lance web designer.  Business contacts you to have you build them a site.  You meet with the client, discuss their needs, and eventually decide that their best option would be to make a Drupal site for them.  You want to charge them for the initial setup and design, as well as possibly hosting it.

Example 2:  You set yourself up more as a SaaS provider.  People come to your site, click a big "Launch your site" button, pick their monthly plan and then a Drupal instance is generated for them that they can log into and edit just like any other Drupal site.  Possibly includes some custom modules and themes pre-installed.  You provide support and such for these instances.  Kind of like Drupal Gardens.

What are the licensing/legal implications of those two situations? I.e., can you use them? And if so, are there legal restrictions you should be aware of (for example, do you have to put a giant 'Powered by Drupal' on the site, etc)?

The short answer is: Yes, both your examples are OK to use as a business model with Drupal.  There is also no advertising requirement.

For a longer and more comprehensive answer, including the fine print, you'll find it all answered authoritatively in the Drupal licensing faq.  I understand that you've read that, but didn't find it clear enough.  I shall try to expand on it somewhat.

The most important bit is this:

  Drupal and all contributed files hosted on Drupal.org are licensed under the GNU General Public License, version 2 [GPLv2] or later. That means you are free to download, reuse, modify, and distribute any files hosted in Drupal.org's Git repositories under the terms of either the GPL version 2 or version 3, and to run Drupal in combination with any code with any license that is compatible with either versions 2 or 3, such as the Affero General Public License (AGPL) version 3.

GPLv2 basically says that you've free to use the licenced material in any way you like, including commercial use (i.e. where you make money). Unlike some other free software licences (e.g. the BSD license), there is no "advertising" clause, so you don't have to put up any "Powered by Drupal" signs.

However, there is one important legal restriction tied in with GPLv2 you need to be aware of: GPLv2 or later is a so-called "Copyleft" license.

"Copyleft", in brief, means that if you make any materials (i.e. the Drupal core and any custom development you've done to make it a fully functional website) available to a client, the materials must be made available to the client in source form, and under the same [Copyleft] terms (i.e. GPLv2 or later).

However, the requirement that any material you give your client has to be licensed under the same terms may in some situations be a problem.  This means that your client is free to use the licenced material in any way your client like, including modifying and reselling it (also reselling it without giving you a cut of the proceeds).

I should add that usually, this is not a problem.  Your client is probably not a Drupal developer (that's why they hired you), so they if they resold it, they would not have the skills to maintain it.  But it is a real legal implication of GPLv2 or later you should be aware of.

Also, note at GPLv2 or later doesn't say you have to give you client access to the material.  If you include hosting in the package you sell. And in particular, if you sell it as SaaS (your example 2), then no material changes hands and your client don't have access to anything they can resell.

Providing a website as SaaS without giving access to the material is permitted under GPLv2 or later.

Note that the Gnu Affero General Public License version 3 (AGPLv3) requires SaaS providers to give clients access to, and permission to resell, any material the service is based upon.

(AGPLv3 in not used by the Drupal core, but may be used by some contributed modules offered by third parties as it is upstream compatible with GPLv2 or later.  However Drupal.org does not permit contributed modules that is under APGLv3 only to be hosted on Drupal.org)


How can I display a node so that it appears as a regular page When I am using Drupal through the standard user interface, and click on a node title, Drupal will show the content in the main content area and (depending upon permissions and configuration) will add some tabs between the title and the content. If comments are enabled for the node, a comment entry form will appear below the content field.  The tabs and the comment form can be seen in the image below, with the text in red coming from the node fields that resides in the database.

I want to do the same programmatically from the inside of a module.  I.e. I want to pull a node from the database, and then display it so that it looks the same as if I've clicked on its title in the user interface.

Here is a more detailed description of what I want to do: I am writing a module to display a node for the user.  This module have a button ("Get info") that the user may click. When the user clicks the button, it module pulls various data from a number of external sources, does some processing of this data, and stores the results as a new node object in the database (all this already works).

However, I want to show this node object to the user that pushed the button as soon as it has been created (i.e. to avoid having the user click through a link in order to view it). The user experience I am after his that the user clicks on a "Get info"-button, and then automatically is shown the new node that has been created programatically as a result of this click.

The last bit (showing the user the newly created node) does not work.  I am asking for help to get that part of this module right.

So far I've tried to use the following code (suggested here, but later deleted):

$node = node_load($nid);
$elements = node_view($node, 'full');
$full = drupal_render($elements);

This results in the follwing display on the page:

Note that there are no tabs ("View", "Edit", etc.)  between the title and the content, and no comment form below.  The blue "The title" is a hyperlink, i.e. it neccessary for a user to click through that hyperlink to get to a full node view with a comment form.

If its the path name you want different how about simply using Pathauto

If not - for setting the page title u should do a drupal_set_message() with $node->title and disable it in the node object.

I hope this is of some help.

EDIT
Trying to be of help again

  '' However, I want to show this node object to the user that pushed the button as soon as it has been created (i.e. to avoid having the user click through a link in order to view it) ''

If it is one node at a time, since you are creating the node programmatically, how about redirecting the user to the node right after you create/save the new node?


Passing a node field as a contextual filter to a view pane I am trying to pass an contextual filter to a views content pane from a field in my node and have followed the procedure described in this question without success. I see that the OP of that question eventually resorted to a PHP contextual filter as well.

The only difference is that I am using Panelizer rather than Panels. My field is called field_organization_contact_recor. My view works if I test it with legal values for that field in the views UI and gives the correct results in the preview.

I have chosen "from context" and checked that I am passing the correct field in the "Argument input" settings for the views pane. I checked by using firebug to check the field name of the selected option was correct. I get "no results" for my view.

I have also tried setting it up as "Input on pane config". If I do that and pass in a hard-coded value in the pane settings I also get the correct view results in my panels page. On that settings popup there is a prompt "You may use keywords for substitutions." What is the required format of these keywords to pass a field value? I have tried the format shown on the list of built-in contexts on the contexts tab "%node:field_organization_contact_recor". This format doesn't work in my case.

Additional info: This field is CiviCRM contact reference field. Perhaps there is a particular hook that this field type doesn't implement?

I found a straightforward solution for this in a comment in the issue queues:

  Basically there is a Display Mode on each content type for Tokens that can be used to control exactly what is rendered by tokens that are used.

  To enable it per content type, do the following:

  In the actual Content Type itself, got to the "Manage Display" tab.
  Scroll down to the end of the field listing and click the "Custom Display Settings" link.
  Enable (Check) and Save the Token option to enable the Token Display mode.
  Go to that display mode (Grey display mode tabs near the top) and any field settings you do here effect what the tokens render (which is the same ones Panels uses).


Theme developer module crashes the whole site when enabled, how to fix? I'm working on a clean Drupal 7.x installation, downloaded Theme developer and its dependent module simplehtmldom API( another required module for Theme developer) using drush.

I found out that simplehtmldom 7.x-2.x is incompatible; so I removed it, and  Installed  the 7.x-1.12 version using Drush, enabled it, enabled the Theme developer module was available to be enabled. Now the site doesn't work anymore.

All I'm seeing is just some tags like this.

< /> < /> < /> < /> < /> < /> < /> < /> < /> < />

The problem is fixed when I disable the Theme developer module manually with Drush; everything gets back to normal, when I disabled that module.

I've tried to navigate the site using /node/1 and tried to go to the administration panel; all I noticed is that the title of the page (the one appearing on the browser's tab) appears but the content seems to be the same.

How do I solve this issue?

This is a screenshot.

I did manage to get it to work properly … eventually. This is how, on D7 7.5.

Download and install Theme Developer 7x. Do not enable yet.
Download and install SimpleHTMLDom  7.x-1.12. Do not enable yet.
Download SimpleHTMLDom library from
http://sourceforge.net/projects/simplehtmldom]1 and install to
sites/all/libraries, so that your library path is
sites/all/libraries/simplehtmldom/simple_html_dom.php.
Now you can run drush en -y devel_themer and it will automatically
enable the simplehtmldom.

I did notice that my /tmp folder was not giving correct permissions to the /tmp/devel_themer folder, so doing a chmod -R on that fixed the problem.


How can I filter a View by the value (or data) of field? This seams like quite a basic thing but I cannot work out how to do this in Views, since the Views filter criteria has no option to use the data/value from a specific field or token. There is only an option to add a constant value or to expose the field, neither of which are useful in my case.

I have a list of entities which I would like to filter based on the value of a node field; and this value is auto assigned through a default token set in the content type. The field is a plain text field with a date in it, which I would like to use to filter my list of entities to only show the entities created on that particular date.

I have worked out how to do this finally. You need to install the token filter module and then when entering a value for a filter inside Views, you can make the operator "equal to" a token. Meaning, you can filter by the value of a particular field or anything else exposed as a token.


How to design content for sub-pages Just looking for more experienced drupal developers to steer me in the right direction, it's kind of a basic question:

What is the best way to design the content of the pages, as in, I have the page templates done (front/sub-pages), now I have a bunch of informational sub-pages that I have to design the content for. I thought I could just populate them using the wysiwyg editor, but starting to realize that has limitations. So what's the protocol?

thanks

I think you should try Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc.

This is a great tutorial to understand how Display Suite works.

Hope this answer may help you.


How can I make the list of exposed filters hide options with no existing nodes? I'm using Drupal commerce, and I have a "Product Type" select field in the "Accessories" content type. There are 20+ options. In the views page I'm exposing that field, but I want only the options to display that have 1 or more nodes with that option selected. Is that possible?

I am not sure if that can be done with views. Even if it can be done, I am sure it will take a considerable amount of coding and I am not sure if it will be performant enough(might reduce the performance).

This can be done easily with Apache Solr module.

  Faceted search is supported if you use the facet API module. Facets
  will be available for you ranging from content author to taxonomy to
  arbitrary fields.

When you enable facet API with apache solr module, you should get the facets(similar to filters). Facets will be displayed only if there are some results which have the value of the facet in their node.

Note : You will need to set up a Java server to have the Apache Solr running.


retrieving values from a database in drupal 7 I am new to drupal. I am trying to create a function that will retrieve rows from a database and display the results.From the tutorials I have read, I am trying to implement a function I have created but no results are displayed. There's just a whitespace. Where might I be going wrong? Here is my code.

function print_users(){
$query = "SELECT first_name, middle_name, last_name FROM {registered_users}";
$header = array(
array('data' => t('Cell 1'), 'field' => 'first_name', 'sort' => 'ASC'),
array('data' => t('Cell 2'), 'field' => 'middle_name'),
array('data' => t('Cell 3'), 'field' => 'last_name'),
);
$q = db_query($query . tablesort_sql($header));
while ($r = db_fetch_array($q)) {
    $rows[] = $r;
}
print theme('table', $header, $rows);

}

and am calling it as follows via a menu link

 $items['view_users'] = array(
        'title' => "view",
        'description' => 'Viewing service',
        'page callback' => "print_users",
        'access callback' => TRUE,
        'weight' => '2',

);

$select = db_select('registered_users', 'c')
->condition('c.fieldname', $id)  //try the condition if u have anything
->fields('c');

$result = $select->execute();
if($result->rowCount() == 0) return false;

$val = $result->fetch();

for sorting try asc or desc followed by the condition
you can get the answer in google itself