How do get a body.onload event executed? Background:

(*) I'm a JavaScript dilettante -- I just dabble when I need to.

(*) I have a piece of javascript that I've tested with a dummy page that I loaded by just calling it from a <body onload="..."/>.  It does what I want there.   (See https://github.com/cwestin/bobt/blob/master/site/style/article.html , and the sibling file http://github.com/cwestin/bobt/blob/master/site/style/bobt.js).

(*) I want to add this onload behavior to my Drupal site.

I followed the instructions on how to create a Drupal 7 module from here:  http://drupal.org/node/361112.

However, this seems to be aimed at PHP development of block modules that generate content.  All I have is the JS file, which will act on some div classes I put in my content's unfiltered HTML markup.

I also found instructions on managing JavaScript here: http://drupal.org/node/756722.

And, a search on this site found these instructions for including JS:  Best way for including javascript/jQuery OnLoad in EVERY page on my site .  However, that didn't really seem to answer the question it posed -- that I could tell.

However, having created a module by following these incomplete instructions as best I can, it doesn't look like my JS is getting triggered.  A View Source shows that my .js file is being included in the pages, but the transformation it does isn't happening (it did work in my dummy test page).  It's possible I'm not translating into jQuery correctly; I've never used that before, and the syntax is clearly not just plain old JS.

Here's the module:  https://github.com/cwestin/bobt/tree/master/site/style/sectiontoc .  As you can see, in the spooky function($) thingy, I add the required attach() to try to add my behavior to $(document).ready at the bottom.  But as I said, it's not getting triggered.

Could anyone please tell me what I'm missing, or what I'm doing wrong here?  Thanks in advance for any help.

Putting $(document).ready inside of Drupal.behaviors attach is redundant.

The point of attach is that it will run when the document is ready.


How can I allow more file extensions with file uploads? I've got a module that let users upload files, and everything works as long as the files are in the standard array of allowed extensions. I've tried using file_validate_extensions(), but this doesn't seem to change anything.

This is the code I'm using to upload now (the docx extension is added to the standard allowed ones, but it doesn't seem to get picked up):

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}

You actually have to check for the return values of the file_validate_extensions() function in order to detect if any errors have occurred.

so your code would be something like this:

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  $extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  if (!$extension_errors) {
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  } else form_set_error('attachment',$extension_errors[0]);
}


Tweet a published content on twitter from Drupal 7 My goal is tweeting content from a Drupal site as soon as a node / content is posted on the Drupal 7 site.

I follow all the instruction from this post "How to automatically tweet a published content on twitter from Drupal 7?" and did not work. What they recommend is to use the Twitter Module, this module you need to created an app at Twitter to make authentic it. I created the app and I'm able to pull all the tweets from Twitter to my site. Also, I'm able to sign in with Twitter however, I'm not able to automatic post a tweet after a node its created.

I can see the Twitter tab on my content type before I create a node. After I created the node a message said "Successfully posted to Twitter" but on twitter I cant see anything.  Can anyone tell me how to troubleshoot this ? Or do I'm missing something ?

Have you created the Twitter app with the correct permissions? By default apps are only created with read-only permissions


Previewing a view does not show a phone number but when I look at the view by visiting the URL of the page it does? I have taken over a Drupal website and I am completely new to Drupal. One of the features of the website is to list out all the employees of a company (a Directory).

The directory is displayed with a tabled view, and is pretty easy to understand.

When I look at the view while editing it in the preview view I don't see the each employees' list of phone numbers, I dont see a field for those numbers (i.e. Content:Phone_Number) either, but when I actually look at the view, from visiting the URL of the page I see the phone numbers.

Additionally, when I visit the URL that is hosting the View and use Firebug (DOM Explorer) I can see that there is a td tag that is holding the phone numbers. But, when I visit the View from a editor standpoint and check the preview view with FireBug (DOM Explorer) I see that exact td tag, but it's holding the user's NID number, not the phone numbers!

How is this possible?

Please and THANK YOU.

They most likely modified a tpl.php file.  In the Views module when you are viewing to edit it, look for Theme: information and click information.

You will then see a list of possible tpl.php files.  If you see one that is not in the first position and bold, then you know they did some type of override on the tpl.php.  Look in the theme folder for that file name.

If its not in there, then you will want to look at your themes template.php for some type of override.  Finally, some people will put these overrides in a utility module.


Cannot submit forms in Drupal 7 When I submit forms(all forms) in Drupal 7 it shows the Your configuration settings have been saved message, but the form values are still the same as the values before submission. I have cleared the cache but the problem still exists.

Any suggestion?

I can suggest how you can test what's happening:

Create custom test form with submit function.
Install Xdebug on your LAMP, or WAMP or MAMP
Than watch callstack. look what functions have been called.

Looks you've done some specific changes in your instalation.
Also try to download clear drupal instalation and check forms there.

(P.S. If you have opportunity switch to new instalation).


How to change labels on node add/edit form inside Authoring information box? I have a Drupal 8 site with the Bartik theme. How can I change label text on node add/edit form inside 'Authoring information' box. This box contains:

-Menu settings
-URL path settings
-Authoring information
-Promotion options

I want to rename some labels and add a new input text field. The main thing I want to change is the Authoring information box and the information inside of it. Is this done with hook form alter?

:

Those are the uid and created base fields, so yes hook_form_alter() or using interface translation are your options.

To add a new element in there, you need to set the right group, from NodeForm:

<?php
if (isset($form['uid'])) {
  $form['uid']['#group'] = 'author';
}


How can I replace a node reference field with a node edit form? I have two content types - parent and child. There is a one to many relationship (many children to one parent). I am migrating this content, and the current situation is that that node reference field is on the child, pointing to the parent. However, I may be able to change this to have a node reference field on the parent set to an unlimited number of items (though its probably better if I keep the existing "schema" to avoid problems after migration).

I would like to create a node edit form for the parent. In this node edit form, I want to have the child node edit form embedded on the same page, either as a replacement for the node reference field, or as a view displaying node edit forms of existing children of parent. I will create an interface that displays the child node edit form(s) when the user clicks on an accordion-like button at the top of the form, and beneath the form, a "Add another", which creates a new child node add form.

My first thoughts are to over-ride the template of the node reference field to embed the node edit form in the theme. However, this method seems to have potential side effects that have to be dealt with, as the current "schema" is the child nodes pointing to the parent nodes, which I prefer to keep.

My ideal solution is to use panels, but after playing with panels and doing some googling, I haven't found a solution that is specific to my needs.

How do I embed the form (either an existing node edit form or a node add form with a node reference field pre-populated) using panels? Is that even possible? If not, what is the best way to accomplish this?

You can achieve this by Installing Entity Reference and Inline Entity Form


Highlight valid form element I'm using clientside validation module. It highlights only errors. How to display for example a green mark beside valid form elements?

The Clientside Validation module adds classes 'valid' and 'error' to all form elements. You could use the class 'valid' to add the green mark simply with some css.


Field configuration changes after clearing the cache I have a content type with only an image field where users can put multiples images.

Sometimes, after clearing the cache, the configuration of the field resets by itself and it sets the cardinality to 1, not letting users to more than an image.

How can I prevent this problem?

This is a strange problem which should not happen. I'm afraid you have some debugging to do.

First of all, try to reproduce the problem on a clean installation with just Drupal core, no additional themes or modules. If you can reproduce the problem, you probably found a bug in Drupal core. Search in the issue queue if it has already been reported. If not, report the problem in a new issue.

If you cannot reproduce the error with just Drupal core, it must be a problem in your site. Duplicate the site (so you're not destroying work you have already done) and turn off modules one by one. Once the problem goes away, you know you have roughly located the problem. Then you can either try to debug the module yourself, or go to the issue queue of that module and try to work with the module maintainer to figure it out.


How to make a select form element with textfields for the array id and key? In a custom module which I'm working on, I have a select list which currently has a hard-coded array of key=>value which could change and I would like to expose these options to the user.

I would like to be able to have a select form element which contains one textfield for the user to enter the ID of the option and another for the user to enter the value of the option. I could make a separate form for these options, but I'd like to keep all the configurations on one page since there aren't too many.

Does anyone know how I can make a select form element where the key and value of each option is keyed in by the user?

Do you know of Drupal's core field type "List" or what it's called and its "Allowed Values" field? Where admins can enter key|value pairs divided by a pipe character?

It's exactly what you seem to describe.

I'd start by mimicking exactly that. But all in one form. Maybe multi-step. Maybe peppered with some Ajax...


Problem with views edit link not appearing I have created a view (block) that has contained in its fields user account information (including content profile fields). Along with that, there is an edit link to edit the profile information. The problem I am experiencing is; when logged in as a regular user, the edit link does not appear. When logged in as user 1 it does appear. I thought this would be a permission issue but I can't see what should be checked. I think I have enabled all the necessary permissions. Aren't users enabled to edit their profiles by default?

Here is a screenshot of the view's settings:

I am using Drupal 6.26 and views 6.2.16 and displaying this view in a panel. Any suggestions as to what I may be missing?

Thanks.

Found the answer to my problem. I had missed enabling access user profiles permission for authenticated users.


What is the purpose of the entity_metadata_wrapper() function, and why should I use it? I seem to be developing add-ons to a lot of modules that use Entity API at the moment, and the entity_metadata_wrapper() function keeps on popping up.

The docs page says this about it:

  Returns a property wrapper for the given data.

  If an entity is wrapped, the wrapper can be used to retrieve further wrappers for the entitity properties.

Ignoring the wonderfully Freudian spelling of the word 'entity' in there, I don't really understand what the purpose of these wrappers is.

I understand that the function essentially returns a EntityDrupalWrapper class:

  The wrapper eases applying getter and setter callbacks of entity properties

But what I can't understand is how it makes things easier.

For example, to update the status property of a node I could use this code:

$node = node_load($nid);
$node->status = 1;
node_save($node);

That's pretty clean. As I understand it (but may be wrong) the equivalent code using entity_metadata_wrapper() would be more verbose than that.

I'm not sure if it's simply the use of the term 'wrapper' that's tripping me up here, but I've looked through the code in the Entity module too and I'm not really any closer to understanding it.

Is anyone able to explain what the benefits of using this function are, and perhaps provide a simple code example for a common use-case?

Yes, changing the status of a node is trivial, as that is a hardcoded property.

Fields on the other hand, are much more complicated. They are nested three levels deep, while there is field_get_items() to get them in the correct language, there is no such function for setting field values. So, you always need to check whether a field is translatable or not and you need know which property exactly contains the values you're looking for/want to set.

Two examples, that show what the entity wrapper can do:

The following line adds the commerce line item to the order, taking care of the language and the actual property that holds the reference id, taken from the following answer https://drupal.stackexchange.com/a/23513/31

$order_wrapper->commerce_line_items[] = $line_item;

In a similar way, being able to directly access a value of a field, without having to check the language, or the delta, even being able to directly access referenced entities, taken from https://drupal.stackexchange.com/a/33010/31

$subnode = entity_metadata_wrapper('node', $node)->field_subnode->value();
$default = $subnode->title;

The entity wrapper is the driving force behind flexible, powerful modules like Search API and Rules as it allows them to work their way through multiple levels of references, so that you can e.g. access a field of the product a user bought in an order with something like [commerce-order:commerce-line-items:0:commerce-product:some-field] (might not actually be correct, but something like that), or add the body summary of a referenced node to your search index.

That said, I'm not necessarly fond of the actual API of the wrapper, it's huge internal arrays and that even simple properties are again wrapper classes. I hope that the improved entity (and hopefully field) system in Drupal 8 will remove the need for such a wrapper thanks to having classed entities.


Creating a user using Services results in user not being able authenticate using HTTP Basic Auth I'm developing a backend for an Android application using Drupal, and I've run into somewhat of a weird problem. I'm using Services and Views for the input and output of various content types. In order to make requests to the Services module, the users need to authenticate using HTTP Basic authentication.

When users create a new account in my app, I use the Services endpoint to create the new account using data that the user enters himself. However, the password that gets send to the endpoint is not the same as the password that gets saved.
This results in users not being able to authenticate other requests using HTTP Basic Auth with the password they set, as Drupal does not recognize the password. However, logging in using the Services endpoint DOES work with the set password.

When changing this user's password manually in the Administration panel to the value they set in the app, the HTTP Basic auth requests suddenly work, and they can still login using the Services module as well.

What's going wrong here, and even better, what can I do to remedy this problem? I'm not looking forward to changing every user's password manually so they can use the rest of my backend, and dropping the HTTP Basic Authentication is not an option either.

Edit:

Further investigation has shown that it's also not possible to login to the Drupal frontend using an account created by the Services endpoint, unless you change the password manually.

@Sander van't Veer - I struggled with this same problem recently. It looks like there's a bug in the services module where the password doesn't get set. Try this patch and you should be good.

https://drupal.org/files/issues/user_create-2198005-1.patch


Custom "normal" page in module Is it possible to create a normal content page in a module? At the moment I only know the $form type. But I need to add a page with some statistics.

Or is there a way to add normal content to a hook_form?

At the moment I have:

.module file:

$items['admin/config/services/push_notifications/stats'] = array(
'type' => MENU_SUGGESTED_ITEM,
'title' => 'Push messages stats',
'access arguments' => array('Push messages stats'),
'page callback' => 'drupal_get_form',
'page arguments' => array('push_notifications_stats_form'),
'description' => 'Push messages stats',
'file' => 'push_notifications.admin.inc',
'file path' => drupal_get_path('module', 'push_notifications') . '/includes',
'weight' => 80,
);

And in the .admin file:

function push_notifications_stats_form($form, &$form_state) {
$form = array();
$id = $_GET['id'];

$form['id'] = array(
'#type' => 'item',
'#title' => 'Application ID',
'#description' => t('The application ID you are viewing: @appId', array('@appId' => $id)),
);

return $form;

}

what you want is hook_menu:
  function pushnotifications_menu() {
    $items['admin/config/services/push_notifications/stats'] = array(
      'page callback' => 'yourverycustomcallbackforpushnotfiers_abc_view',
    );
    return $items;
  }

  function yourverycustomcallbackforpushnotfiers_abc_view($ghi = 0, $jkl = '') {
    // all your logic here
  }

btw: DO NOT DO THIS!!:
$id = $_GET['id'];
Sse drupal_get_query_parameters() instead, if you really have to fiddle with it directly. Otherwise use $args.


"Page not found" with new content type I already have a custom content type (jobs). When I create jobs nodes, they are displayed. I have created a new content type (ideas). When I add an idea node, I get a Page not found error. Any new custom content type I create gives me the same error.

The nodes I created are published. I cleared the cache.

I tried re-building the node permissions here: https://www.foo.com/admin/reports/status

Which didn't work.

There does appear to be  Experimental modules found: Content Moderation. This would no longer be experimental in 8.6, currently the site is running 8.2. Not sure if that upgrade would help or create more problems.

There is this error which is interesting:

Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions. Content
The node.field_recognition_date field needs to be uninstalled.

But I am not sure how to uninstall that or how to fix this issue. Any help would be appreciated.

Sound like you have removed a dependency from the codebase that a field a certain field depends on, usually it's a module. If that's the case you will need to reinstate it, then uninstall it. But also, you might want to try drush entup and drush updb

Also, it's a good idea to check the error reports for a more detailed explanation of what has happened


Grab Node ID from URL of Current Page? How do I grab the Node ID in the URL of the current page and pass it through a link?

1) The URL on the current page is in the format:  website.com/parameter/parameter/parameter and the third parameter is the Node ID.
2) I want to grab that Node ID and put it into a link on that page like Link

The screen capture illustrates this.

screen capture

1) You just need to add a contextual filter of "Content: Nid".

2) Then select Provide Default Value, type: Content ID from URL.

3) Add a field of Nid and check mark the box that says "exclude it from display".

4) Add a custom field, Deliberables

PS: Make sure the nid field is above the custom field so the custom filed can use the nid token.


How do I create a computed field? I'm creating a Webform in Drupal 8. On the form, I have two number fields; when a user populates them with values, a third field will display the value of the two field multiplied together.

How can I create that computed field?

P.S. If the user changes the values in either the fields, I need the value in the computed field to update on the fly.

There is a recipe for How to implement client-side calculations.


How do you implement a custom submit handler in hook_form_alter()? I've been updating one of my Drupal 7 modules to 8 and I'm having an issue with my form alter. I'm adding a validation function and a submit handler. The validation function is getting called just fine, but the submit function is not getting fired. I'm wondering if this means there is a Symfony-style approach that needs to be taken to adding submit handlers to existing forms. I've done a lot of searching and I can't find any examples. Also looked through some work-in-progress D8 modules but I haven't really found any working examples there either.

Does anyone have any idea what the correct Drupal 8 way to do this is?

According to the example in the documentation it's the same as for Drupal 7:

$form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';

You can find similar (working) logic in

contact_form_user_form_alter()
editor_form_filter_format_form_alter()
locale_form_language_admin_edit_form_alter()

And a few others besides.


Fresh install of COD: Anonymous users get "Access denied" on homepage Problem

I created a clean VM & installed COD. Unfortunately, when people aren't logged in they see:

How should I go about diagnosing further and/or resolving this issue?

Things tried

I thought this might be because the first conference wasn't published but the published flag was set, and I ticked the 'Promoted to front page' option.
That did not resolve the issue, so I created a basic page and applied the same options. No change to the homepage.
The homepage was set to node/1 so I changed it to no extension so that it could use the default homepage. No change.
UPDATE: Ticked Grant content access and Grant own content access for anonymous users in admin/people/permissions
UPDATE: Tried to use the rebuild option (/admin/reports/status/rebuild) to no avail

The permission required is View published content.

It turns out the content access module has a lot of different permissions that can be assigned to roles and this one is not selected by default for anonymous users.

This is a really easy permission to miss. It sits deep within nodes permissions and if you use the search facility for words like view or access you won't get it in the search result. Heck, if you search View published content it isn't returned.


Date format on user profile form shown incorrectly - how to change I added a date to the user profile form under admin/config/people/accounts/fields. The field is of type 'date', the widget of type 'select list' and I only collect year, month and day.

Without altering anything the date entry widget is shown on the form in the order year-month-day.

Since the order in the Netherlands should be day-month-year, I set out to change the date format by:

Adding a new custom format d/m/Y under admin/config/regional/date-time/formats
Create a new date type called 'test' and referencing the custom format from the previous step under admin/config/regional/date-time
Changed the date display format to the 'test' type, under admin/config/people/accounts/display - press update and save the settings

In the date preview of admin/config/people/accounts/display, the date is shown as DD-MM-YYYY which is the format I want.

Now, going to the user profile page under user//edit, the date order shown as month-day-year.

I have tested this on a clean installation of Drupal 7.33 and the only module added is the date module 7.x-2.8.

How can I change the display order for this specific field?

Kind regards,
Eric van der Staaij

Date entry format is configurable, what you did was changing the way the date will display on content but not on create content form. To change it go to your field configuration page on content type then find more settings and values collapsed fieldset and inside it look for date entry options and change to whatever.

https://docs.google.com/a/srijan.in/file/d/0B9FG53CLjf-YdEFfdzVEV1hmcWc/edit?usp=drivesdk


How to implement grouped filters filtered by roles? Is it possible to make exposed grouped filters where some filters are only available for certain roles?

Clone the view you already have into an additional views display, add the exposed grouped filters to that cloned views display, and then limited that additional views display to only those "certain roles".


How to insert textfield in the table and submit button under the table I want to create receive item from my purchase order node.
I have to create a table and displayed all data from node.
In last column of table I need to add a textfield and a submit button under the table.

I have read a lot of reference, but still getting error.
I hope somebody help to solve my problem.

by this code i want to create a form in table

function wespi_po_page(){
    $nid =arg(1);
    $form = array();
    $items = db_query('Select
                          Count(field_data_field_item.delta) As items
                        From
                          node Inner Join
                          field_data_field_item On node.nid = field_data_field_item.entity_id
                        Where
                          node.nid = :nid',array(':nid'=>$nid)
                    )->fetchField();
    drupal_set_message('Items counted : ' . $items);

$header = array(
    array('data' => 'Title', 'field' => 'title'),
    array('data' => 'On order', 'field' => 'on_order'),
    array('data' => 'On received', 'field' => 'on_received'),
    array('data' => 'Receive', 'field' => 'receive'),
    );

    $result = db_query ('
                        Select
                          field_data_field_item.field_item_nid As nid,
                          node.title As title,
                          field_data_field_on_order.field_on_order_value As on_order,
                          field_data_field_on_received.field_on_received_value As on_received
                        From
                          field_data_field_item Left Join
                          field_data_field_on_received On field_data_field_item.entity_id =
                            field_data_field_on_received.entity_id And field_data_field_item.delta =
                            field_data_field_on_received.delta Left Join
                          field_data_field_on_order On field_data_field_item.entity_id =
                            field_data_field_on_order.entity_id And field_data_field_item.delta =
                            field_data_field_on_order.delta Inner Join
                          node On field_data_field_item.field_item_nid = node.nid
                        Where
                          field_data_field_item.entity_id = :nid
                        Group By
                          field_data_field_item.field_item_nid', array(':nid' => $nid)
                );
    $rows = array();
    foreach ($result as $data) {
        $rows[] = array(
                    'data' => array(
                          l($data->title, 'node/'. $data->nid),
                          $data->on_order,
                          $data->on_received,
                          //$data->status
                    )
        );
    }
    $output = theme('table',
                            array(
                                'header' => $header,
                                'rows'=>$rows,
                                'sticky' => TRUE,
                            )
        );
    return $output;
}

function wespi_po_theme($existing, $type, $theme, $path) {
  return array(
    'wespi_po_table' => array(
      'render element' => 'element'
    ),
  );
}

function wespi_po_tab_page_form_submit(){
    drupal_set_message($items . ' Items received');
}

implements hook_form in your module and fetch any data you want from database as well as add textfield.
After completion of all form items you can theme it as using

$output = theme('table', array( 'header' => $header,  'rows' => $rows));

in your page callback function.
for more information you can check form api in drupal.org.


How to disable a form button in DrupalGap after it is clicked? I am experimenting with the Stripe Cordova plugin that seems to provide for an easy addition of Stripe payments to a Phonegap app.

I have created a form with the necessary fields (name, amount, CC numer, CVC, expiration month and year). It is of course important to prevent double clicking/double charging.

What is the most reliable way to disable the submit button immediately after it is clicked and prevent double charges?

Scenario 1:

/**
 * Define the form's submit function.
*/
function stripe_payment_form_submit(form, form_state) {
  try {
    var points = form_state.values['points'];
    var number = form_state.values['number'];
    var exp_month = form_state.values['exp_month'];
    var exp_year = form_state.values['exp_year'];
    var cvc = form_state.values['cvc'];
    var fullname = form_state.values['name'];
    chargeCard(points, number, exp_month, exp_year, cvc, fullname);
}
  catch (error) { console.log('stripe_payment_form_submit - ' + error); }
}

function chargeCard(points, number, exp_month, exp_year, cvc, fullname){
  stripe.charges.create({
  amount : points,
  currency : 'usd',
  card : {
    number : number,
    exp_month : exp_month,
    exp_year : exp_year,
    cvc : cvc,
    name : fullname
    },
   description : "Stripe Test Trasnfer"
},
  function(result){
    // asynchronously called
  });

}

Scenario 2:

/**
 * Define the form's submit function.
*/
function stripe_payment_form_submit(form, form_state) {
 try {
   stripe.charges.create({
   amount : form_state.values['points'],
   currency : 'usd',
  card : {
   number : form_state.values['number'],
   exp_month : form_state.values['exp_month'],
   exp_year : form_state.values['exp_year'],
   cvc : form_state.values['cvc'],
   name : form_state.values['name']
  },
  description : "Stripe Test Trasnfer"
 },
 function(result){
  // asynchronously called
 });
   }
  catch (error) { console.log('stripe_payment_form_submit - ' + error);   }
 }

Senario 1 or 2 would both be fine, the trick is to disable the button immediately before the ASYNC call begins. This can be easily accomplished with a little jQuery:

$('#my-submit-button').prop('disabled', true);

Then I'd recommend re-enabling it in the success and error handlers for the ASYNC call to Stripe:

$('#my-submit-button').prop('disabled', false);


I'm trying to make a module that searches LDAP for users I want to be able to search LDAP users by first name, last name, or email, and in the results show the user's picture, first/last names, role, and email.  I've looked into it a little and found the LDAP module for drupal, but all I see is syncing with users.  Is this something I can do using this module? Am I going to have to sync the LDAP db with a table in my MySQL db and then reference that table?

I think you'll find that LDAP modules for Drupal are primarily for allowing LDAP users to use Drupal.

My understanding of what you're saying is that you just want to display the LDAP users, sort of like a directory system?

If Drupal doesn't have to really interact with your LDAP users,  you should be able to create your own module for this pretty easily.

There are quite a few LDAP functions in PHP:  http://ca2.php.net/manual/en/ref.ldap.php

Create a module that makes use of them, and then passes the data over to a node for display purposes.


Can I connect via REST services with a mobile app I will develop? I'm thinking of developing an e-commerce with Drupal 8 and Drupal Commerce, but I need to know if I can connect via REST services with a mobile app that I would develop too. The app would need to be able to create carts, make orders, payments, and so on.

I have already developed several apps which connect to Drupal 8 and created content, but I need to know if it's possible to create orders, carts, payments, etc.

yes you can exposes entities and other resources as RESTful web API by activating the core RESTful Web Services module

  /admin/modules


Using Profile2 and Views - How to display the separate profile data on a single row I have several different pieces of info in separate profile2 forms.  When I run the view to display the data I want, it looks like this:

Profile      UID PID IID  Name         Email                     Membership
Main Profile 124 15  1237 Bernardo Lee BernardoLLee@teleworm.us
Membership   124 76                                              Basic Member

The Membership and Main Profile show up on different rows for the same users. I was hoping that by not displaying Profile and PID, the data would show up on one line like:

UID IID  Name         Email                     Membership
124 1237 Bernardo Lee BernardoLLee@teleworm.us  Basic Member

But it still shows on two lines.

Also, I can't figure out where the "profile2" table is. The query in Views is

        SELECT profile.type AS profile_type, profile.uid AS profile_uid, profile.pid AS
     pid, 'profile2' AS field_data_field_ibo_number_profile2_entity_type, 'profile2' AS
     field_data_field_first_name_profile2_entity_type, 'profile2' AS
     field_data_field_last_name_profile2_entity_type, 'profile2' AS
     field_data_field_primary_email_profile2_entity_type, 'profile2' AS
     field_data_field_cell_phone_profile2_entity_type, 'profile2' AS
     field_data_field_globalnet_membership_plan__profile2_entity_, 'profile2' AS
    field_data_field_monthly_educational_book_profile2_entity_ty
        FROM
        {profile} profile
        INNER JOIN {users} users_profile ON profile.uid = users_profile.uid
        WHERE (( (profile.type IN  ('main', 'knowing_you_better', 'website_info',
 'credit_card_info', 'membership', 'line_of_sponsorship')) ))
        ORDER BY profile_uid ASC

but when I drop it into mysql, it's an invalid query

I don't understand the {profile} and {users} nor the 'profile2'
I was hoping to rewrite the query if I can't get views to directly display what I am looking for.

I am not sure how you have created the view. But this would be the method to go about it

Create a view of the user.
Create two relationship of the type User : Profile One for the Main Profile and the other for the Membership
Add the required fields choose The corresponding  relationship for each of the fields, that is choose the one we created for Main Profile for the fields with in Main Profile and Membership for the ones in the membership.

That should bring it all in one line.

You might not be able to have the Profile and PID like in the first out put but I guess you dont want that .


how to send muliple emails in drupal in same time in my site when user submit a dination i want to send email to donor,charity and delivery service at same time(three different emails) in code and i want to kown how can i achieve that,below is the my mail seding function,i already tried call email function with 3 times with different keys for $key but that time emails are sending with out body content

 function zgRequestsdonor2_mail ($key, &$message, $params) {
  switch ($key) {
  case 'aftersubmit_donor':
    // Set headers etc

    $message['subject'] = t('email to donor');
    //$message['body'][] = t('Hello @username,', array('@username' => $params['username']));
    $message['body'][] = 'tyrtyrtyrtyty';
    break;
  }
}

calling it at

function zgRequestsdonor2_form_submit($form, &$form_state) {
  drupal_mail('zgRequestsdonor2','aftersubmit_donor',$donoremail, $language, $params = array(), $from = NULL, $send = TRUE);
}

If you want to send same mail to donor, charity and delivery service, then you can use CC feature of the mail.

$message['headers']['CC'] = "myemail@me.com";


Rules condition: check for a product with particular value for a field in the cart I have to aplly a custom fee if in the cart there's a product with a certain value for a field (producs with particular kind of battery). I use Commerce fees for applying the fee.

Every time the cart is updated I have to check: if there is at least one of those products the fee is applyed; if there's not (or there's not anymore) I have to not apply or remove the fee.

Removing a fee is a problem, as the module doesn't allow this.
But the bigger problem is whith rules: in conditions I can look for a particular SKU (only one) or a particular content type; instead I have to check something like this: "if there's in cart at least one product whith the value 1 for the field_battery,..."

Field_battery is a boolean field thath allow to the store's owner to flag products whith particulr battery, that require the extra fee.

I'm trying with the event "After updating an existing ordine commerce" btu I need help for conditions...

Thanks.

Not sure if this is the best way, but its the only way I can think of to do it.

You can do this by adding 3 different rules as well as adding a new field to "order" at admin/commerce/config/order/fields. We will call the field "Apply Fee" (apply_fee) and it is of the field type "integer"

Rule # 1,
Event: when product added to cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "1"

Rule # 2,
Event: when product removed from cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "-1"

Rule # 3,
Event: Apply fee to order
Condition: Entity has field: Entity=order Field=Apply Fee
Condition: Data Comparison: order's field Apply Fee is Greater than 0
Action: Apply a Fee to order


Charset issue in a webform We have got a multisite structure with several sites. One of the sites has got a webform, from which client needs to download submissions from time to time. However, when we choose to export to Excel using the default values (delimited text and \t as delimiter format), Turkish characters get corrupted on a Windows. I have got no trouble on Linux, but client uses Windows. I must also mention that this behaviour doesn't occur on another site in the same multisite structure. What could I be missing?

EDIT: We are running Drupal 7.34, Webform 7.x-3.21, PHP 5.2.17, and we are using MS Office 2007. I export to Excel using /node/%nid/webform-results/download. I have also tried exporting the Webform to another site on the same multisite structure (hence the same PHP version) and verified it works fine there.
Regards,

This might be a fix for your problem, perhaps you should try this on your test environment: https://www.drupal.org/node/2060519


call a modules function from preprocess_page I want to be able to call the current nodes taxonomy tree from page.tpl.php by using a function already in the taxonomy module. So far I've only been able to obtain the current nodes taxonomy id with:

$tid = $variables['node']->field_category['und'][0]['tid'];

I tried using: taxonomy_get_tree($tid);

but this only returns an empty array.

is there a way for me to use functions from other modules in _preprocess_page ?

full code:

function centro_preprocess_page(&$variables) {
     $tid = $variables['node']->field_category['und'][0]['tid'];
     $variables['taxTree'] = taxonomy_get_tree($tid);
 }

You are getting a taxonomy id. However, taxonomy_get_tree needs a vocabulary id as parameter, according to the documentation: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_tree/7.x . That's probably why you are getting an empty array.

In order to be able to call taxonomy_get_tree, you would need to get the vocabulary id first:

$term = taxonomy_term_load($tid);
$vid = $term->vid;
print_r(taxonomy_get_tree($vid));

(see this question for more details about getting the vid from a tid).


Problem with overlay in custom webform extension (D7) I'm doing my first drupal module (webform extension) and I have a problem with the overlay when editing a webform.

I added the "Factors" tab in my hook_menu():

$items['node/%webform_menu/webform-factors'] = array(
    'title' => 'Factors',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forms_grade_factors_create_factor'),
    'access callback' => 'user_access',
    'access arguments' => array('access administration pages'),
    'weight' => 5,
    'type' => MENU_LOCAL_TASK,
  );

But when I click on this Factor tab, the overlay disappears:

I don't know if it's important, but when I click on the other webform tabs, their urls are something like this:

drupal.dev/node/12#overlay=node/12/grant

And my module:

drupal.dev/node/12/webform-factors#overlay-context=node/12

How can I keep the overlay layer?
Thanks a lot!

EDIT:

I also implemented hook_admin_paths:

function webform_factors_admin_paths() {
  return array(
    'node/*/webform-factors' => TRUE,
    'node/*/webform-factors/*' => TRUE,
  );
}

The overlay automatically applies to paths that Drupal recognizes as being 'administrative'. That's always the case for paths that start with "admin", for example.

For custom node tabs, however, you'll need to implement hook_admin_paths() to register your custom path pattern:

<?php
function hook_admin_paths() {
  $paths = array(
    'node/*/webform-factors' => TRUE,
  );
  return $paths;
}
?>


Is there a way to resolve a list of references in a view without cloning entire rows of data? I'm playing around with the drupal views and reference relationships. I have an entity of type A that has a reference to entity of type B, and a list of references to entities of type C. Reached this point thanks to : this question

Using views -> advanced -> relationships I can create a relationship to B and then add the fields that I want from B in the view of A. However, when doing the same thing for the list of C, I am seeing the same entity of type A repeated as many times as there are references to the entity of type C.

Is there a way to have the list of C entities without the duplication behavior?

Depending on how you want to use the results of the query, you could use a GROUPBY option within the Views config.
Find the GROUPING options by clicking on the word "Settings" under FORMAT. The link for "Settings" appears to the right of the pipe symbol which separates the chosen format from the "Settings" link.
Once you do this, it should remove the duplicates.


Load a views block in a tpl file with his custom template I have a custom tpl file for a node type, in this file i want to load a views block i created.
This block has a custom template file to style the block itself.

I load the views block in the node template file with views_embed_view() but this just gives me the default html of the block and not the output of the blocks tpl file.

Is this possible with the views_embed_view() function or do i need to use some other function?

So to do this you just need to use the views_embed_view() function. I just had a typo in my template file.

So for someone who's looking for a way to do something similar:

<?php print views_embed_view('VIEW_NAME', 'DISPLAY_NAME', 'ARGUMENTS'); ?>


Drupal db_or() only returning one result Can someone please tell me why this code always returns only the last value of the query? I have tried many ways to dynamically build the condition statement for the querying of the database. I have looked at a couple examples and from everything i have seen, this is the way to do it. Any help would be greatly appreciated. Thanks!

function get_drupal_school_info($schoolIds) {
$or = db_or();
foreach ($schoolIds as $index => $data){
$or->condition(db_and()
    ->condition('f.field_external_id_value', $data['entity_id'],'=')
    ->condition('f.bundle', 'school')
    );
}

$query = db_select('field_data_field_external_id', 'f');
$query->leftJoin('field_data_body', 'b', 'f.entity_id = b.entity_id');
$query->leftJoin('field_data_field_partner_code', 'pc', 'b.entity_id = pc.entity_id');
$query
    ->fields('f', array('entity_id'))
    ->fields('b',array('body_value'))
    ->fields('pc',array('field_partner_code_value'))
    ->condition($or);

return $query->execute()->fetch();
}

It's, because you are calling fetch(). That method fetches a single result.

If you want all, you can simply loop over the return value of $query->execute() or use fetchAll() or one of the many related helper functions.


How can I keep a record of user email addresses when users update their email address? I have a site where a minority of users are causing trouble by registering with one email address and then changing to another email address. Email Change Confirmation helps with this, but I would also like to keep a record of changed email addresses per-user, preferably in the Drupal UI.

I am thinking about making an email address field and using rules to automatically add an old email address when the user changes his or her email, but if there is a more robust solution I would love to know about it.

The first thing that came to mind is Drupal's revision feature. Out of the box, Drupal let's you keep records of what changes are made to nodes over time. Users are a different entity, but the User Revision module aims to provide the same functionality. This Lullabot article explains it pretty well. You could give it a shot.


Show jCarousel if number of items are more than 3 I am using the jCarousel Views module; I want to hide the view when the number of items are not greater than 3. How do I do it?

You can use JCarousel views as block display and then set a visibility condition by executing custom php condition test code (This will require to enable PHP Filter module)

$result = views_get_view_result('view-name', 'display_id');

Then you can analyze the $result and count the number of results.
Most probably you need to do ....

if(count($result)<3)
    return FALSE; //Would not let to show that block
else
    return TRUE; // Would let to show


How $form_state->setRebuild(); works? I have created one form. In function buildForm() I'm firing query by getting parameters from url.

So suppose my url is [example.com/myform/myshort-title][1]

Now during form build, it gets the default argument as url parameter, and render results of query.Let's say my query result is an array of entity ids.

$entityids = array(1,2,3,4,5,6);

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

$query = \Drupal::entityQuery('mycustomentity');
$query->condition('colname', $short_title);
$entity_ids = $query->execute();

}

Now in  form submit handler, I'm rebuilding form state like shown below:

class MyForm extends FormBase {

  protected $myvar;
  protected $step;
  protected $correct_ans;

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

    $query = \Drupal::entityQuery('mycustomentity');
    $query->condition('colname', $short_title);
    $entity_ids = $query->execute();
    $i = 0;
    foreach ($node_storage as $nodeID=>$nodeData) {
       if ($i == $this->step)  {
echo $this->correct_ans;

       $correctAns = CategoryController::getCorrectAnswer($op,$entityid);
       $form['answer'][$i] = array(
            '#type' => 'hidden',
            '#value' => $correctAns,
      );
     }
    }

    }
public function submitForm(array &$form, FormStateInterface $form_state) {
$aString = $form_state->getValue('answer');
foreach ($aString[0] as $key1 => $value1) {

                         $this->correct_ans= $value1;

}
   $form_state->setRebuild();
   $this->step++;

    }

}

Debugging results give:

At first, when form gets loaded, it takes default parameter as argument from url == short_title.

print_r($entity_ids); gives array(1,2,3,4,5)
print_r($correctans); echo "<br>";gives arary(0=>myanswer1)

Hit Submit

  array(1,2,3,4,5) array(0=>myanswer1)

  array(1,2,3,4,5) array(0=>myanswer1) array(0=>myanswer2)
  array(0=>myanswer1) array(0=>myanswer3)

and echo $this->correct_ans; always gives myanswer1.
On every form submit form gets rebuild and $this->correct_ans takes default array value which is array(0=>myanswer1)

But I want, On first submit, I get array(0=>myanswer1), On second submit I want array(0=>myanswer2), On third submit I want array(0=>myanswer3) and so on...

Where I'm doing mistake?Please help.

You are trying to store state values into a protected variable in the class. That will not work. You will have to store state values into the form.

So instead of using

$this->step

and other class properties to store values use

$form_state->set('step', $value);

to persist values between submissions.


Cron Tasks not running in background, causing pages to take forever to load We recently upgraded to D8 and I have been experiencing weird issues with Cron. Specifically, whenever the Cron is running, web pages are taking forever to load because cron is running some JS on the front end of any page you attempt to load. Specifically, it appears to be a timeout method that is holding up the page load.

NOTE: I will update this post and provide the exact JS file and function that is running on the front end the next time it happens to me. At the time of writing, cron wasn't running and therefore I couldn't inspect the web page to get the running method

I know it's not the CPU on the server because when cron was running it never got above 20% CPU utilization.
Isn't cron suppose to run in the background? Why would cron have a JS file being executed on every page, causing any page not to load until cron finishes?

Part of the settings on /admin/config/system/cron are for the Automated Cron module, which adds them via automated_cron_form_system_cron_settings_alter(). The form field it adds has the following description.

More information about setting up scheduled tasks can be found by reading the cron tutorial on drupal.org.

If you follow that link, you will read the following sentences. (Emphasis is mine.)

The automated cron module has the disadvantage that it is triggered by a request, and the unlucky user who sends the request may experience a fairly long delay. For this reason, the automated cron is typically used by smaller sites that are unable to create a cron job manually, e.g. using the Linux crontab. If crontab is desired, Drupal console command may be used to simplify the configuration (rather than curling the long URL show in /admin/config/system/cron. Here is an example crontab entry:
30 * * * * web_user /var/www/html/vendor/bin/drupal --root=/var/www/html/docroot cron:execute > /dev/null 2>&1

Essentially, what you are experiencing is how the Automated Cron module work, but that isn't the only way to run cron tasks for Drupal.
You could also pass the URL shown on on /admin/config/system/cron after To run cron from outside the site, go to to wget or curl. This requires that you have access to, for example, cPanel for the site, which allows to set cron tasks.


Related content in drupal 7 I'm developing a site in drupal 7 that needs a related content block. The problem is that I tried Similar entries and Similar by terms modules but it looks like they are not compatible with views 7.x-3.0 I'm using, yet.

There is an error message when I install both modules and in the bug reports I found posts with errors just like mine but without good solutions.

I was thinking until the modules are ready, maybe, I can, somehow, use views and show random content based on the taxonomy term in the node and not show the current node.

Is there a way to use contextual filters and use arguments from taxonomy in the current node?

If you know some other way or module to achieve something similar please point me in the right direction.

I've achieved this using a view to pull nodes that share the same taxonomy as your current node.

Basically create a view that uses the 'Has taxonomy term' contextual filter. And also include a content NID contextual filter to exclude the current node (in the list appearing in that view).

Follow the example here to create the view ('Views 3' steps at top):
http://www.metachunk.com/blog/adding-related-content-view-drupal-7

I've also taken it a bit further and ticked 'Reduce Duplicates' and 'More > Allow multiple values'. That way you can specify multiple terms from your current node and only get a node once if it appears in more than one term.

Make sure you select the fields you'd want to see in your template.

My view is also filtered to one content type  'news' so i've named it 'related_news'. I use the following code in my template.php to grab the views content and pass the template an array. Add your custom fields to the $terms array to then use their ID to find related content.

/**
 * Return result of Related News view for a specific node.
 * TO-DO: Add default functionality.
 * @param object $node
 * @return array
 */
function [template]_get_related_news($node) {

    $terms = array();

    //Get terms from fields.
    $terms = array_merge($terms, $node->field_field_term_1);
    $terms = array_merge($terms, $node->field_field_term_2);

    //Build array of ids
    $termIDs = array();

    foreach ($terms as $terms){
        $termIDs[] = $terms['raw']['tid'];
    }

    //Load view
    $relatedView = views_get_view('related_news');

    //Execute view with term ids as argument. Include node id to exlude it from results
    $relatedView->set_arguments(array(implode('+', $termIDs), $node->nid));
    $relatedView->execute();

    return $relatedView->result;

}

You could also get the view to produce a block and use this to display the content within your theme.


Prevent anonymous to input a registered email during commerce checkout through Rules? In Drupal Commerce, how to prompt a warning message and keep it in checkout process if an anonymous inputs a registered email? I know there is a Commerce Checkout Login, but it is just an AJAX addon.

I believe I can do it through Rules and that's what I did.

Event: Process checkout pane
Conditions:

Data comparison: [commerce-order:uid] == 0
NOT Data value is empty: [commerce-order:mail]
Entity exists by property: User/Email, [commerce-order:mail]

Actions:

Show a message on the site: Warning, ...
Update checkout status: checkout

In first trial, it seems work well. But the weird thing is, when I change the email field to an unregistered one, I can still spot the warning message generated by Show a message on the site. Is there something wrong in my rule setup?

Refer to this Anonymous can use registered email address: intended behavior?.

With @RyanSzrama's suggestion, I pursue a form validation solution. What I finally use is to implement a hook_commerce_checkout_pane_info_alter. The following is a simplified code snippet for that.

/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  if(isset($checkout_panes['account'])){
    $checkout_panes['account']['callbacks']['checkout_form_validate'] = 'MYMODULE_form_validate';
  }
}

function MYMODULE_form_validate($form, &$form_state, $checkout_pane, $order) {
  if (!user_is_logged_in()) {
    $mail = $form['account']['login']['mail']['#value'];
    $query = sprintf("SELECT COUNT(*) FROM {users} WHERE mail = '%s';", $mail);
    if (db_query($query)->fetchField()) {
      $msg = t('The email address is registered to an account!');
      form_set_error('[account][login][mail]', $msg);
      return FALSE;
    }
  }
  return TRUE;
}

Hope that also provides some hint or help to others. For form validation, please refer to Adding validation to commerce pane form.


Way to remove the Override Title form option in Panel component config? I am making a Panel Component, in D7, and do not want to show the title. I can just not render out the title on the page - that's fine - but I'd also like to remove the form fields that allow you to enter in the title.

Would anyone know how to do this? I cannot find any info out there.

The function responsible for the overriding title:

/**
 * Add the default FAPI elements to the content type configuration form.
 */
function ctools_content_configure_form_defaults($form, &$form_state) {
  $plugin = $form_state['plugin'];
  $subtype = $form_state['subtype'];
  $contexts = isset($form_state['contexts']) ? $form_state['contexts'] : NULL;
  $conf = $form_state['conf'];

  $add_submit = FALSE;
  if (!empty($subtype['required context']) && is_array($contexts)) {
    $form['context'] = ctools_context_selector($contexts, $subtype['required context'], isset($conf['context']) ? $conf['context'] : array());
    $add_submit = TRUE;
  }

  ctools_include('dependent');

  // Unless we're not allowed to override the title on this content type, add this
  // gadget to all panes.
  if (empty($plugin['no title override']) && empty($subtype['no title override'])) {
    $form['aligner_start'] = array(
      '#markup' => '
',
    );
    $form['override_title'] = array(
      '#type' => 'checkbox',
      '#default_value' => isset($conf['override_title']) ? $conf['override_title'] : '',
      '#title' => t('Override title'),
      '#id' => 'override-title-checkbox',
    );
    $form['override_title_text'] = array(
      '#type' => 'textfield',
      '#default_value' => isset($conf['override_title_text']) ? $conf['override_title_text'] : '',
      '#size' => 35,
      '#id' => 'override-title-textfield',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );
    $form['override_title_heading'] = array(
      '#type' => 'select',
      '#default_value' => isset($conf['override_title_heading']) ? $conf['override_title_heading'] : 'h2',
      '#options' => array(
        'h1' => t('h1'),
        'h2' => t('h2'),
        'h3' => t('h3'),
        'h4' => t('h4'),
        'h5' => t('h5'),
        'h6' => t('h6'),
        'div' => t('div'),
        'span' => t('span'),
      ),
      '#id' => 'override-title-heading',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );

    $form['aligner_stop'] = array(
      '#markup' => '
',
    );
    if (is_array($contexts)) {
      $form['override_title_markup'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => t('You may use %keywords from contexts, as well as %title to contain the original title.'),
      );
    }
    $add_submit = TRUE;
  }

  if ($add_submit) {
    // '#submit' is already set up due to the wizard.
    $form['#submit'][] = 'ctools_content_configure_form_defaults_submit';
  }
  return $form;
}

states on line 513:

  // Unless we're not allowed to override the title on this content type, add this
  // gadget to all panes.

which means you could just add the following array members to the existing $plugin or $subtype:

  $plugin['no title override'] = TRUE;
  $subtype['no title override'] = TRUE;

and theoretically it should work.


Programmaticaly remove a member from a group Using the Group module, what is the function to remove a user from a group using its user ID and the group ID?

The entity type interface (GroupInterface) has a removeMember method; all you need are the relevant entity objects:

if ($account = \Drupal\user\Entity\User::load($user_id)) {
  if ($group = \Drupal\group\Entity\Group::load($group_id)) {
    $group->removeMember($account);
  }
}


Access Denied when redirecting to alternate view I've designed a view that shows a table of data.  Within the global header, I've written

  Click here to
  see your events in a calendar
  format.

The intent is to redirect to another view if the user clicks the link(s).  This works correctly if the user is using Chrome or IE as a browser.  However, if FireFox (on Windows), or, Safari (on Mac), are used, the user gets:

  Access Denied You are not authorized to access this page.

And, they are asked to login again.  I've checked permissions and everything seems to be in order.  Does anyone know why this is happening?

Please check if cookie & javascript is enabled on the test machines for Mozilla & Safari browser.


What happens when you choose a default country during installation? In the last step when you install Drupal 8 under "Configure site" you can choose a "default country":

However no clues are provided about the option...

What happens when you choose a default country for the site?
And what happens when you just leaves it as "none"?

In drupal core this is only used for date and time formats. If you leave it empty you can set it later in the admin menu:

/admin/config/regional/settings


$query->limit(10) gives fatal error I am trying to develop a simple module in Drupal 7. I want to return a table with some data in a function, which i am able to achieve. I am stuck in the pager part though.

I used

pager_default_initialize($total, 10);
$html .= theme('pager', array('quantity',$total));

and I can see the pager below my list, also I have 21 records for now and it shows << < 1 2 3 > >> which means it calculating 10 records each.

But my issue here is I can see all the 21 records at once regardless of whichever page I go to. I suppose I have goofed up my page_query.
When I tried using $query->limit(10) it gives error Fatal error:

  Call to undefined method SelectQuery::limit() in C:\xampp\htdocs...............

If I comment $query->limit, there's no error but it does not work completely.
This is my query

$query = db_select('profile');
$query->fields('profile', array('id', 'name', 'store_name', 'company', 'city', 'email', 'phone'));
$query->orderBy('id', 'DESC');
$query->extend('PagerDefault')->limit(10);
//$query->limit(10);
$results = $query->execute();

Please help!

Thanks in advance! :)

extend() isn't chain-able, it returns a new extended query object, so you need to assign the result back to the query object, e.g.

$query = $query->extend('PagerDefault')->limit(10);

Otherwise the query won't actually be extended and won't have the limit() method, hence the error you're getting.


How do I alter the title of a menu link? In my website, users can collect some 'points' over time. I have a top-bar menu with some links (e.g. "home", "profile", "logout"). I want to alter the menu item "profile" and add the number points owned by the current connected user.

I tried several hook, and I almost succeeded in getting what I wanted with hook_link_alter().

function mycustommodule_link_alter(&$variables) {
  if ($variables['text'] == "profile") {
    // Do some work.
    $variables['text'] = $variables['text'] . " (you have $nb_points points)";
  }
}

I cleared the cache (with drush cr), and the menu item shows the value I want. But, if the value changes for some reason, it shows the old value. I must clear the cache all the times to update its value.

How can I avoid cleaning the cache to update the menu title all the times the points gained from the user change?

I suggest implementing a custom menu link plugin. The code below assumes your module name is example.

<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Database\Connection;
use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $dbConnection;

  /**
   * Constructs a new points menu link.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Menu\StaticMenuLinkOverridesInterface $static_override
   *   The static override storage.
   * @param \Drupal\Core\Database\Connection $db_connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, StaticMenuLinkOverridesInterface $static_override, Connection $db_connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $static_override);
    $this->dbConnection = $db_connection;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('menu_link.static.overrides'),
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = $this->dbConnection->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

If you don't want to inject the database service the class would become much simpler.

<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

Next you need to put the link definition into example.links.menu.yml file.

example.user_points:
  route_name: <front>
  menu_name: main
  class: Drupal\example\Plugin\Menu\ExampleMenuLink
  weight: 30

The caching problem

Whenever the number of points is changed the menu link cache should be invalidated as follows.

 \Drupal::service('cache_tags.invalidator')->invalidateTags(['example.points_count']);

You need to find out the right place for this. If the points managed by contributed module check the module API and pick up an appropriate hook (hook_points_insert(), hook_points_delete() and so on).

Since the number of points is calculated for each user account individually you may consider using per account cache tags (something like ['example.points_count.' . $uid]). Therefore the cache will be preserved  for users with unchanged points.

To generate code for the Menu link plugin I used Drupal Code Generator.


Automatic product variations pricing I have a site where a client wishes to sell products that have a lot of different variations (ie size, colour, length etc), but each of these will make a slight change to the price. I know about the ability to make variations of products so that the price changes when you pick different items in the drop downs, but these have to be manually entered. For my client, each time the variations are open to the end user, the price increase will always be the same.

Both have the size option available to user -the price will increase on top of the base price by the same increment based on the selection.

eg:
Small = no change
Medium = +£5
Large = +£10

Product A, starting price: £10
Product B, starting price: £20

So Product A with medium will be £15, Product B with large would be £30

I realise in this example it would be simple to add this in manually, but if she has 3 (or more) different options open to the end user, with upto 10 options within, multiplied by her entire product range, it would take forever to do.

What I had thought is if it was possible to add a price addition field to the product category listing, and then use a (rule/module?) to automate this price being added on. Is there anything already out there that does anything like this, or if not, how could I go about creating it.

Many thanks

How about the Commerce Customizable Products Module.  I just saw this video today, maybe it will help.

Drupal Commerce allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:

Business cards that require contact information and a logo upload.
Event registrations that require attendee information.
Donations the allow the customer to specify a donation amount.

The core Line Item module accommodates these scenarios by letting you add any number of fields to the Product line item type and expose them to the Add to Cart form. However, sites that sell multiple types of customizable products or a mixture of customizable and non-customizable products need to define multiple line item types to handle the different configurations of fields. That's where this Customizable Products module comes in!
It gives you the ability to define new line item types on the fly at Administration > Store > Configuration > Line item types. This is functionally equivalent to defining the new line item type in code, which is still recommended if you are able.


Giving Blocks a Fixed Width Hello i am having a few problems with 3 menu blocks i have in a region of my theme. You can view this region on the main top of this page
http://onlinebanter.com/latest

The top block just consists of 3 menu items and when you click one the child items appear (seperate menu block level). They appear to the right of the lower level menu block though.

Ive tried giving the first menu block a fixed width

.menu-block-14 {
width:500px;
}

To see if that will 'push the other menus down' but to no avail.

Can anyone suggest something for me to try?

thanks

This should work:

.menu-block-12,
  .menu-block-14 {
    float: left;
    width: 100%;
    clear: both;
  }


Retrieve Webform submission data from database Here's a little background on my project: I have 10 or so webforms let's call them Forms A thru J which are for different departments of a college.  I also, have 1 credit card processing form let's call Form Z.  I will be collecting information from a form like Form A specific to that departments needs and upon submission will redirect the user to Form Z to process a credit card transaction.  I have created a webform handler to redirect the user from Forms A-J to Form Z and a handler to process the credit card transaction.  In the redirect handler I am able to pass all of the information from Forms A-J to Form Z using the query string in the URL.  I want to avoid this since there would be Personal Identifiable Information (PII) being passed through the URL.
I want to be able to retrieve the data submitted on say Form A from the database when Form Z is loading.  I should be able to pass the webform node ID and submission ID to Form Z through the URL query string and use them to get the data from the database.  I found these posts which give me an idea of how to retrieve the data from the database:
Programmatically update Webform Submission by sid
Load webform submission
https://www.drupal.org/project/webform/issues/2911356
What I can't find is how do I get this to run when Form Z is loading.  I've seen a couple of posts on hook_form_alter but those posts are using it in a different way from what I am trying to do so I don't know it that's the way I need to go.
Once I retrieve the data from the database I need to populate that data into I'm thinking some hidden webform fields on Form Z.  I'd like to be able to fill billing address with the address submitted with the previous form upon request (checkbox or button).  Also, I need to be able to have the data from the previous form available once Form Z submits so that I can send a custom email Confirmation depending on which form the information came from (i.e. Form A or B or J).
Being new to drupal development I've gotten some great assistance with this project from this site and I am very grateful to those who have been assisting me.  :)
EDIT:
So based on Remy's recommendations I have created a custom module with these two files in \modules\custom\cc_processing_getsubmissiondata:
cc_processing_getsubmissiondata.info.yml
name: 'CC Processing Get SubmissionData'
description: 'Provides a custom webform handler for retrieving the previous forms submission data'
core_version_requirement: ^8.8
Core: 8.x
package: Custom
type: module

CCProcessingGetSubmissionData.module
<?php

/**
 * Implementation of hook_form_alter
 */

 use Drupal\Core\Form\FormStateInterface;

 function CCProcessingGetSubmissionData_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    echo "form alter hook triggered";
        $form['street_1'] = '92-2000 Some Rd.';

    if($form['#webform_id'] == 'credit_card_billing_information') {
        echo "form alter form id found";
        $form['credit_card_name'] = 'Jared';
    }
 }

At this stage I am just trying to get the hook_form_alter to just do something so that I know it is being triggered.  However, I am getting nothing.  I even tried the function name CCProcessingGetSubmissionData_webform_credit_card_billing_information_form_alter but that didn't work either.  Any suggestions?

Easiest is probably to preprocess the webform's new submission, load the desired submission, and then pre-populate your fields. I doubt that this is built-in.
fe
<?php
function HOOK_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form['#webform_id'] == 'your_webfom') {
    $form['elements']['your_element']['#default_value'] = $your_value;
  }
}

There may be several ways by not-coding, but using modules.
LMGTFY - https://www.drupal.org/forum/support/post-installation/2021-02-01/how-to-use-webforms-submissions-in-other-forms

Install the 'Webform Views Integration' module.
Create the view for display submissions of the 'Client' webform.
Add to the view the 'Entity Reference' display and add the 'Name' field (or any field you want to see on the 'Project' webform).
Click on the 'Settings' and check the field that will use for serach.
In the 'Client' webform select the following reference method: 'View: Filter by an entity reference view'.
Select the view created by you from the 'View used to select the entities' list.

The screenshots of the example:

https://ibb.co/ZJxgK9w
https://ibb.co/C6sxCFv
https://ibb.co/mFWDCTX
https://ibb.co/QcwYYm6


Get Div's Text in Drupal Forms API I have this code below:

$form['id']['mypreview_modal'] = array(
    '#type' => 'item',
    '#markup' =>
        '
12345
'
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'myid_user_page_form_ajax_submit',
    ),
);

function myid_user_page_form_ajax_submit() {
     $myid_user = ; //Get mypreview_modal's text/innerHTML
}

I want to get mypreview_modal text and assign it to myid_user. How will I do that?

An AJAX callback is not a submission callback; the submission callback is the usual one a form uses, independently from the form using AJAX or not.
An AJAX callback is given the $form and $form_state parameters, allowing it to produce a result, which it returns for rendering. Since it gets $form as parameter, accessing that value simply means parsing $form['id']['mypreview_modal']['#markup'].

function myid_user_page_form_ajax_submit($form, $form_state) {
  // Parse $form['id']['mypreview_modal']['#markup'].
}

Keep in mind that usually an AJAX callback just returns the part of the form that needs to be rendered. See poll_choice_js() as example.

function poll_choice_js($form, $form_state) {
  return $form ['choice_wrapper']['choice'];
}

The rest is done from the submission handler. (In the case of the Poll module, and for the form using the previous AJAX callback, this is poll_more_choices_submit().)

  // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
  if ($form_state ['values']['poll_more']) {
    $n = $_GET ['q'] == 'system/ajax' ? 1 : 5;
    $form_state ['choice_count'] = count($form_state ['values']['choice']) + $n;
  }
  // Renumber the choices. This invalidates the corresponding key/value
  // associations in $form_state['input'], so clear that out. This requires
  // poll_form() to rebuild the choices with the values in
  // $form_state['node']->choice, which it does.
  $form_state ['node']->choice = array_values($form_state ['values']['choice']);
  unset($form_state ['input']['choice']);
  $form_state ['rebuild'] = TRUE;


How to change the Zen theme to a single sidebar layout? I'm using Zen (version 7.x-5.5) as a base theme.

The problem is that it's showing with 2 sidebars layout. I searched in the documentation but I didn't find a way to change it to 1 sidebar layout (with main content of course ).

I changed the SCSS files in _responsive.scss, but nothing changed.

Is there any way to make this work?

In page.tpl.php, at line 109 and line 110, delete the sidebar you don't want

In style.css change this class
.region-sidebar-second{
float:left;width:20%;margin-left:0%;margin-right:-20%
}

to be
.region-sidebar-second{
float:left;width:20%;margin-left:0%;margin-right:-20%;display:none;//add a display:none
}

and change .two-sidebars #content {
float: left;
width: 60%;
margin-left: 20%;
margin-right: -80%;
}

to be

.two-sidebars #content {
float: left;
width: 80%; //change 60% to 80%
margin-left: 20%;
margin-right: -80%;
}


How to restrict a view to display only 2 content types? I have created a view (/page_view), which displays two content types.

This view contains a contextual filter for user to be able to see only one particular content type (/page_view/content_type_1 and /page_view/content_type_2).

But in my case the user by typing for example /page_view/content_type_3  is able to see other content types which should not be included into the current view.

How can I restrict a view to display only 2 content types?

Sounds like you need to set a filter type as well instead of just your contextual filters. So under filters choose "Content Type" and choose ONLY the content types you wish the user to see. Then the contextual filter set it to "No results found" (see screen shots)


Drupal modal form save data twice In my Drupal site I am using Webform module Modal forms (with ctools) module.

When I place file field (to get opportunity attach files) on the form, form save data twice. But when I delete file field, form work perfect, e.g. save data once. Maybe someone has already faced this problem. Any help will appreciate.

Image-1

Image-2

I found solution.
In the file

  modal_forms.pages.inc

inside the function modal_forms_view_webform($js = NULL, $node) place $form_state['rebuild'] = TRUE; after $output = ctools_modal_form_wrapper('webform_client_form_' . $node->nid, $form_state);

Then modal form will save data only once.


Throw entity field value from submission to route path? I have created two entities and I want to connect them by route.
my edit route is:

entity.entity_two.edit_form:

  path:
'/property/configuration/communication/{entity_one}/variant/{entity_two}/edit'

  defaults:

    _entity_form: communication_variant.edit
    _title: 'Add/Edit Email Variant'
    entity_one: '%id'
  options:

    parameters:
      entity_one:
        type: 'entity_one'
      communication_variant:
        type: entity:node

but I get an error on edit path as it says: entity one is empty but as i check entity one has value in the table.
so my idea is that on submission of entity two form, I get entity_one id by entity reference and set in my route. so I want to implement that idea any help?

I have found the way to pass the value in edit route without using route subscriber or any pram converter. I will pass the value to Entity list builder default operations function. From there I can change the URL of edit and delete.

public function getDefaultOperations(EntityInterface $entity) {
    /* @var $entity \Drupal\my_module\Entity\entity_two */
    $operations = parent::getDefaultOperations($entity);
    $cid = $entity->cid->getString();
    $edit= \Drupal\Core\Url::fromRoute('entity.entity_two.edit_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['edit'] = array(
        'title' => $this->t('edit'),
        'weight' => 10,
        'url' => $edit,
    );
    $delete= \Drupal\Core\Url::fromRoute('entity.entity_two.delete_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['delete'] = array(
        'title' => $this->t('delete'),
        'weight' => 11,
        'url' => $delete,
    );

    return $operations;

}


Completely Locked out of website via User Permissions The story:

Here's the full story. I disabled the Drag 'n Drop uploads module and then I was prompted to rebuild user permissions. So I was like, Ok and I rebuilt the user permissions. Then I noticed I couldn't see my admin toolbar, so I scrolled down the list of modules and it was unchecked, so was almost everything else. I went through and rechecked the modules I needed and then I clicked save. Nothing happened so I decided I'd put my site in maintenance mode until I sorted out the problem (so I did). I couldn't figure out what was wrong or how to fix it so I restored my entire website from a backup made earlier (1:28 AM) today but now it's giving me an error and I can't even access my site.

The Error:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.role' doesn't exist: SELECT r.rid, r.name, ur.uid FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid IN (:uids_0); Array ( [:uids_0] => 0 ) in UserController->attachLoad() (line 314 of ...public_html/modules/user/user.module).

The question:

Is there any way to fix this error?

It sounds like the roles database table got randomly deleted, which should basically never happen under the circumstances you describe.

If you have a recent database backup, I suggest you grab the structure and content of the roles table from that database backup and restore that to your site database so you have the right content.

If you don't have a backup, I suggest you do a new installation on a separate site (or your local computer) and then export JUST the roles table from that new installation and import the roles.


`Drupal\DrupalExtension` extension file or class could not be located I got this error upon launching behat tests:

  [Behat\Testwork\ServiceContainer\Exception\ExtensionInitializationException]
  Drupal\DrupalExtension extension file or class could not be located.

Does any additional module is required?
Found https://www.drupal.org/project/behat but for d7

The Drupal Extension requires no modules, only composer installation.
Execute:
composer require drupal/drupal-extension='~3.0'
See the docs for other setup information: https://github.com/jhedstrom/drupalextension/blob/master/README.md
Update
to install the latest version just use
composer require drupal/drupal-extension

[version 3 is kind of outdated and in this time latest version is 4.1]


Image Styles and Effects Once I've created different Effects under Image styles. How do I flip between them in the Manage Display/Manage Fields windows for the content type?

I can't figure it out.

Or am I just meant to create Different Image styles for each different effect I might like to use?

The display formatter for an image on "Manage Display" allows you to select which image style to use.

The image style itself contains the relevant effect(s)


How to hide a DIV if ther's no value in that Content in a node--customtpl.tpl.php file How can I hide a DIV if ther's no value in that Content in a node--customtpl.tpl.php file? I have used a code something like this, but if hides everything weather it has data or not. Can anyone help me with this code?

I want to hide this "special-offer" div if there's no value in that field in drupal (this_is_a_drupal_field).

<?php
if ($content['this_is_a_drupal_field'])
  {
  print "
";
  print render($content['this_is_a_drupal_field']);
  print "
";
  }
?>

<?php if(empty($content['this_is_a_drupal_field'])){ ?>

Your if statement needs a condition, ex: 'greater than' > 'less than' < 'equal to' == or 'not equal to' !=

The special NULL value represents a variable with no value.

So try:

<?php if ($content['this_is_a_drupal_field'] != NULL): ?>
  <div class='special-offer'>
    <?php print render($content['this_is_a_drupal_field']); ?>
  </div>
<?php endif; ?>

So basically we're saying if $content['this_is_a_drupal_field'] is not equal to empty print...


How to clone a entity with its attached fields? I am trying to create a entity with few bundles. I have used EntityDefaultUIController as admin UI callback. This provides me with few default functions such as clone, import and export. The problem is when I try to clone or export the entity. It does not export or clone the fields attached to it. Has anyone faced similar issues. I traced back the issue to entity_ui_get_form function which does not have any function related to getting the field information. How could I clone entity with its fields attached to it?

Kindly help me figure this out.

A recent module called Replicate provides an API to easily clone any entity, including of course its fields and references.


Drupal Commerce. Trigger shipping rules based on product field value I'm really losing the will to live and hope somebody can help me.

I want to trigger a 'free shipping' rule based on a product field value, but for the life of me can not expose the free shipping field to rules.

I have read about bringing items into scope and have created a component which has access to the field. But when I attempt to add the component as a condition of my rule I am prompted to enter data selector -  none of which seem to lead anywhere. I think it was wanting a product ID, which does not make any sense to me.

What am I doing wrong?

MORE BACKGROUND

I have tried two scenarios, one of which is to create a shipping rule,based on the conditions below. The other is to create a component, as described above

Condition1 - Entity has field > Parameter: Entity: [commerce-order], Field: field_free_shipping

Condition2 - Date value is empty (also tried data comparison) > However this does not lead me to the field stated in Condition1

I eventually managed to get this working by dropping the idea of having custom fields and replacing them with taxonomy terms. For whatever reason (probably inexperience) I could not expose my custom fields to the rules module in order to trigger the shipping rules that I wanted.

By leveraging the Commerce Rules Extra module I was able first to trigger my shipping rules based on taxonomy terms instead of custom fields and secondly to define additional conditions for firing these rules with the help of the modules maintainer @MarcElbichon as discussed here https://drupal.org/node/2087815


How to assign users to a group How do I assign users to a group in Drupal 7? Basically I wanted to have following groups in my website.

Administrators
Content Writer and Publisher
Registered users

I wanted to assign all of the newly registered users to "Registered users" group automatically and I as a member of administrator should be able to assign some trusted users into "Content Writer and Publisher" group.

Each of these groups will have different-2 permissions as expected.

From a permission point of view, (instead of groups) these are called "roles" in Drupal. (From a content-user-access point of view there is the Organic groups module, but that's another story.)

You can administer roles at admin/people/permissions/roles. You can mass assign users to roles at admin/people (Update options - Add a role to selected users).

All registered users automatically have a role called "authenticated user", so there is no need to duplicate that functionality.

For more info check out "Managing access control with permissions and user roles" at
https://drupal.org/node/22275


Bartik theme: How to extend text/content below blocks in sidebar 1 and 2 Am using the Bartik theme on my site. I noticed that whenever i place a block in the sidebar 1 and sidebar 2, all the space below the block becomes 'redundant' (i.e. content is limited to the middle of the page.) All the text on the page becomes restricted to the middle of the page.

Please, is there a way to make the content/text extend below the blocks in side bar 1 or 2?

Edit your page.tpl.php
Cut and paste both the sidebar sections into the content section.
Content section starts with:

I mean these parts:

<?php if ($page['sidebar_first']): ?>

      <?php print render($page['sidebar_first']); ?>

  <?php endif; ?>

<?php if ($page['sidebar_second']): ?>

    <?php print render($page['sidebar_second']); ?>

<?php endif; ?>

I think you will need some extra CSS to make it look nice.


Deleting a field from a content type deletes the view where that field has been included Have started to play with Drupal8 recently by trying to jump from D6 to D8, skipping D7 part. While playing, have tried to re-create a simple slideshow view, using a separate "slideshow" content type and an existed image field.

Since an upload via old image field hadn't worked, decided to delete and re-create that field after slideshow view was created.

But, it seems, that Drupal has deleted not only an image field from a content type, but a View, where that field were included.

Has anyone seen something like this, or is there anything wrong with my configuration?

Yes, that's what currently happens. Drupal informs you on the delete confirmation page that will be deleted.

https://www.drupal.org/node/2468045 is an issue that tries to improve it so that the view updates itself instead.


How do we programmatically place a section and then a block in that region on module install? We are looking for the best way to export a defined/built layout with inline blocks and then use that to programmatically set both them during a module install.

eg.

module install

create node in content type
apply section
create and apply block to section in node

Currently we are having to print the array, strip UUIDs.. then attach them to the layout field value of the node we create. Which can lead to issues if not cleaned up correctly.

Put this code in an .install file:
// Create a Home web page with alias 'home'.
  $node = Node::create([
    'type' => '<node_type>',
    'langcode' => 'en',
    'uid' => 1,
    'title' => 'Home',
    'status' => 1,
    'path' => [
      'alias' => '/home',
      'pathauto' => PathautoState::SKIP,
    ],
  ]);

  // Variable to hold the sections for this node.
  // Defaulting to have a blank section first.
  $sections[] = new Section('layout_onecol');

  // Create a new section.
  $section = new Section('layout_onecol');

  // Config for the multi-type list block.
  $pluginConfiguration = [
    'id' => '<block_id>',
    'provider' => 'entity_block',
    'label_display' => FALSE,
    'view_mode' => 'default',
  ];

  // Create a new section component using the node and plugin config.
  $component = new SectionComponent($node->uuid(), 'content', $pluginConfiguration);

  // Add the component to the section.
  $section->appendComponent($component);

  // Add the section to the sections array.
  $sections[] = $section;

  // Set the sections.
  $node->layout_builder__layout->setValue($sections);

  // Save the node.
  $node->save();


Posts of a taxonomy term in views block I have created a Taxonomy vocabulary called "Model" that has some Term like: Beautiful - Cool - Cute - Awesome so-forth. Now, i want to show most recent 6 posts under "Beautiful" term from "Model" vocabulary using a views block. But can't understand how to build the views block. I came through this many Q like this

How do I show only 3 of the latest posts for each term in a view?
Show newest nodes for each taxonomy term in Views

but cant understand how to make a views block to show recent 6 posts under "Beautiful" term from "Model" vocabulary using a views block? Any idea? Thanks

Create a view and then under display configuration settings set Items to display = 6 and also select sorted by as Newest First. Then go to Filter Criteria and add filter  Content: Has taxonomy term Then select term "Beautiful" Then add a new block display to the view and save. Refer the images below.

Step 1:

Step 2:

Step 3:

Step 4:

Step 5:


Drupal - Shared Backend How can I, in Drupal, install a project that have 2 different websites(frontend) but share the same backend? Is it possible?

Simple answer is YES. What you are trying to do can be achieved by using one of these modules:

The Multi Site installation module (It requires separate database for each site or common database with table prefix.)
The Domain Access module

These are just general suggestions, as there are several ways to achieve your goal. You have to choose the right method suited for your needs. This is a screen-cast which would be helpful for you.


add a menu to a user menu I'm defined a menu with a hook_menu, but he appears in navigation menu.
how do I put in the user menu?

$items['budget/view'] = array(
    'title'             => t('Ver gastos'),
    'description'       => 'Veja quanto é que anda a gastar',
    'page callback'     => 'page_budget_view',
    'page arguments'    => array(2,3),
    'access callback'   => ($user->uid > 0),
);

You can use  'menu_name' => 'primary-links'; in your code and of course you have to alter the primary-links to the menu of your choice.

$items['budget/view'] = array(
  'title'             => t('Ver gastos'),
  'description'       => 'Veja quanto é que anda a gastar',
  'page callback'     => 'page_budget_view',
  'page arguments'    => array(2,3),
  'access callback'   => ($user->uid > 0),
  'menu_name'         => 'primary-links',
);


How to get number of results from MySQL query without getting all result data? For a Google Maps application, I built an AJAX call that dynamically checks whether there are markers in a given viewport range. All marker information is stored in a node (note that I am using projective coordinates x, y instead of lat,lng) and the text in the body field also matches a condition. The MySQL query is as follows:

var $text = 'Test';
$query = db_select('field_data_body', 'b');
$query->join('field_data_field_x', 'x', 'b.entity_id = x.entity_id');
$query
  ->fields('b', array('entity_id'))
  ->fields('x', array('field_x_value'))
$query->where('b.body_value LIKE :text', array(':text' => $text));
$query->where('x.field_x_value >= :num1', array(':num2' => $xmin));
$query->where('x.field_x_value <= :num2', array(':num2' => $xmax));
$result = $query->execute();
if ($result->rowCount() < $maximum) {
 process_data($row->entity_id, $row->field_x_value);
}

Now, whenever the amount of markers exceeds a number $maximum, a clustering mechamism sets in. For this purpose, I really need to

1) check if there a less than $maximum results,

and only in this case

2) pull that data and process it.

Since quite many markers are stored in my database, my MySQL query should be as slim as possible, ideally it would first only give me the number of results (similar to a COUNT* query) and pull the result data only if needed.

Can anybody advice me on whether my $query->execute()->rowCount() code does that job? Or does $query->execute() automatically pull all results, and rowCount() is a PHP counting routine? The $result object does not seem to contain the explicit data, therefore it seems plausible to me that the data might not have been pulled yet at that stage...

Thanks for your help!

MySQL has no mechanism like that; you'll need to run two queries, the first a count query, and the second for the data if your condition on the first query result passes.

The PDO rowCount() method isn't used for SELECT queries, just DELETE, INSERT and UPDATE queries.

You'll need the countQuery() method to determine the count with a separate query, then simply run the original query  if the count query gives the right result


Search API and Facets API with multilingual taxonomy I have some taxonomy terms and the settings look like this.

All these terms have been translated.

After indexing the content with Search API and Facets API, the facets are not shown with translation.

Why is it happening?

To localize FacetAPI you should install FacetAPI i18n.

  The Facet API Translation module integrates the Facet API and
  Internationalization projects allowing site builders to translate
  configuration settings. This module also overrides common mapping
  callbacks, such as the content type mapping callback, to translate the
  display name of facets.