How to set page title of panel page I have a panel page that includes several views. I want to use the title field of one of the views as the page title. So far, I have not been able to figure out how to do this.

I have installed Panel Variant Page Title module. However, I don't seem to have access to the field I want to use. The closes substitution available is %arg:title.

If I use this substitution, the page title is set to the whole URL.

Any ideas about how to accomplish this?

Go to the Panel Configuration page into the Content section. Now choose in the dropdown field "Title type" the value "From pane".

Now select a pane with the view and click on the configuration link of this pane and choose "pane title".

Your Panel shows now the title of your selected pane.


Dynamically enabling checkout panes based on cart contents? I am working on a service booking website and below is a customer scenario:

i) A customer arrives at the site, views the various services and clicks the "make a booking link" for a particular service.

ii) They are redirected, a view of all available services of that type (product with time/date field & service_type_id) is then generated.

iii) The customer selects the timeslot suited and clicks on a "Book now" button (overidden "Add to Cart"), the Review page is skipped and they are redirected to the checkout page

On the checkout page I am trying to dynamically add suggested services that compliment their current selection. The problem I am having is how to dynamically add this checkout pane?

Currently I am using rules to detect what service has been added to cart, using entity has the field (service_type_id) & a data comparison to allow me to know what added service type I should suggest. I am trying to use commerce extra panes to create and display the content.

I am just wondering what is the best way to go about dynamically adding panes based on the contents of the cart?

I imagine I will have to write a series of rules that enable/disable checkout panes based on the carts contents but am hoping there is a simpler way to get the functionality I am looking for?

Allowing for the display of extra panes to be integrated with conditionals derived from rules would be a very handy feature for a variety of uses.

Any thoughts/help appreciated.

Kind regards,
Ruairi

You may want to follow this issue:
http://drupal.org/node/1122386

it develops Rules based pane visibility.


Convert a SQL database design to a drupal schema installation file I have a, rather big, application that I would like to integrate into Drupal reusing the current database design / logic.

Is there a tool out there that can help me to build the PHP part of the hook_schema definition taking the current database model or an SQL file with the DB declaration as a starting point ?

From what I know it should be pretty trivial to convert a SQL file to a PHPish definition compatible with drupal.

The utility should convert SQL types to Drupal types and declare primary keys, unique keys and index ala drupal.

I knew of a few possabilities, only 2 may work. I haven't tried:

dbtng_migrator - migrates a drupal db to different DBMS engines at will. no schema export support.

Data - module to move data into and out of drupal databases.

  The Data module provides

  an API for dynamically allocating tables for single-row records. an
  API for insert/update/delete operations and describing how tables join
  to each other. automatic views integration. a way to export table
  definitions to code.

Schema - drush dl schema Includes the following functionality not found in Core:

  Schema structure generation: the module examines the live database and
  creates Schema API data structures for all tables that match the live
  database.

I have a drupal DB with other database connections defined in settings.php. You can go into Schema settings and tell to look at any named database connection (by default drupal is default). Here I select dew_remote_sources -- a "remote" (non drupal) database of data. The inspect tab then lists the SchemaAPI hook_schema defintion for each table with dummy comments to fillin.

Lastly views_schema is pretty cool. It creates the hook_views_data for drupal tables based on their schema api definition.

Honestly I dont think you looked at @4Life answer close enough because given a db connection string, Schema does what you want.


how to make cron run once at specific time per day? I want the cron run only once at say 01:00 hours after midnight, just to save shared hosting resources as cron empties the caches. My new site is using too much of resources and I'm trying my best to stick with shared hosting. I want to set cron run once in a day. It should run at midnight so that some cache is built before day time, when traffic is high.

I've only two somewhat related threads: make sure hook cron is only run once a day setting
and
How to run cron more often than every hour?

But for such simple thing it don't want to use Elysia module.

From this post: How do I get the (date)timestamp since last cron run? I understand if we manually set cron_last variable then may be next cron time will be calculated with respect to this.

Another way I can do is to run drush cron from a script from crontab which will run it at a particular time. Similarly we can call cron from crontab ( as in here).

I'd want it to be done from within a module etc so that whenever I move my site, it'll work at any new setup without doing any configuration.

Any suggestions?

I think you've covered the options well in your question.  However, your combinaton of requirements - i.e.:

no poking of cron.php from crontab;
settings kept in database to be migrated along with the site ("done from within a module");
the management module must not be Elysia.

is a problem. This combination excludes all the possible answers. There is no solution that will satisfy all three requirements.

If you want to use a module, that module is Elysia cron.

You seem to think Elysia cron is overkill for this.  I happen to agree.  Besides, Elysia does not work too well when triggered by the built-in default poorman's cron.  You really want to use an external crontab poke together with Elysia to get the type of fine-grained control you seem to be after, with Elysia.

So while your first requirement rules out poking of cron.php from crontab, that is my suggested solution.

Actually, since the crontab entries for all your sites can be kept in a single file on a single server, I do not see how this set-up should be considered too difficult to maintain.


Using hook_mail_alter() for pending approval admin does not make any effect I want to disable the emails sent to admins when a new user account is being created, Account details for (user name) at site name. (pending admin approval).

I tried adding the piece of code in the hook_mail_alter function but that does not give me any change. Below is the code change that i made

function hook_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {
    if ($message['id'] == 'modulename_register_pending_approval_admin') {
      $message['send'] = FALSE;
      return;
    }

    if (!example_notifications_optin($message['to'], $message['id'])) {
      // The usual code for sending mails.
    }
  }
}

Please let me know how can i disable the emails sent to admins.
I could not find any place where I can disable the email functionality from the UI end.

The emails are being sent because in admin/config/people/accounts the option Visitors, but administrator approval is required is selected for Who can register an account.

If you selected Visitors or Administrator only no email would be sent.

In the case you wanted to just avoid emails where sent to the administrators, but still wanted the administrator users to approve accounts, then the implementation of hook_mail_alter() should look for messages whose ID ($message['id']) is equal to user_register_pending_approval_admin_. Also, the example in the documentation of hooks don't show the correct name a hook implemented by a module should have: Always replace hook_ with the short name of the module implementing the hook.


How do I embed an "EVA" view display in a twig template? I installed the "Twig Tweak" module for Drupal 8

I created an "EVA" display. The view id is "contenu_relation_groupe" and the display id is "entity_view_1".

I added the following in the twig template for my nodes:

{{ drupal_view('contenu_relation_groupe', 'entity_view_1') }}

But nothing is displayed. Any idea why?

I've never managed to embed an "EVA" view in a twig template.

EVAs get added as a field with name like VIEW_ID_DISPLAY_ID. They should appear in the content variable like any other field.

If you've added your EVA to the node's display you should be able to render your EVA, with the configuration from the Manage Display screen, like

{{ content.contenu_relation_groupe_entity_view_1 }}.


twig to print paragraph field in controller new to d8. I have a result page where I need to print the field values of a paragraph field into my controller. The paragraph field is called field_classrooms.

text values print fine for example
{{ teacher.field_last_name.value }}

but when I need to print
{{ teacher.field_classrooms.value }}

I get

  User error: "target_id" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

You have to get the paragraph entity with .entity

{{ teacher.field_classrooms.entity.field_in_paragraph.value }}

where you can get the fields inside of the paragraph.


hook_form_alter() adding ajax event I have a custom module that is adding a new field in the form in hook_form_alter().

In my hook_form_alter() I have

function mymod_form_alter(&$form, &$form_state, $form_id) {
     $form['complaint']['complaint_category'] = array(
        '#type' => 'select',
        '#title' => t('Complaint'),
        '#options' => myfuc(),
        '#required' => TRUE,
        '#empty_option' => t('Choose complaint category'),
        '#default_value' => $selected_complaint_category,
        '#ajax' => array(
          'callback' => 'mymod_complaint_dependent_dropdown_callback',
          'wrapper' => 'dropdown-complaint-remark',
        ),
      );
}

If I add a break point in my code in the function mymod_complaint_dependent_dropdown_callback() it is not triggered. Another element in the form has a #ajaxsetting and a break point on it works.

In the UI no spinner is added to the page. So it looks to me like the ajax event is not being registered. Any ideas?

You could try adding an 'event' item to the ajax array in your FAPI code. The form needs to know when to trigger the ajax callback. The FAPI documentation says you don't have to specify it explicitly but try 'event' => 'change', and see if that works for you. Since you are not specifying it, perhaps the default one that Drupal uses is not right for a select type.

See https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#ajax_event


Publish content on user unblock event Drupal 7 I know that this is most probably and easy question but I simply can't get it to work. I have a custom module which generates a form to create a content (unpublished) of a certain type and also register the anonymous user creating that content with a username and password.

I am using the User verification module  to send a validation mail, and when the client clicks the link the account is unblocked.

I want a rule (I tried using the Rules module) to publish the content when the account is unblocked or validated (i need it to work on one of these to events) , but I can't find either of these events, nor can I manage to set the data selector to publish that specific content when setting the action to publish content.

If anyone can explain to me what I am missing or doing wrong it would help me a lot.

In your custom module you could use a hook_user_update and if the $account->original->status == 0 & $account->status == 1 (meaning that the user just got active [untested]), publish the content.

something like:

<?php
/**
 * Implementation of hook_user_update()
 */
function MODULE_user_update(&$edit, $account, $category) {
  if($account->status && $account->status != $account->original->status) {
    // with the user id you can find (i suppose) the content this user has just
    // created and publish it, using something like the link below
  }
}

publish-unpublish


Add a node as a select list in Webforms Drupal 6? I want to make a Webform in Drupal 6 where I can put a <select> list where the lists are a node. I already created a content type which is events and these events expires. So what I want is when the user submits a form he/she has the ability to select from the <select> list so when the form is submitted, when I go to the submission results, I can see the content type(events) which the user chose upon submitting the webform. Is this possible? Thanks

If you are using D6 then consider the Webform View Reference Component module. Here is a quote about it (from the module's project page):

  ... adds a webform component where you could use a View as a datasource for your normal webform select component. Instead of hardcoding all the selectable values in the component values field you just select a reference to a View similar to the CCK nodereference. The selectlist/radiobuttons/checkbox then automatically gets filled with all the nodes from the View.


Output all instances of a repeating field together I have Paragraphs installed and am creating a content-type which has nested Paragraphs - so there is a Paragraph with a Title Field, a Body Field - this is then nested in a another Paragraph, so that I can have several boxes across the page. So far so good - what I want to learn is to output the fields so I can put them in jQuery UI tabs.

In my template I currently have:

{{ content.field_tab_title }}
{{ content.field_body }}

Which outputs:
Title Body Title Body Title Body etc.

What I need is:
Title Title Title Body Body Body

So that I can put all the titles in li's for jQuery UI. I've tried putting

{% for item in items %} {{ content.field_tab_title }} {% endfor %}

But then nothing comes out at all.

UPDATE
Following Kevin's Suggestions, I've started again with my templates and have now got;

in paragraph--tab.html.twig:

{{ content.field_tab_title }}

{{ content.field_body }}

and in field--paragraph--tab.html.twig:

{% for item in items %}

{{ item.content }}

{% endfor %}

but this is still outputting:

Tab Title - 1

Body Copy 1

Tab Title - 2

Body Copy 2

But what I need is:

Tab Title - 1

Tab Title - 2

Body Copy 1

Body Copy 2

This is going to be tricky, but you will need to think through the rendering layers via twig and work inside out.

Example, if you need all field tab titles in li's, the twig for field tab title (field--field-tab-title.html.twig) should look something like this:

{% for item for items %}

{{ item }}

{% endfor %}

In your Paragraph field twig, you would put the wrappers as needed, like:

  {{ content.field_tab_title }}
  {{ content.field_tab_body }}

The same applies to Body:

{% for item for items %}

{{ item }}

{% endfor %}

Here is a similar example perhaps you can follow. This isn't tabbed content, but it is accordion based, so it is similar. Still paragraphs.

Main container (paragraph--component):

  {% block content %}
    {{ content }}
  {% endblock %}

Main accordion paragraph twig, extends the main container (paragraph--component is a custom twig suggestion I made for easier theming):

{% extends 'paragraph--component.html.twig' %}

{% set attributes = attributes.addClass('c-accordion') %}

{% block content %}
  {{ content }}
{% endblock %}

The accordion item itself, containing a title and other fields:

  <input type="checkbox" class="c-accordion__trigger visuallyhidden" id="step-{{ paragraph.id() }}" />

    {% if paragraph.field_accordion_step_title is not empty %}

{{ content.field_accordion_step_title }}

    {% endif %}

{{ content.field_accordion_title }}

{{ content.field_accordion_body }}

When this renders, all X accordion items are rendered the same way into one container. Granted, in my example, the markup container for fields live outside of the field twig and in this twig here, because I chose to have 0 field markup in that project. You can go either way you want.


How do I get a list of bundles? In Drupal 8 how do I programmatically get a list of bundles for an entity type, for example the list of content types. Specifically, I'm looking for the machine names.

To get the bundles for an entity type, use the entity_type.bundle.info service, like this:

\Drupal::service('entity_type.bundle.info')->getBundleInfo('ENTITY_TYPE')

or use dependency injection to inject the service.

See the documentation for getBundleInfo for more information.


How to use hook_menu title arguments Reading hook_menu it says this:

"title": Required. The untranslated title of the menu item.
"title callback": Function to generate the title; defaults to t(). If you require only the raw string to be output, set this to FALSE.
"title arguments": Arguments to send to t() or your custom callback, with path component substitution as described above.

So how to use it? Right now i have this
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title' => 'Get directions to @hotel',
        'title arguments' => array(1),
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

So knowing that default function for title callback is t() how to actually pass the @total wildcard to the t() function?

When you define title arguments as an array, each array element will be passed as arguments in that sequence.

Now you have title arguments defined as array(1), which means the actual call would mimic t('something') if the URL path was custom_gmap_neo/something/something_else/something_else_1.

If you want to call t() function as t('Get directions to @hotel', array('@hotel' => 'something')), you need to define your own title callback, because automatic integer to path argument translations only happen in the root level array elements.

<?php
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title arguments' => array(1),
        'title callback' => 'custom_gmap_neo_get_map_title'
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

function custom_gmap_neo_get_map_title($hotel) {
  return t('Get directions to @hotel', array(
      '@hotel' => $hotel
    ));
}
?>

However, if your first URL argument (hotel) is a node, consider using %node as the path wildcard, because it can load the node for you, and handles page not found errors automatically if node_load returns an empty result. Otherwise you will have to call node_load twice. node_load caches results, but there are many loader functions that do not cache results.


How to customize validation functions for some field? I have the standard node add or edit form.
The edited node has several fields.
How can I customize validation functions for a field ?
For example, I need to switch off or change validation function for some field.
How can I do it ?

In order to add a validation for a entity field and that validation can work in any form you can use entity validation constraints, and add programatic validations.

/**
 * Implements hook_entity_base_field_info_alter().
 */
function foo_entity_base_field_info_alter(array &$fields, EntityTypeInterface $entity_type) {
  // Add Bar constraint to the user name.
  /** @var \Drupal\Core\TypedData\DataDefinitionInterface[] $fields **/
  if ($entity_type->id() == 'user' && !empty($fields['name'])) {
    $fields['name']->addConstraint('Bar');
  }
}


Add field value in the value of another field I'm sorry about the title (I think it's a bit confused :D) I can explain better what I need to do.
I have one product with several fields, among which: title,date, description, price, etc... I would add in a field (for example: description) a value of another field (for example: price). I would also that this setting is applied to content type because that field must always belong to the other field, for every content creation.

I searched on Google and it seems the module Token could be a solution but there are many tutorials (and also different among them), so could you help me. Are appreciated other solution, no just Token.
Thank you

You might find Field reference useful. If you're trying to leverage more functionality, you might like to use Entity reference. But you sound like you want embed the value of one field within the value of another, more like concatenating strings?


How to send an email notification reminder based on a user's date of entry field? The authenticated users on my Drupal website have "Entry date" in their profile (= date when they registered). I want to send out notifications to me (the admin) when a user has been registered on my website since more than 5, 10 or 15 years. So each time a user surpasses for example 5 years of registration time, I get an email notification 1 month in advance.

How can I achieve this?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate date.
Step 1: Create a field to store the reminder date
Similar to that "Entry date" field you already have, add another field to the "user" entity with machine name (say) field_next_reminder. Allow only 1 date (to store the date of the "next" reminder), I don't see any reason why you'd want to make it required (it doesn't matter in the context of this answer). And set its initial value to "5 years after the entry date", using the same procedure you have in place already for that "Entry date".
Step 2: Create a Rules "Component"
Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_be_reminded" : { "label" : "User to be reminded", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : "[site:mail]" ,
          "subject" : "Time flies ...",
          "message" : "This is a reminder about another 5th anniversary for user with eMail id [user-to-be-reminded:mail] on [user-to-be-reminded:field_next_reminder] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other To eMail ID.
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_on_new_user_registration" : {
    "LABEL" : "On new user registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [], "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_reminder" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-reminder",
            "date_offset" : { "value" : 2592000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_be_reminded" : [ "account" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step.
Also note the machine name of field_next_reminder in this rule, which is the field's machine name created in Step 1 (if in step 1 you used another machine name, then also replace the machine name field_next_reminder in this rule with the machine name of the field created in Step 1 (if you don't have such field yet, or the field names don't match, then the import of this rule might not work).
The schedule_delete part of this rule ensures that previously "scheduled" reminders are removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).
Step 4: Add 5 more years to the reminder date
With what's above you should receive such reminder eMails after 5 years. But you also want that to happen after 5 (or 10) years later on (for 10 years or 15 years).
Probably the easiest way to do so, is to have some mechanism in place so that around the time you actually perform some action (to process your reminder), you also add 5 more years to the field_next_reminder. In doing so, the above magic will get triggered again (via that very same rule).
You can apply such update manually (don't forget it though). Or (my preference) you could use the Flag module to implement a designated (global) flag to flag users. And combine this with an extra custom rule with these specs:

Rules Event: User gets flagged (with the designated flag).

Rules Actions:

Do whatever you want to happen to actually send congratulations (or anything like that?) to that user. E.g sending an appropriate eMail, grant user points, grant a special user badge (yearling?).
Update the field_next_reminder (using "set a data value") to add 5 more years for your next reminder.

True, this would be a minor extra effort to get it implemented (it may take up to 5 minutes, say 15 at most ...). But the ROI of doing so would be that authorized users would only have to flag those yearling-type of users (somewhere after they receive the reminder eMail ... in which you could even include a relevant hyperlink to make the magic happen). Even better: you could use this flagging facility to start nagging yourself to not forget to flag that user ... (logic: reminder date is below 30 days, and user is not yet flagged).
Step 5: Further tuning and enhancements

The date_offset (=2592000) in the above rule corresponds to "30 days in advance", which may need review / tuning (it's about 1 month, right?).

You might want to also use the Field Permissions module to set field-level permissions to edit, view and create fields on any entity. In your case maybe you only want admins to edit that reminder field.

5 years is a long time ... remaining homework: what if the user account has been deleted.

Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Step 6: User boarding
With the above solution in place, you have a solution for (a) all future new user accounts that will be created and (b) all existing accounts for which a date is entered (manually?) in that  field_next_reminder field. However you could take advantage of that existing "Entry date" you mentioned, to also get a similar process in place for your existing user accounts, by performing an (one time only) appropriate mass update (bulk) operation. If you wonder how to also get that to work, then use this link.
Note: Using Rules to send an email X days after a user registers also contains quite some details that may help you.


How to check if user has access to node creation page from passed parameter? I have set some users with 'update' access to some books and all other users have only 'view' access. I have used hook_node_view_alter() to remove the 'Add child page' link for users with 'view' only access. The problem this only hides the link from the corresponding node pages, those users are still able to add a child page by manually going to the url: /node/add/child-content-type?parent="mlid" where mlid is the "menu link id" for the parent node. The users might not know particular parent node link id's, however this is a security hole I want to get rid of.

How can I get this passed argument as "?parent=" in a php variable and what hook function should I use to run the condition checks for user access? I am using drupal 7.

After some more internet research and experimentation on my side, I solved the problem.

The passed argument as "?parent=" was acquired using $_GET['parent'].
I programmatically checked if the user has access to create a child with the provided parent using the hook_FORM_ID_alter().


Twig template breaks when adding blocks Here's the issue:

I have a custom content type for the contact page. Twig template: page--node--9.html.twig. When I add blocks to this template, e.g. {{ page.contact-first }}, it breaks. How can I display blocks on it?

The solution was simple: the naming of the regions need to use underscores, not dashes.

In theme.info.yml

regions:
  contact_first: 'Contact (First column)'

In the twig template:

{{ page.contact_first }}


Domain Access and One.com hosting (funny subdomain rewrite) I have a D7 installation that uses Domain Access to distinguish between a main website example.com and a minisite event.example.com. They share the same document root / Drupal installation and the same database. I use Domain Path to have subdomain-specific aliases.

This worked fine, until I decided to move this website to a webspace at One.com. They do this thing were you can create a subdomain just by creating a directory in the document root. So /folder/ can automatically be accesssed in three ways:

http://folder.example.com/
http://example.com/folder/
http://www.example.com/folder/

By default, there is an A wildcard DNS-record for *.example.com.

The relevant part of my /.htaccess currently looks like this:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
  RewriteEngine on

  #strip www.
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  #pass all requests that do not refer to files to index.php
  RewriteCond %{HTTP_HOST} ^(event\.)?example\.com [NC]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]
</IfModule>

This messes up all static files on event.example.com. When http://event.example.com/sites/default/files/css/css_*.css is accessed, Apache tries to find an /event/ directory, which doesn't exist and gives a 404.

I attempted to fix this by symlinking /event/ to /. Now the static files work, but domain paths on event.example.com no longer work (they all give 404s) and links tend to get rewritten to http://event.example.com/event/somelink.

I also tried to fix this by adding the following, but that didn't help.

RewriteCond %{REQUEST_URI} ^/event(.*)$ [NC]
RewriteRule ^ http%{ENV:protossl}://event.example.com%1 [L,R=301]

Any ideas?

It turned out that my symlink from /event/ to / was correct, but that I additionally needed to specify RewriteBase / to fix the link rewriting part.


Create module with custom entity and CRUD Using the Drupal CLI I've generated a D8 module. Now I want to generate a content type with additional fields, for which I can define my own CRUD, forms and other logic. I used drupal generate:entity:bundle
which generates the new content type and makes it possible to add new fields through the admin interface.

I don't want to add fields through the UI; I want to add fields through code, so I can add new logic in the (CRUD) controller. This will be adding fields, defining new views, adding validation etc. I tried to use drupal generate:entity:content, but it doesn't seem to get me anywhere.

How could I do this?

The main purpose of content types/entity bundles is to allow users to configure/create subtypes/bundles of your entity type and add configurable fields to them.

If you want to have two different things, just create two different entity types. Each will have its own table then and its own set of fields. Completely separated.

If you want to have a single entity type/table with different sets of additional fields, then you can for example use entity bundles and just don't expose a UI for them, buy removing all forms, routes and the field_ui_base_route. Then the only way to add per-bundle fields would be through the API/Code.

Or you implement it all yourself using bundleFieldDefinitions(), hook_entity_field_storage_info() and so on. But that would require quite a bit of code as you need to take care of installing the field storage definitions and so on.


DrupalVM ubuntu 14.04 vagrant provision error 'packages cannot be authenticated' I ran vagrant provision and I get this error:

at: apt-get install -y -qq software-properties-common python-software-properties

error message:
WARNING: The following packages cannot be authenticated!
python-software-properties

When I try run sudo apt-get update on the VM I get these errors.

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-backports/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-backports/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.

Note that there is no InRelease file in these directories:

http://us.archive.ubuntu.com/ubuntu/dists/trusty/

http://old-releases.archive.ubuntu.com/ubuntu/dists/trusty/InRelease

I am using:

Host machine:
OS: Ubuntu 16.04 x86_64
vagrant: Vagrant 1.8.5

VM:
box 'geerlingguy/ubuntu1404' (v1.1.3) for provider: virtualbox

config.yml:

vagrant_hostname: iemp.local
vagrant_machine_name: iemp

vagrant_box: geerlingguy/ubuntu1404
php_version: "5.6"
drupal_major_version: 7
drush_version: "7.x"

php_packages:
  - php5
  - php5-apcu
  - php5-mcrypt
  - php5-cli
  - php5-common
  - php5-curl
  - php5-dev
  - php5-fpm
  - php5-gd
  - php5-sqlite
  - php-pear
  - libpcre3-dev
php_conf_paths:
  - /etc/php5/fpm
  - /etc/php5/apache2
  - /etc/php5/cli
php_extension_conf_paths:
  - /etc/php5/fpm/conf.d
  - /etc/php5/apache2/conf.d
  - /etc/php5/cli/conf.d
php_fpm_daemon: php5-fpm
php_fpm_conf_path: "/etc/php5/fpm"
php_fpm_pool_conf_path: "/etc/php5/fpm/pool.d/www.conf"
php_mysql_package: php5-mysql

build_makefile: false
build_composer: false
build_composer_project: false
install_site: false

vagrant_synced_folders:
  - local_path: ./
    destination: /var/www/drupalvm
    type: nfs
    create: true

I ended up reinstalling the host machine, Virtual Box and Vagrant. It seems like I broke something by manually deleting the Virtual Machine via the Virtual Box Admin Interface.

With the new installation and the same configuration it worked perfectly.

I suggest using vagrant destroy to delete your virtual machine files.


Multisites with different database share rules I create two sites with same code and different databases, but when I activate rules in the second site I can see the first site's rules.

I can disable the rules in second site and keep them active in the first, but rules with automatic name (ex. "Email on User Restriction") only appear one time.

Its a problem of my configuration? registry_rebuild.php does not fix.

SOLVED: Problem appear when a sigle site (default) is moved to a multisite (sites/XXX).
SOLUTION: erase rules in the other site don´t erase in the original site.


Omega override simple-layout.tpl.php for content types I have copied the simple-layout files and customized, the custom layout is simply mats2015.simple-layout (mats2015.simple-layout.tpl.php). I need to override this file for a specific content type (plain-page).

Before Omega 4 (and using the layouts extension) I would use the following:

In theme_alpha_preprocess_html(): $variables['theme_hook_suggestions'] = array('html__plain_page_wrapper');
In theme_alpha_preprocess_page(): $variables['theme_hook_suggestions'] = array('html__plain_page');

And, together, those two template files (html_plain_page_wrapper.tpl.php, html__plain_page.tpl.php) would simply render $page['content'] and nothing else.

If, within mats2015.simple-layout.tpl.php I include get_defined_vars() I see this:

'omega_layout' =>
array (size=7)
  'name' => string 'mats2015.simple' (length=15)
  'path' => string 'sites/all/themes/mats2015/layouts/mats2015.simple' (length=49)
  'file' => string 'sites/all/themes/mats2015/layouts/mats2015.simple/mats2015.simple.layout.inc' (length=76)
  'info' =>
    array (size=4)
      'name' => string 'MATS 2015 Simple' (length=16)
      'description' => string 'preview = preview.png' (length=21)
      'template' => string 'mats2015.simple-layout' (length=22)
      'regions' =>
        array (size=11)
          ...
  'theme' => string 'mats2015' (length=8)
  'attached' =>
    array (size=0)
      empty
  'template' => string 'mats2015.simple-layout' (length=22)
  'theme_hook_suggestions' =>
    array (size=0)
      empty

So, the question is: is there a preprocess hook I'm missing that I can use to switch from mats2015.simple.tpl.php to some-other.tpl.php based on content type? Or is there a naming convention for the layout extension files that I'm missing?

Thanks!

So, I was able to accomplish this using the following:

tl;dr: Create another layout extension, and use theme_omega_layout_alter(&$layout) to switch.  That's the preprocess function I had to track down.

(assuming use of included layout *simple-layout* and you want to create a layout for node type plain-page [the naming convention doesn't matter])

Copy themes/_your-theme_/layouts/simple to themes/_your-theme_/layouts/plain.
Modify the file names:

simple.layout.inc -> plain.layout.inc
simple-layout.tpl.php -> plain-layout.tpl.php

Modify plain.layout.inc (It's just like a .info file for a theme, self-explanatory)
Modify plain-layout.tpl.php to suit your needs (In my case, I need to remove everything except render($page['content']).
Open themes/_your-theme_/template.php and add theme_omega_layout_alter(&$layout):

// this is specific to my use case
// change 'theme' to your theme name, as you would with any
// preprocess function
function theme_omega_layout_alter(&$layout) {
  $cPath = current_path();
  if (strpos($cPath, 'invite-print') !== 0) {
    $layout = 'plain';
  }
}

The following is only necessary if you want to change parent structure (<html>, <head>, etc.), which I needed to

Open themes/_your-theme_/preprocess/html.preprocess.inc and put this in:

 // this is specific to my use case
 // change 'theme' to your theme name, as you would with any
 // preprocess function
 function theme_preprocess_html(&$variables) {
   $cPath = current_path();
   if (strpos($cPath, 'invite-print') !== 0) {
     $variables['theme_hook_suggestions'][] = 'html__plain_page';
   }
 }

Create /themes/_your-theme_/templates/html--plain-page.tpl.php and modify as necessary.

It felt like overkill for my situation (having to create entire new layouts) but I understand why it was done - it's crazy powerful for sites that need to make drastically different layouts for different pages.  Think different regions, stylesheets, js, etc - completely different .info files, essentially.

Hope this helps someone!


Views - display node referenced by user profile field Office is content type

User accounts have a Node reference to Office, field_office.

I need to create a view which displays Office->name where Office->nid = Current_User->field_office

I can't believe something this simple is so difficult to setup. I've setup another view where User->field_office = Project->field_office. In that case I created two relationships:

Field: Office
(field_office) Content: Office (field_office) - reverse (to User)

And a Contextual Filter

(field_office) User: Uid

Where the default value is current logged in user's uid.

That was easier since both fields are the same (field_office). But I can't figure out how to link a field to a Content nid.

Update

It would be simple if I could just create a Contextual filter on Content: nid and set the default value to User: field_office. I can't figure out how to do that though. The only contextual filter option which might support that is PHP code, but what would I tell it to return? This doesn't seem to work (breaks AJAX)

$user_data = user_load($user->uid);
return $user_data->field_office['und']['0']['value'];

Figured it out. Had to create a contextual filter on Content: nid and set the default value to PHP code:

$uid = $GLOBALS['user']->uid;
$user_data = user_load($uid);
return $user_data->field_office['und'][0]['nid'];

Really weird that this isn't easier to do.


Migration Group Not showing in UI I am trying to migrate users table from drupal 7 to drupal 8 for that i have created custom migration module and create two file in config/install folder with the following names

custom_migration.migration_group.open.yml
custom_migration.migration.custom_user.yml

and User.php in Plugin/migrate/source for mapping fields.
The following showing content for custom_migration.migration_group.open.yml
id: open
label: Open Migration
description: Custom Migration user table form drupal 7 to drupal 8.
source_type: Drupal 7
source:
  key: drupal_7
dependencies:
  enforced:
    module:
      - custom_migration

Following Content is from custom_migration.migration.custom_user.yml
id: custom_user
label: Custom user migration
migration_group: open
source:
 plugin: custom_user
destination:
 plugin: entity:user
process:
 uid: uid
 name: name
 pass: pass
 mail: mail
 status: status
 created: created
 changed: changed
 access: access
 login: login
 timezone: timezone
 langcode: language
 preferred_langcode: language
 preferred_admin_langcode: language

When i enable the module it should show migration group in Structure->Migration . But it is not showing. Any idea why?

The filenames are wrong - they need to be migrate_plus.migration.*, not custom_migration.migration.*. The first component of a configuration entity filename is the module that defines the entity type, not the module defining the entity instance.


Add class to views row if image fields has content I have views which has multiple image fields. In some cases all those image fields are empty, but some cases one of them has content.

When image field has content I want to have extra class .has-image for views row.

There is image fields: image_field_1, image_field_2 and image_field_3

It can be done programmatically, but I'm lost how to check those fields.
I know this much:

function YOURTHEME_preprocess_views_view_unformatted(&$vars){

SOLUTION

There can not be used $vars['classes_array'][$id][] because $classes_array[$id] is not an array.

Here is code for working solution.

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image) || !empty($row->field_field_image_2) || !empty($row->field_field_image_3)) {
      $vars['classes_array'][$id] .= ' has_field';
    }
    else {
      $vars['classes_array'][$id] .= ' has_no_field';
    }
  }
}

When you use the preprocess function you find the result in

$vars['view']->result

and the corresponding classes array under

$vars['classes_array']

where in results and in classes array the corresponding rows have the same key.

You can do now something like this in your preprocess function:

foreach ($vars['view']->result as $rid => $row) {
  if (isset($row->YOUR_FIELD) && !empty($row->YOUR_FIELD)) {
    $vars['classes_array'][$rid][] = 'has_field';
  }
  else {
    $vars['classes_array'][$rid][] = 'has_no_field';
  }
}

It is untested and just a little scribble but maybe it helps you.


How to insert conditions into Global Custom Text? I am new to drupal and getting hang of it. I have a custom text in one of my view and I need to display the title based on a condition.
This is what I have right now,

 <h1>[title] | [field_annual_number] </h1>

But I need to display this only if the title doesn't contains the work "multi".
So basically, the pseudo code is like this,

if([title].contains('multi')) then <h1> [title] </h1> else <h1> [title] | [ Field_annual_number] </h1>

Any help would be appreciated.
TIA.
Srividhya

Add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder)

function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){

        if (strpos($vars['fields']['title']->content, 'multi') !== false) {
          $vars['fields']['title']->content = "
" . $vars['fields']['title']->content . "
";
        } else {
          $vars['fields']['title']->content = "
" . $vars['fields']['title']->raw . "|" . $vars['fields']['field_annual_number']->raw . "
";
       }

      }

    }

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name

Once you update your template.php file, don't forget to clear/flush your cache in Drupal to see changes.


How to write a db_query with condition on a datefield with enddate - value1 and value2 Trying to do following select query on a node with datefield with endvalue:

  SELECT nid FROM {node}
  WHERE uid = $uid
  AND type = $type
  AND field_mytime(value) > $daystart
  AND field_mytime(value2) < $dayend;

  db_query('SELECT nid FROM {node}
     WHERE uid = :uid AND type = :type AND field_mytime['und'][0]['value'] > :value, field_time['und'] [0]['value2'] < :value2',
    array(':uid' => $u, ':type' => 'mycontenttype', ':value' => $daystart, ':value2' => $dayend))->fetchField();

This do not work of cource:
  field_mytime['und'][0]['value']
  field_mytime['und'][0]['value2']

But what will work? Please help.

Fields are not stored in the node/entity table to which they relate, it would be quite inefficient to do that.

Drupal 7 introduced the new EntityFieldQuery class to help you build up these kinds of queries. I'd recommend reading the docs, but for your purposes the code would look something like this:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type)
  ->propertyCondition('uid', $uid)
  ->fieldCondition('field_mytime', 'value', $daystart, '>')
  ->fieldCondition('field_mytime', 'value2', $dayend, '<');

$results = $query->execute();
if (isset($results['node'])) {
  // Load all node objects based on the results of the query
  $nids = array_keys($results['node']);
  $nodes = node_load_multiple($nids);
}


Show result summary in theme table Can we show the result summary like "Displaying X to Y of Z records" while using the "table" or "tableselect" themes? I mean just the thing we do in views header/footer using the "Global: Result summary" option.

Hope I am clear with the requirement.

On your theme's template.php override the theme_pager function as below.You need to do some HTML customization as per your need.Hope this helps.

function themename_pager(&$variables){

$element = $variables['element'];
global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$pager_current = $pager_page_array[$element] + 1;
$pager_max = $pager_total[$element];
$total_items = $pager_total_items[$element];
$limit = ($pager_limits[$element])?$pager_limits[$element]:10;

$start = ($pager_current-1)*$limit+1;
$end = ($pager_max != $pager_current)?$pager_current*$limit:$total_items;

$text = "$start to $end of $total_items Records";
return $text.theme_pager($variables);
}


How to scrape content from a Drupal Site? I am a victim of Drupageddon on one of my sites and even though I patched Drupal core (maybe not fast enough) recently my Drupal database got completely messed up and my webhoster confirmed there were massive attacks on the Drupal database.

Now, I have the luck that my site still is visible including all content. But I cant login anymore, getting PDOexceptions and so on.

My question is, how to backup the content (nodes) from remote, maybe scraping node by node, field by field? (Reverting to backups before Oct/15 is no option currently, I need all the content.)

Update: The database is a mess, I can not login because of database errors. I need a remote solution. Or maybe I can extract the content from a database dump?

The way I would go about it is:

At .htaccess / nginx.conf level, I'd disable access to site for anyone but my own IP. You know, to be sure.
Directly in database, change email address of user 1 to my own OR restore user table from a backup
Use password restore feature to get admin access
Use whatever module I want to export content (stripping it from any html, js, php if it's there)
Delete site thoroughly from the server
Rebuild it, or restore it from pre-Drupageddon backup
Re-import content.


Populate nodes with XML data via XSLT I have a Drupal 6 website that needs to populate a page with data from an XML feed.  We are considering using XSLT to transform the data into an appropriate format, however in searching the internet for ideas I haven't come up with much.

So far I've found CCK XSLT, which doesn't seem to have much documentation behind it, and Services, which seems to interact only with an XML-RPC server (we would simply be pulling a feed itself, not interacting with a server).

Is there a good way to go about doing this?

(Also, I don't have enough rep to create an XSLT tag.  If some kind user would like to retag for me, I'd appreciate it)

The easiest (though probably not the best), is to do something like:

// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_permission/7

function mymodule_permission ()
{
    return array(
        "view mypage" => array(
            "title" => t("View My Page"),
            "description" => t("View My Page"),
        ),
    );
}

// http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7

function mymodule_menu ()
{
    $items = array();

    $items["mymodule_mypage"] = array(
        "title" => "My Page",
        "page callback" => "_mymodule_generate",
        "access arguments" => array("view mypage"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function _mymodule_generate ()
{
    $path = drupal_get_path('module', 'mymodule');

    drupal_add_css("{$path}/mymodule.css", array(
        "type" => "file",
    ));

    $xsl = new DOMDocument();
    $xsl->load("{$path}/mymodule.xsl");

    $xslt = new XSLTProcessor();
    $xslt->importStyleSheet($xsl);

    $xml = new DOMDocument();
    $xml->load("{$path}/mymodule.xml");

    return (string) $xslt->transformToXML($xml);
}

This is stripped down code I have taken from a custom module I have for displaying a resume maintained in XML format.


Disabling Browse to Library in Media Upload Field I'm on d7.2 with the included Media Module. I'm also using WYSIWYG if that matters at all.

I'm seeing that when a user clicks the image upload field, they have a choice of either 'web' or 'library'.  The Library option shows all files that other users have uploaded to be included in other nodes. How do I disable that so that they don't see all the other files?

I don't use galleries- just upload/attach images to nodes that the users themselves create. Guests and Registered Users BOTH can see the nodes and image files- but I don't want them to have access to all the images that have been uploaded previously.

I think this has something to do with Private/Public, but I can't figure it out. Any input?

This can be accomplished with a module, and this hook:

/**
 * Implements hook_media_browser_plugins_alter().
 */
function my_module_media_browser_plugins_alter(&$plugins) {
  // Hide the "Library" tab on the WYSIWYG media upload widget.
  unset($plugins['library']);
}


Redirecting and removing user role after user account submit I like to redirect my users after they submit their user/edit page.
On their user/edit submit i like to remove a certain role from them as well.
The redirect hasn't been a problem however removing the role is.

In a custom module i have the following code:

  function regform_user_profile_form_submit($form, &$form_state) {
  global $user;
 drupal_goto('user/' . $user->uid);

I am quit a beginner with php and couldn't find any could that fitted in this function properly.
Using rules is not an option as it conflicts with the Oauth module.

Help appreciated,
thanks.

I would try implementing hook_user_presave().

function custom_module_user_presave($edit, $account, $category) {
  $role_position = array_search('undesired_role', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}


drupal CDN module not altering URLs I'm using Drupal 7 on an Ubuntu VPS, I'm trying to setup CDN module with Rackspace cloud files. I'm using file conveyor and the whole setup going well. the only problem I have that Drupal CDN module not altering the files url to use the cdn urls. it still use local files.
- the files already synced to rackspace.
- file conveyor working fine.
- Drupal CDN configured correctly  and it show me that it sees file conveyor working and it's sees the sync file database.

more details about the issue: I'm using multisite setup and I'm using file conveyor with the public files folder.

Any Advice? Thanks

I suspect you have a setting or two wrong.  On admin/config/development/cdn make sure you are enabled, and not in testing mode:

Then goto admin/config/development/cdn/other, expand all of the sections and make sure you aren't excluding actual pages.


Checkbox-Field Tree Menu When creating content, I'd like to have something akin to a drop down menu.  You could hover over an item and a list of checkboxes would appear.  Essentially it'd be a Select List with sub-items.  Is there any easy way to do this?

You can try Hierarchical Select module. Project page says

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.

It will give you a way to select hierarchical items using select boxes.


How to submit form on selecting image in file select widget? I am using Drupal Form API to upload profile image for user.
I found two file upload widgets in FORM API:

'#type' => 'managed_file' &
'#type' => 'file'

managed_file requires first selecting the file, then uploading the file and then submitting the form to change the image

file requires first selecting the file and then submitting the form to change the image

What I want to do is just when you select the image file and click ok in the file browser, the form should get submitted and image should be changed.

Is it possible using FORM API?
If not please recommend an alternative solution.

Of course it is possible. You need to take regular managed file and add some JavaScript to the file selection in it. To see how it is done, please see AutoUpload module:

  This module removes the extra button press and hides the "Upload" button via JavaScript for a quicker, automatic file upload. When JavaScript is not enabled, it falls back to the "Upload" button.

The most interesting is line 9, out of it's 22 lines of code:

$('.form-item input.form-file', context).change(function() {

And maybe simply using this module is all you really need?


RedHen Registration: where is the display settings? I'm using the RedHen module for registration to an event.

I created the registration type and a content type Event that has a field "Registration".
For what I read, when one visualize a instance of a content Event it should appear the fields of the registration type but it isn't. In the description it says that depends on the "display settings" but when I create registration type I didn't see an option like that.

What can be wrong? Thanks in advance.

Well after a break and with my mind a bit clearer.
The display settings don't depend of the registration type, they can be found in "manage display" of the content type (in my case "Event"). Only that no matter what display one choose it will always appear a tab for "registration", but I think this can be manage with the css.


Every five seconds without refresh the new web page How can I on a drupal site do a partial refresh of a page's content with AJAX every 5 second?

Well it totally depends on what you want to refresh. I think what you are probably after though is Block Refresh which will allow you to refresh blocks every x seconds.


Problem with text format and base64 inline images I am using Drupal 8.6.13 text field with Full HTML text format for a field where we want to have content with inline base64 images (due to the synchronization with Gather Content).

Synchronization works well and images content is being saved in a Drupal text field but "data:" part is somehow filtered out - most probably by the Text format filter.

Long text field's source content:

becomes

after saving.

Limit allowed HTML tags and correct faulty HTML is active for Full HTML text format. We need this to limit heading types. If I disable "Limit allowed HTML tags" option then it works as expected.

Allowed tags are:

 <s>

 <button>

Any idea how to prevent data: from being filtered out of the src attribute of an image tag and keep "Limit allowed HTML tags" option active?

I believe I tracked this down. With the filter formatter you mentioned, it calls Xss::filter() on the text.
Xss::filter() looks at the src attribute and will strip any protocol that have not been allowed. It sees anything XYZ: as a protocol, in this case data:.
I added - data to my docroot/sites/default/services.yml filter_protocols value and stopped the data: from being stripped.
I don't know if this opens any other security concerns or not.


Display a View Block multiple times in a region with each view using a different filter Here's a visual representation of what I wanted to happen.

<my-region>

    <article-list-view filter=article-type-1 />

    <article-list-view filter=article-type-2 />

    <article-list-view filter=article-type-3 />

</my-region>

Now I can actually just go ahead and create a separate region and a separate view block for each type of filter but it doesn't look like good design since It's going to be repetitive.

Is my goal doable? If not, what's the common approach to accomplish this task?

Based on what you have described, yes.  It is not only doable, it is quite easy.

You can add different pages, blocks or even attachments.  When you creating/editing a view, click on "Add" then select what you would like.

With an attachment, you can select before, after or both for each attachment.

The key to making this work is to only set criteria for that display only.  In the example below, I am in the "Add Fields" dialog.  If you want a separate filter for this particular page/block/attachment, make sure to select "This Page (Override)"

When you do this, anything in this view will be restricted to this display only.


Look for documentation about how precisely modules parts are loaded (Drupal 7) Developping my custom module, I ran several times into misunderstood issues regarding the precise order used by Drupal when loading parts of a module.
Each time, I finally got rid of it after any disabled and suppressed then recreated, but this is obviously not satisfying.

So I'm now looking for sufficient information to be able to understand what happens in those circumstances.

This time the problem I have is as follows:

Having my module working fine on a site under D-7.34, I upgraded it to D-7.35, following all necessary steps.
After successfully executing update.php (which notified that no update was needed), I clicked to go to front page: this one was properly displayed.
NOTE: necessarily, my module was already involved at this stage, since it works during output rendering (so whatever the path indicated by the URL)
But from there, then, any attempt to access another page (either public or administrative one) fires a PHP error "Call to undefined function myfunction()...", where myfunction() belongs to my module.

I can't figure out how it is possible, since my code schematically looks like:

file: mymodule.module

<?php

module_load_include('inc', 'mymodule', 'mymodule.core');

function mymodule_some_hook() {
    # ...
    myfunction();
    # ...
}

file: mymodule.core

<?php

function myfunction() {
    # ...
}

In other words, in my eyes:

when the error fires, it necessarily means that mymodule.module was loaded, since it is where myfunction() call resides
then if mymodule.module was loaded, it should have first executed module_load_include(), so loading mymodule.core and defining myfunction()

Yet it is clear that, in this case, something is happening differently!

But why this behaviour now, and not at the first access to front page?
And why this behaviour with D-7.35 (where no changes seem to be involved here), and not with D-7.34?

NOTE: I suspected something wrong with caching, so I tried flushing it. But flushing process failed with the same "Call to undefined function".
Then I used directly PhpMyAdmin to truncate all cache tables, without success: behaves the same after that.

Comments greatly welcome, and notably if pointing to any documentation about detailed process of modules load.
Thanks in advance.

After a lot of tests, I'm now pretty convinced that, despite it is not mentioned in the release notes page, a change happened in 7.34, which consists in that, now, the full-bootstrap condition is not reached yet when the MODULE.module file is loaded.

According to module_load_include() page, this function requires Drupal to be fully bootstrapped: this clearly relies to the use of drupal_get_path() (see the function code in this page), which is not available without full-bootstrap.

It is why my (global-scoped) module_load_include() calls are executed but without result (see 'file: mymodule.module' in my question above).

I had to modify my module, including a dedicated module_load_include() call inside each function which needed it, like this:

<?php

function mymodule_some_hook() {
    module_load_include('inc', 'mymodule', 'mymodule.core');
    # ...
    myfunction();
    # ...
}

This way, now all works fine anew.

I verified it is the same with Drupal 7.36: my module doesn't work in its original implementation, then it does with this modification.

Hope this helps.


How do I remove the revision information from a node edit form? I'm hoping someone can help a Drupal beginner removing a view from my page. The purpose of it is a for data collection.

This is the section I am trying to remove:

In your MODULE_form_alter hook add:

$form['revision_information']['#access'] = FALSE;


Bots taking over my site I just noticed that bots have been taking over my Drupal website for quite a few weeks. There are over 600 pages of content. I only noticed now because the website is on hold (still available online) at the moment. I just got a message from the hosting company that the maximum disk space has been reached, which came as a total surprise.

I've tried changing password but it's still uploading. I deleted the Basic page content type because all the content was created with that content type, but now they are using a different content type, and the content is still there even though I thought it would remove all the content when I removed basic page.

How can I stop them from creating content?

In the People config page you can set up who can register accounts. Put that option on Administrators only.
After that identify the bots users and delete them (make sure to delete them, not just disable).
Then, identify content created by bots and delete it.
Also, don't forget to check who can create content on the website (permissions page).


How should I configure the trusted hosts setting? I am trying to add the Trusted Host setting. I copied the code directly from the settings.php file, making sure I removed the * and changed the example to my domain.  Using the first example

$settings['trusted_host_patterns'] = array(
  '^www\.example\.org$',
);

The site would not load....got an error stating domain was disallowed

Today using this code
and

$settings['trusted_host_patterns'] = array(
  '^example\.org$',
  '^.+\.example\.org$',
);

I am getting an unexpected error and the site won't load

This is a new site on a shared host.  It can't be this difficult!  I must be missing something!

I don't know if I was introducing a problem by editing the settings.php off line and then uploading it but decided to edit it with the editor in the file manager on cpanel.  I first changed the permissions on the default folder to 755 and opened the folder.  Then I highlighted the settings file and changed the permissions to 755.  Then I clicked the edit button and located the Trusted Host settings and copied the code.  I then pasted it AT THE END of the settings.php file and made the necessary changes to reflect my domain and saved the file and closed the setting file.  In a different window, I had the website status page loaded and just refreshed it.  IT worked!  I don't know why doing it this way worked (editing the file on the server vs offline and uploading it.) but it did! Then I just change the file permissions back to what they were .


How to bypass HTML mail for specific Webform I have configuration Mailsystem to send all webform emails as HTML, I thought I could use the "key" in mailsystem's configuration to specify which webforms' submissions get sent as HTML or plain text. Unchecking the checkbox on the webform's email handler to say "Send email as HTML" only strips HTML from mail, but the wrapper is still HTML.

While keeping HTML emails for most webform generated emails, how do I configure one to be sent as plain text?

There are two parts to this answer 1) Mailsystem configuration and 2) Mailsystem template suggestions.

1) Mailsystem configuration

This solved the issue for me and I was perhaps being silly:
Go to /admin/config/system/mailsystem and set Mime Mailer as your default config, well I want that as default.

Then below I had webform config for all webforms, but this was overkill as the settings above already made webforms use Mime Mailer, what I needed to do was add an override for this one email handler:

The specific email handler machine name was email so you can see its key is "email_email".

2) Mailsystem template suggestions

Something I learnt while investigating this is that there are template suggestions added by mimemail.module of the following pattern:

$suggestions[] = "mimemail_messages__" . $variables['key'];

So the above webform email, if using mimemail would use a template named mimemail-messages--email-email.html.twig


How to hide Regions and Themes in the block setting admin page? When editing the setting of a block you can specify Themes and Regions where the block is going to be shown.

I need to hide some Region and a Theme for a given role?
Can I do this?

I tried with http://drupal.org/project/block_access but is not useful for this.

it's a bit late but for the people in the same situation :

function MODULE_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == 'block_admin_configure'){
        if(in_array('your_role_name',$user->roles)){
            hide($form['regions']);
            hide($form['visibility']); //for the visibility region
            hide($form['visibility_title']); //for the visibility region
        }
    }
}


Drupal Multisite (subdomain) Not Working Drupal 6, default installation, default .htaccess, default http.conf for Apache.

sites/ directory looked like this:

all
default
subdomain1.maindomain.com

default site and subdomain1 working well.

Added a new directory, subdomain2.maindomain.com. It has the same ownership and permissions as subdomain1.maindomain.com. It contains default.settings.php, the out-of-the-box one, and settings.php, which is a copy of default.settings.php. The permissions and ownership of the two files are correct.

The 'sites' directory now looks like this:

all
default
subdomain1.maindomain.com
subdomain2.maindomain.com

Visiting subdomain2.maindomain.com returns an error. Visiting subdomain2.maindomain.com/install.php returns an error. I can download an example file from  maindomain.com/sites/subdomain2.maindomain.com/files/example.txt when it is located at /sites/subdomain2.maindomain.com/files/example.txt.

Basically, I've followed all the steps in the docs, and I'm unable to create another 'subsite' accessible from a new subdomain. What am I doing wrong? What else should I be doing?

If you want to run several sub-domains on the same code base you need to make sure that either both the sub-domains resolve to the same IP address as your main domain, or that your main domain supports wildcard DNS. You also might consider giving Subdomain module and Domain Access module a try.


Making custom fields available to views module I have gone through tons of reading... I even went into drupal archivess looking for help :(

I have defined my own content types and fields as well as my own db tables.
I want to be able to display these fields using views module in drupal 6.

This is the coding I have done so far:

function svm_mail_views_tables() {
  //Define the groups table
  $table['svm_mail_groups'] = array(
      'name' => 'svm_mail_groups',
      'join' => array(
          'left' => array(
              'table' => 'node',
              'field' => 'nid',
              ),
          'right' => array(
              'field' => 'nid',
              ),
          ),
      'fields' => array(
          'group_id' => array(
              'name' => t('SVM: Group ID'),
              'help' => t('The group id'),
              'sortable' => TRUE,
              ),
          ),
      'sorts' => array(
          'group_id' => array(
              'name' => t('Group ID'),
              'help' => t('The Group ID')
              ),
          ),
      );
  return $table;
}

I still don't have this available in my views module when building a view.

Can anyone help me out here and tell where I'm going wrong?

Thanks in advance.

If you want to add custom database tables in a view, you need to let views know about it by invoking hook_views_data() http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/

There is also documentation for this within the views module.

It looks like you are on the right track but your function name is _tables() instead of _data().


Convert theme from ASP.net-based site to Drupal I'm supposed have to launch a Drupal 6 site within 4-6 weeks. Most of the content is already loaded into Drupal. But I'm having a dilemna about the fastest way to approach theming. Our university web developer is using Sitefinity (ASP.net) while I chose Drupal for our site. He gave me a copy of the unfinished template files a month ago (HTML, CSS, JS, images) which were designed using Blueprint CSS. I have just received  access to the main university site including admin priviledges. Since it is apparent that a lot of the final design was created using a skinning feature in Sitefinity, I downloaded the complete site using WinHTTrack and am trying to cobble together my "interpretation" of the design using the main CSS file done with Blueprint, and the Sitefinity system CSS files. The Sitefinity CSS files have their own layout which is based on percentages. I'm looking at creating either a Zen or Fusion based theme. I've tried removing all the Sitefinity styling and re-building the design from scratch using Blueprint in Dreamweaver.But I'm afraid this is a waste of time. I'd appreciate some advice on how others would approach replicating an ASP.net template for use in Drupal. While not at all familiar with Sitefinity, I did download a copy of all the files from the server in case they could be used to convert the layout to Drupal, although I know PHP and ASP.net themes are nothing like each other. Any strategies would be appreciated.

I don't think there's any tool doing something automatic for you. Just take the ASP.net as as a prototype and start again with a solid base theme like zen.


Does Drupal 7 use a publicly-available function to concatenate text in the "text area with summary" widget? I'd like to make use of functionality similar to the "display summary if filled in, if not display shortened body" that is used by Drupal's text area with summary widget. Is there a publicly available function that will concatenate body text to a certain word length, taking into account that there may be embedded HTML?

The code used to render that field is contained in text_field_formatter_view():

case 'text_summary_or_trimmed':
  foreach ($items as $delta => $item) {
    if (!empty($item['summary'])) {
      $output = _text_sanitize($instance, $langcode, $item, 'summary');
    }
    else {
      $output = _text_sanitize($instance, $langcode, $item, 'value');
      $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
    }
    $element[$delta] = array('#markup' => $output);
  }
  break;

You are interested in how $output is set. _text_sanitize() is a function that you can use to write similar code more specific for your case, while text_summary() is a generic enough function you can use for your own code.

function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}


how to get views field names/values for hook_views_pre_render? I'm trying to figure out how to modify a view's results with hook_views_pre_render.
How do I get the available values to work with?
I've turned on Devel and Kint, but I don't see any array on the page that includes views stuff.

I've tried blindly finding fields using machine names, but it just breaks the page. I'm sure I'm doing the right thing, I have one field field_byline that I'm able to get just fine with a simple set() to see if I'm able to do anything.

Here's what I've got:

function webinar_rearrange_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->current_display == 'block_1') {
    foreach ($view->result as $key => $value) {
      $value->_entity->set('title', 'test title'); // worked
      $value->_entity->set('body', 'test body'); // worked
      $value->_entity->set('field_byline', 'test byline');
      $value->_entity->set('field_view_node', 'http://test.com'); // DOESN'T WORK - maybe it's an array? How do I do those?
    }
  }
}

How do I get the available values to work with?

To get values from result you can do something like:
$value->_entity->title->getValue()[0]['value'];
Here is example to get body and title you can do the same with other fields.

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->current_display == 'page_1') {
    foreach ($view->result as $key => $value) {
      //- Get title value
      $title_value =  $value->_entity->title->getValue()[0]['value'];
      //- Get body value
      $body_value =  $value->_entity->body->getValue()[0]['value'];
     //- Get Other field values ...
    }
  }
}


How do I redirect in a class sub-classing the EventSubscriber class? I want to redirect to a specific URL in an EventSubscriber class instead of showing the Page not found page. I followed Symfony2 redirect for event listener? but the redirect goes to the home.

This is the code I am using.

use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class PageNotFound implements EventSubscriberInterface {
  public function pageNotFound(GetResponseEvent $event) {
    $request = $event->getRequest();
    $id = '1234';
    $scheme_and_http_host = $request->getSchemeAndHttpHost();
    $url = Url::fromRoute('myroute', ['id' => $id])->toString(); // this url exist (checked)

    $response = new RedirectResponse($scheme_and_http_host . $url, Response::HTTP_MOVED_PERMANENTLY);
    $event->setResponse($response);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['pageNotFound'];
    return $events;
  }
}

mymodule.services.yml

services:
  mymodule.page_not_found:
    class: Drupal\mymodule\EventListener\PageNotFound
    tags:
      - {name: event_subscriber}

How do I redirect users from an EventSubscriber class?

To catch a 404 exception you need to subscribe to a KernelEvents::EXCEPTION event. As there is already a base class for html exceptions you don't need to code this yourself. You can simply put the code in an on404() method of a class that extends HttpExceptionSubscriberBase:

  Utility base class for exception subscribers.

  A subscriber may extend this class and implement getHandledFormats()
  to indicate which request formats it will respond to. Then implement
  an on*() method for any error code (HTTP response code) that should be
  handled. For example, to handle 404 Not Found messages add a method:

  public function on404(GetResponseForExceptionEvent $event) {}

  That method should then call $event->setResponse() to set the response
  object for the exception. Alternatively, it may opt not to do so and
  then other listeners will have the opportunity to handle the
  exception.


What hook to use to update history table What hook can I use to update the history table for my use case?

I am using the answers module. When viewing a question it appends a view of answers by format of view mode. The history table for the question type is updated, but not for the answer type. This has the effect that all comments on the answer are always tagged as new. I added code to the hook_node_view for the question type wherein I get all related answers and update the history table correctly for them. However, hook_node_view runs before hook_comment_view and now all comments do not get a tag at all. I probably need to alter the history table after hook_comment has run. Any suggestions?

You are looking for the node_tag_new() core function.

function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')->key(array(
      'uid' => $user->uid,
      'nid' => $node->nid,
    ))->fields(array('timestamp' => REQUEST_TIME))->execute();
  }
}

Normally you'd just pass the full node object to the function, but if you only have the nid, you can just pass a dummy object.

$node = new stdClass();
$node->nide = 1234;
node_tag_new($node);

Modifying the OP's own answer, this would be:

function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    if ($user->uid) {
      $results = db_select('field_data_answers_related_question', 'rq')
        ->fields('rq', array('entity_id'))
        ->condition('answers_related_question_target_id', $router_item->nid)
        ->execute();
      foreach($results as $row) {
        $node = new stdClass();
        $node->nid = $row->entity_id;
        node_tag_new($node);
      }
    }
  }
}

However you should probably be using EntityFieldQuery since it will handle all all the specifics about which tables/columns to use:

function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'answers')
          ->fieldCondition('answers_related_question', 'target_id', $router_item->nid);
    $result = $query->execute();
    if (isset($result['node'])) {
      foreach ($result['node'] as $answer) {
        node_tag_new($answer);
      }
    }
}


How to redirect to a page after submitting a form I have a custom module that displays a form.

Upon submitting the form, I want to redirect the user to a different page.

How can I do that?

In the submit handler you do

Drupal 7:

$form_state['redirect'] = 'url';

Drupal 8:

$form_state->setRedirect('route', $args, $options);
$form_state->setRedirectUrl(\Drupal\Core\Url);


How to restrict access to files to files of a node while keeping the node itself viewable? I'm writing a module that allows users to configure special access restrictions on nodes to reflect academic publishing agreements (called 'embargoes'), which are stored in a custom config entity that points to a node and describes what types of access restrictions should be applied, and who is exempt (users, roles, IP ranges, etc). One of the requirements for the module is that users should be able to restrict access to the entire node (a "node embargo"), OR just the files on the node (a 'file embargo') so that the node itself is accessible and shows up in searches, but the files associated with it are not accessible.

I have implemented the 'node embargo' portion of the module using hook_node_access and checking a custom service to determine if the user should see the node or not, and returning \Drupal\Core\Access\AccessResult::forbidden() if they shouldn't. This works exactly as desired, and not only blocks access to viewing the node, but also access to the files associated with the node.

function embargoes_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  $nid = $node->id();
  $ip = \Drupal::request()->getClientIp();
  $embargoes = \Drupal::service('embargoes.embargoes')->getActiveNodeEmbargoesByNode($nid, $ip, $account);
  if (!empty($embargoes)) {
    $access = \Drupal\Core\Access\AccessResult::forbidden();
  }
  else {
    $access = \Drupal\Core\Access\AccessResult::neutral();
  }
  return $access;
}

What I cannot figure out how to do is implement the "file embargoes" in which the node is still viewable but the files are not. Since the private files are no longer accessible when hook_node_access returns \Drupal\Core\Access\AccessResult::forbidden() on the node they belong to, there must be some system in Drupal that is checking to see what node the files belong too. If I could figure out how to access that I might be able to use hook_file_download and check the node the file belongs to and see if the file should be accessible or not; in fact I already have a function in my custom service that does exactly this, but it needs a node ID in order to see what embargoes exist for the node.

Does anyone know how to do this? What is Drupal doing when a private file is accessed to see if the associated node is accessible or not?

The answer ended up being the function file_get_file_references(), referenced in /core/modules/file/src/FileAccessControlHandler.php

https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_get_file_references/8.2.x


Letting anonymous user to see fields? I just created a content type with a field:images.
Then I added some content and I create a View to show these content. Then the view shows the images (from the images field)
Everything works fine but when I logout the anonymous user can not see the images.

As you can see in this picture I have "checked" Access content for anonymous user. But it doesn't work...

.

What I need to do to make the images visible for anonymous users is to have 'checked' View field_images. You can see the picture.

my question: do I need to checked on every field I create to make them visible to anonymous users? Is there any way to set that any new create field should be visible to anonymous users.

Thanks

If there is no field permission module installed, all fields are always visible. So if you don't want to restrict any fields, then disable the content permissions module.

Once such a module is installed, it works as implemented by that module. And there is no way for such a module to guess the permissions you want (should it be visible to auth users only, or anon users too.. maybe only a specific role?), so it can only chose the safe way and does not grant anything automatically.

That is consistent with all other permissions, when you install a new module.


Adding custom button to Add Article form? I can't seem to get this to work. In my template.php, I have:

if($form_id == 'article_node_form'){

    global $user;

    if (in_array('administrator', array_values($user->roles))) {
        //print "here" --> this prints out just fine so this is getting hit
        $form['actions']['save_send_review'] = array(
        '#type' => 'submit',
        '#value' => 'Save & Send for Review',
        '#name' => 'op',
        '#submit' => array('myFunction_form_submit'),
        '#weight' => 1000
        );
    }
}

I can't get the button to appear. What I want to do is:

Have the button appear next to the Save/Preview buttons. Then once clicked, I want it to trigger Workflow to change the status from Creation --> Review automatically (without saving it as Draft first).

In template.php the form is already build.

You have to create a simple module and a hook_form_alter to edit your form or add buttons, fields etc.


Adding a table with items and prices to a drupal site I am not sure how to ask this question, but I hope I will be making myself clear.

We are building a CMS-like site for the most part, but the customer also wants the capability of adding a prices table for goods that can be consumed by a user on a daily basis.

So far, there is a custom content type 'user daily report' whose purpose is to store info of the likes of:

user1 - 2015/05/01 - 1 breakfast - 1 lunch - 3 drinks

At the end of the month, I have to be able to provide a report which summarizes how much the user has to be charged for his/her accumulated consumption.

I'm not sure how to exactly phrase my question here, since I'm fairly new to Drupal. Therefor I'll try to describe my requirement / question using some language I'm more familiar with:

Have Drupal create a products table, a prices table (foreign key-ed to the products table), and add a couple fields to the daily report content type (product_id, amount).
In order to create the monthly report, I think I would just use a grouping SQL query (with group by and sum).

The above is not very 'drupalish'. But at the same time, I fail to see how the products and prices tables could be implemented using content types.

To make the question more precise, it is actually a 2 parts question, being:

1) I am not sure that putting the products and prices info inside of Drupal is best achieved by using custom content types. What is the best way to go for you people when faced to this type of functionality?

2) What is the best way of extracting/summarizing the info at the end of the month? I have struggled my way using the views module, but being myself much of an 'old school programmer' I am not necessarily confident that all I need can be achieved by using 'views'.

With all that in mind, my question is: what's the best approach to achieve this goal in a way that integrates well with 'the Drupal way'?

Any hint on the topic is most welcome!

Thanks In Advance!

PS. I've tried the entity-references + views_calc way with a wee prototype.
In general, I feel satisfied with the tests I've carried out.

What we need to be able to implement is several tables of products/prices available to different sets of users. All of it based on organic groups (we are using an openatrium distribution).

Using an entity-reference as a field in the users content type, and then adding the necessary relationship when using the views module, I can get what I need. Plus with the Views Calc module I get the summarized stuff.

I still have to try it all in our fully fledged openatrium dev install and see what happens when associating products/prices to groups. But so far, seems promising.

I've learned that my original version of the question didn't fit the questions policy because it was too loose and prone to answers based in personal opinion vs facts (and sorry about that). Maybe the edited version will prevent it from getting closed?

I'll choose Pierre's answer as right, as it has certainly been helpful.

Your question consists of 2 questions ... I'll use the same numbers to answer them.
1. Alternatives to using Custom Content types
a) Use Drupal Entities (Option 1)
Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...) like Products and Prices. For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node_reference' and 'user_reference' as contained in CCK for D6).
Maybe modules like Display Suite or Panels could help to enhance the look and feel of it all also?
b) Use custom tables and/or an external database (Option 2)
Custom tables are tables you create yourself, in the same Drupal database. External Databases are databases that are different from the Drupal database, which are typically in formats such as Oracle, PostGress, MS Sql, MySQL, SQLite, some PDO compliant DBMS.
Using this alternative, you can use the Forena module for reporting about the data from within a Drupal site (as further explaining within "reporting" below also). To perform updates (delets, inserts, etc), you'd use your own tools that you'd prefer for the DBMS of your choice. Same for creating the tables, etc.
2. Reporting
Consider using modules such as (either one, or both, depending on your requirements):

Views, combined with Views Calc also probably. Have a look at How to calculate the sum for each option of all webform results in a Drupal webform grid? to get an idea of using Views Calc.

Maybe you want to consider the Forena module as a supplement / alternative. E.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc. Here is a quote about it:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Disclosure: I'm a (co-)maintainer of some of the modules mentioned,
I hope this does not violate the site's policy on self-promotion.


Contact form on maintenance mode page I'm using Drupal 7 and I wanted users to be able to contact me via email whilst I'm still working on the website. So my plan was to use 'create a contact form', as I don't want to expose my email address.

However whenever I try to add an input element in the maintenance mode message it is completely ignored in the output. I think that this is because the message uses the filtered HTML file as I do have other bits of HTML the message that are rendering just fine, but I can't see any option to change which filter is used.

Is there a way to change the filter to full HTML or is there a better a option?

If you are comfortable with Custom coding, you can try following route

On your theme template.php implement template_preprocess_maintenace(), this will help you introducing new variables to maintenance page tpl file, something like below

function yourtheme_name_preprocess_maintenance_page(&$vars) {
  if (function_exists('_your_form_builder_funtion')) {
    $vars['your_custom_form'] = drupal_render(drupal_get_form('_your_form_builder_function'));
  }
}

Now copy the maintenance-page.tpl.php in your custom theme templates folder and on the template file, you can use the variable like any other being already used. So somewhere on your maintenance-page.tpl.php add following

  <div class="contact-form">
    <?php print $your_custom_form; ?>
  </div>


How to implement field formatters for entity properties I created a custom entity using Entity API that has certain properties defined in hook_schema() and also declared in entityPropertyInfo(), a class extending EntityDefaultMetadataController.

So far so good.

Now I'd like for users to be able to customize if and how these properties get displayed when viewing the entities so I implemented hook_field_extra_fields() and declared them.

Then, in my Controller which extends EntityAPIController I added the properties to the $content array in buildContent() as, outlined here.

It actually works pretty well and properties are rendered and respect the order and visibility settings in "Manage Display".

However, I can't seem to figure out how to add settings in Manage Display to customize the label positioning (inline/above/hidden) and, more importantly, how to specify custom formatters for these properties.

Any clues?

You could create a module providing a "property" field type. Store the the property to be formatted as an instance setting and then apply a formatter to that. It should be relatively straightforward. Relation module has a dummy field module which might help you in figuring out how to code this.


Can't install drush with composer When I run...

composer global require drush/drush:dev-master

...I get...

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - drush/drush dev-master requires consolidation/output-formatters ^3.1.12 -> satisfiable by consolidation/output-formatters[3.1.12].
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - Installation request for consolidation/output-formatters (locked at 2.1.3) -> satisfiable by consolidation/output-formatters[2.1.3].

My PHP version is 5.6.11.

The solution in my case was to run...

composer global update
composer global require drush/drush:dev-master

Previously, I had been running composer update but needed to run composer global update.


Create new content when an image is uploaded, using rules I've been working all day to try and figure this out.

I have a view set up that takes every content type of "Gallery" and creates a nice view of all gallery types. I also have a webform where a user can upload an image. I then set up rules so that when an image is uploaded using that form an entity is created of type "Gallery"....and that's where I've been stuck.

I've been searching online for answers but can't find anything. Is there a way to take the image that was uploaded using the webform, and place it into the new gallery content in the field-images field?

http://imgur.com/hwYBb8H

That's my rules page currently. The php code that I was using was just dsm to check what was actually inside of each entity, along with me trying random code to try and figure out how to do this. None of it worked.

I'm not sure if this is the best way to do this or not, so feel free to let me know if you know a better way to do this (I'm a drupal beginner still).

Any help would be appreciated!

In your conditions, add entity has field: web form > image field.

That should allow you to set a data value on your created node with that image.


Alter display of jQuery Calendar Popup I've got a Date field on my content type and I'm using the jQuery pop-up calendar as the widget. The html rendered for it has extra stuff that I'd like to strip away, but I can't find a way to configure what it looks like.

Here's my current Edit form:

Notice with all of the non-date fields, the name of the field is bold and directly above the textfield/select box, etc.

However, with the date field, the field name is not bold, then there is a space, then a bold "Date" and THEN the textbox which is linked to the popup calendar.

I would like it to end up like this:

I understand that I can try to just hack it by hiding things with css, but that's not what I'm looking for.

I'm looking to find a way to configure drupal to render this field the same way it renders all of the others, instead of rendering tags that just take up bandwidth and get hidden by css.

EDIT: This isn't an issue of a special configuration. I just installed vanilla drupal in a new directory. I installed the date module. I enabled the date module along with the date popup module (comes with it). I added a date field to the Article content type and set it's widget type to be popup calendar. Went to add a new Article node and it appeared just like I said above.

So it turned out to be a two-fold issue. Thank you to Geoff and Clive who provided the larger part of the solution!

Step 1 - By default, the Date module renders a date field as a fieldset which is why the field name is differently styled and separated from the element a bit. The quick solution is to add a very short function to your template.php which tells the system to format a date field in the same way you'd format any other element. Like so:

function MYTHEME_date_combo($variables) {
  return theme('form_element', $variables);
}

I pulled that code from how to avoid fieldset in drupal date field

Step 2 - Edit the Content Type, Edit the date Field, expend "More settings and values", then expand "Advanced Settings", and change the Label position from "Above" to "None." That will get rid of the internal label.