Customizable product bundles, user can add/remove products I'm looking for ways to implement an e-commerce for an organic farmer who sells their products, he offers products and product bundles. Every product bundles has its own price. Each bundle are predefined products group. But I want that when the user buys, can unchoose at most, two products of the bundle and change them for another product in a predefined group of products.

I wonder if anyone knows how I can work this way the product bundles. I've been searching, I saw Tech Talk about commerce bundles, I tried commerce_bundle... but I can't find anything to do this.

Any idea or clue is welcome!

My solution goes here based on Drupal Commerce-
Step 1: Create Product Bundles using Commerce Bundle module. (which you already know).
Step 2: Now you have bundles. The next step is your custom functionality to swap at most two products from the bundle.
Add a new step to your checkout process to implement the custom functionality refer Add a new step in Commerce checkout, explore commerce_checkout.api to get the hold on this.
Adding a new step is nothing but adding a new pane (inside a checkout page) in a Drupal Commerce checkout process where you can list the products in the cart and process them using hook_form_alter().
Refer this link for more details hook_form_alter.
You can make use of hooks provided by Drupal Commerce such as commerce_cart.api, commerce_order.api to edit/update the cart.
Step 3: After processing the cart contents you can update the order details/status using commerce_order.api.
You can alter the checkout pane settings from Home » Administration » Store » Configuration » Checkout Settings page.
Note: You must have Drupal 7 module development knowledge to implement the above solution.
I hope this helps! Thank You.


Get the position of a paragraphs entity in a nested template I try to build an accordion or slider element with Paragraphs.

Therefore I create a Slider element which had slides. Unfortunately the first element should always looks different. I can do this with a CSS class, but how to figure out which is the first slide?

Slider:

            {{ content.field_feature_slider_slides }}

Slide (which will loaded through Drupal Magic):

  ...

How can I get/set/access a variable (here pos) with the current position of the loop?

The Slider uses Paragraphs to add several Slides. The is a template for the slider paragraph--slider.html.twig and paragraph--slide.html.twig for the slides. No For-Loops are involved here. Drupal/Paragraphs rendering the slides through the template with content.field_feature_slider_slides from the slider.

For the Slide, are overriding the default field.html.twig template?
If yes, then you can use the Twig Loop variables:
https://twig.symfony.com/doc/2.x/tags/for.html
e.g. loop.first


Base table missing in database? I just emptied the cache in my Drupal database via MySQL, and all of a sudden I'm getting this error on my home page? Help! How can I fix this? It almost seems like a table was deleted by accident?

Original

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'databasename.entity_test_type' doesn't exist:
  SELECT et.* FROM {entity_test_type} et; Array ( ) in
  entity_test_entity_info() (line 73 of
  /var/www/drupal/true-001/sites/all/modules/contrib/entity/tests/entity_test.module).

Additional

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'databasename.locales_source' doesn't exist:
  SELECT lid, location FROM {locales_source} WHERE source = :source AND
  context = :context AND textgroup = 'default'; Array (
  [:source] => An AJAX HTTP error occurred. [:context] => ) in
  _locale_parse_js_file() (line 1563 of /var/www/drupal/true-001/docroot/includes/locale.inc).

Yes that is correct, the errors are saying entity_test_type and locales_source do not exists. Try searching for them with PHPMyAdmin or any other DB viewer and you will very likely not find them. So yes, somehow those tables got deleted or possibly renamed?

  Help! How can I fix this?

If they got deleted, you have the following options:

A) Disable and uninstall those modules, then enable them again and they should create the missing tables.

B) Revert back to a DB backup where those tables exist, then export the 2 tables only. Now revert back to your latest DB backup where they are missing and just import those 2 tables.

C) Manually re-create those tables with the proper column names


How to show the status of a referenced webform in view of nodes? My use case is a list of events and I want to show a label on the views item, if the event is already booked out. Therefore I would render the status of the referenced event registration webform.

The registration webform ist connected to each event node via the Webform Node module (submodule of Webform). The view consists of nodes of the type event which contains an entity reference field to the resgistration webform.

I have installed the Webform Views Module. Now I want the view to render this entity reference field as the status of the webform, meaning open or closed.

The problem is, that the views UI for the field rendering only lets me select from

URL of the Webform
the whole webform
a link to the webform

The Link option provides a text input field for YAML code. Maybe I could use this? But I don't know how ...

Any ideas, how I can get the view to render the status of the referenced Webform?

Since the webform is added as a reference on the node, you have to add a relationship in views, in order to get the webform's fields.

Go to relationships and add the webform reference, then the status field should be available as a field.


Translate view header I add a simple text as view header but it is not exists in translatable text in admin/config/regional/translate.

In Drupal 7 we could even translate unformulated views header and footer with the following steps:

Go to admin/config/regional/i18n/strings
Check "full HTML" in "Translatable text formats" section
Go to admin/config/regional/translate/i18n_string
Click on Refresh strings

Has this feature been removed form Drupal 8? (I don't think so.)
How can I translate view header and footer simple text?

Enable "Configuration Translation" core module
Go to your view edit and you will see a "Translate view" tab
You'll find your language in the list there. Then click on "Edit"
next to the language
Expand panels and you will find your header text under the "Header"
panel


IMCE file upload dynamic path problem I am trying to setup a filefield using imce to allow the user to upload files however I am having problems setting it up trying to get a unique folder for each node.

So for example I have set the imce directory path to

php: return $user->name.'/'.date('Y-m-d-H-i');

Which will upload files to user/2015-06-12-13-15.

However when the I click use the file browser if I don't upload the file within the same minute as when I clicked use the file browser, IMCE throws an error saying the directory doesn't exist as I imagine the date change throws off the upload.

I don't want to restrict users creating one node an hour so does anyone know of another way of generating random file paths for each node?

This probably isn't the best solution, however it is working for me at the moment.

Using the following php in the IMCE directory path it generates the same random number for 5 minutes.  So I can have the directory structure user/Y-m-d-H-[random number]

php: function random() {  $seed = floor(time()/(60*5)); srand($seed); $item = rand(0,100); return $item; }  return $user->name.'/'.date("Y-m-d-H").'-'.random();


How To Set Order State Completed after Notification? I am Writing a Payment Gateway(Onsite) Plugin For Commerce 2,
I am Stuck with Checkout Flow Step Transitions.
Let Me Explain:
I am extending the OnsitePaymentGatewayBase and in the createPayment() Method
I am setting the payment states to 'pending' [if the payment gateway accepted the request]and the payment state is setting well(no issues with payment state),
Since My Payment Gateway is Async I need to implement onNotify() to change the payment state to 'completed'.
My Issue:
Since Payment Gateway is Async(payment notification will be sent after a day) My order Sates also be needed to be in 'Pending' or something similar states but when I use default checkout flow I am getting the order completed even before the notification is processed. means after I checkout the order state is 'completed',
What I want:
I want the order state to pending or review ..etc even after the checkout.
only after the processing of notification the order state to be 'completed'
Or Simply:
How can I set Order state to Pending or Review or darft..etc  and Not 'completed'
Only after receiving the Notification from Gateway, I have to set order state to completed
Github LINK

Unfortunately, the "Default" order workflow for Commerce 2.x is fairly naive. It only has states for Draft (i.e. shopping carts), Completed (i.e. any placed order), and Canceled. If you need more states, you'll need to supply an alternate workflow. Core ships with a "Default, with validation" workflow you can set for your order type that includes a "Validation" step you could make use of instead.
Generally speaking, it's likely your payment gateway module shouldn't be controlling the actual order state transition. It can and should update the payment transition, and then a separate module specific to your site can be responsible for defining exactly what you want your workflow to be and automating the transition based on the order paid event (cf. OrderEvents::ORDER_PAID).


Difficulties install Drush using composer I have tried to install Drush on OSX 10.9 but it doesn’t seem to have worked. In terminal ‘drush status’ gives

  -bash: drush: command not found

I have followed the instructions on http://whaaat.com/installing-drush-7-using-composer

Composer’s directory seems to be correct as my .bash_profile contains:

export PATH="$Trotter/.composer/vendor/bin:$PATH"

Drush exists in the vendor folder of composer

When I tried to install Drush via composer the feedback seemed to suggest it had worked:

Pauls-iMac:~ Trotter$ composer self-update
Updating to version 8e9659bd8317ad3f623c4d17940380443cf8772c.
    Downloading: 100%
Use composer self-update --rollback to return to version 1.0.0-alpha9
Pauls-iMac:~ Trotter$ composer global require drush/drush:7.*
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.2.1)
    Loading from cache

  - Installing symfony/var-dumper (v2.7.1)
    Downloading: 100%

  - Installing symfony/yaml (v2.7.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Loading from cache

  - Removing drush/drush (6.5.0)
  - Installing drush/drush (7.0.0)
    Downloading: 100%

pear/console_table suggests installing pear/Console_Color2 (>=0.1.2)
symfony/var-dumper suggests installing ext-symfony_debug ()
d11wtq/boris suggests installing ext-pcntl (*)
Writing lock file
Generating autoload files
Pauls-iMac:~ Trotter$ drush status
-bash: drush: command not found

(Note I had previously tried to install Drush 6 but hadn't got this to work either)

I would appreciate any advice on what is going wrong here.

Changing the .bash_profile to the following worked:

export PATH="~/.composer/vendor/bin:$PATH"

Now drush status gives good feedback on the Drush version etc. Thanks to Clive for suggesting this.


Module doesn't appear on update.php I wanted to add columns to my module schema, I added an update hook hook_update_6031
however when I go to the update.php script my module isn't listed at all, not even as "no updates". Do I have to provide some hook to have my module be listed? I can't seem to find any documentation on how to write updates other than the function documentation for hook_update or looking at some other module code.

Some things to check:

Is your update function placed in [modulename].module or in [modulename].install? It should be in the install file.
Is the function really called hook_update_6031? in that case, replace 'hook' with the name of your module. For instance, an update function for the comment module could be called comment_update_6003.

If the above does not help, please update your question with the code of your update function. Also check the value in the schema_version column in the system table for your module - for the [modulename]_update_6031 function, it must not be less than 6031, but not -1.


Timeformat timelineview Bat module I had a reservations system with the .bat module.  But I want to change the timeformat in my timelineview from am/pm to 24hours time notation. I have been looking in batfullcalander and the library of fullcalendar and fullcalanderscheduler. Can someone help me out with this?

To change the timeformat I had to change TimeFormat             from            .replace(':m', ':mm') to  .replace('h', 'HH') in fullcalendar.js


Latest Article Popup I've seen this functionality being used quite often especially on news sites where latest articles snippets/calls-to-action pop out of the side of the browser - See image below:

Any idea what is the most common way this implementation is handled in Drupal?

I had a look at a couple of Drupal modules but didn't strike it lucky.

Install Flippy module.

 1. Go to desired content type -> admin/structure/types/manage/<content_type>
 2. Click on Flippy Settings tab
 3. Select "Build a pager for this content type"
 4. Customize the module or template, theme as you want.


sub theme not inheriting css I have a theme, and many subthemes, with the goal of creating a network of sites that are different, but share some resources (like the stackexchange sites do).
What I want is to include lots of boilerplate css in the master theme, and then site specific css included for each subtheme.
The problem I have is the CSS of the master theme is not being loaded in the subtheme.

The master theme:

name = Master
description = Master theme
core = 7.x

stylesheets[all][] = css/network_style.css

and the sub theme:

name = Red Theme
description = specific theme for site in network
core = 7.x

base theme = Master

stylesheets[all][] = css/red_style.css

Ideally then, the master theme just has network_style.css, and the sub theme has network_style.css and red_style.css.

If I enabled the master theme, then the network_style.css is applied. If I enabled the sub theme, then only the red_style.css is applied. There's no css conflict, and the master theme isn't visible in the page source at all.

Where am I going wrong? I'm somewhat new to Drupal.
I've gone through lots of documentation on the drupal site, and checked through all the drupal 7 specific stuff on theming.
I've tried clearing the drupal cache, plus my browsers cache, even turning server on and off like a mad man.

The base theme should be set to the machine name of the Base Theme. The machine name is the same as the name of the directory that contains it. Yours starts with a capital letter. I imagine that the folder is just master (all lowercase).

Because the .info file is cached, you must clear the cache before any changes are displayed in your site.

Writing theme .info files


Migrated content type fields not showing I'm trying to migrate custom content types with attached fields from Drupal 7 to Drupal 8. Using drush migrate commands I can successfully migrate all content types, but I have problem with fields.

First I run upgrade_d7_field migration, than upgrade_d7_field_instance and last migration is upgrade_d7_node_MY_CONTENT_TYPE_NAME_content.

If I go to Structure -> Content types and then open my custom content type (by pressing Manage fields) I can see all fields attached to it - everything is ok. If I choose Content from main menu and try to create new content for my content type I only see Title field, no more fields are displayed. Same are with migrated content - if I 'm trying to edit it, I see only title.

What I'm missing ? I have migrated data in Drupal 8 fields table - node_field_MY_FIELD_NAME. I am logged in as admin user, so I should have all permissions to view this fields.

It sounds like the fields might be disabled on the entity form.

Goto Structure -> YOUR CONTENT TYPE -> Manage form display

Then move the fields you are expecting to see in the form from Disabled (bottom) to Content.  You can also control the display order from there.


Override "Display select options" to see them in reversed alphabetical order Can anyone advise me how to override the Hierarchical Select module to display select options in reverse alphabetical order?

there seems to be a patch to change the sort order: http://drupal.org/node/466828#comment-4904174


Why timestamp format was chosen for users.created field When I looked into users.created field in the database, it says, that is has type int. Does anybody know, why Drupal team chose this format instead of datetime? Cause timestamp will end with the end of UNIX epoch:

http://en.wikipedia.org/wiki/Year_2038_problem

As they are setting it to this value:

$account->created = REQUEST_TIME;

http://api.drupal.org/api/drupal/includes!bootstrap.inc/constant/REQUEST_TIME/7

And datetime is unlimited. So, why was this inferior variant chosen?

Date/time types vary widely among different DB types. The purpose of the Schema API is to achieve some compatibility at the data definition level.

If you see this http://drupal.org/node/159605 the date/time is not supported in some database type.

So I would prefer to go the way the date module does it and use int if you want to make it compatible across multiple database types.


How to define another teaser for the second theme? I have two themes: regular (1st) & mobile (2nd). Mobile theme binded with subdomain m.mysite.com.

I can't show my mobile node teaser in mobile theme.

I've created that teaser for mobile theme in Display Suite. Next I need to show this one in mobile theme taxonomy tag page. But I can't define theme in DS. When I use [taxonomy-term.tpl] in mobile theme to define mobile teaser, but vars doesn't works: changing $view_mode has no result (type machine name on mobile teaser), $content array is empty. I tryed to use Views, but in displays there is no options to define a theme.

What can I do? Thnx

Problem solves by the following:

Created DS template for default teaser in 2nd theme: ds-2col--node-article-teaser.tpl.php
Place into it code to define my new node_teaser_mobile to show:

print render(node_view($node, $view_mode = 'node_teaser_mobile', $langcode = NULL));


Why page-view counters not working (displayed)? I have set up to display the page-view (hit) counter, using the Drupal 7 core statistics module, following the standard procedure (see, for example, the summary here).

However, (A) only English contents show the counter but none of the other languages on a site, and (B) none of the contents show the counter on another site.

The structure and installed modules in those sites are slightly different.  However, as far as the settings (configuration, permission etc) of the statistics module is concerned, they are the same.

What is happening? Where should I look for to investigate?

I suppose the cause can vary.  However, it seems multilingual sites may have additional factors that contribute to make this counter-related stuffs go wrong.  Here are a couple of example cases for multilingual sites.

I assume you are using the path-prefix based language negotiation as the high(est) priority.
In your case (A), is the English the default language and no path-prefix is defined for English?  In your case (B), are the path-prefixes defined for all the enabled languages, including the default language?  In those cases, it is suspicious some module(s) that use i18n are causing a trouble.

First, check the database table node_counter.  If a node has a non-zero totalcount, and if you don't see the page-view counter when you view the node, then it is likely to be down to either the permission or your theme, which may not show the counter in the first place.

If the totalcount column has zero count, despite you (preferably as a non-authenticated user) have viewed the node (and have flushed all caches), then the statistics module is not working, either due to its own failure or other module(s) fail to access the statistics module.

Have a look at "Recent log messages" /admin/reports/dblog.  If you see (probably plenty of) "page not found" for modules/statistics/statistics.php, then the latter is the case, or at least is contributing.

In that case,

Confirm modules/statistics/statistics.php does exist, and the file permission is set to be readable to any one, as well as all the parent directory permissions are set to be readable and executable to any one.
In the table of "Recent log messages" /admin/reports/dblog, click the links (for TYPE: page not found) modules/statistics/statistics.php in the Message column.  What do you see?  Does the LOCATION include the language prefix (like /fr/)?
If that is the case, your module(s) try to access the non-existing page like fr/modules/statistics/statistics.php instead of the correct path without the language prefix.  Best figure out which module is causing the trouble and fix the module.  If that is not practical, alternatively you can control the path at the server level: read the answer to Why so many “page not found” for statistics.php?.


Display an empty password field I have a password field which currently displays the current password. How can I force the input to be displayed as blank? From the documentation here, it seems that #default_value or #value don't work (so I can give them an empty string as a value). How can I do this?

We have a client who runs a security scan that flags login forms that have autocomplete enabled, and have been using this solution for a few years now:

/**
 * Implements hook_form_alter().
 *
 * Remove autocomplete from all user forms.
 * Based on http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'user_') === 0) {
    $form['#attributes']['autocomplete'] = 'off';
  }
}


How can I add the og to a menu when a new organic group is added? I want to create organic groups that represent counties, and have a menu with some states already Set up, so the user can just select the state for the organic group to be listed under.  The title of the organic group will be the name of the county, which should be the same as the link in the menu.

Is there a way that this can be set up when the organic group is being created?

I'm using the latest release of drupal 6, and organic groups 6.x-2.1.

Is there a module that allows you to automatically assign a sub menu for group content without the user being able to change what the menu title is called? I guess that, ideally, I'd like to have an About page that has the same title and menu path for each group.

You can try this module : http://drupal.org/project/auto_menutitle. It allows to automatically generate menu items based on the node title. If you enable this module on your og content type, it should do it.


How to obtain the complete list of available Drush Output Formats? I'm trying to obtain the complete list of Drush Output Formats. I'm using drush 9.0-dev and in the Output formats section of the Drush Documentation it says:

  The list of formats shown is abbreviated; to see the complete list of
  available formats, run the help command with the --verbose option.

I tried drush help --verbose, but I can't find the information.

Is there another way to have access to this information?

To see the verbose list of output formats use help with a command name. For example the help for the watchdog list command drush help wd-list:

Normally you get:

 --format=<json>                           Select output format. Available: table, csv, html, json, list, var_export, yaml.
                                           Default is table.

But if you use --verbose:

drush --verbose help wd-list

You get the full list:

 --format=<json>                           Select output format.
                                           All available values are:
                                            - table: A formatted, word-wrapped table.
                                            - config: A configuration file in executable php format. The variable name is
                                           "config", and the variable keys are taken from the output data array's keys.
                                            - csv: A list of values, one per row, each of which is a comma-separated list of
                                           values.
                                            - html: An HTML representation
                                            - json: Javascript Object Notation.
                                            - labeled-export: A list of php exports, labeled with a name.
                                            - list: A simple list of values.
                                            - php: A serialized php string.
                                            - print-r: Output via php print_r function.
                                            - var_export: An array in executable php format.
                                            - variables: A list of php variable assignments.
                                            - yaml: Yaml output format.
                                           Default is table.

To get a global detailed list of all formats defined in drush you can use the drush function outputformat_drush_engine_outputformat():

drush ev 'var_dump(outputformat_drush_engine_outputformat())'

EDIT:

If you want to see only the format names you can use:

drush ev 'print_r(array_keys(outputformat_drush_engine_outputformat()))'

Output:

[0] => table
[1] => key-value
[2] => key-value-list
[3] => json
[4] => string
[5] => message
[6] => print-r
[7] => var_export
[8] => yaml
[9] => php
[10] => config
[11] => list
[12] => nested-csv
[13] => csv-or-string
[14] => csv
[15] => variables
[16] => labeled-export
[17] => html


How alter submit user_pass_reset? I can alter every form submit in Drupal with this hook:

  hook_form_alter

On the user_pass_reset form there is a button for auto-login from a link.

I need to add some custom logic just after the user click on the button "Login".

Here's how I tried to do that :

function tools_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

   if($form_id == 'user_pass_reset')
    {
        $form['actions']['submit']['#submit'][] = 'tools_compte_mot_de_passe_reset_submit';
        $form['#submit'][] = 'tools_compte_mot_de_passe_reset_submit';
    }
}

I have set the 2 form methods because I trying to understand which is called.

  My custom submit :

function tools_compte_mot_de_passe_reset_submit($form, \Drupal\Core\Form\FormStateInterface &$form_state)
{
    exit();
}

My custom submit is never called... if I try on a different form, that works, but not on this one.

Where i am wrong ?

From \Drupal\user\Form\UserPasswordResetForm::buildForm:

<?php
$form['#action'] = Url::fromRoute('user.reset.login', [
  'uid' => $user->id(),
  'timestamp' => $timestamp,
  'hash' => $hash,
])->toString();
?>

If you look at the form in your browser, you can see that it directly POSTS to that other route. as a result of that, your submit isn't called because for that, it would need to actually submit to itself again.

That then points to \Drupal\user\Controller\UserController::resetPassLogin(), which calls user_login_finalize(), which calls user_login().

Depending on what you want to do on submit, you can either do in hook_user_login() or by altering that route.


Ubercart Ajax change attributes on checkout I want to change the Product Attributes on checkout page by ajax. But when I save it by uc_order_product_save() in my ajax request and go to the preview step the attributes are gone.

It seems that preview step retrives the $order from form storage but not mine saved order. It is here:

function uc_cart_checkout_form_validate($form, &$form_state) {
$order = $form_state['storage']['order'];

How can I access to the storage order object in form to save attributes?

Thanks.

This may not be the best/proper way to do it, but I have manipulated product attributes in

function uc_cart_view_form($form, &$form_state, $items = NULL)

it is located in uc_cart.module

$items is filled with products and you can loop through and review/assign attributes.


How to utilize custom form modes to edit a user entity? My project requires two different pages to edit a user. The first one being at /settings/{user}/my-profile, where the user updates their name, address, etc. The other page is at /settings/{user}/login-credentials, where the user updates their username, password, etc.

After navigating to /admin/structure/display-modes/form, I have created a custom form mode called "My Profile" which has the id user.my_profile, and activated it at the bottom of admin/config/people/accounts/form-display.

Now I need to create a page that utilizes this new custom form mode, and I'm a bit lost.

I looked into how the standard user edit route is created at /user/{user}/edit, and I found the code in the route provider at namespace Drupal\user\Entity;. This is what is in that method (other routes have been removed)...

public function getRoutes(EntityTypeInterface $entity_type) {
  $route_collection = new RouteCollection();

  $route = (new Route('/user/{user}/edit'))
    ->setDefaults([
      '_entity_form' => 'user.default',
      '_title_callback' => 'Drupal\user\Controller\UserController::userTitle',
    ])
    ->setOption('_admin_route', TRUE)
    ->setRequirement('user', '\d+')
    ->setRequirement('_entity_access', 'user.update');
  $route_collection->add('entity.user.edit_form', $route);

  return $route_collection;
}

Then I did some research on the routing system, and I've created a routing.yml file. The name of my module is sc, and the file is at modules/custom/sc/sc.routing.yml.

sc.routing.yml

sc.my_profile.edit:
  path: '/settings/{user}/my-profile'
  defaults:
    _entity_form: 'user.my_profile'
    _title_callback: 'Drupal\user\Controller\UserController::userTitle'
  requirements:
    user: '\d+'
    _entity_access: 'user.update'
    _permission: 'access content'

I'm logged in as user1, cleared the cache, and when I navigate to /settings/1/my-profile, I get "Page Not Found". Am I on the right track? How do I create these pages with different form modes?

You have to add the form mode in the handlers section of the user entity:

/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('my_profile', 'Drupal\user\ProfileForm');
}

Use the standard class ProfileForm as you only want a set new form mode, not a new form class.

Then you can use this new handler in place of user.default in the routing file:

'_entity_form' => 'user.my_profile',


Update values of multiple value field programmatically? (Rules action) I'm trying to create a rule to populate a multiple value order reference field in Drupal Commerce, on checkout complete.

I haven't been able to achieve this through Rules UI, so instead I'm trying to programmatically create the action but can't figure out how to set the actual value.

I simply want to add a reference of the newly created order to the purchased product, while keeping the references already set (in this particular case an order will never contain more than one product).

I have added an order_reference_field (Commerce Order Reference module) to my product, showing checkboxes with multiple values allowed.

Below my code:

function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;

    $wrapper = entity_metadata_wrapper('commerce_product', $product);

    $wrapper->field_order_reference /***** What to do here? *******/

    $result = $wrapper->save();

  }
}

EDIT:

I have gotten a little further with the code below.. It works the first time an order reference is set, but the second time i get the following error "The website encountered an unexpected error. Please try again later."

Found the example a bit down this page: https://drupal.org/node/1021556

function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased Product'),
    'group' => t('Custom action'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $orderID;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}

DOH! - Seconds after adding my previous edit i realised what was wrong. Below the final code :)

function example_rules_action_info() {
  $actions = array();

  $actions['commerce_set_product_order_ref'] = array(
    'label' => t('Link an order to the purchased product'),
    'group' => t('Custom group'),
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
    ),
  );

  return $actions;
}

function commerce_set_product_order_ref($line_item, $order) {
  if (in_array($line_item->type, commerce_product_line_item_types())) {

    $sku = $line_item->line_item_label;
    $product = commerce_product_load_by_sku($sku);
    $orderID = $line_item->order_id;
    $wrapper = entity_metadata_wrapper('commerce_product', $product);
    $curr_list = $wrapper->field_order_reference->value();
    $new_ref = commerce_order_load($orderID);

    if (!$curr_list){
        $curr_list = array();
    }

    $curr_list[] = $new_ref;
    $wrapper->field_order_reference->set($curr_list);

    $result = $wrapper->save();

  }
}


Remove content from a view I have a Master view & numerous child views for the same content type. The Master View has all nodes from the content type. The content gets copied to the child view from the master view basis of specific requirements by the user. I want to have the functionality to remove specific content from the child views. I do not want to delete it as the content would be reused for others from the Master View.

Is there any module to achieve this?

I am not developer.

When you click on a field or a setting. At the very top, you need to use the For "override" option. (select This [view type] override) so it only affects your current view.


How do I make the same variable available to all my theme files? In mytheme.theme I have the following:

function mytheme_preprocess(&$variables) {
 $current_path = \Drupal::service('path.current')->getPath();
 $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
 $variables['currenttab'] = explode('/', $result)[1];
}

This function is extracting the first dirname from my url, for example, httttp://server/dirname/pagename it sets currenttab to 'dirname'.

It is working reasonably well, but I notice that if I click around on my site in a specific way, occasionally I get a page where the sidebar template has the correct {{ currenttab }} but the navbar has the {{ currenttab }} value from an older page.

I thought this theme preprocess would make {{ currenttab }} be the same in all my theme templates, but that does not appear to be the case. Once this problem appears, I can reload the page many times and it persists. I think this is related to the order in which I change urls.

What is going on here?

You would have to add a cache context:

$variables['#cache']['contexts'][] = 'url.path';

Now you cache for each relative path a different version of the template.

However, it is not a good idea to add this context to all templates. Only add it to those templates you intend to use the variable, otherwise you fill up your cache with a lot of useless variations:

function mytheme_preprocess(&$variables, $hook) {
  if (in_array($hook, ['foo', 'bar'])) {
    $variables['#cache']['contexts'][] = 'url.path';
    // add variables depending on the relative url
  }
}


Per site htaccess with multisite In short: Can I have a separate .htaccess file per site on a multi-site installation?

I've read quite a lot of conflicting stuff about this, including some which suggests you can put a .htaccess file in the site folder (i.e. /sites/www.site1.com/). However, some commenters seem to be saying this won't work.

As I am moving several non-Drupal sites over to a single multisite there will need to be lots of rewrites for old URLs, so this is pretty much essential for me.

Thanks,
Chris

Multisite logic (picking what site is what) works in Drupal itself, rather than the Apache level.

I do not think that putting a .htaccess in the sites folder would work, mainly because nothing is really fetched from there from Apache's perspective, except for files.  Normal URLs would never see that file.  There would also be some weirdness with the RewriteBase, and other complications because of the way .htaccess gets processed up the directory hierarchy.

My suggestion would be to use the Redirect module.  This module essentially presents a UI for making and managing redirects for your Drupal site.  You can enable this per site in your multisite setup.  Therefore each domain could redirect its own URLs.  I have found this module very useful for new site launches that use a new URL scheme.

Your other option would be to RewriteCond, eg

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule some/old/url.html the/new/url [L,R=301]

I would do this as an include from the main Apache configuration, rather than .htaccess, unless you a really careful about backing this up when you update core.

Of the two options, I would use the Redirect module.  I would also think very carefully about committing to a multisite solution.  They tend to create more problems than they solve.


What is the best way to keep your site code in git and pull in core and contrib in the same repository? Back when drupal was in CVS I had my sites in a git repository and then pulled in core and contrib via CVS. The two systems happily co-existed and I could track changes to everything and make patches to contrib modules. Now with git I am unsure whether to just download contrib and core and check it into my site's git repository, or maybe use submodules?

I am wondering if there are any best practices on this yet? I am particularly puzzled about how to have core as a submodule if my repo uses drupals root directory as its own root?

Not exactly the same question as https://drupal.stackexchange.com/questions/260/deploying-drupal-with-git but I have the same answer for you.

http://freso.dk/en/2011/02/26/managing_fresodk_from_cvs_in_svn_to_git

I think it can be useful to have Drupal Core as a real check out, makes it for example easier to track hacks. Because sometimes, there simply is no other way, be it changes to .htaccess or maybe you applied some patches for bugs which affect you directly.


Passing an extra element to $edit array when creating an account I added an extra user registration validation critera in my custom module by implementing hook_user

if ('validate' == $op && 'user_register' == $edit['form_id'] && 'account' == $category && !$edit['remote_create_user']) {

    // Is the mail address OK?
    if ($email_in_use) {
    // No, set error on mail form field
    form_set_error('mail', t('Your email address is already associated with a account.'));
    }

I added the !$edit['remote_save'] because I don't want this extra validation if I am creating accounts programmatically. The code I am using to create accounts is

 $form_state['values'] = $account;
    $form_state['values']['pass'] = array(
      'pass1' => $account['pass'],
      'pass2' => $account['pass'],
    );
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['remote_create_user'] = TRUE;
    $ret = drupal_execute('user_register', $form_state);

As you can see, I tried to add an extra form element called 'remote_save' $form_state['values']['remote_save'] = TRUE;. However, in the hook code above $edit['remote_save'] is empty so I can't use it to stop the extra validation. How can I pass a value from $form_state to the $edit array? Or is there a better way to do this?

EDIT: So I tried to use hook_form_alter with the code below

function module_form_alter(&$form, &$form_state, $form_id)  {
  if ($form_id == 'user_register') {
    $form['remote_create_user'] = array('#type' => 'value', '#value' => FALSE);
  }
}

However this code $form_state['values']['remote_create_user'] = TRUE; which is in a separate module, does not set the value of $edit['remote_create_user']. The value of $edit['remote_create_user'] is still false.

If you are actually trying to prevent a user from registering with an email that is in use, Drupal already has that built in. It also has a check that prevents users with an IP in the blocked IP address list to create an account.

Solution

Your flaw in the above code is that drupal_execute calls drupal_process_form which will rebuild the $form_state['values']. A solution could be to add a hidden/value form element to the user_register form with hook_form_alter. Doing that should allow you to send your custom value through drupal_execute.


What is your way to add images into panels - simple and fast? How can you upload images into panels simply and fast? That's all I need - images in panels, simple and fast. thanks.

Using CKEditor with CKFinder:

On pane gear menu click add content
Choose 'New custom content'
In the body field use the image button to either find an existing image on the server or upload a new one.

CKFinder requires a licence, it's pretty cheap.


How to update block with step links based on AJAXified multipage entity form state? Brief

I'm using Entityform with Field group configured as Multipage with AJAX enabled for multipage groups provided by Field Group Ajaxified Multipage. So there are multiple steps and user can access (jump into) these steps through provided Multipage jumplist block.

See some sample images (to give you some visual idea):

Problem

The problem is that form is AJAX (dynamic) and jumplist block is static (which is unaware of form context and links doesn't work) with some basic jQuery code (so it's not reloaded when user goes to next pages).

As result this is what happens:

when field_group multipage is AJAX, the form validation works per step, but jumplist doesn't work (jQuery events are not attached to the links and other steps are not available as it needs to be loaded via AJAX),
when field_group multipage is not AJAX, the jQuery events works, so you can switch between pages, but the server-side validation doesn't work as nothing is submitted on Next button

but I need both to work (server-side validation and jumplist links).

Further info

See also the following related issue.

I'm thinking to do:

jQuery, but I'm not sure how to access the step the user is in,
rendering navigation block (or jumplist it-self) with the AJAX form (dirty and tricky), e.g.

// Implements hook_form_alter().
$block = module_invoke('multipage_jumplist', 'block_view', 'd07d74b8ad268f8c');
$rendered_block = theme('block', $block);
$theme_code = theme('multipage_jumplist', $foo);
$form['navigation'] = array('#markup' => $rendered_block);

not to use AJAX, but I need it for step-by-step server-side validation (FGAM+IFE),
create a session variable and pass to the JS (but the page won't be reloaded), or override jumplist theme hook, e.g.

// hook_form_alter - Get step we're in.
$step = empty($form_state['storage']['field_group_ajaxified_multipage_step']) ? 1 : $form_state['storage']['field_group_ajaxified_multipage_step'];
$curr_step = &$_SESSION[end((arg())) . '-step'];
$curr_step = max($step, $curr_step);
// theme_multipage_jumplist_item - Parse the jumplist
$visited_steps = &$_SESSION[end((arg())) . '-step'];
if ($variables['counter'] <= $visited_steps) {
    // return either clickable item or not.
}

customize/patch the module (where to start),
find some alternative solution

Question

How do I alter/update my multipage jumplist block (unaware of form context) based on the current step user is in having AJAXified form?

By updating I mean either knowing which element is active, or have ability to extend the behaviour and disable further steps (from being clickable) which weren't visited yet.

What's your suggestion? What would be the Drupal-way?

This was implemented by patching/extending FGAM module and the following jQuery code:

/**
 * @file
 * Connect jumplist to their corresponding multipage panes.
 */
(function ($) {
  Drupal.behaviors.multipageJumplistFix = {
    step: 1,
    maxStep: 1,
    attach: function(context) {

      // Wrapper changes its id but it's id must be static!
      $('div[id^="foo-entityform-edit-form"][id$="form-ajax-wrapper"]').attr('id', 'foo-entityform-edit-form-form-ajax-wrapper');

      this.step = $('.multipage_step_change.active').attr('step');
      this.numSteps = $('.multipage-jumplist > li').length;
      this.maxStep = Math.max (this.maxStep, this.step);

      this.updateActive ();

    },
    updateActive: function () {
      $('.multipage-jumplist a').removeClass('active');
      $('.multipage-jumplist a[step=' + this.step + ']').addClass ('active');

      for (var i = 1; i <= this.numSteps; ++i) {
        if (i > this.maxStep + 1)
          $('.multipage-jumplist a[step=' + i + ']').addClass ('disabled');
        else
          $('.multipage-jumplist a[step=' + i + ']').removeClass ('disabled');
      }
    }
  };

  $(function () {
    $('.multipage-jumplist').html($('.multipage-jumplist').html());

    $('.multipage-jumplist a').each(function (index, el, e) {
      el.step = index + 1;
      $(this).click (function (e) {
        console.log (this.step);
        if (!$(this).hasClass('disabled')) {
          $('.multipage_step_change[step=' + this.step + ']').trigger('mousedown');
          return false;
        }
      });
    });

    Drupal.behaviors.multipageJumplistFix.attach();
  });
})(jQuery);

which is loaded from the theme and then few enhancements in template.php:

/**
 * Implements hook_form_alter().
 */
function theme_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'entityform_edit_form') !== FALSE) {
    drupal_add_js(drupal_get_path('theme', 'foo') .'/js/eforms.js');

    $step = empty($form_state['storage']['field_group_ajaxified_multipage_step']) ? 1 : $form_state['storage']['field_group_ajaxified_multipage_step'];
    $curr_step = &$_SESSION[end((arg())) . '-step'];
    $curr_step = max($step, $curr_step);

    unset($form['actions']['prev']);
    unset($form['actions']['next']);

    if (!empty($form['#multipage_jumplist_instances'])) {
      $num_steps = count($form['#multipage_jumplist_instances'][0]['panes']);

      for ($i = 1; $i <= $num_steps; ++$i) {
        $active = $step == $i;
        $is_prev = $i == ($step - 1);
        $is_next = $i == ($step + 1);
        $form['actions'][$is_prev ? 'prev' : ($is_next ? 'next' : ('step' . $i))] = array(
          '#type' => 'submit',
          '#value' => $is_next ? t('Continue') : ($is_prev ? t('Previous') : ('Step' . $i)),
          '#id' => 'step' . $i,
          '#attributes' => array('step' => $i, 'style' => (($is_prev || $is_next) ? '' : 'display: none'), 'class' => array('multipage_step_change', ($active ? 'active' : ''))),
          '#submit' => array('theme_multipage_step_change_submit'),
          '#ajax' => array(
            'wrapper' => 'foo-entityform-edit-form-form-ajax-wrapper',
            'callback' => '_field_group_ajaxified_multipage_form_callback',
          ),
        );
        if ($i < $step) {
          // We don't want validation when going back.
          $form['actions']['step' . $i]['#limit_validation_errors'] = array();
        }
      }
    }

  }
}

function theme_multipage_step_change_submit(&$form, &$form_state) {
  $step = substr($form_state['triggering_element']['#id'], 4);

  $form_state['triggering_element']['#array_parents'] = array('actions', 'step' . $step);
  $form_state['triggering_element']['#parents']       = array('actions', 'step' . $step);

  _field_group_ajaxified_multipage_form_submit($form, $form_state);

  $form_state['rebuild'] = TRUE;
}

This can be also extended by theme overrides for: theme_multipage_jumplist() and theme_multipage_jumplist_item().

Hope that helps.


send emails to specific addresses based on value of fields I have field_a with select list of 10 value

when field_b is checked
and
when a value of field_a is alfa or beta or ecc, send email to address1 or 2 or ecc

I try with custom module for advance control of features

function test_mail_node_submit($node, $form, &$form_state) {
 if($node->type == 'rso') {
  if ($node->field_b['und'][0]['value'] == TRUE){
   if ($node->field_a['und'][0]['tid'] == '10'){
    mail('example1@mail.com', 'example2@mail.com', 'example text');
   }
  }
 }
}

I did not understand how to use drupal_mail, or hook_menu hook_mail_alter

I am a little confused about your question. But here is an example for you to send email using hook_mail. Hope you can get some idea from this:

/**
* Implement hook_mail() function
*/
function test_mail_node_mail($key, &$message, $params) {
   $headers = array(
     'MIME-Version' => '1.0',
     'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
     'Content-Transfer-Encoding' => '8Bit',
     'X-Mailer' => 'Drupal'
   );

   foreach ($headers as $key => $value) {
      $message['headers'][$key] = $value;
   }

   $message['subject'] = $params['subject'];
   $message['body'] = $params['body'];
}

/**
* Implement hook_submit() function
*/
function test_mail_node_submit($node, $form, &$form_state) {
   if($node->type == 'rso') {
     if ($node->field_b['und'][0]['value'] == TRUE){
       if ($node->field_a['und'][0]['tid'] == '10'){
          // mail('example1@mail.com', 'example2@mail.com', 'example text');
          $valid_email = array('example1@mail.com', 'example2@mail.com');
          $params = array(
             'body' => 'Your body text',
             'subject' => 'This is a subject',
          );
          drupal_mail('test_mail_node', 'HTML', $valid_email, 'en', $params));
       }
     }
  }
}


Services for Products I have a requirement where my website serves both products and services. I am using Drupal e-Commerce module for the same. It works perfectly fine for Products where we can set price for each product and user checks out from cart.

However, Services differ in their workflow. Each service product for ex: Electrician, will be associated with a service resource person, let's say Mr. XYZ. Now following are the requirements:

Service Person is allocated to a service request product.
The price of the service will be estimated after the service is provided.
Rating & Reviews provided in case of service should be attributed to the Service resource as against that of the Product where rating is associated with a product.
The price for a provided service has to be updated to the Order after the service is completed.

These differences are identified for starters, many more complex things might come in future. I have searched enough and I could not find a module which would satisfy the needs of both products and services. In fact, there is none for services. Is there a way to achieve what I want?

Agree with the above and I would also add several suggestions:
 - use Taxonomy and Taxonomy Access Control modules to control access to
   content and who can update which service node
 - use Computed Field module that would take a value from related content to change a value (price) of the service/order depending on who did the work and what was the final price

Also, maybe this problem should be approached from a different angle? Maybe the service "product" should still be sold through e-commerce but instead of being "sold" would be "ordered" first, service performed and only then the final price updated, sold and ready for payment? Possibly that would require adding extra step in the checkout or allowing people to "order service" (Service would be a content type that people could assign to themselves as the "buyer") and only when performed and price was assigned, the Service would go through regular e-commerce checkout process with payment mechanism.


Can't get workflow to show up on D7 Menus The workflow menu doesn't seem to show in the menu system in Drupal 7. The only place that I see "workflow" is in the configuration section, and it appears as a section called "workflow" and it only has Rules in it!

This is the exact same problem on the documentation (https://drupal.org/node/872876), however that did not help!

I've installed workflow UI and workflow API, Rules and Rules UI,  flushed all caches, uninstalled rules and workflow modules, reinstalled, tried various combinations of the modules, etc. Still no workflow option in the configuration menu.

I must be missing something stupid because lots of people are using workflow...

Make sure your account has "Administer workflow" permission.


Boolean field inside node twig renders ok but does not work in if statement I have an node twig and I want to use field of that node inside if of that twig. I managed to get the boolean value via content.field_sample|raw. But it looks like it doesn't work in if statement. For give code:

Value: {{ content.field_sample|raw }}
{% if content.field_sample|raw == '1' %}
    OK
{% else %}
    Error
{% endif %}

I get output:

Value: 1
Error

Sames goes for {% if content.field_sample|raw == 1 %}.

{% if content.field_sample|raw == true %} always returns true, regardless the boolean is on or off (it returns true for both Value: 0 and Value: 1). I guess it's  because it just checks if fields exists.

In content is the render array of the field output. A boolean is probably a text in #markup. What text this is for 0/1 can be configured in the display mode. But don't try to find it there, better use for coding the node. There you get the values directly from the database.

{% if node.field_sample.value %}


Trigger Authcache Reload on Field Change for Drupal Commerce Products I activated authcache and the cache system is working well.
When i change the price for a product the page is read from the cache.
How can i trigger to reload the page from database if one specific field (price field for example) is changed?

Information on my installation:

I have installed Drupal Core 7.37 , Commerce 7.x-1.11. and AuthCache 7.x-2.0-beta5.

Authcache comes with an integration module for the Cache Expiration project. See also the Authcache 2 tuning guide - integrate with Cache Expiration module.

It might get tricky to find all pages where a particular product/price is displayed due to the separation of products and display nodes in commerce. Depending on how frequent prices are changed, you might consider nuking the whole cache, e.g. using a combination of Rules and the Cache Actions module.


Field formatter only displays file name not link to file I installed Drupal 8.3.5, no extra plugins or themes. I have added in the "base page" (structure/type) a field (file_in) to upload files.

If I add a new page (node/add/page) and also load a file in file_in (file2.txt), the new page displays me the link to the file.

Then I add a new field called file_ext as entity reference (file type). If I add a new page (node/add/page) and put in file_ext a reference to the file2.txt, I see the new page, but with only the label name of the file, not its link.

File module is enabled, version Drupal 8.3.5 (new and clean).

You should go to (structure -> content types -> page -> manage display):

/admin/structure/types/manage/page/display

and set your fields format and its corresponding settings the way you prefer.

Further reading on the topic: here

Youtube tutorial: here


hook_block_view not being called I have a custom module which has some custom blocks in. My blocks display in the block page so they are being registered with hook_block_info.

However my modules are not displaying anything on the screen. I have added a dpm('hit') at the the top of hook_block_view for my module but nothing is being displayed.

I have added hook_block_view_alter to my module and see that the blocks are being displayed there but with the $data parameter being null/empty.

I have run my code through the coder module and it is not seeing any errors.

What could be going wrong?

After looking around the code I ended up the _block_load_blocks function. Before calling drupal_alter('block_list', $block_info); I had 6 elements in $block_info. After the function had run I had 2 items.

Doing some digging in drupal_alter I fount out what modules were touching $block_info. The domain module was removing the blocks.

Looking at the settings on the block page I did not have my domain ticked. The message under the domain options did say:

  Limit block display to these affiliates. This block is visible on all
  domains by default using this theme.

So thought the block would appear by default. This was not the case.


Weird behaviour when using dsm I am using Drupal 7 on a CentOS 6.5 box. I am trying to debug some code which produces the following error:

  User error: ImageMagick error 1: convert: no decode delegate for this
  image format  /tmp/thesis-163.OBJ.xml' @ constitute.c/ReadImage/503.
  convert: missing an image  filename
  jpg:/tmp/thesis-163.OBJ.PREVIEW.jpg' @
  convert.c/ConvertImageCommand/2800.  in _imagemagick_convert_exec()
  (line 519 of
  /var/www/html/sites/all/modules/imagemagick/imagemagick.module).

I can see that the problem is caused by the fact that ImageMagick is trying to make jpg out of a xml file. What the error is about, isn't really the issue. The issue is that, when I insert a dsm statement to check what is going and run the program again, the error goes away. If I comment out the dsm statement and run the program again the error returns. I have never seen this type of behaviour before and can't explain it.

Unfortunately, I can't reproduce this behavior with a small snippet of code otherwise I would post it here.

Can someone explain why this is happening so that I can fix it?

You may be experiencing a Krumo side effect:

https://drupal.org/node/1855468

The problem is that PHP handles references to array elements in a risky way, see this article: PHP: References To Array Elements Are Risky

I haven't read the post deeply, and can't assure you have this problem, but you may try the workaround to see if it works: use Krumo NG.

Another way is to use dd to dump your traces to a file, see functions documentation: https://api.drupal.org/api/devel/devel.module/function/dd/7


Please explain caching in complex render arrays The Scenario

In hook_block_configure(), I'm displaying a configuration form to users that is represented by a fairly complicated render array. The purpose of the form is to allow users to configure an arbitrary number of buttons as part of a button set.

Each button is individually configurable.
As part of each button's configuration, the user can select an icon from a list of icons. This list is mostly static, although users can upload additional icons on a per-site basis.
This module is for use in a Drupal multi-site configuration, where each site can field one or more of these button sets.
Each button configuration also features a preview rendering of the button.
There is a single rendering of the entire button set on the form as well.

The Question

How best to use caching within this render array? Is it possible to separately cache portions of the render array? For instance, could I separately cache each button configuration, as well as the icons and the rendered buttons?

While solutions to this exact situation would be appreciated, I'm actually more interested in insight into the finer points of adding caching to a complex render array. I believe that I've read most of the introductory documentation on caching that is readily available on the Internet, but haven't found much regarding more involved render arrays.

Sources

I found these sources to be very useful in attaining a basic understanding of caching in Drupal:

https://www.lullabot.com/articles/a-beginners-guide-to-caching-data-in-drupal-7
http://omnifik.com/blog/render-arrays-and-cache-drupal-7

Thanks to all for your insights!

http://omnifik.com/blog/render-arrays-and-cache-drupal-7 is an excellent resource, I use it as a guide when caching render arrays. The nice thing about render arrays is they are recursive. So for the hook_menu page callback you can have that function return mutiple items. As an example I have the page callback function looks like this

function my_page_callback() {
  // Form dumps values in the URL, act on them.
  $input_values_from_form = drupal_get_query_parameters();

  // Get form with URL values set in the form as defaults.
  $input_form = drupal_get_form('my_form', $input_value_from_form);

  // Build table render array.
  $table = array(
    '#theme' => 'table',
    '#pre_render' => array('my_table_pre_render'),
    '#header' => $header,
    '#rows' => $rows,
    '#links' => $links,
    '#url_queries' => $url_queries,
    '#filters' => $filters,
    '#entity_types' => $entity_types,
    '#missing_info' => $missing_info,
    '#attributes' => array('class' => array('table', 'table-striped')),
    '#attached' => array('css' => array(drupal_get_path('module', 'my_module') . '/css/table.css' => array('type' => 'file'))),
    '#cache' => array(
      'keys' => $input_values_from_form,
      // Cache this for 1 hour.
      'expire' => REQUEST_TIME + 3600,
    ),
  );

  // Put them together.
  $page_array = array($input_form, $table);

  return $page_array;
}

So this will render the input form first and the table second. Using this you can in theory split up your complex page into many smaller parts caching each array separately.

In the above example theme_table does most of the work but some other parts get used inside my_table_pre_render so the '#theme' => 'table', here is a complex example but it shows how to do this.

Pick the keys for each render array wisely as in make it relevant only to that part of the page; see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_render_cid_create/7.x


save/get data from map field type What I want to do is give a possibility to the user to save as many images as he likes. For this, I have created a specific field type

    $fields['photo_ids'] = BaseFieldDefinition::create('map')
  ->setLabel(t('Photos'))
  ->setDescription(t('The photo ids of the Item entity.'))
  ->setSettings([
    'max_length' => 50,
    'text_processing' => 0,
  ])
  ->setDefaultValue('');

here I want to save, add, delete IDs of pictures. Not sure if this is the best approach to this problem. The problem is I can't find the way in Drupal 8 to serialize/deserialize and save these data into the database;

You should not create your content type programmatically, if there's no special reason. Take a look at any intro like this https://www.youtube.com/watch?v=Nfu6nckjuno - then create a content type and fields with the excellent admin UI.

Serialization to DB is done by the Drupal core.


Custom Entity API does not give individual fields in Views, only (sometimes information-less) rendered entities note: I'm currently exploring hook_entity_property_info_alter and clearing the cache forcibly by truncating the cache table as I've had many iterations of work on this over the years. (Though I wouldn't recommend you trying that and if you do, back up first!)

I've defined entities in hook_entity_info. But when I have I get differing results and none of them work in Views as I was hoping.

"Paid subs" doesn't give me control of individual fields and therefore allow me to mix one field here with another of a joined entity there. But it does give fairly decent information.

This is its definition in hook_entity_info:

$info['paid_sub'] = array(
    'label' => t('Paid subscription'),
    'plural label' => t('Paid subscriptions'),
    'description' => t('company paid subscriptions (in theory
        this could be just postage or the full cover price etc.'),
    'base table' => 'company_paid_subs',
    'entity keys' => array(
        'id' => 'psid',
    ),
    'uri callback' => 'entity_class_uri',
    'entity class' => 'PaidSubEntity',
    'controller class' => 'PaidSubEntityController',
    'admin ui' => array(
        'path' => 'admin/paid-subs',
        'controller class' => 'PaidSubEntityUIController',
        'menu wildcard' => '%paidsubentity',
        'file' => 'paidsubentity.admin.inc',
    ),
    'module' => 'company_subs',
    'access callback' => 'paidsubentity_access_callback',
    'label callback' => 'paidsubentity_label_callback',
    'views controller class' => 'EntityDefaultViewsController',
);

paid subscriptions

Subscription

This one: "Subscription" doesn't do anything remotely useful.

hook_entity_info code:

$info['subscription'] = array(
    'label' => t('Subscription'),
    'plural label' => t('Subscriptions'),
    'description' => t('A subscription (as opposed to
        user registrations, paid recipients of magazines, promo readers etc.)'),
    'base table' => 'subscription',
    'entity keys' => array(
        'id' => 'sid',
        'revision' => 'revision_id',
    ),
    'entity class' => 'SubscriptionEntity',
    'controller class' => 'SubscriptionEntityController',
    'module' => 'company_subs',
    'access callback' => 'subscriptionentity_access_callback',
    'label callback' => 'susbcriptionentity_label_callback',
    'revision table' => 'subscription_revision',
);

Is it because I have been overriding default configurations? What's the cause? Ideally I'd like to be able to select individual fields within an entity rather than having to rely on a rendered entity because I'd like to be able to select one field from one entity and another from another entity by using joins in hook_views_data_alter, like this (which worked just fine until I stopped defining each field in hook_views_data and turned the bespoke tables into entities specifically to try and utilise the extra functionality of core and contrib modules etc.):

$data['subscription']['user_id']
['relationship']['handler'] = 'views_handler_relationship';
$data['subscription']['user_id']
['relationship']['base'] = 'users';
$data['subscription']['user_id']
['relationship']['base field'] = 'uid';

If you've tried conventional approaches and they haven't worked (like me) then you might find that there are a few things that you need to do:

Firstly for me was truncating the cache table just to get rid of a whole heap of old data from previous iterations of my designs. Then it was simply defining hook_entity_property_info as suggested. To check if things are working you can debug and use hook_views_data_alter(&$info) and check out the variables. You'll probably see views has two varieties (unless I'm still doing something wrong):

entity_subscription and views_entity_subscription...

entity_subscription Array [3]
    table   Array [2]
        group   Subscription
        entity type subscription
    user_id Array [4]
        title   user id
        help    user id of registrant
        field   Array [2]
            handler entity_views_handler_field_entity
            type    user
        relationship    Array [5]
            handler entity_views_handler_relationship
            base    entity_user
            base field  uid
            relationship field  user_id
            label   user id
    magazine_id Array [4]
        title   magazine id
        help    magazine id of this subscription
        field   Array [2]
            handler entity_views_handler_field_entity
            type    magazine
        relationship    Array [5]
            handler entity_views_handler_relationship
            base    entity_magazine
            base field  mid
            relationship field  magazine_id
            label   magazine id
views_entity_subscription   Array [1]
    rendered_entity Array [3]
        title   Rendered Subscription
        help    The Subscription of the current relationship rendered using a view mode.
        field   Array [3]
            handler entity_views_handler_field_entity
            type    subscription
            real field  entity object

And then as is suggested a whole heap of different places, those fields will be available and if you go to "Relationships" in the Views config then you can also add other entities and their properties. For example 'user' as is the case with "entity_subscription" above, defined by specifying "type" as "user".

Oh, and also - the views_entity_subscription was just a rendered entity, I presume this is for a direct entity/views use, for example when creating a view just of that entity type.

One final thing: the entity api module itself actually has, in the folder within that module called 'modules' (i.e. sites/all/modules/entity/modules/...) a whole heap of hook_entity_property_info() for the main (core) Drupal entities. This means you can open user.info.inc for example and see how the module authors wrote the entity_property_info for the user entity.


Upgrade from D6 cause unability to edit existing node After upgrading my Drupal website from D6 to D7, I regularly get this error message that prevents me from being able to edit existing nodes:

  The website encountered an unexpected error. Please try again later.

  PDOException : SQLSTATE[HY000]: General error: 1366 Incorrect integer
  value: '' for column 'field_galerie_image_vdl_width' at row 1: INSERT
  INTO {field_data_field_galerie_image_vdl} (entity_type, entity_id,
  revision_id, bundle, delta, language, field_galerie_image_vdl_fid,
  field_galerie_image_vdl_alt, field_galerie_image_vdl_title,
  field_galerie_image_vdl_width, field_galerie_image_vdl_height) VALUES
  (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6, :db_insert_placeholder_7,
  :db_insert_placeholder_8, :db_insert_placeholder_9,
  :db_insert_placeholder_10), (:db_insert_placeholder_11,
  :db_insert_placeholder_12, :db_insert_placeholder_13,
  :db_insert_placeholder_14, :db_insert_placeholder_15,
  :db_insert_placeholder_16, :db_insert_placeholder_17,
  :db_insert_placeholder_18, :db_insert_placeholder_19,
  :db_insert_placeholder_20, :db_insert_placeholder_21),
  (:db_insert_placeholder_22, :db_insert_placeholder_23,
  :db_insert_placeholder_24, :db_insert_placeholder_25,
  :db_insert_placeholder_26, :db_insert_placeholder_27,
  :db_insert_placeholder_28, :db_insert_placeholder_29,
  :db_insert_placeholder_30, :db_insert_placeholder_31,
  :db_insert_placeholder_32), (:db_insert_placeholder_33,
  :db_insert_placeholder_34, :db_insert_placeholder_35,
  :db_insert_placeholder_36, :db_insert_placeholder_37,
  :db_insert_placeholder_38, :db_insert_placeholder_39,
  :db_insert_placeholder_40, :db_insert_placeholder_41,
  :db_insert_placeholder_42, :db_insert_placeholder_43); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 97
  [:db_insert_placeholder_2] => 98 [:db_insert_placeholder_3] =>
  contenu_sortie_action [:db_insert_placeholder_4] => 0
  [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 251
  [:db_insert_placeholder_7] => [:db_insert_placeholder_8] =>
  [:db_insert_placeholder_9] => [:db_insert_placeholder_10] =>
  [:db_insert_placeholder_11] => node [:db_insert_placeholder_12] => 97
  [:db_insert_placeholder_13] => 98 [:db_insert_placeholder_14] =>
  contenu_sortie_action [:db_insert_placeholder_15] => 1
  [:db_insert_placeholder_16] => und [:db_insert_placeholder_17] => 252
  [:db_insert_placeholder_18] => [:db_insert_placeholder_19] =>
  [:db_insert_placeholder_20] => [:db_insert_placeholder_21] =>
  [:db_insert_placeholder_22] => node [:db_insert_placeholder_23] => 97
  [:db_insert_placeholder_24] => 98 [:db_insert_placeholder_25] =>
  contenu_sortie_action [:db_insert_placeholder_26] => 2
  [:db_insert_placeholder_27] => und [:db_insert_placeholder_28] => 253
  [:db_insert_placeholder_29] => [:db_insert_placeholder_30] =>
  [:db_insert_placeholder_31] => [:db_insert_placeholder_32] =>
  [:db_insert_placeholder_33] => node [:db_insert_placeholder_34] => 97
  [:db_insert_placeholder_35] => 98 [:db_insert_placeholder_36] =>
  contenu_sortie_action [:db_insert_placeholder_37] => 3
  [:db_insert_placeholder_38] => und [:db_insert_placeholder_39] => 254
  [:db_insert_placeholder_40] => [:db_insert_placeholder_41] =>
  [:db_insert_placeholder_42] => [:db_insert_placeholder_43] => ) dans
  field_sql_storage_field_storage_write() (ligne 451 dans
  /var/www/drupal7/modules/field/modules/field_sql_storage/field_sql_storage.module).

What can I do to fix this?

I also can't finalise my upgrade due to missing a widget in field type too - could these problems be linked?

If there was changes in the fields you were using in the very nodes, that renders nodes unusable, you will need to export data from 6.x site to some more or less universal format, like csv or xml, and import it anew to 7.x

Delete migrated data and it's content type
Create new content type with new-style fields, that maps 1:1 to old node structure. If possible, keep names
Export node data from original site (recreated from backup if needed), using Node Export, Views data export or similar tool
Secure all the files referenced by nodes
If needed, manually upload secured files to new version; see next step
Import nodes using tool like Node Export or Feeds - it may be required for files to be already uploaded, read the manual of your importing tool


Using twig|without for a commerce product I have a twig template for my commerce product, commerc-product--contenttype.html.twig:

      {{ product.field_price_original }}
      {{ product.variation_price }}

      {{ product.field_discount_percentage }}

  {{ product|without('variation_attributes', 'product.field_price_original', 'product.variation_price', 'product.field_discount_percentage') }}

I want to print three fields separately first and then print the rest of the content except for the first three fields (which have already been printed).

However, even though this note implies that without can take multiple values, everything is being printed; the without is ignored.

If I try a single value like this:

  {{ product|without('product.field_price_original') }}

The without is still ignored.  What might be the cause of this?

Drupal 8.4 and Commerce 2.1

You remove the sub-keys below product:

article{{ attributes }}>

      {{ product.field_price_original }}
      {{ product.variation_price }}

      {{ product.field_discount_percentage }}

  {{ product|without('field_price_original', 'variation_price', 'field_discount_percentage') }}


Apache filehandle issue expected to be mission critical for image uploading I have a fresh install of Drupal Commons (version 6.25), and I am not allowed to upload an image. See the full description of this so called image upload issue here on this site.

new Update one a sitenote...

i want to mention  that i - for the purpose of some tests have put two sites onto the server

http://schulcenter.net (for sure Version Drupal-Commons 6.25)
http://schulcenter.org - (probably Version Drupal-Commons 6.23)

and they run on the same database ;-)

guess that that can cause the open File handles
what do you think !? Love to hear from you

well i guess that i have to switch off one site. ;-) greetings (end of update)

here the original-initial-thread starts:

I have changed some settings regarding the file handling; I set the permissions for sites/default/files, I created a temporary directory and edited the paths accordingly. All of these seem to work, and workarounds did not change the bad habit of the site: The image upload is impossible.

Can we verify the impact of a decreased amount of Apache File handlers on the possibilities and capabilities of file, and image-handles, especially of the option to upload images? Is there any impact?

dman, a very experienced web and Drupal developer, had a closer look at the site and noticed the site status under the 'Reports' tab lists many errors, including the following one:

  opendir(*) [function.opendir]: failed to open dir: Too many open files in /home/vhost/WWW/schulcenter.net/includes/file.inc on line 963.

It seems like it could make anything on the site break, especially things that work with files, but also anything that reads files.
I have more than 1200 repots of such message about opendir("profiles/drupal_commons/modules/acquia/acquia_search/apachesolr/drush").

I do not have installed any drush.
Besides this thing, I have no clue why we get such a big amount of open file handles the server is faced with.

  The dblog module monitors your website, capturing system events in a
  log to be reviewed by an authorized individual at a later time. The
  dblog log is simply a list of recorded events containing usage data,
  performance data, errors, warnings and operational information. It is
  vital to check the dblog report on a regular basis as it is often the
  only way to tell what is going on.

  Details
     Type   php
    Date    Sunday, 18 March, 2012 - 21:48
     User   martin
     Location   http://schulcenter.net/?q=admin/reports/dblog
     Referrer
     Message    opendir(profiles/drupal_commons/modules/acquia/acquia_search/apachesolr/drush) [function.opendir]: failed to open dir: Too many open files in /home/vhost/WWW/schulcenter.net/includes/file.inc on line 963.
     Severity   error
     Hostname   188.99.184.201
     Operations

Did you find this comment on drupal.org?

  The problem is a maximum open files limit per users.
  We had several web servers, and several new Apache2 VirtualHost; Apache2 (www-data) reached the maximum number of open files (1024).

  You can check that with ulimit -a  or ulimit -n. (The default is maximum 1024 open files.)

  You can modify it with ulimit -n 1500, but it will be lost after reboot.

  To make the change permanent, add in /etc/security/limits.conf:

#<domain> <type> <item> <value>
#
www-data soft nofile 1600
www-data hard nofile 65535

  Of course, restart your web server.

It explains how to set a per-user limit and increase the number of files that can be opened.  If you don't have enough memory in the server, there may not be many options.


Making a view block display link I'm currently migrating a website from Drupal 5 to Drupal 6. I've migrated most of the modules but something keeps nagging me: on Drupal 5 I had a block that displayed a snippet of text with a "More" link in a separate line. This snippet of text sent the user to a page with the full text.

After the Drupal 6 migration that snippet of text no longer links to anything. How can I make it lu

Fixed it by going to Views, selecting this particular view, selecting Block display and in the Field section editing the Node: title checking the box labelled "Link this field to its node".


Fill #options of select field I have a select field for a content type which has options generated dynamically. The options are updated in hook_form_alter(). The problem is that when I try to manipulate the posted data in submit callback, the field values are empty. Below is an example to better understand the issue.

function my_form_alter(&$form, &$form_state) {
    $options = array('a' => 1, 'b' => 2, 'c' => 3);
    $form['my_field'] = array(
        '#type' => 'select',
        '#title' => t('Label'),
        '#multiple' => TRUE,
        '#options' => $options,
        '#default_value' => '',
    );
    $form['#submit'][] = 'my_submit_handler';
}

function my_submit_handler($form) {
    echo "<pre>";
    var_dump($form['my_field']);
    echo "</pre>";
}

If I select options 2 and 3 for example; the var_dump returns empty array().

Submitted values are contained in $form_state['values']:

function my_submit_handler($form) {
  $selected_options = array_filter($form_state['values']['my_field']);
}

e.g. if you select '1' and '2' on the form, $selected_options will be array('a', 'b')


Flag count is incrementing only after page reload I have a views with like and unlike flag. When I click on like flag the count not increments. But when I reload the page, then only like's count will change. How can I solve this issue?

Note: I have already enabled ajax for my views.

I had the same problem, and find how to solve it. The Views Flag Refresh module is only available for Drupal 7, but someone ported it to work on Drupal 8, here is the download link.
I find it in this issue comment by WalkingDexter.
In my case I need it to work on Drupal 9, so it is necessary to change a line in a file in the downloaded custom module as Akash_Daimari explains in this comment.
The module would go in /modules/custom/
In the view you have to use Ajax and add the flag in 'Flag refresh' options.
As a note, in the View preview the count does not update, but on the page it does.


How to create custom entity in Drupal 8 I have a big personal project build on Drupal 7 that has many custom entities. I want to start upgrading the project into Drupal 8 but the completly rewritten Drupal 8 core is too big for me to get my head around without any documentation(+ Symfony is totally unknown to me, I'm just a simple Drupal-only guy).

I tried to create a custom entity just by looking at some of the core modules code but without any success.

Can you point me to some articles about custom entities in Drupal 8(I haven't been able to find single one) or give me some basic step-by-step guide?

Thanks.

I'm working on Entity API documentation here: https://drupal.org/developing/api/entity.

The question is too big to answer in detail, and it depends on whether you need content or config entities. Assuming you want content entities (stored in database, can be fieldable/revisionable/..., details in the link above), you need to do something like this, the documentation linked above will eventually cover each step, including tutorials, right now, it only covers the first steps.

Provide an entity class and add the necessary annotations to expose it as an entity.
Provide the necessary table(s), you don't have to change much if you already have your 7.x schema, but you want to add a uuid and possibly langcode column if your entity can have a language/be translatable. See the node example linked in step if you want to make some base fields (properties) translatable or revisionable, you currently need to provide the necessary tables yourself.
Provide the base field definitions in your baseFieldDefinitions() method.. Note that the way this works will change in https://drupal.org/node/2047229 (from arrays to classes).
Implement the necessary pre/post Save/load/Delete methods if you have custom logic that needs to happen e.g. before saving an entity (like updating the changed timestamp).
Implement an access controller if you have non-trivial access logic and override the checkAccess() and checkCreateAccess() methods or specify the admin_permission in your annotation if you just have a single permission that allows full access.
It is recommended although not technically required to provide an interface for your entity class (e.g. NodeInterface for Node) that includes useful (usually get/set/isSomething()) methods for your base fields, so that you can type hint on the interface and get auto-complete for those methods.

Depending on what you need, there will also be further steps, like defining the necessary forms, possibly a render controller and so on, but those should probably be separate questions if you need more information.

Notes:

Config entities are basically similar, except you need to use the config storage controller (https://drupal.org/node/2119905 will make this easier), you don't need to define table schemas (obviously) but you need to provide a config schema file, see e.g. those for taxonomy vocabularies or node types.
Content entities don't have their base fields defined as public or protected properties, instead, they are automatically managed in the values and fields properties. Access them either through get()/set() or the corresponding magic methods. ($node->title is equal to $node->get('title')).
Help on the documentation there would be very welcome. I've created a basic outline for the content/structure I'd like to have, so just create a new page and get started on e.g.  I'm also interested in having simplified tutorials, for config entities, there's one here already that I will move over to the entity documentation when ready: https://drupal.org/node/1809494
Core has quite a large number of content entity implementations, if you want to see working examples: Node, User, Term, Comment, CustomBlock, ... as the article linked in step 1 explains, you can always find the entity types provided by a module in the Entity namespaace.
@fago just gave a presentation about Entity API at the DrupalCamp Vienna this weekend, covers a lot of what I wrote here and more.


Change the value of a piece of content using a comment I have a content type which I don't want a user to be able to edit once it has been created.  but I want them to be able to change 1 value and the way I want them to do that is through a selection box on a comment.  For example, on the content type there is a priority field.  When a user leaves a comment I have a selection box added to the comment with the same options.

How can I get that option box to sync with the option in the node itself?

Thanks

Kieran

Assuming your content type is called your_content_type and your module is called yourmodulename, you can use the following code:

It will set some state when a none-priviledged user posts a comment, and show a state selection UI for priviledged users. The state will be saved to the CCK field_erledigt_warten in the node in either case.

<?php
/**
 * Implementation of hook_comment().
 * Fill a CCK field  in Drupal 6
 */
function yourmodulename_comment(&$comment, $op) {
  global $user;

  if (is_array($comment)) {
    $node = node_load($comment['nid']);
  }
  else {
    $node = node_load($comment->nid);
  }

  if ($node->type == 'your_content_type') {
    switch ($op) {
      case 'insert':
      case 'update':
        if (user_access('edit field_erledigt_warten')) {
          // QD-Mitarbeiter
          if (isset($comment['field_erledigt_warten']) && $comment['field_erledigt_warten']) {
            if ($node->field_erledigt_warten[0]['value'] != $comment['field_erledigt_warten']) {
              $node->field_erledigt_warten[0]['value'] = $comment['field_erledigt_warten'];
              drupal_set_message(t('Status wurde auf %v ge&auml;ndert.', array('%v' => $comment['field_erledigt_warten'])));
              node_save($node);
            }
          }
        } else {
          // Kundenaccount
          $node->field_erledigt_warten[0]['value'] = 'neu';
          node_save($node);
        }
        break;
    }
  }
}

/**
    Implementation of hook_form_alter
 * Add a input box to the comment form
 */
function yourmodulename_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    if (is_array($form) && isset($form['nid']) && is_array($form['nid'])) {
      $node = node_load($form['nid']['#value']);
    }
    if (isset($node) && is_object($node) && isset($node->type) &&
      $node->type == 'your_content_type' && user_access('edit field_erledigt_warten')) {
      $states = array_flip(array('some', 'values', 'come', 'here'));
      foreach($states as $text=>$index) $states[$text] = $text;
      $status = $node->field_erledigt_warten[0]['value'];
      $form['field_erledigt_warten'] = array(
        '#type' => 'select',
        '#title' => 'neuer Status dieser Forumseite',
        '#default_value' => $status,
        '#options' => $states,
      );
    }
  }
}


Image with title over top I am trying to create a view that has a image that is linked to another node, which I can do. However, I want to take the title (of content) and place it over top of the image like this.

I tried with CSS. Am I missing something?

This isn't really a Drupal question.

One of the usual methods is to use absolute positioning to remove the title from the document flow. Starting from HTML looking something like (e.g., rewriting with views):

Image title

Then use CSS rules something like:

.my-frame { position: relative; }
.my-title { position: absolute; top: 10; left: 10; }


What's the correct format for submitting a null value to an integer field using metadata wrapper? Problem

Whenever I submit a nothing to an integer field using the EntityMetadataWrapper I get the following error.

What's the correct format for submitting a null value to an integer field? (I don't want 0, but a blank value).

  EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in
  EntityMetadataWrapper->set() (line 122 of
  C:\XAMPP\htdocs\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).

How do you clear a field value with entity_metadata_wrapper()?

The post above implies I should be able to use:

$wrapper->title = '';

However this still throws the error.

Example

I have an integer field Salary added to a custom node type. (Along with several other fields which work as expected.)

Properties:

Not required
Has no minimum value
No default value
Can only hold one value.

I have a custom form which looks like this. This is the entry field:

$form['field_salary'] = array(
    '#type' => 'textfield',
    '#title' => t('Salary'),
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t('Please enter a valid number'),

This is the submit function taken from here:

function postajob_form_submit($form, &$form_state) {

 $values = array(
      'type' => 'job_advert',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 1,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    //.... (other fields in the form are here)
    $ewrapper->field_salary->set($form_state['values']['field_salary']);

    $ref_nid = 15;

    $my_date = new DateTime('January 1, 2013');
    $entity->field_my_date[LANGUAGE_NONE][0] = array(
       'value' => date_format($my_date, 'Y-m-d'),
       'timezone' => 'UTC',
       'timezone_db' => 'UTC',
     );

    $ewrapper->save(true);
    entity_save('node', $entity);

}

My guess is that it can't hold nothing? But that seems weird because it's not required.

I can for example create the node using the drupal default form with no errors and it works fine.

EDIT:

The solution from Wayne, removes the error but what I was hoping for was the ability to submit a blank value without it throwing an error. Unfortunately the following doesn't work.

'#default_value' => NULL,

I've considered using a string field instead of an integer one and then validating only for numbers, but this means I'll lose the ability to use the numeric range search facets, again not ideal.

Have you tried to check if the value exists before setting it?

//.... (other fields in the form are here)
if (!empty($form_state['values']['field_salary'])) {
  $ewrapper->field_salary->set($form_state['values']['field_salary']);
}

This way you're not touching the value if it's not set.


How to validate a custom widget? I have created a custom widget that I would like to add some validation to. Specifically, if the widget is marked as required, to check that it actually has a value entered. I figure this should be pretty straight forward but Googling isn't returning any results that I am looking for. Probably using the wrong search terms. If someone can provide a link on how to do this or provide some hints that would be great!

Thanks.

For a form API element, just set $form['element']['#required'] = TRUE;

More info: #required

  Indicates whether or not the element is required. This
  automatically validates for empty fields, and flags inputs as
  required.

For more control, consider an #element_validate handler

Note, for a custom element using hook_element_info, #validate and #element_validate callback handlers are supported there in the element definition.


Manage/Assign Roles to Users Other than Administrators I was asked to create a module that allows a user with the specific role to assign roles to other users w/no 'administer user' permissions or not an administrator. The user must not be allowed to edit info about the users with 'administer user' permission/admin.

How can I do this? Do I have to create a custom module for this? Is it possible to use Views module for this?

NOTE: Since Drupal 6 is un-supported now (check announcement), you won't get a module which still have the D6 version actively supported. Also don't expect the module to be supported for any issues.

You can check the Role Delegation module, which allow users to set user roles to other user. Following is the module description from module page:

  This module allows site administrators to grant specific roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

The last release of this module for Drupal 6 version was made available on 9 Dec 2010, you can download it from here.


Change field label used in node display I have a custom content type in Drupal 8.6.x. I want to be able to change the text used for a field label based on the value of a taxonomy term reference in the node.

For example, I want to change the field label used for the body field, to display "Description" or "Definition" or "Introduction", etc. based on the value in the taxonomy reference field. This is when rendering the node - I don't need to change the field label on the form. I'll need to alter the label in the full and teaser display modes, and just for the custom content type. I don't need to change any of the text in the body field, just what label is shown above it.

You can do this by implementing hook_entity_view_display_alter in a custom module.

Some code like this should work:

function HOOK_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
  if (
    $context['entity_type'] == 'node' &&
    $context['bundle'] == 'CUSTOM_CONTENT_TYPE' &&
    (
      $context['view_mode'] == 'full' ||
      $context['view_mode'] == 'teaser'
    )
  ) {
    foreach ($display->getComponents() as $name => $options) {
      if ($name == 'text' && isset($options['label'])) {
        $node = \Drupal::routeMatch()->getParameter('node');
        $options['label'] = $node->FIELD_TERMS->entity->label();
        $display->setComponent($name, $options);
      }
    }
  }
}


flowplayer with videojs module and video-js I'm not sure how to integrate videojs module with video-js libraries because at the moment I am using the code for video-js to open the swf player in my drupal page which works fine. However I can't get it to play FLV type video and that is because apparently I need flowplayer as fallback from html5.

My question is where should I place the flowplayer folder in conjunction with the rest? Should it go in sites/all/libraries and then I create a content type with field to use videojs module?

Why do I even need videojs module if you can just place video-js javascript code and html code in body of node?

As the project page says

If you are using latest videojs module i.e 7.x-2.3 with 3.x video.js version it comes with Flash fallback. Video.js library will handle the flash fallback option. You don't need to install swf tools or flowplayer API. You don't need to place flowplayer folder inside libraries folder.

If you would like to use flow player API you might need to use 7.x-1.x version of video.js module. As long as you follow installation instructions here you are good to go with 7.x-3.x version of module. Make sure you use right library of video.js version vs Module version as shown above and follow instructions in Readme file.


Print theme logo path in my twig file In mytheme.theme file I have:

function mytheme_preprocess_page(&$variables) {
      $variables['logopath'] = '/' . drupal_get_path('theme','mytheme') . '/logo.png';
}

In my menu--main.html.twig I have:

<img class="img-responsive" src="{{ logopath }}" />

But it's not printing my logo? The src is still empty?

You use different theme hooks page and menu.

If you want to use the variable in

menu--main.html.twig

use

function mytheme_preprocess_menu(&$variables) {


How to assign alt text to current inline images Let me set the scope first, these images are not uploaded from an image field, they are uploaded from CKeditor, via imce or ckeditor_image2. Therefore, they are in node body, together with other text (isn't that the worst scenario you can imagine?).
Now how do I approach this accessibility improvement after already having hundreds of potential images without alt text.

You can use my module Image auto ALT Filter in this case
https://www.drupal.org/project/image_auto_alt_filter
Only enable this filter for your text format, and all images will be with ALT tags. ALT generates from text keywords (I'm going to add some features in next release)