set variable in user object Recommended practice I use a field in user account to store some user variables. These variables are not accessible by the user.
I am worrying about the efficient of using the user_load in every page in order to access the variables.
Maybe it is better to use the variable_set() ? What is the recommended procedure of setting/accessing variables in drupal?

If efficiency is the goal, and your variables aren't too complex, you could take advantage of the data property of the user entity. It's stored as a serialised string in the {users} table and is available by default as part of the global $user object. As it's loaded from the database for any type of user load (even the bare minimum one) you can reduce the overhead to basically nothing.

The best example of how to use it comes from the docs for hook_user_presave():

function hook_user_presave(&$edit, $account, $category) {
  // Make sure that our form value 'mymodule_foo' is stored as
  // 'mymodule_bar' in the 'data' (serialized) column.
  if (isset($edit['mymodule_foo'])) {
    $edit['data']['mymodule_bar'] = $edit['mymodule_foo'];
  }
}

Then to retrieve the value at another point in code it's as simple as:

global $user;
$mymodule_bar = $user->data['mymodule_bar'];

Fields are great but as you know they do add overhead, so for small amounts of data I can't see any reason not to use the data property in this way.

I think using the variables table would get unmanageable quite quickly; you'd either end up with a different variable for each user, or having to store a single variable containing all users' data...neither of which are that desirable.


Print array of imagefield fields for node type I need to get an array of imagefields for a specific node type or even just all imagefields or all fields for a node type.

You can get a list of all fields for a particular content type using the content_types() function:

$type = content_types($type_name);

if (isset($type['fields'])) {
  $fields = $type['fields'];
}

From there you can just loop through and see what type of field each is, and act on it accordingly.


Special non-utf-8 characters appearing in feed imported from a windows based system? I have a custom feed importer that import content from an external feed. The import happens on cron and everything is working fine except that the content comes with special non-utf-8 characters. I looked on stackoverflow and there are a few suggestions about how to do this in code, I tried couple and it has not worked for me yet. I am hoping to see if there is a drupal way of handling it.
The character that I am having problem with is Â. It represent a space I believe and it only appear at end/and beginning of sentences.

You can use the Feeds Tamper module to do this with a custom plugin.

In your module:

/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($owner, $plugin_type){
  if ($owner == 'feeds_tamper' && $plugin_type == 'plugins') {
    return 'plugins';
  }
}

and in your module/plugins/utf8_encode.inc

$plugin = array(
  'form' => 'MYMODULE_utf8_encode_form',
  'callback' => 'MYMODULE_utf8_encode_callback',
  'name' => 'Convert ISO-8859-1 to UTF-8',
  'multi' => 'loop',
  'category' => 'Text',
);

function MYMODULE_utf8_encode_form($importer, $element_key, $settings) {
  $form = array();
  $form['html'] = array(
    '#markup' => t('This will convert all ISO-8859-1 characters to their UTF-8 equivalents.'
),
  );
  return $form;
}

function MYMODULE_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $field = utf8_encode($field);
}

If that doesn't work, then you can use one of the strip-non-UTF8 regex functions to do it in the callback instead.  I use

$regex = '/((?:[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}[\xF0-\xF7][\x80-\xBF]{3}){1,100})|./x';

preg_replace($regex, '$1', $field);


How can I programmatically insert content via a script or import instead of through the UI? I have a custom content type and I now need to create thousands of entries using that type. It would take a very, very long time to go through the interface and add these one by one. I'm hoping there is a plugin, module, or some kind of API so that I can create all of these entries in an excel and simply import them into the database. Is this possible?

I have not been able to get Drush working so that isn't really an option for me.

The most direct answer to your question is Migrate Source XSL module for the D8 Migrate API.

Or hell, dont have Windows/Excel installed do the same with Google Sheets Migrate Plus plugin.

I'm not sure if there is a UI for Migrate yet in D8. But this would be the most flexible solution. If needed you could use the drupal api itself to code simple insertion from a php script to create Nodes from an excel script; but the above migrate plugins should be much for flexible to debug in the long run -- but may require Drush support currently.

Edit

Ask previously, how to create a Node in D8:
Programmatically create nodes


How to change the "Add new comment" message for custom comment form? I have custom content type called books that represents a book that can be reviewed by using a custom comment type called reviews.

My problem is the comment form title above the comment form shows as "Add New comment", which I need to change as "review the book".

How can I change this to read as "review the book"?

The Add new comment header is a part of theme layer.

You can copy your theme's existing comment template (e.g. core/themes/classy/templates/field/field--comment.html.twig if you're using a theme that utilizes the base classy theme) over to your theme's template dir and rename it to match your specified field (e.g. field--field-my_custom_comment_machinename.html.twig). If you're not familiar with this, enable Twig template debugging.

Once you've create a copy of the template, you can then edit template header as you see fit.


How to create multiple nodes using Rules once? I have a content type named Run that have two entity reference

entity reference field named participants which reference user.
entity reference field named examinations which reference content type Examination.

I want to use Rules to create multiple nodes of content type "Results" for each user "participant" referenced in "Run". the number of Results nodes equals the number of examination.

So I created a rule that fires when the user views the node of type run and I made a loop through examination and I created results node. This runs OK for the first time. But when the user views the node again the nodes are duplicated n times as per number of node views.

Any suggestions how I can make the rule run once per user? Or any other work around.

You could use the Flag module and define a none global flag used to flag nodes of type "Run" (name the flag whatever you want).

Then extend your existing Rule like so:

Add an extra Rules Action to flag that node of type "Run" (to indicate that the rule was executed a first time for that user).
Add an extra Rules Condition to check that the node was NOT yet flagged by the user viewing the node.

Using this approach, you have a mechanisme in place that allows you to keep track of the users for which your rule was yes or no executed exactly 1 time.


How to show and hide menu tabs in module I have created tabs in module for different functions. As per code shown below, all the tabs are shown simultaneouly when I login to the module. But, I want to show specific modules depending on the play formats, how can I do that? I tried hook for menu_alter and created custom module but all hides specific menu directly and not condition wise.

Play URLs

$items['abc/play'] = array(
    'title' => t('Welcome Player'),
    'access arguments' => array('administer users'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('score_entry_table'),
    'access callback' => TRUE,
    'file' => 'scoreentry.inc',
);

$items['abc/play/cricket_score'] = array(
    'title'         => t('Cricket Scoreboard'),
    'page callback' => 'cricket_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'file' => 'cricketscore.inc',
    'weight' => 2
);
$items['abc/play/soccer_score'] = array(
    'title'         => t('Soccer Scoreboard'),
    'page callback' => 'soccer_score_table',
    'page arguments' => array(1),
    'access arguments' => array('administer users'),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'file' => 'soccerscore.inc',
    'weight' => 1
);

Now it shows both tabs after login, I want to show only one tab as per format. I go to scoreentry page, where I get the format code and I want to hide the tab based on that format.


How do I move a view display from a view to another one? I have a old view named Users with two displays (All-Users and Flagged-Users) and today I create another view named Flags and I have a display named Flagged-Books, but now I want transfer my display named Flagged-Users to my view named Flags.

I search inside the view configuration and inside the display configuration and I can't found this functionality. There is a trick or a way to achieve this?

I have installed Views 3.11.

This is tricky, but you can export both views to code and then add the desired display manually to the View.

In your case:

First export User view and Flags views

The exported views should be something like this:

$view = new view();
$view->name = 'frontpage';
$view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Front page';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Content: Sticky */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Promoted to front page */
$handler->display->display_options['filters']['promote']['id'] = 'promote';
$handler->display->display_options['filters']['promote']['table'] = 'node';
$handler->display->display_options['filters']['promote']['field'] = 'promote';
$handler->display->display_options['filters']['promote']['value'] = '1';
$handler->display->display_options['filters']['promote']['group'] = 0;
$handler->display->display_options['filters']['promote']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'frontpage';

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Front page feed';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'rss.xml';
$handler->display->display_options['displays'] = array(
  'default' => 'default',
  'page' => 'page',
);
$handler->display->display_options['sitename_title'] = '1';

As you can see, first you have the general View config, and then the definition and config for each view's displays.

Then you have to select the code regarding your display in User view and copy to the code of the Flag view, so you end with a Flag view with an added display.
Using the import functionality of Views import the modified view.

If everything is ok, Views will import your modified view with the added display.

The two views should be similar (they should show similar content, for example).


Is there a way to group Rules by type? I would like to know if there is a way to make groups or collections of Rules so it is easier to see the types of Rules I have created. Is there a module for this? Is this something where I can/should add a taxonomy term field, assign a term to each Rule and display it in a View?

You can "Tag" rules which is a nice feature to group / filter them.


How can I remove preview button from contact form? How to turn off preview in contact form in Drupal 8.1.x

A custom module can utilize hook_form_alter() to strip out the preview button form element in any form:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // Look for any form provided by the contact module.
  // If you want to target a specific form you'll use the whole form ID
  // (e.g. Website feedback = 'contact_message_feedback_form').
  if (strpos($form_id, 'contact_message_') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
  }
}


form_set_error() field not highlited red When validating a field manually from my form a error is displayed but the field doesn't get red. For the first parameter i used the name of the input element. DRUPAL 7

if($form_state['values']['panes']['webform_nid31'][0]['contact_person'] == '') {
    form_set_error('panes[webform_nid31][0][contact_person]', t('You must select a name for this group of settings.'));
  }

If your form element is defined like that:
$form['panes']['webform_nid31'][0]['contact_person'] = array( ... );

your form_set_error call should look like that:
form_set_error('panes][webform_nid31][0][contact_person',
                t('You must select a name for this group of settings.'));

You need to set full path to element, without outside [ and ]. You could have many "contact_person" fields in one form, just in different branches of a form tree. Using only last index would made setting errors ambiguous, thus it's not supported. At least officially. Might work, but only as an undocumented feature.
Formatting this string is described in API:

Parameters
$name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

Last but not least, actual output is defined in theme, it might well be something other than red border if theme author decided so.


Send an email notification to admin prior to poll close date I'm using Advanced Poll module and it has a nice "Time management" feature. We can schedule when to open or close the poll.

I want to send an email notification to the administrator one day prior to poll close date. So that, admin gets notified and create an another poll.

Is there any way to make this possible with Rules module or hooks?

You will need to create a Rule that will schedule component evaluation (send email).

CREATE COMPONENT

Create component plugin of type Rule (admin/config/workflow/rules/components/add) - name it "Notify admin about poll closure".
Provide a variable for the component to act on. Variable Data type = Content, Label - Poll Node, Machine name = poll_node, Usage = Parameter.

Add Conditions if you need any
Add Actions -> Send HTML e-mail. Set you email parameters
below is the export of the component

{ "rules_notify_admin_about_poll_closure" : {
    "LABEL" : "Notify admin about poll closure",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_i18n", "rules", "mimemail" ],
    "USES VARIABLES" : { "poll_node" : { "label" : "Poll Node", "type" : "node" } },
    "DO" : [
      { "mimemail" : {
          "key" : "poll_closure_notify_admin",
          "to" : "adminemail@email.com",
          "subject" : "Poll will close tomorrow",
          "body" : "Poll [poll-node:title] will close tomorrow",
          "plaintext" : [ "" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

CREATE RULE

React on Events: "After saving new content of type Advanced Poll", "After updating existing content of type Advanced Poll"
Add Conditions "Entity has field": Entity: node, Field: advpoll_dates
Add action "Schedule component evaluation" - select the component that you created "Notify admin about poll closure".

Scheduled Evaluation date -> node:advpoll-dates:value2. Add offset "-1 days". This will schedule the email 1 day before poll closing.

Set an identifier to something like "Poll closure notification: [node:nid] - [node:title]". It should have unique values everytime new scheduled task is added in queue, that is why you should use node:title and node:nid.

Set Poll Node field to node.

Save your rule and test.

{ "rules_schedule_notification_about_poll_closure" : {
"LABEL" : "Schedule notification about poll closure",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : {
  "node_insert--advpoll" : { "bundle" : "advpoll" },
  "node_update--advpoll" : { "bundle" : "advpoll" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "advpoll_dates" } }
],
"DO" : [
  { "schedule" : {
      "component" : "rules_notify_admin_about_poll_closure",
      "date" : {
        "select" : "node:advpoll-dates:value2",
        "date_offset" : { "value" : -86400 }
      },
      "identifier" : "Poll closure notification: [node:nid]",
      "param_poll_node" : [ "node" ]
    }
  }
]}}

I provided an export of the component and the rule that you can use and modify to your preference. Hope this helps.

P.S. Cron should be enabled and configured on your website in order for scheduled events to work properly.


How can I set value to hidden field (Form Api) and send them with post method? I’ve created a form with Form Api in a custom module.

I send datas with post method to a web service.

In buildForm()

$form['mode'] = array(
    '#type' => 'hidden',
    '#value' => 'INTERACTIVE',
);

$form['amount'] = array(
    '#type' => 'textfield'
);

$form['signature'] = array(
    '#type' => 'hidden',
     // here is the field I need to set its value on submit because its value depends on other field.
    '#value' => ''
 );

$form['#action'] = 'https://url-webservices.fr/‘

It works. But I need to set value to hidden fields 'signature' on submit.

How can I set value to hidden field and send them with form with post method ?

Something like this but it doesn't work :

in submitForm()

form_state->setValue('signature', $signature);

I’ve studied some examples and I can do that :

In validateForm()

$signature = 'string-to-send';
$form_state->setValue('signature', $signature);
$form_state->setRebuild();

And in buildForm() :

$signature = $form_state->getValue('signature');

$form['signature'] = array(
    '#type' => 'hidden',
    '#value' => $signature
);

Of course, it works only when page is reloaded when the form is rebuilt. If datas is send to an external URL with POST method, the field value is empty.

To summarize the question : I use an API where a SHA signature had to be sent along the form . That signature is calculated based on the other form inputs, so it had to be calculated after the user clicks the submit button and it had to be sent as a form field with POST method .

In buildForm(), I have :

$form['#action'] = 'https://url-webservices.fr/';

It is like it is executed before I can call validateForm() where I can set the value I need.

I've searched a lot for a solution but didn't find an easy way like set a news value in submitForm().

So here is a solution. I'm not completely happy with it but it works.

I've built a 2 steps forms.

In first step, the $form['#action'] is empty. After validation, I set a value to $form['#action'] and to the form fields I need :

$form_state->setValue('action', $url_action);

I also change the text of the submit button with something like "confirm".

Then user could confirm and validate the form.

All the mechanic of the 2 steps could be seen in that answer (thanx to Clive) :

How to use ConfirmFormBase to confirm the action of another form?


How can I create a Feature and have it saved under 'features manage' tab? I see that I can create a Feature, but the only option is to download it. Is there a way I can just have Drupal import it to the manage tab of Features?

You can use the "Direct save" feature of the Features Tools module if you want to do this from the UI instead of the command line with Drush.


In which file is the list of the installed modules saved? I am trying to synchronize some config data, and I'm getting the following error:

X depends on modules (examples here) that will not be installed after import.

Now I'm fine with adding the setting that they'll be enabled after synchronization, but I cannot for the life of me find any documentation or where in the config files this lives.

Does anyone have any information?

You are looking for core.extension.yml. Directory for configuration synchronization is set up in settings.php with variable $config_directories.

Here is the documentation, but it's not full.


How to remove base field overrides? Half of our content types have had their publication status fields overridden. The override is causing the fields to read "Publishing status" and have the description "A boolean indicating whether the node is published." I believe this is the same problem described in this comment. The row names are in the format core.base_field_override.node.[content-type].status in the database.

However, I am unsure of how to properly remove these overrides. Certainly I could just delete that row of the config table, but I am unaware of what consequences that may have or whether that would be the appropriate way to handle this one-time problem.

Can anyone tell me the correct way to remove base field overrides? Thanks!

Don't modify the config table. Export the config, delete the yaml file and import the config again.

From the command line you can delete configuration items with drush:

drush config:delete core.base_field_override.node.[content-type].status


Can we use the same path for a different route? Are we allowed to use the same path for two different routes? For example, can I use the following code?

function mymodule_menu() {
  $items['myUrl/dboperation'] = array(
    'title' => 'some custom db operation for insert',
    'page callback' => 'mydboperation1',
    'access callback' => TRUE,
    'file' => 'my_dboperation.inc',
  );

  $items['myUrl/dboperation'] = array(
    'title' => 'some custom db operation for delete',
    'page callback' => 'mydboperation2',
    'access callback' => TRUE,
    'file' => 'my_dboperation.inc',
  );

  return $items;
}

The code doesn't work. It works when I change the second path.

I was searching for the answer and came across How should I implement hook_menu()? but it doesn't explain what to use for the route path.

Why doesn't my code work? What should I instead use to make it work?

The short answer is NO.
Your would ether make a different path to each function or send an argument to a single function through the url.
eg. different path:

function mymodule_menu() {

    $items['myUrl/dboperation/insert'] = array(
        'title' => 'some custom db operation for insert',
        'page callback' => 'mydboperation1',
        'access callback' => TRUE,
        'file' => 'my_dboperation.inc',
    );

    $items['myUrl/dboperation/delete'] = array(
        'title' => 'some custom db operation for delete',
        'page callback' => 'mydboperation2',
        'access callback' => TRUE,
        'file' => 'my_dboperation.inc',
    );

    return $items;
}

See the hook_menu docs for how to send an argument if you choose to do it that way.


Ubercart module, understanding drupal_get_form This is all taken from ubercart uc_attribute module.

So in hook_form I have this:

  $items['admin/store/products/attributes/%uc_attribute/edit'] = array(
    'title' => 'Edit attribute',
    'description' => 'Edit a product attribute.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_attribute_form', 4),
    'access arguments' => array('administer attributes'),
    'file' => 'uc_attribute.admin.inc',
  );

As far as I understand this menu entry will call the function drupal_get_form that will call the function uc_attribute_form using %uc_attribute as a parameter.

Now if I go to the function definition:

function uc_attribute_form($form, &$form_state, $attribute = NULL) {

  // If an attribute specified, add its ID as a hidden value.
  if (!empty($attribute)) {
    $form['aid'] = array('#type' => 'value', '#value' => $attribute->aid);
    drupal_set_title(t('Edit attribute: %name', array('%name' => $attribute->name)), PASS_THROUGH);
  }

It is clear that $attribute is not an integer when it is used by this fucntion. It actually is an attribute stdClass object probably loaded by uc_attribute_load(...).

My question is: What's happening behind drupal_get_form that at the end an integer (the attribute ID) coming from the URL, ends being a full attribute standard object.

I'm kind of learning / developing a module extension and tried to backtrace but definitely couldn't get to an answer.

Thanks!

Juan B.

Its not related to drupal_get_form, its completely separated events sequentially fired in Drupal.

step 1 - First in menu: argument %something loaded via something_load and passed to page callback as parameters.

step 2 - Second in menu: page arguments will passed to function specified by page callback.

step 3- Third in drupal_get_form: get first argument uc_attribute_form as form ID and use it for build form and get second argument 4 from menu which loaded in step 1. 4 means fifth argument in path 0-admin/1-store/2-products/3-attributes/4-%uc_attribute/5-edit

EDIT:
read more about hook_menu

  Registered paths may also contain special "auto-loader" wildcard
  components in the form of '%mymodule_abc', where the '%' part means
  that this path component is a wildcard, and the 'mymodule_abc' part
  defines the prefix for a load function, which here would be named
  mymodule_abc_load().


Create a view from both user and node content Is it possible in Drupal 8 to create a view from both Users and other content? I need a page that shows photo's from Users and logo's from a content type 'Organisation'.

If I make a page view from content, it will not give the possibility to select data from 'Users', and vice versa.

You would normally add a relationship to the view to achieve this. I'm guessing you've got a field on either the user entities the organization entities that references the other?

If you add that field as a relationship in the view that will expose that entity's fields for you to add into your view


How to execute hook_cron after a rule with event Cron maintenance tasks are performed? I have a rule with event Cron maintenance tasks are performed.

It is executed when a cron run.

I have implemented hook_cron in my custom module and I want this hook_cron should be run after that rule is executed.

But the problem is my hook_cron executed first and then that rule is executed.

Is there any way to run my hook_cron after that rule?

You can adjust the weight of your module so that it gets executed after Rules.

See this question  for more details.


SEO-friendly Views: How do I make contextual filters work together with exposed filter criteria? I have substituted my frontpage with a view at http://example.com/frontpage.
I use it with two exposed filters: country and city. The current url format (http://example.com/frontpage?country=us&city=New York) is not too much SEO friendly.

What I would like to use is http://example.com/frontpage/us/New-York.

How do I do it with Views and Drupal 7?

You're nearly there, but you need to replace your exposed filters with equivalent Views arguments (i.e. Country and City). Then if you change the view's 'page' display path from frontpage to frontpage/%/%, each percent will be mapped to the arguments in the order they appear.

Once the above is done you can still use exposed filters for other fields to control the view, but they will need to be other for fields. If you need to change the city/country arguments inside the %, look into making a 'Jump menu' view display to provide a drop-down to control the view, rather than an exposed filter. Also see the Jump module.

If you need more power, a related alternative is to re-create the page in Panels which will allow you to pass arguments to several views in different panes at the same time. Views should do the job on its own for you, though.


Multilingual front page- redirect anonymous users based on browser language I have a Drupal 7 site that is available in both English and Japanese.  I am using i18n and entity translation; I have configured the User interface text language detection at /admin/config/regional/language/configure as follows:

User
URL
Browser
Default

This is great for authenticated users and for all pages of the site except the front page, which is the most important.

I would like users with Japanese browsers to be taken to the Japanese version and all other users to be taken to the English version.  However, since the site default language is English, it appears that all users are by default taken to the English version.

If it matters, my front page is actually a panel.

How can I configure it so that users with Japanese browsers are redirected to the Japanese language version?  I don't want to move browser to the top of the list because I want to respect user preferences for authenticated users, and I also need URL to precede browser because I want people to be able to use the language switcher block to change the language if for some reason they are using a browser in a language they are not comfortable with.

This is inspired by a deleted answer, but my first approach would be to have the whole site built with Panels, and then have an English variant and Japanese variant for each.

For each variant, you would use the PHP Code selection rule, and then add your logic.

For unauthenticated users, you could examine $_SERVER["HTTP_ACCEPT_LANGUAGE"] and return the proper thing.  For authenticated users, would would use your normal method.

Preferably, you would put the logic in a module function that you would call from the PHP Code selection rule, so you only need to change things in one place.  You could also do a ctools plugin to make your own selection rule, too, using the same logic.


Why is my custom theme template not found? In my theme's template.php file, I defined a new theme hook using hook_theme():

function MYTHEME_theme() {
  $hooks = array(
    'custombody' => array(
      'template' => 'custombody',
      'variables' => array(
        'content' => array(
          'body' => '',
        ),
      ),
      'path' => drupal_get_path('theme', 'MYTHEME') . '/templates/custom',
    ),
  );

  return $hooks;
}

I also placed a file named custombody.tpl.php under templates/custom.

But I can't get this template working. It's not found from Drupal. I keep getting this warning in the log:

  Theme hook custombody not found

Details:

I am trying to use this template to style the body part of HTML emails. I'm using Swift Mailer to send HTML emails and I want to theme the body part with my custom theme. There is no problem on the swiftmailer part.

Normally swiftmailer.tpl.php prints the body text as it is:

<?php print $body; ?>

I've changed this in my own implementation of swiftmailer.tpl.php in my theme folder like that:

<?php print render($body); ?>

And I'm sending a render array as $body, instead of a string, what normally would be expected.

The array I'm sending is:

$variables['body'] = array(
  '#theme' => 'custombody',
  '#content' => array(
    'body' => 'Actual body text here',
  ),
);

What am I missing, that my custombody template is not being found?

UPDATE:

I also created a theme_custombody() function in my template.php file to test it, but it also doesn't work.

function theme_custombody($variables) {
  return 'TEST';
}

Try something like this:

function mytheme_preprocess_page(&$variables, $hook) {
  $variables['theme_hook_suggestions'][] = 'custombody';
}

to add a theme hook suggestion a template called 'custombody.tpl.php'.

However it sounds like what you really want to do might be to render the $body directly, before it gets passed to the default template. In that case you'd use a process or preprocess function to do that directly instead of doing it in the template itself.


custom.module vs template.php This is a not-so-targeted question but I can't find any good information on this.

When is it considered correct practice to put code inside your template.php file and when to implement it in a module?

I mean in my current example I need to call hook_preprocess_node and inside perform a drupal_get_form and render that form. I've put my logic inside template.php.

Is that correct? If not, can you give me a short list of DOS and DONTS regarding the issue?

There are two things I try to keep in mind when making this decision.

Is this a functional feature, or a purely visual one?  Functional components go in modules.  Purely visual ones go in the theme.

What happens if I alter or radically change the theme down the road and/or allow multiple themes for my site?  If you don't want to replicate the feature, then it should go in a module.

Drupal does make it easy to intertwine content, business logic, and presentation.  For the long term maintainability of a site, you really need to be careful when you implement things.

A good rule of thumb is that a theme should not need to know about IDs ($nid, $uid, $tid, etc) for anything, and should only need to know machine names to alter visual appearance.

In your case, adding a form to a node is a functional change, and I would really put that in a module.


Entity browser or Media Library for PDF uploads? Client has a custom Content Type for downloadable PDF document detail pages, which contains an entity reference to the File media type.
They want Full and Teaser view modes to display a thumbnail image, user-friendly title (not PDF filename), and link to download.
I added the field_media_image to the media file bundle, and I used the media file's Name field for the "friendly name" of the file.
The image and name could be edited by clicking the pencil icon on the image field to edit the media file directly, but it is a better user experience for content editors to edit the media file attributes from the detail page node, along with the rest of the document details.
If I change the field widget for the entity reference in the detail page's form display from Media library to Entity browser these fields are easy to edit from the detail page node by clicking the Edit button.

This works well for editing existing content, but this widget is not configured correctly for uploading new PDF content:

There are some customizable widget settings in the form display configuration, but nothing that seems useful for my purposes.
The client is accustomed to uploading PDFs using the Media library widget, which looks like this:

Unfortunately, the Media library widget does not allow user to edit fields on the media file bundle. This widget does not offer any customizable settings in the form display configuration.
Is it possible to write a small Drupal 8 module to use the Media library widget on this field if it is empty (or NULL), but use the Entity browser widget on this field if a PDF has been uploaded?
That would be ideal. If it's not possible, perhaps someone can help me to configure the Entity browser widget to behave more like the Media library widget for PDF uploads.
EDIT:
I think I might be on the right track:
Home >> Administration >> Configuration >> Content authoring >> Entity Browsers
I'm trying to add a new PDF Entity Browser. But when I use that, I get the following error message:

What am I missing?

Going to Home >> Administration >> Configuration >> Content authoring >> Entity Browsers and creating a new entity browser is the right way actually.
But you probably have attached a media entity field to your content type therefore you must configure your new entity browser to be used on the media form display level.
Lets say your new entity browser is called Document browser you should go to the media form display for document media and make use of the new entity browser.
Here is a screenshot that might help understand better

The content type form display widget for the respective field should remain as Media library in order to pick up the media library from previous step.


Webform: how to display warning message, when clicking upload, and no file is chosen? I have a webform, in which I have file upload.

However, when user chooses no file, he is still able to click upload and nothing happens. I would like to have there similar message like when he chooses file with extension which is not allowed.
How can I achieve this?

You could use the client side validaiton module install it then configure it for webforms , you could also use the module's hooks to customise error messages or create custom error handling functions  client side validation


Problem Trying to upgrade webform to latest version using composer I've been trying to upgrade webform 5.19 to version 6 using composer but I keep getting this error:
Your requirements could not be resolved to an installable set of packages.
Problem 1
drupal/webform_ui 5.19.0 requires drupal/webform 5.19.0 -> satisfiable by drupal/webform[5.19.0] but these conflict with your requirements or minimum-stability.

I asked over at the module's help and was to to try here. Has anyone seen this or have an idea what I'm doing wrong?

Manually editing composer.json to add "drupal/webform": "^6.0" did the trick.


'Access denied' to Content Type I've a website that I didn't build that is giving me some trouble. A whole Content Type is returning "access denied" error when authenticated users try to view it (Guests can).
The access is only denied when a field is set to 1, but the are no dependencies set. I really can't figure out from who the access is beeing denied.

I didn't find any access content modules.

Has somebody any ideas?

From the limited details provided in your question, it could very well be that one of your enabled rules (created with the Rules module) is what is causing your issue.

To actually confirm, for sure, if it is any of the enabled rules, use these steps:

Disable of all your enabled rules. If the problem persists, you can be sure it is not because of a custom rule (don't forget to re-enabe the temporary disabled rules). If the problem is gone, continue with the next step to find which rule is causing your problem.
Re-enable your temporary disabled rules, but only 1 at a time, and check if your problem comes back (each time after you re-enabled one more rule). At some point your problem should come back. As soon as that happens, the most recent re-enabled rule is what is causing your issue. In that case, re-enabe the remaining temporary disabled rules and continue with the next step.
If you cannot find out what the actual problem might be in the re-enabled rule that causes the problem, move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

After you're sure it's not Rules causing the problem, I'd consider the "Workflow" module (which you also seem to be using) as the next suspect on my list. As a quick test (to see if that's the direction to go for further debugging), temporary disable the Workflow module: if the problem remains, then it is not the Workflow module either (don't forget to re-enable it afterwrds).


Drupal integration with external binary program to convert an image? Using Drupal 8. On a cloud based site, I have a program for converting images into svgs that takes, at times, a few hours of run time. I can easily run the external binary program (configured to run through java as a commandline). At the end I have the program spit out the relevant files. I need to integrate this with Drupal and am wondering the best procedures.

What do I use to grab the image and have an actual file on disk? How can I get the files back into drupal whenever this program finishes. I can easily add in commands to run after the program finishes, and can get the program to run with an exec() but how do I hook the rest of it up? A working proof of concept would be great. Even better if it could run on a spun up virtual computer on google cloud services.

Not anything near a working proof of concept, but a hint in the right direction:

You could use FileEntities for the upload of the Files, for example via a FileField on a node.

In hook_node_insert() and or hook_node_update() you can get the path to the file in the filesystem via:

$file = $node->field_source->entity;
$path = FileSystem::realpath($file->getFileUri());

You could than trigger the execution of your external program. By using hook_cron() you could regularly check for results. You could than attach the resulting file to the node like this

// Create FileEntity from a local file.
$uri  = file_unmanaged_move($path, 'public://'.$result_filename, FILE_EXISTS_RENAME);
$file = File::Create([
    'uri' => $uri,
]);
$file->save();
// Load node and attach the file.
$node = Node::load($nid);
$node->field_result->setValue([
    'target_id' => $file->id(),
]);
$node->save();


How do I create a folder structure inside a view I have created a view to get the all images that I have used in the website.  But it returns as a bulk list. But I have saved the images according to a folder structure. How do I get the images according to a folder structure in my view.

Below is my view

Currently it returns a bulk list. How do I get the images with the folder structure?

For an example I need to get the /path1/path2/image.jpg inside a folder named path1 which contains a folder named path2.

The feature "Group by field" provides a hierarchy, but you don't have the path components out of the box.

Are you using a module that is controlling the paths that is also integrated with views, maybe File field paths? If you can get a field to display a path component you will be able to group by them, effectively getting a folder structure.

Views tree also helps, if you have the path components.

This comparison list might help: File Uploading and Managing.

If no module provides this already you'll have to create your own Views Field formatter for the file URL link field and use with some hierarchy mentioned above, or create a completely new Views Format for the File Views type that displays results in a hierarchy.


Cannot assign roles creating User through REST endpoint Sidenote, already seen this page, doesn't seem to help: How to create user with role(s) through REST service?

I've setup a new endpoint on my platform to try to allow a 3rd party to create users on the site, I've connected it up and I'm testing it out through a REST client on Firefox. So far it seems to be working fine with the exception of applying the role to the new account.

According to the link pasted above, it needs to be set to:

{
  "name": "rest_user_1",
  "mail": "rest_user_1@test.com",
  "pass": "abc123",
  "status": "1",
  "roles": [
    "5",
    "6"
  ]
}

But that doesn't work, I've got the debugger enabled, and I can see from the response it seems to be coming back with this

Array
(
    [0] => Array
        (
            [name] => rest_user_1
            [mail] => rest_user_1@test.com
            [pass] => abc123
            [status] => 1
            [roles] => Array
                (
                    [0] => 5
                    [1] => 6
                )

        )

)

To me it looks like it's assigning the role IDs (5/6) as the values in an array, rather than the keys, so instead I tried writing my body in a different way:

My body at the moment is:

{
  "name": "rest_user_2",
  "mail": "rest_user_2@test.com",
  "pass": "abc123",
  "status": "1",
  "roles": {
    "5": "Role 1",
    "6": "Role 2"
  }
}

And the response in the log messages looks like:

Array
(
    [0] => Array
        (
            [name] => rest_user_2
            [mail] => rest_user_2@test.com
            [pass] => abc123
            [status] => 1
            [roles] => Array
                (
                    [5] => Role 1
                    [6] => Role 2
                )

        )

)

Which looks like exactly what I'd expect, but yet, still it hasn't applied the roles to my account. Can anyone help?

For other people reaching this post, the answer to this is to use some kind of authentication on the REST endpoint, that only allows trusted users to create new users.

Otherwise anonymous users would be able to create admins and crash the site.

So this code is correct,

"roles": [
  "5",
  "6"
]

but the problem is that the user calling the endpoint has to have the administer permissions and administer users permission to be able to set roles to users.

That can be done by setting a role that has those permissions and also has permission to call the endpoint.

oAuth could be used to do that.


How to make Forena render my SVG Graph properly? I am trying to create a bar graph using Forena's SVG Graph facilities. But it shows output like this:

As shown in the above image, it is not rendering the SVG Graph properly.

I am using this SQL statement (my "data block" related to the SVG Graph I try to create):

SELECT Type,count(*) as Number
FROM node
GROUP by type

Following is a screenprint of the related FRX file:

And here is a textual version of that FRX file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>

<title>Graph Demo</title>
<frx:category>Sample Graph</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>

The issue you described in your custom graph, is pretty sure similar to what is also happening when viewing the delivered graphs. So make sure that the delivered graphs work before moving on to custom graphs, such as the SVG Graph Demo, which is one of the delivered SQLite sample reports and graphs. Visit relative path /reports/sample.svg_demo in your own site. If you don't get the very same graphs in your own site, then use this checklist to get that issue resolved:

After you installed/enabled Forena, complete the required setup to Enable SVGGraph library (reports/help.setup#svggraph in your own site is where you can find the same). Pay special attention to this part documented around there:

  If you don't see a nicely formatted graph, but only some square with a gray background (about the size of the SVG graph you should see if it would have worked), or you're getting some error messages, you may want to checkout the issue queue on Drupal.org (search for html filter) ...

Obviously, if you change "gray" to "white", your first screenprint is pretty similar to "... some square with a gray background ..." (more details on that "html filter" in the next bullet).
Quite often the reason why Forena doesn't seem to render SVG Graphs correctly, is because the input format used by Forena is simply stripping out the SVG tags. To remedy this, this is what's needed:

  go to admin/config/content/forena in your site and ensure that the Text Format specified does NOT strip out SVG tags.

Additional info: have a look at "Prepare a text format to be used by forena" within the Installation and Configuration section of the Setup guide. At the very end of it there is this note:

  Especially if you're planning to use SVG graphs it is important to avoid that tags are being stripped out, as this could cause such graphs to not be shown at all or with errors.


Rule to remove two specific items from commerce cart I am using Drupal commerce and I try to make a rule to remove two specific line items from the cart. However, the most I can achieve is to empty the whole cart.

Can this be done with rules?

You remove a product from the cart by deleting the line-item entity for that product.
But first you must expose the line-item data to your Rule so you can check whether it should be deleted. Line-item data including sku is not available to Rules Actions unless you do this.
Note that you can access some properties about the line-item, such as commerce-line-item:type, in your Rule Condition, but this is for the line-item referenced in the event, not for the other line-items in the cart. You cannot access other line-items' data, such as sku, in your Rule Action.
You force the other line items' sku and other data to become available to your Rule Actions by checking a property of each line item in the Action, even if you don't otherwise need to do the check. In this example I check the type of each line-item to be evaluated for deletion.
Much of the documentation available as of today is a couple of years old and calls for use of Rules components ... nowadays Rules Conditional is the way to go as it allows you to bring conditional logic right into your Action (so you can choose which line items to delete, for example). You may choose to put this Rule in a component if you have many varied situations in which you want to call it. If you only have one or two situations, using conditional logic within the Rule Action, via Rules Conditional, is much simpler.

In the example below, the Rule is evaluated on the event "After removing a product from the cart" because I have an add-on product that should be removed after the "mother" product is removed by the customer. But you can use any Commerce event.

The Condition here is to check whether the product removed from the cart by the customer was a "mother" product ... you may not need any conditions for your Rule.

The Action first does the aforementioned check of the line-item type to bring the line-item properties into scope for the Action data selector, then loops through the list of line-items, and tests each one for the skus you want to delete. Then deletes the line-item if there is a match. You could of course delete based on price, quantity, or anything else in the line-item data.

Note that once you start to loop through a list, the data you are after will be accessed through the variable list-item: which represents whatever you are looping through; in this case, the line-items. Note that list-item and line-item are syntactically very close, watch for typos!

{ "rules_delete_products_from_cart_by_sku" : {
    "LABEL" : "Delete Products from Cart by SKU",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Cart" ],
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart" ],
    "ON" : { "commerce_cart_product_remove" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-line-item:type" ],
          "value" : "my_product_type"
          }
       }
     ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "list-item:type" ], "value" : "product" } },
                  "DO" : [
                    { "CONDITIONAL" : [
                        {
                          "IF" : { "data_is" : {
                              "data" : [ "list-item:commerce-product:sku" ],
                              "op" : "IN",
                              "value" : { "value" : [ "SKU-01", "SKU-03" ] }
                            }
                          },
                          "DO" : [ { "entity_delete" : { "data" : [ "list-item" ] } } ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Hope this helps someone on the same journey I am!


Field image in attachment affect block settings I created a block in views with field image and title.

Then I created an attachent after the block with title only.

The field image in block is gone after I removed the field image in attachment.

How do I make it override? I can't find the settings.

View module provides ability to override changes based on display. Please check steps below:

Go to Attachment display.
Click on Down arrow, next to Fields, and click on Rearrange. As per shown in screenshot.

Click on For drop down and select "This attachment (override)" and click on Apply button. check screenshot below:


Validate text format when render page Im making an exportation process (from SQL Server to MySql) and in the text_format column insert NULL values, currently the page is rendering the pure html (plain text) instead of render the html correctly in the browser.

Somebody know how to force the output text_format to be filtered_html to my specific content type?

Thanks in advance

Assuming the inserts are taking place on field tables (e.g. field_data_body, field_data_field_MACHINE_NAME), you shouldn't insert NULL into the *_format columns. Rather, you should be inserting the machine name of your desired filter format (e.g. filtered_html for Filtered HTML or full_html for Full HTML). See the filter_format table for all available machine names for your installation.


Database error after transferring Drupal 6 site I just moved a Drupal 6 site from one server to another and have just started getting an error.

Warning: Table 'mydatabase.watchdog' doesn't exist.

The table does exist in the database and it does have the proper data in it. Some content does show up so the connection information is correct. Does anyone have any suggestions for this error? I am stumped.

Check that the table isn't corrupted or locked in some way. phpmyadmin should show you this when you view the list of tables in the database.

Try dropping the table and re-importing just that table, not the entire DB.


Search API highlight using the search API module I highlighted the search text. Key words take the whole width of the block, how to insert them in the text? my current setup is:

Highlighting prefix : <p class="views-highlight">
Highlighting suffix : </p>

CSS:  .views-highlight {color: black; background-color: yellow;}

my search results

You should not be wrapping your keywords in p tags. P is a block-level element, and that is why it stretches 100% width of your container.

Use mark, span or any other inline-level element instead.


How to display an HTML table after the form submission on the same page as the form? I am trying to build a form which takes the food item and the no. of servings and calculates the total calories for that particular food and displays it to the user.

User, can add another food by filling out the form again and the calculated calories for the second food is added to the first and the total calories are also displayed. He can add as many food items as he wants and the form shows the total calories of all those food items.

I want to display this information to user in a table. table will have the following columns.. food item, servings, calories and in the last row the total calories of all those food items. I also want to have a another column with a "delete" button to delete that particular food item from the table and refresh the table without that particular food item.

The main problem am facing is, How can I show this table on the same page as that of the form ?

I have been saving all the user submitted info in session variables and I am being able to create and show such table on another page (for example, when user adds many food items and clicks "Done" button, its redirected to another page and the table is shown there.) But I dont want the user to be redirected. I mean if he wants to add another food item to the table, he has to navigate to the form page again and that's not convenient to the user.

To learn how to write forms, I followed this guide, http://drupal.org/node/262422. So my form is in a file, say..myform.module. Now, I have all the data to create an HTML table (Am saving all the food details given by the user in session variables), but how can I make it displayed on the same page as that of the form ?

or in other words, path to my form is, http://localhost/d7/?q=calorie_consume , I also want the table to be showed on the same path or page. How can I do it?

Where should I put the code for creating the table inside myform.module file ?

So how can I achieve this ? Or is there some other approach to creating such calculators that am not aware of ?

Thanks in advance.

If you're saving your data in $_SESSION vars, I think the easiest way would be to check for the existence of your session data when you build up the form. Then you can show the table at the top of the form if the user has already submitted data, and the normal part of the input form directly underneath. A basic example:

function my_form($form, &$form_state) {
  if (isset($_SESSION['my_var'])) {
    $form['table'] = array(
      '#markup' => 'Your table markup based on session data here'
    );
  }

  $form['input'] = array(
    '#type' => 'textfield',
    '#title' => 'Title'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );
}

function my_form_submit($form, &$form_state) {
  $_SESSION['my_var'][] = $form_state['values']['input'];

  $form_state['rebuild'] = TRUE;
}

You'll probably need to put some sort of mechanism to clear that session var at some point, if you want users to be able to reset their submission.

A more complete example with functionality to remove items:

function MYMODULE_form($form, &$form_state) {
  // If we have some session data set, build a table
  if (isset($_SESSION['MYMODULE_data'])) {
    $header = array('Food', 'Calories');
    $options = array();
    $total = 0;
    foreach ($_SESSION['MYMODULE_data'] as $item) {
      $options[$item['identifier']] = array(
        $item['food'],
        $item['calories']
      );

      // Keep a running total
      $total += $item['calories'];
    }

    // Add the total row
    $options[] = array('Total calories', $total);

    $form['existing_data'] = array(
      '#type' => 'tableselect',
      '#options' => $options,
      '#header' => $header
    );

    $form['remove_item'] = array(
      '#type' => 'submit',
      '#value' => 'Remove Selected',
      '#submit' => 'MYMODULE_form_remove_item'
    );
  }

  $form['food'] = array(
    '#type' => 'textfield',
    '#title' => 'Food'
  );

  $form['calories'] = array(
    '#type' => 'textfield',
    '#title' => 'Calories'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );

  return $form;
}

function MYMODULE_form_remove_item($form, &$form_state) {
  $remove = array_filter($form_state['values']['existing_data']);
  foreach ($remove as $key) {
    unset($_SESSION['MYMODULE_data'][$key]);
  }
  $form_state['rebuild'] = TRUE;
}

function my_form_submit($form, &$form_state) {
  // this example will just use the food name as the identifier
  $_SESSION['MYMODULE_data'][] = array(
    'identifier' => $form_state['values']['food'],
    'food' => $form_state['values']['food'],
    'calories' => $form_state['values']['calories']
  );

  $form_state['rebuild'] = TRUE;
}

I haven't tested that but it should give you a good starting point even if there are a few bugs.


Webform Add More for grouped elements I'm building a Webform in Drupal 8. One section has repetitive grouped elements that could be added more than once. For instance, it's something like:

Where they could add more if they want. If this was a node, I'd use Paragraphs to create a bundle for the language name, writing proficiency and speaking proficiency, and they'd be able to add as many as they like. I'm not sure how to do it in the new D8 Webform module though. I know something like Webform Add More kinda works (though, it's really just hiding a preset number fieldsets until they're needed, not creating them dynamically), but I can't figure out anything else even close to that.

Should I just make a set, static number? Or is there another way? I know Webform is totally different now in D8, with YAML config files and how the data is stored; should I try to just make my own custom field in code?

If I gather correctly what you are asking then you are hitting https://www.drupal.org/node/2824714 . You need to write your own composite element, webform for now doesn't support this.


Change css based on the page url I am using drupal 7. I wanted to change the colors of the block and everything for certain pages. The ThemeKey module works fine but i have to do all the block configurations again in this. This is tedious. Since i want to change only the css any other module will solve ma problem?

The body element will have a boatload of classes on it.  This does vary by theme, but typically there will be a class like

body.page-the-url-for-this-page

that you can use in your CSS.

Do a view source on various pages and take a look.  Or, use the Inspect Element feature of Firefox's Firebug or Google Chrome, or the Firefox Web Developer extension.

If the class isn't there, you can do something like

function thetheme_preprocess_html (&$variables)
{
  $variables['classes_array'][] = "page-" . str_replace("/", "-", request_uri());
}

You may also want to investigate the Context module, which can aid in section-specific features for a site.


Drupal 7 - Entitiy Reference - Reference field to a conent as a link I created content - lets call it X - which has a field with the type of entitiy reference (done with Entitiy reference). This field refers to a content that can be selected via select list. When X is shown the reference field appears but not as a link so that I can directly forward to that content. Do I need any additional module for that?

On the Manage Display page (Structure->Content Types->Your content), first be sure the display format is set to Label. Then, click on the gear on the right. You will see a checkbox with "Link label to the referenced entity". Check that and click Update, then save our display. The label will now link to the entity.


'Edit Own Content' permission missing in custom entity I have generated a custom entity using Drupal Console.

drupal generate:entity:content

The entity doesn't have the permission edit own content which we usually have in node types etc... The entities entity_name.permissions.yml the file has the following enteries.

add company entities:
  title: 'Create new Company entities'

administer company entities:
  title: 'Administer Company entities'
  description: 'Allow to access the administration form to configure Company entities.'
  restrict access: true

delete company entities:
  title: 'Delete Company entities'

edit company entities:
  title: 'Edit Company entities'

access company overview:
  title: 'Access the Company overview page'

view published company entities:
  title: 'View published Company entities'

view unpublished company entities:
  title: 'View unpublished Company entities'

I tried understanding, how this is done in node. But in node types permission file also I couldn't find this permission entered.

If you look at the end of the node permissions file, you'll see:

permission_callbacks:
  - \Drupal\node\NodePermissions::nodeTypePermissions

If you look at the buildPermissions method, you'll see where the rest of the node permissions are created.

And then in node.module, take a look at node_node_access implementation of hook_node_access.

Also, see: \Drupal\node\NodeAccessControlHandler and the corresponding Interface class. It seems fairly complex, but both the node_node_access method and the NodeAccessControlHandlerInterface are well-documented and seem like a good place to start for developing your custom entity permissions system.


Disable Ubercart download limits accumulation By default the Ubercart module, accumulate the download limit of a file if this one is purchased twice. How can i disable this ?. I just want to notify the user that he already have privilege to download the file and prevent him from downloading it again.

Set the download limit as Unlimited, then at the next time user click on add to cart button, then check this product is he already checkout or not (for this you can use order table). If it is already purchased by that user, then you can redirect him separate page or you can display a message about the same.


How can I add an existing field to a new content type? I have a content type with name category and have title and an image under it. I want a select option with this category name while for my new content type "videos". How can I do this?

You can find an option to select existing field under the list of fields :


How to grant access to a user to all content created by certain users? I've been looking all the options commented on Controlling Acces to Content Overview but I don't see any that allow one particular user to access all content created by other particular users.

Something like: User A have permissions to see all nodes created by users B, C and D.
(No need to include a reference or a taxonomy term to each node).

Any insights?

Thank you so much!

Sorry telling you that as far as I know there is nothing like this out of box.
Maybe if you mention the requirement we will be able to help you.
For now don't think about users and think about roles. if you want to make it more flexible I suggest using workbench access so the created content will have a section (Taxonomy term) and the section will be accesed by user A and B only.
Hope that help


How to split taxonomy checkboxes on node edit form I figured how to do it on node output, but i can not figure how to add css for specific field, in this case taxonomy checkboxes, 50 of them, and split in 4 columns on node edit form.

You can do it with css. You will need to add the following to your Admin theme's css file.

The Drupal default admin theme is Seven theme, located in /core/themes/seven. You may want to create a sub theme of Seven and use that as your admin theme, so when you upgrade Drupal your css file does not get overridden; thus, you will not lose all your changes.

#edit-field-name {
  width:760px;
  margin-bottom:20px;
  overflow:hidden;
  border-top:1px solid #ccc;
}

#edit-field-name div {
  line-height:1.5em;
  border-bottom:1px solid #ccc;
  float:left;
  display:inline;
  width:25%; }

replace -name with the actual name of your field.

Source: http://csswizardry.com/2010/02/mutiple-column-lists-using-one-ul/


Custom Fieldable panels pane template rendering the Field collection items I am using Fieldable Panels Panes (FPP). I created a custom FPP and I am using  Field Collection items into my custom FPP.

I want to customize the rendering of Field collection item fields in my FPP template file.

For example: fieldable-panels-pane--my_custom.tpl.php is my tpl file, where I am unable to customize my_field_collection_items fields seperately by using some classes.

Is there a way to customize these fields and render the output in desired way?

I found the answer. Actually, by using $elements in .tpl file, we get all variables and also all fields as an array. You can use it to render the output you want to.


Detaching Drupal Behaviors of another module I'm using this module External Link module which adds "ext" as a class to any anchor tag matching the regex defined via the admin UI provided by the module. I then bind a click event to trigger colorbox for anchor tags with the "ext" tag. Now my issue is, any anchor tags added to the colorbox container are also being added a class "ext".

I understand that this has to do with Drupal.behaviors attach method implemented in the contrib module, but how do I "detach" this behaviors from my custom js file? Specifically for the links within the modal container.

we faced the same issue here we are using lightbox module what we did is we dint used any extra module in common we wrote a Behaviour to add a external class and added condition to when colorbox is added remove external class

Define your base URL in any module in it

"Drupal.settings.baseUrl"

/* external links*/
 Drupal.behaviors.external_link = {
    attach: function (context, settings) {
      $("body .view-content a").once(function() {
                    var anchorlink = '';
                    anchorlink = jQuery(this).attr('href');
                    if(anchorlink != "#" && !$(this).hasClass('lightbox-processed'))
                    {
                        if(!(anchorlink.lastIndexOf('http') == -1) && anchorlink.lastIndexOf(Drupal.settings.baseUrl) == -1 && !jQuery(this).hasClass("external"))
                        {
                            if($(this).parent().hasClass('lightbox-processed')){
                                    jQuery(this).removeClass("external");
                            }else{
                                    jQuery(this).addClass("external");
                                    var targ = "_blank";
                                    jQuery(this).attr("target", targ);

                            }
                        Drupal.attachBehaviors();
                        }
                    }
      });
   }
  };

instead of lightbox-processed replace your class
hope this will help you :)


How to remove the 'Reply' link in comments? I'm currently using the following line of code in my comment.tpl.php file:

<?php print render($content['links']) ?>

This also prints the 'Reply' link, but I'd like to remove that one. How can I do that?

Note: I'm able to hide the 'Reply' link with CSS, but that's not a very nice solution.

If you wanted to remove all links, you could do it in a template file like this:

hide($content['links']);
print render($content);

But I don't know how to hide just the comment reply link this way. Based on a short article here, it looks like you can unset the reply link with a preprocess function in template.php like this:

function themename_preprocess_comment(&$variables) {
  unset($variables['content']['links']['comment']['#links']['comment-reply']);
}


301 redirecting broken links after moving Joomla! to subdomain and giving parent domain to Drupal7? I've recently started doing way more Drupal development than Joomla!, and given I use my personal website as a testing platform that changes about once every few years, am trying to migrate it from Joomla! 1.5 to Drupal 7.

To this end, I've moved the entire Joomla! website to http://v3.aendrew.com and in doing so, broken all incoming links, which are now met with a Drupal install that's never heard about any of my prior content -- http://aendrew.com.

Is there any way I can do the following via Drupal 7?

Detect broken incoming request (Drupal 404s)
Check whether the path exists on the Joomla! subdomain.
Issue a 301 redirect pointing to the Joomla! page if so; issue a 404 if not.

Thank you!

I would personally follow the steps described below:

1) Use this technique to detect the 404s and issue the redirect

2) Since you don't want to issue the redirect right away, but first check whether the URL exists in the Joomla! subdomain, you can use a function like this to determine whether the URL exists.

3) In order to determine what the URL of the incoming request was (so that you can use it to match it against the Joomla! subdomain), you can use this: $_SERVER['REDIRECT_URL']


Taxonomy term not translated in edit node I have a taxonomy called « categories » which have terms as listed below:

Here the term “visuels” is the French version of “visuals” that has been translated.

Now in the edit section of an article with ‘french’ selected as the language, I am not getting the French term but instead it is listing the English version as shown below:

Can someone help me with this?

It seems you are using 'Entity Translation' module and a field type 'Term reference'.

In the content type 'Article' you could try to create a new field type 'Entity Reference' with Target type 'Taxonomy term' and Entity selection
'[Your category vocabulary]'

It should works.


Export exposed fields into a block with Views I'm trying to create a search box from the exposed fields from a view. Is that possible? If I add a block display I also get the results.. I want only the fields, not both.

I also tried embedding a view with exposed filters inside a node, however, when I click "search" I'm not redirected to the view (the url is not constructed correctly: instead of website.com/view?exposed_field=test I get website.com/?exposed_field=test).

Any help is appreciated.
Thank you

This functionality is now built into Views itself.  See How To Display Views' Exposed Filter In A Block And Theme It for details.


How to correctly remove a module in a staged environment? Some modules have deïnstallation routines. Which typically remove databasetables for that module, variables from the variable table and locales introduced by that module. These routines live in the .install of that module.

Therefore, they cannot be ran without that module being present. So here are our current steps. My question is: can this be done simpler and more effectively? Say I remove foo_bar module.

In the RCS, prepare a new release, where:

All css and theme-overrides that use or build on top of- foo_bar are removed.
All css and theme-overrides for modules depending on foo_bar are removed.

Push that release to acceptance. Test the deïnstallation (from admin/modules) with a very recent copy of the production database.
If all goes well, deploy the new codebase to production, and deïnstall foo_bar and its dependencies there. This will invoke the uninstall in the various modules, cleaning up the database.
In the RCS (git), prepare a new release where the code is actually removed.
Deploy that to acceptance where we test if nothing accidentally depended on this (some ugly modules or theme functions include files directly from other modules. Most notably CSS, JS or image-files).
If accepted, deploy new release to production. production now has a clean database and a clean codebase.

Problem that I can't see how to solve, is that this always needs two releases. Since in Drupal a release requires the site to be offline, this means two times downtime just to remove one module. It also requires two release procedures, which, in professional hosting environments can be very expensive, time-consuming or frustrating.

If we remove the module from codebase in the first iteration, we cannot run the uninstall hooks, keeping many lint in the database; not just a few tables, but mostly variables and locales.
If we don't remove the module from codebase, that means the codebase will grow with stale, unused code; this gives no performance overhead, but does make maintaining the code harder and harder.

How do you deal with this?

[edit: added note about deployment being a tough procedure, often]

Be very careful about keeping your database and code in sync; as you mention in your question, the modules to be uninstalled need to stay in the code base until their uninstall hooks are run on the live database.  This is a limitation of Drupal that a git pull workflow alone is not going to solve.

I would recommend that instead of attempting to adjust your process, you instead look for ways to reduce the downtime required to process your updates.  I would recommend setting up a ying / yang multisite staging environment to solve this problem.  n.b. I have not used the scripts contained in the preceding link; you may wish to set things up differently, following the same idea that you can swap your live and stage sites during deployment.

Continue to follow the same procedure you outlined in your question with the following adjustments:

a. Sync from dev to stage (yang) as usual. Test by doing an uninstall of the modules to be removed followed by code removal, etc.  Git workflow notes: create a tag or note the hashid of the different states of your code: all modules in place prior to uninstall, code modules removed, your overrides & c. removed, etc. as needed.  Perhaps only two references are needed.

b. When testing is complete and accepted, restore the code on stage (yang) to the state of live (ying).

c. Prepare the live (ying) site for update by disabling any user's ability to change content on the system. An sql update to the permission table will usually do here. At this point, users will still be able to read content on the live site, but will get a permission denied error if they try to update content. (If you are cool, perhaps you could change the permission denied handler to print an appropriate notice that the function is temporarily unavailable).

d. Now push the live (ying) database back to stage (yang) database, excluding the permissions table from the update.

e. Repeat step a. again.  If you have your hashtags handy, it should be easy to restore to the state where the modules to be removed exist, run the uninstall hooks on the database, and then advance back to the state of the code where your items from step 1 are merged back in.

f. You are now ready to swap ying and yang. Do this by adjusting your Apache configuration directives. Note that if you do an /etc/init.d/apache restart, some connections may be dropped, but /etc/init.d/apache reload will allow for a clean swap.

g. Live is now 'yang'; the permissions table is unmodified here, so users can create content.  If you automate steps e. and f., the time unavailable should be very low.

h. Push live (yang) back to stage (ying), both code and database -- or push from dev, as needed. You now have a clean environment ready for your next iteration.


Using block as sub-menu Is there any module to put blocks under menu items? I will use it to create mega menu. I mean something to generate this code:

    Item

...

best one out there from my experience would be: http://www.drupal.org/project/tb_megamenu --- it should take you no longer than 15 minutes to figure out how it works. you'll still need to do some css width adjustments to get it working with your own layout.


Drupal Commerce PayPal Express Checkout review and confirm step is skipped User is not seeing Confirm Order Page (Express Checkout review and confirm) during PayPal Express checkout.

  The EC module defines a new checkout page called Confirm order between the payment redirect and completion pages and a checkout pane called Express Checkout review and confirm that should only be used on this special page.

I am using 7.x-2.3 release of Commerce PayPal module. Testing with PayPal Sandbox accounts.

After logging into PayPal customer sees "continue" button and a message *"You're almost done. You will confirm your payment on **'s Test Store."*. After clicking "continue" customer is brought right to the Order Complete page and the payment is registered in the system. Which is not the intended behavior of PayPal EC module.

These are Order history messages that have been recorded during checkout with PayPal express:

Status has been set to Checkout: Complete (previously: Checkout: Confirm order).
Status has been set to Checkout: Confirm order (previously: Checkout: Payment).
Payment of $62.00 submitted via PayPal Express Checkout.
Order has been paid in full.
Status has been set to Checkout: Payment (previously: Checkout: Review).
Status has been set to Checkout: Review (previously: Checkout: Checkout).
Status has been set to Checkout: Checkout (previously: Shopping cart).
Product sample2 added to the cart.
Order has been created.

QUESTION: What could be the reason of why Express checkout review and confirm page is skipped?

The only code that would trigger a skip of the order confirmation page is in the checkout router hook implementation commerce_paypal_ec_commerce_checkout_router(). If you take a look at that, you'll see that it skips the confirmation page if the order either doesn't have a record in its data array that Express Checkout was used or if the customer used EC but did not use the EC flow (as opposed to the Mark flow, which is when the customer chooses PayPal from the payment method checkout pane and is then redirected to PayPal):

<?php
  // If the current page is the Express Checkout page but the current order did
  // not use the Express Checkout flow...
  if ($checkout_page['page_id'] == 'paypal_ec' &&
    (empty($order->data['commerce_paypal_ec']['flow']) ||
     $order->data['commerce_paypal_ec']['flow'] != 'ec')) {
    // Update the order status to the next checkout page.
    // ...
  }
?>

This means if it's being skipped for you, you should first ensure it's being skipped when the EC button is being used from the cart form (that's the EC flow) as opposed to when the customer redirects from inside the checkout form.

The second place to look will be the order's data array to figure it if / why the order doesn't have a record that it was paid for via EC.

If the module itself is to blame, please open a bug report explaining how to reproduce the issue. Last I used it, it was all working fine.


Web service APIs returns HTML content instead of JSON response I have used Drupal 7 before and the web services were working perfectly fine. I recently started working on Drupal 8 (8.8 to be precise), and the login service is not working properly. When I do not give the username or the password it should ideally give a message that username/password must be entered. But I am not getting any response here.

It's just returning HTML content. I have been searching lot of posts on this and nothing seems to work for me. I am testing the same in Postman. Below is the screenshot of the same.

I have gone through the below links before posting here..

https://stackoverflow.com/questions/31230351/drupal-8-restful-webservices-only-delivering-html

User login REST POST returns HTML format

User login REST format

Nothing seems to work for me. Kindly suggest. Need your help. Thanks in advance!!

For the postman section of your issue: /user/login?_format=json is a POST request (not get as in your screenshot) and the body should be JSON not x-www-form.


How to comment on image in colorbox (modal form)? I have created view to display images and also user to display it in popup using Colorbox trigger in view.

I want to allow users to comment on each individual image in modal form only. Just like Facebook. I have printed the comment form on popup but it is coming with preview button which redirects user to the photo's node page. And allow there to POST comment which I don't want.

What I want is user should be able to comment in popup with post button and the comment should be posted in modal form only (Should be visible in modal and node page as well). Is there any module to workout this?

Inline Ajax Comments should do the trick for you.

  Inline Ajax Comments is a views handler that allows you to add a field
  to a view to allow users to view and post comments on nodes in a view.
  This is a basic version of what you see with commenting in social
  networking sites like Facebook.

Ajax Comments comments can also be considered.


How to print "Time" field in twig template I have a time field in my content type. But when I entered time in the format 05:00 AM, I get a five digit timestamp eg. 18000 (for 05:00 AM).
When I print this using node.field_time.value|date('h:i A') it prints

10:30 AM

which is 05:30 Hrs extra than the entered one.
How do I'll get the correct time?
The default timezone is set to Kolkata which is +05:30 UTC. Is this something causing the problem?

By default, it considers the entered time as UTC. So when we render the value of the time field, it prints the value according to the user's timezone.

I used below code to print the same value as entered in the backend

node.field_time.value|date('h:i A', 'UTC')

or we can also use false instead of UTC to get the same output without setting any time zone.


node_access by specific role? I am trying to build a list of node ids that have view access for a specific role. Is this at all possible? I currently have an array of all 'page' content type nodes "pages".

I now need to loop through these and see if they have a specific role enabled, if so get the id and display the link on a page if the user has access to that page.

I know I can do that using the following example. But this just checks if the user has view access, and the user could have access from another role they have which my list would not be accurate for what I am trying to achieve.

if(node_access('view', $nodeid, $user)){
    // do something
}

Or is there a way to check if a specific users role has view access rather than just access in general.

The reason I am trying to do this, is I am trying to get the list of specific pages dynamically if a role is given to that node "page".

Sorry if my terminology is off I am not super familiar with drupal.

This is what I ended up using, it could probably be optimized a bit but it works.

<?php
if ($node = menu_get_object()) {
  // Get the nid
  $currentNode = $node->nid;
}
if (in_array("Gold Member", $user->roles)) {
    echo '

Free Courses for Gold Members

';

    echo '
';
        $role_type = 'Gold Member';// Texas Member
        $getRole = db_query("SELECT rid FROM role WHERE name = '%s'",$role_type);
        while ($roleid = db_fetch_object ($getRole)) {
          $roleids[] = $roleid;
        }
        //Get the ID of the role type we are using from the array
        foreach($roleids as $roleId){
            $role_id = $roleId->rid;
        }

        $node_type = "page";
        $result = db_query("SELECT * FROM node WHERE type = '%s'", $node_type);
        $nids = array();
        while ($obj = db_fetch_object ($result)) {
          $nids[] = $obj;
        }

        $idsToInclude = array();
        foreach ($nids as $pageId) {
            $page_id = $pageId->nid;
            $realm = 'content_access_rid';// content access
            $grant_view = 1; // Has view
            $result = db_query("SELECT * FROM node_access WHERE nid != '%d' and nid = '%d' and gid = '%d' and realm = '%s' and grant_view = '%d'",$currentNode, $page_id, $role_id, $realm, $grant_view);

            while ($obj = db_fetch_object ($result)) {
              $idsToInclude[] = $obj;
            }
        }

        //var_dump($user->uid);
        //var_dump($nids);

        foreach($idsToInclude as $id){
            $courses = $id->nid;
            $nodeid = node_load($courses );
            if(node_access('view', $nodeid, $user)){
                echo '
'.$nodeid->title.'
';
            }
        }
    echo '
';
}

?>


Creating a related content block in Drupal 7 using OpenCalais How do I use OpenCalais to display related content in Drupal 7?

I would think I have to create a view, or something. I have nearly all the OpenCalais categories enabled (I'm creating a site for a newspaper), so it seems somewhat impractical to use them all as filters. I think you're supposed to use the More Like This module, but it doesn't have a Drupal 7 release. I am genuinely confused.

Open Calais will take your content and through their web service create metadata for it which the opencalais module can use to create an amazingly diverse variety of taxonomy terms that are applied to your nodes. It is a really cool service.

Once your content had the tags added by OpenCalais you could use one of the modules that provide a "Similar Content" block: http://drupal.org/node/323329 . Most of them are based on taxonomy terms. The More Like This module doesn't look like it has a D7 release but looks like it also uses taxonomy terms.

The simplest method for making a "More Like This" block might be to use Search API Solr or ApacheSolr. If you have full access to your server it is not that difficult to install. Solr's version of More Like This uses Solr's search engine to determine similar content on your site. Also a very very cool technology.


How to filter views block by content type I added two content types for views slideshows.
I added slides to both content types.
I created a views slideshow block using one content type.
I cloned the above view > Now, I have two views slideshow blocks.

Now, both blocks are linked. Updating one setting updating the other. How can I do the settings so views block1 filtered by content type1 and views block 2 filtered by content type2?

Add a filter of content:type in one of your display Also,
You can select this block override at the top when you do any specific block related changes. check the screenshot http://i.imgur.com/vdu0wqg.png


How to add new blocks when "The block X was assigned to the invalid region Y and has been disabled" I have inherited a site (in Drupal 6) and the original developers are completely out of the picture. I need to add a block but it looks like they've customized things and blocks are being rendered in a way other than assigning them to block regions as per the default.

I get a lot of warnings to the effect of The block X was assigned to the invalid region Y and has been disabled but those blocks still appear on the site. So they must be being brought in another way. I am not too terribly worried about the warnings (so seeing this discussion is not really what I need: https://drupal.org/node/1172560). I am more concerned that it is taking me hours to add a link and image to the homepage.

I see that the previous developers installed the Nodeblock and Nodeblock Auto modules and the nodes that come in have html ids like: block-nodeblockauto-node_<NID> so I imagine this is how they are being brought in.

But I don't see any options in the admin panel for configuring nodes any further than what I am used to from the default. In looking through the template files for the custom theme, I also do not see where these are being brought in.

Note: I am not in a position to migrate to Drupal 7 so I have to keep things in Drupal 6 for now.

In D7 I finally got rid of that message by placing an if ($theme == variable_get('theme_default', '0')) around the region assignment. So the block only gets assigned to my (default) frontend theme which actually contains the region the block is assigned to.

function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  if ($theme == variable_get('theme_default', '0')) {
        if (isset($blocks['MYMODULE']['MYMODULE_block'])) {
            $blocks['MYMODULE']['MYMODULE_block']['status'] = 1;
            $blocks['MYMODULE']['MYMODULE_block']['region'] = 'header';
            $blocks['MYMODULE']['MYMODULE_block']['weight'] = 2;
            $blocks['MYMODULE']['MYMODULE_block']['visibility'] = BLOCK_VISIBILITY_NOTLISTED;
        }
    }
}


7 - Can't update page titles I'm currently working on a project on which I'm trying to dynamically shorten the pages titles as following:

"This is very long text blahblahblah | Site Name" becomes "This is very ... | Site Name" but the rendered page doesn't take this into account.

Here's my problem: I tried several hooks to implement this behaviour, using hook_menu_alter(), hook_preprocess_html(), hook_node_preprocess(), etc. and I followed the indications given to update the pages titles when using these hooks, but it always falls back to using the original long title.

Actually, when I set the arrays accurate keys/values, would it be $vars['head_title'], $vars['title'], etc. I can var_dump the array and verify the needed variable is updated, but the title is untouched. Using drupal_set_title($new_title) didn't help either.

I'm quite puzzled; would this be because I'm using Custom Field, Metatag, or a specific module? Or would this be because I'm not updating the page at the correct moment during its generation? Drupal is somehow new to me!

Thanks a lot :)

~Steph

OK! After going back and forth between var_dump's, installed modules list and hooks, I discovered that the ONLY hook that will update the page's tags is hook_metatag_metatags_view_alter(&$output), in which something like this needs to be done:

$output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = "Custom title";

My n00b diagnosis is that this hook is called right after the last Metatag module's function that rebuilds the metatags from scratch, and therefore it's the only one that matters.

Hope this will help others! :)

~Steph


How do I inject services in class that implements an interface? How do I inject services in a class that implements an interface.

class RoleNegotiator implements ThemeNegotiatorInterface {

  public static function create(ContainerInterface $interface) {
    return new static(
      $interface->get('router.admin_context')
    );
  }
  public function __construct(RouteMatchInterface $route) {
    $this->route = $route;
  }
}

The above code throws an error.

You define the necessary services as arguments of the service you implement.

Since you are showing a class that implements ThemeNegotiatorInterface, see the theme.negotiator.default service and the class implementing it, Drupal\Core\Theme\DefaultNegotiator.

Service definition

  theme.negotiator.default:
    class: Drupal\Core\Theme\DefaultNegotiator
    arguments: ['@config.factory']
    tags:
      - { name: theme_negotiator, priority: -100 }

Class constructor

public function __construct(ConfigFactoryInterface $config_factory) {
  $this->configFactory = $config_factory;
}

There isn't any static create() method as in your code.


Modify existing custom content form I'm very new to Drupal development and I am completely stuck(.

I have a custom content form, where I need to hide some fields in Inline Entity Form.
I am trying to write my own custom module to achieve this, I am doing the following:
1. I create module folder, where I put info.yml file
2. I create Controller file, where I add custom class and this code inside this class:

public function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {if ($form_id == 'MY_FORM') {...};

The next thing I am completely stuck at is do I need a routing file to make this work?
I can't find any info about this so I'd really appreciate some help!
And if I need routing, what should I write there?

Thank you very much!
I really didn't need routing!

Well, finally I found the solution to my problem - I created the module with 2 files only - mymodule.info.yml and mymodule.module.
In .module file I only added these lines of code and everything worked! (Almost)

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
if ($entity_form['#entity_type'] == 'node' && $entity_form['#bundle'] == 'my_custom_content_type_machine_name') {
  unset($entity_form['field_I_need_to_hide']);
}}


Removing repeated field items I'm using Flexifield to create a repeating series of CCK field groups via a button that says "Add another item" (I.e., setting the number of field values to unlimited). See below:

My client has requested the ability to remove rows from this list once added. Any idea how I'd do that?

Thanks!

There's an issue that does exactly what I was asking for. Problem solved!


Extra Content Appears Below Footer I have an issue where I have the page for a specific role showing up on every page and additionally an error message.  These show up below the footer on the pages.  I've gone through the theme files and the blocks and I can't figure out what is causing them to appear.  I think the best way to show it is probably from the DevTools and inspecting the page.  You can see where the footer-bottom is and the EOF: #footer is for the theme.  Everything below that before /body and /html shouldn't be there.

Has anyone ever experienced something like this before?  I'm on Drupal 7, using Corporate Clean Theme.

Update:
The extra content also appears to append itself at the bottom when editing certain pages, so if I saved it without deleting it, it would appear within the main content and at the bottom of the page again.

Update 2:
It's definitely something that changed within the database and not the theme files.  When I import the last database before this happened, the extra content goes away, when I import the new one, it comes back again.  Additionally, there are a few pages when looking at in edit mode that are not showing up with the wysiwig editor, it looks like I'm editing them in plain text.

This was being caused by Cron run failing to complete for some reason.  We were able to solve the issue by installing the Cron Debug module and Cron would run successfully from there and clear up the extra text.


Set Generate automatic URL alias during import in Taxonomy how to set 'Generate automatic URL alias' for my terms during Feeds import?

I tried to set 1 or '1' in URL (url) field but it does not work for me.

use views bulk operation module and then you can update nodes or taxonomy on the fly via view....

I have the same problem now for nodes...


How to add custom content before hook_form() Form uploads image and if image is uploaded I'd like it to be displayed before the form. What is the right way to do this?

You can use hook_form_alter() to add a 'markup' element to the form, with a negative weight so that it floats to the top. For example:

mymodule_form_alter(&$form, &$form_state, $form_id) {

  // Only act on my module's form.
  if ($form_id != 'mymodule_form') {
    return;
  }

  $form['top'] = array(
    '#type' => 'markup',
    '#markup' => 'This will be at the top of the form!',
    '#weight' => -100,
  );
}