Issue with attaching an existing file while creating node using RESTWS I am trying to create a new node using the restws drupal module. My content type has just two fields: title and a file. However, when i send the request with following payload, i get an error. The file which i am referring in the payload is already existing on my drupal server.

URL : CMS_BASE_URL/node
Method : POST

Payload:

<?xml version="1.0" encoding="utf-8"?>
<data>
      <field_my_file>
                <file resource="file" id="24">CMS_BASE_URL/file/24</file>
      </field_my_file>
      <type>filetest</type>
      <title>My 1st file test</title>
      <language>en</language>
      <author resource="user" id="5">
      </author>
</data>

Error - 406 Not Acceptable: Invalid data value given. Be sure it matches the required data type and format.

Is there any problem in the way i am sending the payload? If i remove the "file" part from the payload, it is able to create node.Please guide me if this is not correct.

I tested the following code it works fine. Replace your field machine names and bundle name accordingly. Hope it helps

Here is the XML format to send data

<result>
<title>title_of_node</title>
<type>sampleimage</type>
<field_samplefile>
<und is_array="true">
<item>
<fid>18</fid>
<uid>1</uid>
<filename>Drupal.txt</filename>
<uri>public://Drupal.txt</uri>
<filemime>text/plain</filemime>
</item>
</und>
</field_samplefile>
</result>

Here is the JSON format

{
    "title": "title_of_node",
    "type": "bundle_name",
    "field_samplefile": {
        "und": [{
            "fid": "17",
            "filename": "changes.txt",
            "uri": "public://changes.txt",
            "filemime": "text/plain"
        }]
    }
}


How to set the default for checkboxes element I'm trying to set the default of a checkboxes list in the form_alter_hook.

$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a','b','c'),
  '#default_value' => array('a'),
  '#title' => t('The average vote is more than'),
  );

I'm expecting 'a' to be checked, that it never seems to happen. I'm using better exposed filters, but I doubt that would make a difference?

Simplistically, the issue is that the default value uses the array key, not the array value.  So, there are two ways you can change this to make it work.

One:

$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a' => 'a','b' => 'b', 'c' => 'c'),
  '#default_value' => array('a'),
  '#title' => t('The average vote is more than'),
);

or

$form['average'] = array(
  '#type' => 'checkboxes',
  '#options' => array('a','b','c'),
  '#default_value' => array(0),
  '#title' => t('The average vote is more than'),
);


Loading in JavaScript that requires custom vars I'm rebuilding one of my works modules from Drupal 7 to Drupal 8 and I'm 99% of the way there the one thing I'm stuck on is in some cases I need to load in a external library that changes on a users location and other which is defined in a settings form:

In Drupal 7 I'd simply do it with:

drupal_add_js($proto.'://f1.'.$region.'readspeaker.com/script/'.$customerid.'/ReadSpeaker.js?'.$srcparams,array('group' => JS_DEFAULT, 'type' => 'file', 'scope'=>'footer', 'preprocess' => FALSE));

But I'm not sure how to achieve this by creating a library in Drupal 8.

If the settings are global and don't vary per use, I'd implement hook_library_info_alter() and dynamically set the path there. JW Player does something like that: http://cgit.drupalcode.org/jw_player/tree/jw_player.module?h=8.x-1.x#n206

Remember to clear the cache when the settings are changed, so this is updated.

If it's something completely dynamic, or per user or so, you have to either write JS to load it or embed the js tag yourself, e..g with html_head.


How do I limit content type per role? I am running a Drupal 5 site with number of roles. Is there a way to assign limits per role? E.g. Authenticated user could upload 10 documents, whilst Paid user could upload 100 documents. Your help is much appreciated.

The NodeFamily module will allow setting a maximum number of nodes that can be created per user. However it doesn't provide per role maximum number settings.


Object of type stdClass cannot be printed when received JSON response I have:
$result = $client->request('POST', 'http://'.$core_address.':'.$core_port.$core_uri, [
    'body' => json_encode([
        'a' => $a,
        'b' => $value['v'],
        'x' => $value['x'],
    ]),
    'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
    ],
]);

$output = json_decode($result->getBody());

i catch the output and print it like:
drupal_set_message($output);

problem is: if output just a flat string, it work like a charm
but when it receive json like:

{'x': ['Not a valid integer.'], 't': ['Not a valid string.'], 's':
['Not a valid string.']}
192.168.yyy.xxx - - [28/Jul/2016 00:14:59] "PUT /Module HTTP/1.1" 200 -

it give me error:

Uncaught PHP Exception Exception: "Object of type stdClass cannot be
printed." at /path/to/Drupal/Core/Template/TwigExtension.php line 443,
referer: https://url.com/admin/core/my/module/path

why? why?

Short answer: because that is how the API was written.

Long answer is that they do not know how the object should be printed.

To cast an object to a string, you need the object to have a __toString method, which the object in question does not contain.

If you want to print the stringified version of the object then don't transform to an object using json_decode.


How to create a fields on the users profile to allow them choose from a number of opens then order them based on preference On the users profile, I need to add the ability for users to select from a number of options, then order them based on their preference.

e.g.

What are your favorite fruits?

Select from:

Apples

Bananas

Oranges

Grapes

Then I need the users to be be able to reorder them in terms of preference:

e.g.

Grapes

Bananas

Apples

Any thoughts on how to achieve this (existing modules)?

If it's D7, user profiles are fieldable, so you've got what you want out of the box : add a field in admin/config/people/accounts/fields with a select wodget and you're done.

For the ordering, I think Draggable Views could be worth a look.


Entity reference, display custom field, not the title I am using drupal 8.
I have two content types:

ORGANIZATION with the following fields
- Title
- image logo
- much more fields

EVENT
- Title
- Start Date
- End Date
- Reference to the organizations (unlimited)

The event page needs to display the title of the event, start date, end date and all the logos of the organisations (not the titles of the organizations)
How can I do this ?

In the "Manage Display" of the fields in the Event type, in the "Format" there are only 3 options, "Rendered Entity", "Entity ID", "Label". For "rendered entity" there are a few options as "Default", "Full content" and some other. But I cannot see an option to specify only to display the logo.

Create a view and set the filter "Content: Type", to "one of"- Event and Organization. Pull all the fields you want to be displayed and publish the view in a page or as a block on any page. You can further customize the html of said created view per the instructions here :)


How can I print a text field's database value with devel so that it displays on all nodes? I want just the text field's data without an of the "field-" divs wrapped around it. It's a link so I want to do something like <?php print render($content['field_download_link']); ?>.

$...['content']['system_main']['nodes'][7533]['field_download_link']['#field_name'] is the path of the field I want to display, but I want it on every node of the content type feed_item, not just 7533.

I tried placing <?php dpm($node); ?> at the top of node--feed-item.tpl and <?php print dpm($node['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']); ?> where I want the field, but it just causes the page to load without any css.

Based on node.tpl.php, it says

  $node: Full node object. Contains data that may not be safe.

Things I noticed that's not quite right:

dpm() doesnt need to be used with print
dpm($node['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']); wouldn't work since $node is an object.

Things to try:

Use only dpm($node); and see what's the output. If the field you're looking for exists then you can continue with manipulating its data
you could place the structuring of your link in hook_preproess_node() and just render it into your template file.


How can I rebuild my installation after attempting to manually update D8 core using D7 instructions? After following the manual update instructions linked from the download page for Drupal 8.3.4, I got a "The website encountered an unexpected error. Please try again later." This is when I noticed that the breadcrumb for the update instructions said "Drupal 7".

As per the erroneusly linked instructions, I have deleted every file and folder in my drupal 8.3.2 installation except /sites, and I'm wondering what I need to do to restore them. Is there a reliable way to find out exactly which modules I had installed (e.g. translation files, or database tables?), and can I fix the problem by manually uploading the modules to /modules, or could the failed update.php job have damaged my installation?

(My server doesn't support automatic updates, and I only have FTP/MySQL access.)

Manually uploading the 3rd party modules to /modules (atleast the modules i found translation files for in my /sites folder) and restoring my database from backup, allowed me to restart the update process;  so far everything seems to be working again.


How to access node from hook_html_head_alter()? I want to add an og:url tag to the <head> so that the correct image shows up when my page is shared on Facebook.

I've found the hook_html_head_alter() hook which looks like I can add something to the head. I don't see how I can access the node object though when inside this method. I want to check if this page is for a certain Content Type. If it is that type, then look at some of the data on that node to determine which image to put in the og:url tag.

Drupal alter hooks, the group of hooks including hook_html_head_alter(), are not thought to add values, but to alter the values provided by another module. If you need to add a tag to the <head> of a node page, you should:

In a module, implement hook_node_view(), check $view_mode is not equal to 'teaser', and possibly other values for which you cannot provide the tag you want to add. Alternatively you can implement hook_entity_view(), which is called for every defined entity; if you just want to add the tag to nodes, you should rather implement hook_node_view().
You can also implement hook_preprocess_node(), which is invoked every time a node is shown, or hook_preprocess_page(), which is invoked for every page, including the page containing the node edit form. In hook_preprocess_page(), you need to verify $variables['node'] is not empty; if it empty, it means the page is not about a node.
The alternative is implementing hook_init(), but that hook is not invoked for cached pages.
In a theme, implement hook_preprocess_node(), or hook_preprocess_page().

In all the cases, you need drupal_add_html_head() to add the tag, and menu_get_object(), when you don't have the node object, which is available in hook_node_view(), hook_preprocess_node(), and hook_preprocess_page(). You would need to call menu_get_object() in hook_init(), for example.

Notice that menu_get_object() called without arguments returns a node object, if the page is about a node, and its path is similar to node/[node ID], or starts with that string; if the page page is, for example, page/node/[node ID] (where page/node/[node ID] is not a path alias), then menu_get_object() doesn't return a node object; in the example path I used, you should use menu_get_object('node', 2).


Configuration page for module does not apear? This is my hook_menu.

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

        $items['coverflow']  = array(
            'title'           => 'Coverflow Slider',
            'page callback'     => 'coverflow_page',
            'access arguments'=> array('access content'),
        );

        $items['admin/config/coverflow'] = array(
                'title'                 => 'Coverflow Settings',
                'description'         => 'Coverflow Slider Settings.',
                'type'                  => 'MENU_NORMAL_ITEM',
                'page callback'     => 'drupal_get_form',
                'page arguments'    => array('coverflow_admin_form'),
                'access arguments'=> array('administer site configuration'),
                'file'            => 'coverflow_admin_form.inc',
                'file path'       => drupal_get_path('module', 'coverflow'),
            );

        return $items;
   }

And this is my callback function for coverflow_admin_form

function coverflow_admin_form($form, &$form_state){

    $form           = array();

    $form['height'] = array(
      '#title' => t('Height'),
      '#type' => 'textfield',
      '#size' => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['width'] = array(
      '#title' => t('Width'),
      '#type' => 'textfield',
      '#size' => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-size'] = array(
      '#title' => t('Font Size'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-family'] = array(
      '#title' => t('Font Family'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

    $form['font-color'] = array(
      '#title' => t('Font Color'),
      '#type'   => 'textfield',
      '#size'   => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );

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

        return system_settings_form($form);

}

After installing module im not getting configuration link at admin/config/coverflow.

What is wrong in this code?

Got the solution, just have to remove '' from 'MENU_NORMAL_ITEM' because MENU_NORMAL_ITEM is drupal constant for handling Menu Items, after removing '' the code is working as expected.


During checkout, when I click on review order, I would like to do some additional validation When a user goes to checkout and clicks on "review", I would like to be able to hook into that process in order to do some custom validation.

How would I go about doing that?

You can just do a custom validation handler on the checkout form. This would mean the validation is done before you get to the review order screen. Let me know if you need more details.


How do I adjust the 'Create New Account' settings? New registrations are asked to create a password which is, in my opinion, excessively strong. Where do I go to adjust the password strength and other 'new account' settings?  When I looked in the listed modules, the 'User Module' was greyed out.

I am using Drupal version 6.

There were a few options for Drupal 6 so it's hard to give generic instructions. Check the module page for modules that include the word password and check for a "Configure" link.

Take Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


Theming a new Panel Page I think I am missing something really silly here. I am trying to learn theming in drupal. So I downloaded a "starter" theme called Genesis and installed it. This theme has a barebones header and footer. And in the middle the content area is split into left sidebar, main content and right sidebar.

I created a panel page with 'flexible' layout. It has only one region defined and inside it I placed a custom view I had created earlier. Now when I hit this panel page url, it shows up correctly, but inside the main content area of theme. I mean the header, footer, left and right sidebars are still visible.

My question is: By default do panel pages render inside main content area? How can I customize a panel page such that I can do away with the header, footer or sidebars if I want to?

Appreciate any help!!

By default do panel pages render inside main content area?

No, Panels should 'takeover' the page based on your ctools page manager assignments.

See /admin/structure/pages to confirm you have the path set in page manager ("Pages").


Reverse Entity Reference in a Paragraph I have a Paragraph with an Entity Reference Field "link". This Paragraph belongs to Content Type B.

I want to create a reverse Entity Reference for "Link": all nodes that have the paragraph with this Entity Reference should be listed.

I tried

content_dependency - does not seem to work with Entity References within Paragraphs
reverse_node_reference - not working at all?
Custom View: did work with a entity reference without a paragraph (relationship referencing ER field) but not with the paragraph....

Any ideas?

After many days of unraveling views, entity references, and paragraphs, I finally figured this out. The moment was celebrated with an awkward, club-footed jig.

For context, I'm building a financial data delivery site that connects investment fund managers with funds to manage.  My content types look like this:

I have an entity type called Contact, which has inside it a Paragraph field called Job History.  There are 3 different job history paragraph bundles for 3 different types of jobs, but each type has fields for Job Title, Phone, Email, Employment Date, and an entity reference field called Fund.  I also have another entity type called Fund, which is referenced by the Fund reference field.

1. Contact (entity)
- Job History (paragraph)
-- Fund
-- Job Title
-- Phone
-- Email
-- Employment Date

2. Fund (entity)
- Various fields (irrelevant to this solution)

I want to create a table view that will appear on all Fund pages, and show any contacts, with their contact info, for said Fund.  In other words, this view should display any Contact nodes that reference the current Fund node, along with those nodes' phone, email, etc fields.  I can achieve this using only Views...

Create a content view and filter by node type: Contact.
Add a relationship, Content: Field (Job History).  This allows me to access the fields inside the Job History paragraph field.
Add all above fields I want to display (name (title), job title, phone, &
email) to the Fields section, making sure each one uses the Paragraph item from field_job_history relationship.

At this point, I have a view that displays all contact nodes & their fields. Let's narrow it down to those that reference only the current Fund node.

Add a relationship, Entity Reference: Referenced Entity (A bridge to the Content entity that is referenced via field_reference_fund). Use the existing relationship, Paragraph item from field_job_history.
Add a contextual filter for Content: NID. Use relationship, Content entity referenced from field_reference_fund. Provide default value: Content ID from URL.

The view will now display the fields within the paragraph, and limit the results to only those nodes that reference the current node.

I hope this provides the solution you were looking for!


How to set root of programmatically rendered menu I'm currently attempting to create a plugin where the user can choose what level of a menu to render regardless of what page they're on. I'm generating the form where the user can select the menu level here

public function blockForm($form, FormStateInterface $form_state) {
    $menu_name = 'main';

    $menu_tree = \Drupal::service('toolbar.menu_tree');

    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $tree       = $menu_tree->load($menu_name, $parameters);

    $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
        array('callable' => 'toolbar_menu_navigation_links'),
    );

    $tree = $menu_tree->transform($tree, $manipulators);
    $list = ['none' => $this->t('None')];
    foreach ($tree as $item) {
        $list += [$item->link->getPluginId()=> $item->link->getTitle()];
        if ($item->hasChildren) {
            foreach ($item->subtree as $subitem) {
                foreach ($subitem->subtree as $subitem_child) {
                    $list += [$subitem->link->getPluginId() => '-'.$subitem->link->getTitle()];
                    foreach ($subitem->subtree as $sub_subitem) {
                        $list += [$sub_subitem->link->getPluginId()=> '--'.$sub_subitem->link->getTitle()];
                    }
                }
            }
        }
    }

    $form        = [
        'menu'            => [
            '#type'          => 'select',
            '#title'         => $this->t('Top level of menu'),
            '#default_value' => $this->configuration['menu'],
            '#options'       => [
                $list,
            ],
        ],
    ];

    return $form;
}

This works, and the user can select the level of the menu they want, but I'm not sure what to use in order to render the menu at that level. I did see that I could get a plugin

    $menu_name  = 'main';
    $menu       = $this->configuration['menu'];
    $menu_tree  = \Drupal::service('toolbar.menu_tree');

    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $tree = $menu_tree->load($menu_name, $parameters);

    $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
        array('callable' => 'toolbar_menu_navigation_links'),
    );

    $tree = $menu_tree->transform($tree, $manipulators);
    foreach ($tree as $item) {
        var_dump($item->hasChildren);
        if ($item->hasChildren) {
            var_dump($item->link->getTitle().' - '.$item->link->getPluginId());
            foreach ($item->subtree as $subitem) {
                var_dump($subitem->link->getTitle().' - '.$subitem->link->getPluginId());
                foreach ($subitem->subtree as $subitem_child) {
                    var_dump($subitem_child->link->getTitle().' - '.$subitem_child->link->getPluginId());
                    var_dump($subitem_child->link->getTitle().' - '.$subitem_child->link);
                }
            }
        }
    }

I have the pluginID of the selected in the form, but I'm not sure how to make any use of that. I tried using
        $parameters->setRoot('818bf040-f12a-4915-835f-b9339eb7c828');

Where 818bf040-f12a-4915-835f-b9339eb7c828 in this case was the pluginid of the selected menu item, but that caused the menu to not return anything.

Is there a way to render a menu and set the root to a specified location inside that menu programmatically?

Try the following:

$parameters->setRoot('menu_link_content:818bf040-f12a-4915-835f-b9339eb7c828');


Commerce - adding a product to a cart programmatically with custom price I've got a line item type called 'Donation' which has a Product reference field.

Additionally, I have an instance of a Product type called 'Donation' with the SKU of DONATION_ONEOFF (pid=1), which has a price field set to $0.

What I want to do is decide at form submit time what the value of the line item is before I add it to the cart.

I have a test form, that when submitted, runs the following

function jam_test_donation_form_submit($form, &$form_state) {
    global $user;

    // Load the product with SKU DONATION_ONEOFF
    $product = commerce_product_load(1);

    // Try and set the price of the product before passing it.
    $product->commerce_price['und'][0]['amount'] = 22;

    // Create the line item from the product.
    $line_item = commerce_product_line_item_new($product, 1, 0, array());

    // Add the line item to the cart.
    $line_item_added = commerce_cart_product_add($user->uid, $line_item);
}

I was hoping that the new value (22) would display in the Cart, but it's still at 0 - even though the $line_item and $line_item_added objects show the correct field values of 22 and even a calculated total if I add more.

I assume this could be because the cart is referencing the product node directly rather than using the value it was given at commerce_cart_product_add time - is there something I need to call to update this?

I could create a series of products at fixed amounts but I need the ability to specify an arbitrary amount for donation as well.

This is covered at length in a variety of other places. Your price is being lost due to the shopping cart refresh system and your avoidance of the core product pricing API.

You need a custom price field or something to store the price on the line item and then a pricing rule that swaps that custom price in for the unit price during the price calculation process.


Cascade entity reference in a content type I have two content types parts and maintenance.
Parts has 3 fields.

Oven type
Oven Part
Parts price

In maintenance i have a entity reference field with autocomplete that points to parts.
So now when a user types in a part the autocomplete show a list of possible matches.

The problem is that 2 different ovens can have the same parts but the price is different.
So I would like it to be a cascade so that a user can first select the oven and then select the part for this oven.

select the oventype

show the parts that fit this oven

It sounds like you want to try to use Reference Field Option Limit:

  Example 1:

  countries and cities Suppose you want to label articles (or
  products, or businesses, etc) by both city and country so both can be
  used for filtering and searching. You could use a hierarchical
  taxonomy with city terms as children of country terms, but that
  doesn't make sense when you come to set up Views filters.

  With this module, create two separate taxonomies for country and city
  (or content types, or whatever entity you want to use). Then add a
  reference field so that each city points to its country: eg, the term
  'Paris' has a reference to 'France'.

  Then when editing an article, selecting 'France' in the country field
  will cause the city field to update to show only cities in France.

How you denote the different parts based on their price. I dunno. But you can look at this module and if need use it as a starting point to extend or create javascript behaviors or alter sql queries it's using.


Views contextual filters for user term references I have two user roles that have term reference fields tied to profiles. One has a single select (user role A) and the other a multi select (user role B), but they reference the same taxonomy.

I have a view that lists all nodes of type C submitted by various users with a single user reference to user role A. My goal is to filter this to those with a user reference who has a term reference in common with a user of role B. The view is accessed by visiting user B's profile page and displayed as a block.

My thinking was to first add a relationship to the single select taxonomy term reference for role A. Then, add a contextual filter that loads the user id from the current URL and puts all the term IDs from the multiselect into the arg, for example 3+5+9. Finally, I would do custom PHP or Taxonomy term validation to see if user role A is in this list.

Setting the argument works fine. I can dsm this and see the correct TID. For validation, custom PHP doesn't seem to work at all. No rows are returned even when I simply do a "return true;" in there. For taxonomy term, I have it set to

Validator: Taxonomy term
My vocab is checked
Filter value type: term id
Action: no results found

Any idea what I'm doing wrong or the correct way to solve this problem?

EDIT: There was a problem with htaccess which explains why return true was failing. However, I still can't quite get the contextual filter and relationship logic down.

I can try this on a view, but I think the way to do it is to add the relationship, then add a Contextual filter of the Taxonomy Name. That works

with one Relationship to Contextual Filter, so why wouldn't it work with two.


How to sort View on rewritten field? I have a View with a table display format and all columns are set as being sortable. Although the issue isn't specific to Date fields; I am specifically trying to figure out an issue with Date fields.
I have 2 Date fields, one is primary and the other is secondary. I have tried various ways in adding the login for "if (pri) pri, else sec".

using no results option for pri date field
using twig in a custom text field

The results are:

sorts only on the base field; not the rewritten value
wsod when selecting to sort on this column

I have tried this both with db search as well as Search API - same results. I seem to be able, with Search API, to create an aggregated "First" field which seems to work; although the date format is not adjustable. I have also seen a patch which allows formatting of the base date fields; but my guess is that this will then give a string sorting of the aggregated field (i.e. Dec comes before June).
My next shot is to use the aggregated date field formatted as SOLR is giving by default and assume that is a valid date sort (I think it is, YYYY-MM-DD) and then do up a field formatter to display the correct date format.

I think the quick answer is "you can't sort on a rewritten value" in Views; regardless if it's a date field or using Search API.
There are however; various workarounds depending on the particular issue. I have used the following now:

use Computed Field to store the rewritten value in the db and then display/sort on that
SearchAPI is capable of doing simple rewrites with its Aggregated Field; this may work for simple rewrites.

You can often combine a computed field and a rewrite in Views to take advantage of Views field formatting. Keep in mind that the sorting occurs on the original db value for the field. So, for my example above, you could do a computed field to store the timestamp of the Date Range's end date; and then add that to the View but rewrite that field with the formatted end date. This will then sort on the timestamp; but display the properly formatted value.


Is there any Mega menu module? I am building a web site using drupal 8 and I want add a mega menu (3 columns menu with images) to the site.

Previously I have used TB Mega menu, but it does not support Drupal 8. Is there any mega menu module that supports Drupal 8, or is there a work-around which allows to install TB Mega menu on Drupal 8?

You can try the Ultimenu module. It has Drupal 8 version too and it's stable.

https://www.drupal.org/project/ultimenu

  Ultimenu is the UltimatelyDeadSimple™ megamenu ever with dynamic
  region creation.

  The module manages the toggle of Ultimenu blocks, regions, and a skins
  library, while leaving the management of block, menu and regions to
  Drupal.


Installing modules without FTP So I have installed the latest Drupal 7 stable on my new server, and it asks for an FTP user/password every time I try to install a new module from a .zip file. (Or using an URL).

The problem is that I don't have an FTP installed on the machine, and I don't really want to install one. I'm pretty sure this is related to some configuration/permission, but I'm not sure where to start. Tried searching around about the question, but only found "random" answers. Nothing clean and/or official.

It is a permissions issue...basically your web server needs permission to write to 'sites/all/modules' for Drupal to be able to get the new module folder there without using FTP.

However, it's a security risk to do this, so if your server is already configured in such a way that stops the apache/php daemons from writing to those folders you should keep it that way.

The better way to install modules automatically in Drupal is to use the Drush command line tool. You can issue a couple of commands:

drush dl views
drush en views

And the module will be automatically downloaded and installed on your site. Drush is infinitely more powerful than that (you can perform all sorts of administration tasks easily from the command line) so if you haven't come across it before I'd thoroughly recommend giving it a go.


Updating from core 8.7.9 to 8.8.0 I'm running into an issue when updating to Drupal core 8.8.0. I've removed both the vendor folder and the composer.lock file, as per instructions on this link
https://www.drupal.org/node/2700999#s-special-considerations-for-upgrading-to-drupal-880-and-later

I run composer require drupal/core-recommended:^8.8 --update-with-dependencies
and I get the following:

  Problem 1
    - Conclusion: don't install drupal/core 8.8.5
    - Conclusion: don't install drupal/core 8.8.4
    - Conclusion: don't install drupal/core 8.8.3
    - Conclusion: don't install drupal/core 8.8.2
    - Conclusion: don't install drupal/core 8.8.1
    - Conclusion: don't install drupal/core 8.8.0
    - Conclusion: don't install drupal/core 8.8.0-rc1
    - Conclusion: don't install drupal/core 8.9.0-beta2
    - Conclusion: don't install drupal/core 8.9.0-beta1
    - Conclusion: don't install drupal/core 8.8.0-beta1
    - Installation request for acquia/lightning 4.0.4 -> satisfiable by acquia/lightning[4.0.4].
    - Conclusion: don't install drupal/core 8.8.0-alpha1
    - Conclusion: don't install drupal/core 8.9.x-dev
    - acquia/lightning 4.0.4 requires drupal/claro ^1.0 -> satisfiable by drupal/claro[1.x-dev, 1.0.0-beta1, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1].
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.x-dev
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-beta1
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha5
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha4
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha3
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha2
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha1
    - Installation request for drupal/core ^8.8.0 -> satisfiable by drupal/core[8.8.0, 8.8.0-alpha1, 8.8.0-beta1, 8.8.0-rc1, 8.8.1, 8.8.2, 8.8.3, 8.8.4, 8.8.5, 8.8.x-dev, 8.9.0-beta1, 8.9.0-beta2, 8.9.x-dev].

At this point, running composer prohibits drupal/core:8.8.0 won't work because I removed drupal/core as per instructions in the link above.

I can successfully update to 8.7.13, so maybe I can settle for that for now. But our team wants to be ready for Drupal 9 and upgrading to 8.8 will make that transition easier, I hear.

Should I update to 8.7.13 first, before attempting to upgrade to 8.8?

EDIT
I'm able to update to Drupal 8.8 by removing the vendor folder and composer.lock and removing acquia/lightning. I reinstalled acquia/lightning after Drupal core was added.
I am now running into issues when running drush dbupdate.

In your composer.json file (found in the root of your drupal site) find the line "drupal/core": "x.xx" and change it to "drupal/core": "~8.8" and then run composer update drupal/core --with-dependencies

Also, don't forget to run your database updates after! (run drush updb or go to your-drupal-site.com/update.php)


How to theme webform's Custom Composite element? Is there any chance I can move specifics sub-element to Custom Composite? Either, I couldn't find any way how to use flexbox inside in a custom composite.

For example, I wish to have;

[First name] [Last name]
[Yes, I am coming or no, coming] [allergies list]

Rather than all in a row:

[First name] [Last name] [Yes, I am coming or no, coming] [allergies list]

Can I also use conditional logic in the custom composite element such as if people click "Yes, I am coming" means allergies list will be visible?

You can add classes like you do for any other element. The only difference is that in the case of custom composite elements, there are no fields for setting them directly. Instead, you can go to your respective nested element of Custom composite and set your classes like

'#attributes':
  class:
    - trip-departure-date

inside the custom property and theme accordingly. You can also use bootstrap class to change the layout.


How to link to a page view from a template file? If I were linking to a node via a template file I would write something like this...

<a href="<?php echo url('node/22'); ?>">Back to blog

I get that node ID by hovering over the node under 'Admin > Content' and looking at the node number that pops up when I hover over the 'edit' link in the bottom left (in Chrome). In the screenshot attached I've hovered over the 'edit' link alongside the node 'Head of Development' which shows node/5 in the bottom left.

The issue I've got is that I want to link back to a page view which doesn't show alongside all the other content. Thanks in advance.

I would recommend you to use l function to build links in Drupal.

  <?php print l(t('Back to blog'), 'node/22'); ?>

I see Content administration page on you screenshot. If you want to build link to this page you may use next piece of code

  <?php print l(t('Content'), 'admin/content'); ?>


How to implement Administration UI notifications for new revisions? I'm new to Drupal and I'm customizing an administration theme to be designed to our needs.

One of the things we would like to have is a visual notification of a new REVISION (content needing approval/revising/reverting, not already published). I've set this up via email, using Rules, but we need the visual indicator, like a red circle with the number of new revisions in it somewhere in the header.
Extending from that, when they click on the icon, then a page where they can administrate all the revisions needing their attention. The page would list all content types needing approval from an admin for publishing, where the admin can approve, go to the type to edit or revert to previous revision.

I thought I would have access to at least #1 via a module but cannot find something similar. Does anyone know of a module or modules that can fulfill the above requests? If the module was specifically written for something else, like notification of comments, I'm happy to rewrite it to fit - just anything that can me some time.

Eventually decided on using the Flag module for this since it seems less bulky than other workflow alternatives. It also allows us to use flags for other things as well and am quite happy with how easy it is to setup with Rules. I have to do code some of the display we want but it seems worth it. Thank you for your suggestions!


Drupal 7 - How add posfix '.html' to all paths? is it possible to add to all path system or node path postfix '.html'
for example

site.com/index -> site.com/index.html
site.com/user/login -> site.com/user/login.html
site.com/node/add/page -> site.com/node/add/page.html

pathauto

site.com/term-alias/hello-world -> site.com/term-alias/hello-world.html

and so on

Is it?

AFAIK, it is not possible to simply configure Drupal for that. If you serve your Drupal site with Apache, you can configure mod_rewrite to remove the .html suffix. But you will not be able to configure Drupal to add it to the links it produce.

In a custom module, you could implement hook_url_inbound_alter() and hook_url_outbound_alter() to remove/add to .html suffix to all paths.


How can you refer to content ID from underlying URL while adding a new node? In Drupal 7, I have a content type with an entity reference field. When adding new content of this type, an entity reference view filters the available options.

A contextual filter on this entity reference view should check whether the data matches against the node ID from URL being viewed while adding the new content.

I'm not sure whether I understand correctly how Drupal is supposed to work here, as everything I've tried gives no results, unless I manually enter test data in which case it works fine.

Let's say a user is on page site.com/?q=node/75, then adds content. The new URL is site.com/?q=node/75#overlay=%3Fq%3Dnode%252Fadd%252Fcontenttype.

The contextual filter is set for "When the filter is not available" to "Provide default value" of type "Content ID from URL". This returns zero results, even though I could manually provide the filter value and it would show the actual results.

Is this because the "Content ID from URL" is coming from the underlying (originating) URL instead of the overlay new content part of the path? Or is there some other issue?

How is it possible to filter contextually against the content ID of the original page from which a user adds new content? If it could be done by passing arguments to the contextual filter with a token from the entity reference field, that would be fine too, however so far I have tried with current page node and more and run into the same problem, it does not filter any of the appropriate results.

Thank you for your help!

It seems that the node in the original link is only for the source page, not for the page in question when Drupal determines which data to pass into the contextual filter. Instead, I wound up creating a new URL path pattern and filtering on the basis of that structure. Then I could add token-using links to various pages, with the contextual filter picking up the pattern of those paths.

You can find a full write-up at the Drupal forums:

https://www.drupal.org/node/2905210#comment-12238299

Thank you again for your help! :)


Manually populating fields using SQL queries I have created a new field on an existing content type. The field is called "Global News." It's a checkbox and I need it to be checked for all existing nodes. I ran a SQL query to gather all nodes of a specific type joined with the latest revision ID. Both the "field_data_field_global_news" and "field_revision_field_global_news" tables are populated with the correct fields but the checboxes remain unchecked. Is there another table I need to update so this field is linked to the correct nodes?

I tried editing one of the nodes manually, which worked, but the table entry remains the same which leads me to believe there is another table that needs populating.

Any ideas?

Drupal acts a bit differently,

1) Can you try cleaning your cache.

2) Write a function in a custom module

function _get_nodes() {
  $options = array();
  $sql = "SELECT nid, type FROM {node}";
  //adjust the query to filter on content types, if needed
  $result = db_query($sql);
  foreach ($result as $row) {
    $node=node_load($row->nid);
    //dpm(node); maybe you have different naming convengion
    $node->field_global_news['und'][0]['value']=1;
    node_save($node);
    unset($node);
  }
  return $options;
 }


How to hook into file upload and remove button I am implementing a module (in Drupal 7) that allows the user to upload or remove a file using the managed_file form type. I have looked at the form APIs and it states that info about the file should appear in ['values]['form_name'] but that is not what I see. To find any info about the uploaded file I need to look in ['input']['form_name'][0]. And when I do, the only values available are ['fid'] (which is always set to the file id) and ['UPLOAD'] (which is always NULL). The problem is that I don't know if the user wanted to add or remove the file. How do I determine this? What have I screwed up?

Here is my form:

$form_array = array(
  '#type' => 'managed_file',
  '#title' => t('File'),
  '#description' => 'The file associated with this submission',
  '#name' => 'obj_file',
  '#upload_location' => 'private://temp',
  '#default_value' => $submission->file,
);

Here is the submit portion:

if ($file_id == 0 && $submission->file) {
  $file = file_load($submission->file);
  file_delete($file);
} else {
  $file = file_load($file_id);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  file_usage_add($file, 'my_module', 'submission', $submission->id);
}

According to the API file id should be 0 if removed but it never is in my case. Is it possible to hook into file_managed_file_submit()? That would at least provide an avenue to see which button is being pressed.

Any help or insights would be appreciated!

The file managed_file field is used to upload files I am not sure if it can be used to delete a file from the server if that is what you are trying to do.

The process actually works as follows

When you click the upload button it uploads the file to the server and stored the fid to the field itself and this is the only value we need in the submit function to handle the file as we would using the file_load function to load the file and get the file object using the fid alone.

Now when the user clicks the remove button the field value is set to 0. But the actual file is not deleted from the server and the fid is still stored in the file table.

the '#default_value' should be set to variable_get('image_example_image_fid', ''), this would be used in our form submit function when the field is 0.

The documentation is talking about deleting the file from the temporary table and the server. You would need to remove it in your submit function.

Please check the example from the examples module

if ($form_state['values']['image_example_image_fid'] != 0) {
    // The new file's status is set to 0 or temporary and in order to ensure
    // that the file is not removed after 6 hours we need to change it's status
    // to 1. Save the ID of the uploaded image for later use.
    $file = file_load($form_state['values']['image_example_image_fid']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // When a module is managing a file, it must manage the usage count.
    // Here we increment the usage count with file_usage_add().
    file_usage_add($file, 'image_example', 'sample_image', 1);

    // Save the fid of the file so that the module can reference it later.
    variable_set('image_example_image_fid', $file->fid);
    drupal_set_message(t('The image @image_name was uploaded and saved with an ID of @fid and will be displayed using the style @style.', array('@image_name' => $file->filename, '@fid' => $file->fid, '@style' => $form_state['values']['image_example_style_name'])));
  }
  // If the file was removed we need to remove the module's reference to the
  // removed file's fid, and remove the file.
  elseif ($form_state['values']['image_example_image_fid'] == 0) {
    // Retrieve the old file's id.
    $fid = variable_get('image_example_image_fid', FALSE);
    $file = $fid ? file_load($fid) : FALSE;
    if ($file) {
      // When a module is managing a file, it must manage the usage count.
      // Here we decrement the usage count with file_usage_delete().
      file_usage_delete($file, 'image_example', 'sample_image', 1);

      // The file_delete() function takes a file object and checks to see if
      // the file is being used by any other modules. If it is the delete
      // operation is cancelled, otherwise the file is deleted.
      file_delete($file);
    }

    // Either way the module needs to update it's reference since even if the
    // file is in use by another module and not deleted we no longer want to
    // use it.
    variable_set('image_example_image_fid', FALSE);
    drupal_set_message(t('The image @image_name was removed.', array('@image_name' => $file->filename)));
  }


Upload External File to Drupal File System Situation

I would like to be able to upload files programmatically from an external source to the drupal file system. I was thinking of making a RESTful API that allows me to save external files into my site's public file path. The file is an excel file as well if that changes anything.
Problem

Currently, I am thinking of just using an S3 bucket to store the external files. Then within my site, I would simply run a GET REQUEST and programmatically save the file. I was just hoping there was a way to simply POST a file in drupal without me having to use Amazon's S3.
Parameters:

Drupal Version 8.8
Drupal Site BackEnd= PHP 7.3
External App FrontEnd = Vue.js
External App BackEnd = .NET Core
Required File Type: .xlxs
Secondary File Types: .csv, .docx, .json, .jpeg, .mp4, .txt

TL;DR

How can I make it so another site/app can upload files to my site? (using JavaScript)

Notice:
I understand StackOverflow is only meant for help with code issues but I would greatly appreciate some help getting started and if not at least some very useful links that are credible. Some of the research I have found is not useful seeing that I am on Drupal 8.8

Take a look at foldershare and foldershare_rest modules, they provide entire data management pipeline on a Drupal site, along with a ready to use rest client cum command line utility. Here are couple videos that show the module's capabilities

Managing data via REST client for automation and power users (5 mins)
Managing data on SeedMeLab for users(3mins)

Disclosure: I am the maintainer for these modules.


No more error messages shown, once i uploaded a file of invalid size? The scenario is as follow:
when i uploaded a file with invalid extension a proper error shown, everything is fine. nothing bad with invalid extensions.
where as:
when i uploaded a file of larger size (greater than limit) an error shown.
and if i tried second time with invalid file(i.e both for size and extensions) no error shown and file is also not uploaded.
i want to display errors in all tries with invalid files.
and i am using HTML5 Drag & Drop File module for uploading multiple files by browsing or drag and drop

any help please

The error about invalid extension which you're seeing is invoked by File module in modules/file/file.js, here is a snapshot:

/**
 * File upload utility functions.
 */
Drupal.file = Drupal.file || {
  /**
   * Client-side file input validation of file extensions.
   */
  validateExtension: function (event) {
    // Remove any previous errors.
    $('.file-upload-js-error').remove();

    // Add client side validation for the input[type=file].
    var extensionPattern = event.data.extensions.replace(/,\s*/g, '|');
    if (extensionPattern.length > 1 && this.value.length > 0) {
      var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi');
      if (!acceptableMatch.test(this.value)) {
        var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", {

Since it worked for the first time, but not on the second time, it's possible that you've some JS error which preventing this event to be invoked. If that's not the case, make sure file.js is included on the second time.

To debug that issue, you may create a breakpoint in above code to see if it's triggered properly. If it's not, using DevTools try enabling Event Listener Breakpoints for Control change/submit events, then try to reproduce the issue, so you'll know exactly what's happening.

Test also if you can reproduce the issue with File it-self using the default theme. If not, maybe it's worth to report a bug against that module.


How might I show only the first level of an Exposed Taxonomy Filter in Views? In Drupal 7, I have a exposed filter set at first in its hierarchical fashion

with the following structure:

Adjunct
-Adjunct Lecturer
-Adjunct Professor
Chairperson
Clinician
Container
-Director Advising & Student Affairs
-Managing Director TIC
Deans
-Associate Dean Undergraduate Advising Administration
Department Chair
Emeritus
-Associate Professor Emeritus
-Professor Emeritus
Lecturer
-Senior Lecturer
Professor
-Assistant Professor
-Assistant Professor in Residence
-Associate Professor
-Associate Professor in Residence
-Research Scientist & Professor
Speech Pathologist
Visiting
-Visiting Assistant Professor
-Visiting Associate Professor

In the exposed filter, is there a way to expose only the parent (first level) items (Adjunct, Deans, Department Chair, etc)?

Update: Grouping the exposed filter in views did not work (ticket).

Add " Taxonomy: Term ID (with depth)" and set the depth to "1" it will show the first level of terms.

For Drupal 6:

Views Taxonomy: limit exposed dropdown by term depth module provides enhanced functionality for the exposed dropdown filter for taxonomy terms in Views.

  Exposed term filters can already be limited to display only terms
  selected in the Views interface. But what if content creators add new
  taxonomy terms? They will have to navigate the Views interface and add
  these new terms to the list of terms shown by exposed filters.


Content Moderation: Editorial workflow not installed and broken/missing handler on the moderated content view I'm having troubles enabling Content Moderation Module (content_moderation) on a Drupal 8.7.8 site.

During installation everything seems fine, drush en content_moderation finishes without errors, workflows module is already enabled before.

After install the editorial workflow is missing, but it's possible to create a new content moderation workflow.

All role permissions are available and the Moderation State widget shows up on nodes of the selected types. But using the widget has no effect, nodes don't get published or unpublished.

The database tables for Content Moderation are created properly (ie. content_moderation_state and three more with similar names).

Also the view moderated_content shows "Broken/missing handler" where the filter criteria "Content revision: Moderation state (exposed)" and "Content revision: Moderation state (<> Published)" are supposed to be.

Clicking the Broken/missing handler fields shows some details for the two broken handlers:

The handler for this item is broken or missing. The following details are available:
id: moderation_state_1
table: node_field_revision
field: moderation_state
relationship: none
group_type: group
admin_label:
operator: not in
group: 1
exposed:
is_grouped:
entity_type: node
plugin_id: moderation_state_filter
Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.

Second field shows this info:

id: moderation_state
table: node_field_revision
field: moderation_state
relationship: none
group_type: group
admin_label:
operator: in
group: 1
exposed: 1
is_grouped:
entity_type: node
plugin_id: moderation_state_filter

I also can't add any moderation state related fields to the view like "Moderation state". The fields do not show up in the "Add fields" dialog.

I'm having no problems setting up Content Moderation on a vanilla Drupal 8.7.8  it just fails on this existing site (same version).

I already tried reverting the site and reinstalling workflows and content_moderation on different ways, with drush and manually. I uninstalled all custom modules and patches and reinstalled content_moderation.

Are there any modules (except workbench) or settings known to cause problems with Content Moderation?

Any ideas what could be causing the problem or where to start looking?

Thanks a lot!

The guys over at Drupal's Slack channel pointed me in the right direction. I added detailed troubleshooting infos to the Content Moderation Guide.

If you enable Content Moderation (drush en content_moderation) on a site, that was not installed using Drupal's Standard Profile as a base, you will run into some problems which require a few manual steps before you can use Content Moderation, as detailed in the guide.

Fix missing Editorial workflow

If the Editorial workflow was not created when enabling Content Moderation, you can either manually create a new workflow and assign a content type, that's used with your new workflow or import the Editorial workflow manually.

The template for the Editorial Workflow is:

langcode: en
status: true
dependencies:
  module:
    - content_moderation
id: editorial
label: Editorial
type: content_moderation
type_settings:
  states:
    archived:
      label: Archived
      weight: 5
      published: false
      default_revision: true
    draft:
      label: Draft
      published: false
      default_revision: false
      weight: -5
    published:
      label: Published
      published: true
      default_revision: true
      weight: 0
  transitions:
    archive:
      label: Archive
      from:
        - published
      to: archived
      weight: 2
    archived_draft:
      label: 'Restore to Draft'
      from:
        - archived
      to: draft
      weight: 3
    archived_published:
      label: Restore
      from:
        - archived
      to: published
      weight: 4
    create_new_draft:
      label: 'Create New Draft'
      to: draft
      weight: 0
      from:
        - draft
        - published
    publish:
      label: Publish
      to: published
      weight: 1
      from:
        - draft
        - published
  entity_types:
    node: null
  default_moderation_state: draft

Copy the template to some yml file and import it using drush config:import --partial.

Fix Broken/missing handler on the Moderated Content view

This error occurs, if there exists no moderation workflow that is assigned to a content type. Wether you just imported the Editorial workflow as described above or created a custom moderation workflow, you'll have to make sure it has at least one content-type assigned to it. Just edit your moderation workflow, scroll to the bottom of the page and select at least one content type that is used with this workflow. After you save your changes, the "Broken/missing handler" on the Moderated Content will be gone and the view at /admin/content/moderated will work as expected.


SQL Error on main forum list page I've just activated the Forum module and installed Advanced Forum. My 3 forums and 2 containers work when I browse straight to the forums and containers. The main list doesn't work though. When I go to /forum I get a SQL Error

  General Error
  SQL ERROR [ mysqli ]

  Access denied for user 'username'@'hostname.com' (using password: YES) [1045]

  An sql error occurred while fetching this page. Please contact an administrator if this problem persists.

Isn't the main forum page supposed to list all the containers and forums like this http://drupal.org/forum? Do I have to enable anything or make a main container to make it do that?

The error message is saying that the user you set in your settings.php file doesn't have access to the database, which could happen because the password you wrote in that file is not the correct one.

Any Drupal module that accesses the database is using the database API, which doesn't require any username or password, as those are taken from a file that Drupal reads during its bootstrap.
The Forum and the Advanced forum modules are not an exception. If you are getting that error, it means there is an error with the settings.php file, or a problem with the database server.


How to track errors in view I write some PHP code in my views, i.e. in contextual filters and the PHP area of view, but when something goes wrong, it becomes very difficult to find errors as line numbers thrown in error does not holds good.

Which way can I trace it ,or is it not advisable to write PHP code in views directly?

Views is created in a very object oriented way, which is really great. What this means is that if the default Views behavior doesn't work for you, you can extend the classes that Views supply and alter only what you need to overwrite. I wrote a blog post about this focusing on filters, but the principle is the same for contexts, sorting ...

In views lingo a context is called an argument.


View Content inside of User edit form I created a view content about active classes and now I want to show them inside of user edit form to that they can see their clasess active with a contextual fiter url at view content, how can I make that? please help

You need to pass a contextual filter in the view of User ID, and pass the User ID from url as the value. It doesn't matter if this path is aliased, as it will look at the system path (user/uid) to get the value.

Then, the view will filter content based on relationship to that user id.

Without much more information, that is all I can give you to go on. But if it is a basic setup, that should work.

See: https://www.drupal.org/node/1578564

Then to show it on the form, it depends on what or where you want it.

One way would be to create a Block display of your View, and place it in a region on the block admin page. Be sure to set the visibility to authenticated roles, and the path to 'user/*/edit' so it only shows for users on the user edit form.

Another way, if you want to code it, would be embedding the output into the form with views_embed_view inside of a hook_form_alter for the user edit form. There are some examples on that doc page on how to use it.

Example:

$form['classes'] = [
  '#markup' => views_embed_view('your_view', 'block_display_id', $user_id);
]

Where $user_id is the user viewing the form.


Archiving forums on time basis in drupal 7 I am using advance forum on drupal 7. I want to add following functionality to it:

Archiving:

I could define forum posts older than 6 months or so should be automatically be archived and visible only to admin.

Any module or pointers to achieve same highly appreciated.

You could use the Rules module.

Create a rule to set the node status to "unpublished" when the node is older than 6 months and make it execute every time the cron runs.

Also, make sure you allow only the admin to see the unpublished content


how can I restore my site I mistakedly erased a site from a server with ftp last night. Now luckily, I had a backup from not too long ago. I copied all the files from my back up directory back into my site using filezilla (I backed the site up using wget). Now when I go to my site, I gert an error like

  Fatal error: require_once() [function.require]: Failed opening
  required 'includes/ckeditor.user.inc'
  (include_path='.:/usr/local/php5/lib/php') in
  /home/content/q/u/a/quaa7882/html/sites/all/modules/ckeditor/ckeditor.module
  on line 48

This error first appeared on my apps module. So I copied to apps directory out of the sites/all/modules directory but then, the same error appears again for the next module alphabetically so I assume it would appear for every single module. I tried to run update.php but I get a Server error in Chrome, it tells me:

  The website encountered an error while retrieving
  http://quaaoutlodge.com/update.php. It may be down for maintenance or
  configured incorrectly.

I'm wondering what might be going on here and how I can retore the site...?

Thank you!

EDIt1

The files in my backup directory are:

-rw-rw-r-- 1 ron ron 20581 Aug 24  2013 CHANGELOG.txt
-rw-rw-r-- 1 ron ron  2616 Aug 24  2013 ckeditor.api.php
-rw-rw-r-- 1 ron ron  3867 Aug 24  2013 ckeditor.config.js
-rw-rw-r-- 1 ron ron  3395 Aug 24  2013 ckeditor.css
-rw-rw-r-- 1 ron ron   354 Aug 24  2013 ckeditor.info
-rw-rw-r-- 1 ron ron 21467 Aug 24  2013 ckeditor.install
-rw-rw-r-- 1 ron ron 26478 Aug 24  2013 ckeditor.module
-rw-rw-r-- 1 ron ron   519 Aug 24  2013 ckeditor-rtl.css
-rw-rw-r-- 1 ron ron  3749 Aug 24  2013 ckeditor.styles.js
-rw-rw-r-- 1 ron ron 18092 Aug 24  2013 LICENSE.txt
-rw-rw-r-- 1 ron ron 21347 Aug 24  2013 README.txt
-rw-rw-r-- 1 ron ron 10521 Aug 24  2013 TROUBLESHOOTING.txt
-rw-rw-r-- 1 ron ron  1547 Aug 24  2013 UPGRADE.txt

EDIT2

I actually found my ckeditor.user.inc now, it was under sites/all/libraries/includes/ckeditor.user.inc instead and this is also where it is on my ftp. It's got a 175 lines of code and I didn't necessarily want to post the complete file unless required. What should I be looking out for?

Your backup is incomplete. Talk with your hosting company. In the meantime you can try to download fresh copy of ckeditor module, but even if it'll help, you will never know for sure what else is missing.


How do I include JavaScript with assets (libraries.yml)? This is my mytheme.libraries.yml file:

global-styling:
  css:
    theme:
      css/style.css: {}

  js:
      js/effect.js: {}
    dependencies:
    - core/jquery

This is my js/effect.js file:

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
      alert("Hello World");
  }
};
})(jQuery);

I created jquery.js in core folder of my site root.
Even if I remove the  dependency line from my libraries.yml and remove jquery syntax from my effect.js, I receive nothing on my site.

Most times it's about blanks. The yml files are very picky about this. Looks like your effects.js has 6 blanks instead of four.

And make sure, that you have your global-styling listed in the libraries section of your theme.info.yml.


Get Field Collection values not IDs I am searching for a solution for past few days but can't find it :(

I have exposed a node with rest api views and there's a couple of field collections inside my node which i want to access over API but the api is retuning field collection IDs not the actual data. How can i get the values of field collection without sending aother request to api for values?

"field_custom_data": {

"und": [

 {
   "value": "3",
   "revision_id": "3"
 },
 {
   "value": "4",
   "revision_id": "4"
 },
 {
   "value": "5",
   "revision_id": "5"
 },
 {
   "value": "6",
   "revision_id": "6"
 },
 {
   "value": "7",
   "revision_id": "7"
 },
 {
   "value": "8",
   "revision_id": "8"
 }
] },

Before returning response to api you should load field collection using field collection ID, then you can get fields value of field collection.

entity_load('field_collection_item', array($item_id))

Source: How to load field collection


Limit entity reference field formatter to certain entity types I've created an entity reference field formatter. It works fine. However, the field formatter will only work properly on entities of type user, so if the referenced entity type is different, I don't want the formatter to appear in the list of options.

I tried adding entity_types = { user } to my annotation for the formatter, but this didn't work. I'm suspecting it cannot even be done, but I thought I'd ask here before opening up an issue in core, to suggest it for future development.

Does anyone know if this can be done, and if it can, how?

I think this will work...

There is an isApplicable() method in Drupal\Core\Field\FormatterBase. You can implement it in your FieldFormatter class like this:

public static function isApplicable(FieldDefinitionInterface $field_definition) {
  return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'user');
}


How to trim text fields entered in the node automatically Just now i've discovered that my operator was entering many times organization name prefixed/suffixed with a space. For example " Microsoft" or "Microsoft  ".

That is causing problem when this value is being passed as contextual arguments in the views with this space character making a difference.

I need help as to how I can trim already fed in text and secondly store only trimmed version of text.

I could only find this useful page about this issue.

To correct all those values entered into the database already, I'd suggest doing a mysql trim on those values and resetting them. Make sure you backup the tables first of course, but something like this should do it (if your field name is field_text_test):

UPDATE field_data_field_text_test SET field_text_test_value = TRIM(field_text_test_value);
UPDATE field_revision_field_text_test SET field_text_test_value = TRIM(field_text_test_value);

After you've run those statements, do a flush all caches on your drupal site.

And then to avoid this happening again, you could use the Form API Validation module which adds a trim filter on fields.


All taxonomy term paths default to the www.example.com root directory After creating a new vocabulary and adding terms to it, clicking on the view tab of the term edit form sends me back to my root directory. And, of course, typing the term path in the url results in a page not found error message. What is going on?
Strangely enough, not too long ago, I created a vocabulary and it still works well (clicking on the view tab takes me to the term page view.) However, older vocabularies no longer work when hey used to.
Does anyone know what is going on?
Any help on this one would be greatly appreciated.
Thanks. :)

If you have pathauto module installed, you might want to check the taxonomies aliases go to "/admin/config/search/path/patterns" and look for the old Vocabularies and see how the path is setup. moreover you might want to delete all aliases and do a bulk update for theme "/admin/config/search/path/delete_bulk" then "/admin/config/search/path/update_bulk".


How to display number of posts in author pane? I have installed Advanced Forum and Author Pane modules.

Now I want to show user's post count instead of 'Last seen':

  Last seen: 2 weeks 6 hours ago

I could not see any guide in the docs so appreciate your help.

it appears you need another module that will feed this info to author pane. This module is User stats.

Apparently though User stats has only a development release for D7 and reading through this issue, I would be reluctant to implement it on a production site. Will keep you updated if I find a better way to deal with this.

Edit: I've tested the 'post count' functionality of the 7.x-1.x-dev version of User stats and it seems to be working fine.


Content Region Not Displaying I'm relatively new to Drupal and am just squashing bugs on my first site.

I have a region that I declared in my theme.info file:

regions[alert] = 'Sitewide Alert'

and I have a block that has a custom template block--alert.tpl.php with some custom fields. Everything works great when I have my Sitewide Alert block assigned to my Alert region. But when I disable my Sitewide Alert block, no content renders in my content region. If I enable the Sitewide Alert block, or any other block in the sitewide alert region, all my content comes back.

Using the themer module, I can see that all the same variables are still available on the page, but it's like none of my templates are being called or something. Can anyone help me troubleshoot this or point me to some resources?

UPDATE:

I forgot that I was preprocessing my custom block. This is where my issue was. Within my theme_preprocess_block function, I was running the following code:

// Sets the character limit for the Custom Block
if ($vars['id'] == '2') {
    $vars['content'] = truncate_utf8($vars['content'], 170, TRUE, FALSE);
}

What I found out is that the $vars['id'] changes depending on what blocks are called on the page. When my custom block was active, it's id was 2, but when it was inactive, my content block had the id of 2 and so was being truncated.

I changed this to:

// Sets the character limit for the Custom Block
if ($vars['theme_hook_suggestions'][0] == 'block__alert') {
    $vars['content'] = truncate_utf8($vars['content'], 170, TRUE, FALSE);
}

If anyone has a better way of selecting a block to preprocess I'd love to see it.

Well, just off the bat I haven't seen anyone use single quotes on the human-readable name. For instance, I'd change it to:

regions[alert] = Sitewide Alert

You might have a PHP if statement in your page.tpl.php somehow affecting your content region. I'd double-check the template file and see how it matches up with the default Bartik page.tpl.php


How Generate Configure button ? (Module Page) What hook or how do I generate the configure button in the module page?

I'm trying to have the operation button that user click on the module page to take them to the configuration page.

If someone can provide me good resource or an example I will appreciated.

Here is an example of what I'm trying to generated.

test.info file

    name = configure test
    description = configure test.
    core = 7.x
    ; NEW LINE
    configure = admin/config/test

test.module file

<?php
/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();
  $items['admin/config/test'] = array(
    'title' => 'Test',
    'description' => 'Configuration for test module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
?>


Use hook to remove height from img tag? The theme I am building is responsive and so many images have max-width:100%; applied in CSS. Can I use a hook in template.php to strip the height attribute from img tags because it is causing lots of distortion issues, and how would I go about this?

Thanks for your time!

Assuming that your images are being built by theme('image',...) you can override its default...

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

}

...in your template.php file along the lines of this:

function YOURTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';

}

and now those pesky height=s and width=s should be gone.


Remove trailing whitespace from a field Here is a slice of code from my twig template, which outputs the contents of some fields into a p tag:

<p>
    {{ content.field_story_program_name }},
    {{ content.field_story_relationship}},
    {{ content.field_story_city }},
    {{ content.field_story_state }}
</p>

The output on the page renders a trailing white space after each field's content, which I don't want (because it creates spaces before the commas):

  Local Head Start Program Provider , Head Start administrator , Los Angeles , CA

Things I've tried:

Based on this post, I checked my field.html.twig template to see if it's introducing spaces (it's not).
Tried putting a - in the {% endfor %} on that field.html.twig template anyway to see if it would help: {% endfor -%} (it didn't).
Put all of my values on one line in case a carriage return was being interpreted as whitespace (I think that was a Drupal 7 issue that I read) as in:
{{ content.field_story_first_name }} {{ content.field_story_last_name }}, {{ content.field_story_program_name }}, ...etc
But that didn't fix it
Tried {% spaceless %} though I know it's just for spaces between tags and so of course that didn't end up helping
Using the |trim Twig filter, which makes the entire value disappear and produces a rendering error. I suppose that technically solves the whitespace problem...  ;)

Can anyone help give me a clue? I would like to either

Find out where the extra space is coming from and turn it off there, or
Use the appropriate Twig filter to remove the space

Okay, here is what finally worked: wrap every individual field in {% spaceless %} (not just the whole block) and use render and trim together.  Trim alone makes the variable disappear. Here's my markup:

<p>
  {% spaceless %}{{ content.field_story_program_name|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_relationship|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_city|render|trim }}{% endspaceless %},
  {{ content.field_story_state }}
</p>

Extra thanks to @Cyclonecode for giving me a variety of tricks to try.


Only the word "array" gets printed when I try to render custom block in template I am building a custom block in a module, like this:

<?php

function filterblock_block_info() {
  // Sökfilter till temperaturöversikten.
  $blocks = array();

  $blocks['filterblock-temperatur'] = array(
    'info' => t('Temperatursökfilter'),
  );

  return $blocks;
}

function filterblock_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'filterblock-temperatur':
      $block['subject'] = t('');
      $block['content'] = filterblock_block_content();
      break;
  }
  return $block;
}

function filterblock_block_content(){
    return drupal_get_form('temperaturfilter');
}

function temperaturfilter($form, &$form_state)
{
    $form = array();

    $form['alla'] = array(
        '#type'         => 'textfield',
        '#title'        => t("Alla"),
        '#weight'       => 10,
        '#required'     => false,
    );
    $form['IR'] = array(
        '#type'         => 'textfield',
        '#title'        => t("IR"),
        '#weight'       => 11,
        '#required'     => false,
    );

    $form['hightemp'] = array(
        '#type'         => 'textfield',
        '#title'        => t("> +500 °C"),
        '#weight'       => 12,
        '#required'     => false,
    );
    $form['lowtemp'] = array(
        '#type'         => 'textfield',
        '#title'        => t("< -50 °C"),
        '#weight'       => 13,
        '#required'     => false,
    );

    return $form;
}

In my template file I have this:

   <?php $block = module_invoke('filterblock', 'block_view', 'filterblock-temperatur'); ?>
   <?php  if ($block['content']) {
     $output = "
\n";
     $output .= "
".$block['content']."
\n";
     $output .= "
\n";
     print $output;

But the only thing that is rendered on the page is the word "array". I have checked with var_dump in the block module that $block['content'] actually contains the fields from the function temperaturfilter. I have tried to use print render($output) in stead of just print, but with no luck.

What am I doing wrong?

You haven’t rendered the render array:

$output .= "
".render($block['content'])."
\n";


Variable passed into a preprocess function has incorrect data or or an unexpected format I wanted to change some of the forum’s topic's preprocessing. So I copied template_preprocess_forums() into a custom module (myModule), and renamed the function myModule_preprocess_forums().

I get an error that a method cannot be used on a string, $topic. I inspected. When the code is looping through the array $variables['topics'], it expects each array item to be an object.  However, in $variables['topics'] there are items that are strings and arrays and no topic objects.

To debug, I inspected $variables['topics'] in the Forums module, but all the  items are objects, as expected.

Why would the values passed to myModule_preprocess_forums() differ from what template_preprocess_forums() implemented by the Forums module gets?

It happens because template_preprocess_forums(), which is executed before any hook_preprocess_forums() implementation, overrides $variables['topics'] with the render array for its table.

It would have been better to put the render array in a different array value. As you notice from the function code, starting from Drupal 8.6.x, the original value of $variables['topics'] is available in $variables['topics_original'].

  $variables['topics_original'] = $variables['topics'];
  $variables['topics'] = $table;
  $variables['topics_pager'] = [
    '#type' => 'pager',
  ];


Simplenews newsletter unsubscribe page- Access denied I am using Simplenews newsletter module on my Drupal-7 website to send newsletters, but when you click on the unsuscribe link, the user gets an access denied page-you need an account to view this page etc.
Where can I make this page visible to all users or/and change what this page says?
 For example, instead of Access denied to show an image or say "Error" or something else.

The access arguments for that page are subscribe to newsletters, meaning that you need to grant that permission to anonymous users, in order to allow them to unsubscribe without logging in.

Here's how to do that:

Navigate to /admin/people/permissions.
Find "subscribe to newsletters" item.
Grant the permission to anonymous users.

Note: I just told you how to allow to do it for everyone. You need to evaluate if this fits your website and workflows.


Field collection fields are empty in edit mode Problem

My content type has several fields and one of them is a field collection.
Currently I have following issue:
After adding and saving content everything is displayed fine.
When editing, the contents of the field collection are all empty, but are saved in the database.
After adding the same contents in the empty field collection and saving, when editing again the values are displayed.

So I do really not understand why this append, maybe someone can help me understand it and fix the bug.

P.S.: Please forgive my English (still learning).

I've experienced this a while ago with field collections and paragraphs but can't remember the exact cause.  Suggestions for troubleshooting:

Check to make sure there's no updates available for the field collection module, Drupal Core, or any other modules that may be impacting the types of fields you're trying to assign in your field collection.
If your field collection involves an entity reference to either:

another node and allows creation of said node within the edit form, make sure to click save on the embedded node creation form before saving the overarching node.
a file upload, make sure to upload the file before clicking save on the overarching node.

If this still doesn't work, try creating the field collection from scratch, adding one field at a time to determine which one is causing the issue.


exposed filter dropdown by year I am looking for a way to produce a dropdown filter by year of drupal 'post date'. i was able to produce somewhat of this result with an exposed criteria but that requires updating.

Is there a way i can just make the sort criteria exposed with dropdown of years?

this is what i have so far

if ($form_id == 'views_exposed_form_clone_of_post_by_date_block'){
  $year_filter = array();
  $years = array();
  $counter = 0;
  for ($i=date("Y");$i>=2009;$i--){
    $counter++;
    $years[$counter]=$i;
    $dstart = $i."0101";
    $dend = $i."1231";
    $year_filter[$counter] = array('title'=>$i,'operator'=>'between','value'=>array('type'=>'date','value'=>$i,'min'=>$dstart,'max'=>$dend));
    $form_state['input']['edit_created']['#options'] = $years;
  }

How to produce a dropdown filter by year of post date isn't as immediately obvious as you might think - but it doesn't need any custom code when using Drupal 7 with views.

Within your view add a new filter. You might think you need to choose 'Content: Post date' but this will not give you the options you need. You should actually choose 'Date: Date (node)'. For data selection form element choose 'select' to create your dropdown. Set Filter granularity to 'year'. Give a starting year e.g. '-10 years from now' and an ending year e.g. '+ 0 years from now'. Then in 'date fields' you select where the date(s) are drawn from, it is here that you choose the 'content: post date'.

It is worth noting that other date fields are exposed here, so you are not limited to the post date.


Shipping address, rates selection asked even if there's no physical products We have made a Drupal 7 website with Commerce module. The website has a combination of physical and non-physical products.

The shop has a small problem (or potentially big), in that it asks for shipping address and shipping rates (flat rate) from the shopper even if they only buy non-physical products.

We have used the Physical Product module and Physical Fields module to accomplish the physical product functionality.

I found a similar question, regarding a different (older) commerce version (7.x-1.0), but this question had no accepted answer, so I decided to ask my own question for my relative version of Commerce (7.x-1.3).

Any help, pointers on where to look/investigate this problem, or even a confirmation whether the single answer posted on the similar question is the right way to go about accomplishing this would be greatly appreciated.

If you need any more information from me, please ask.

Ok I just found a Rules rule with machine name commerce_shipping_method_flat_rate. So I added a condition to this rule "The order contains shippable products". I also unchecked the tickbox labelled "Require a shipping service at all times, preventing checkout if none are available." in Store-> Configuration-> Checkout Settings, and Shipping Service pane config.

This seemed to have done the job. However I had the Shipping Service pane in the "Shipping" part of the Checkout process, so now if you're buying non shippable products, you enter your details in the first page, then go to the Shipping page it displays a blank form with a Continue or Go back buttons to proceed to the Review page.

Is there a way to go straight to the Review page if there's no shippable products?

I've been able to sort this out by adding the condition "Commerce order contains shippable products" supplied by the physical product module to the existing shipping rules, and also added a new shipping flat rate service called "No Payment". And this new flat rate shipping service is £0.00 amount and checks for condition "NOT Commerce order contains shippable products" (Negated, hence the "NOT").

I also unchecked the tickbox labelled "Require a shipping service at all times, preventing checkout if none are available." in Store-> Configuration-> Checkout Settings, and Shipping Service pane config.


Programmatically set a datetime field I already asked a question like this (Set date field in D8).

Ok duplicate entry? NO!

Now i have also to set a time and i'm using a array.
My code looks like this.

$field_array = [
##begin of creating node
'uid' => $new_old_uid["new_uid"],
'type' => $content_type,
'langcode' => $lang,
'status' => (!empty($import_node->status)) ? $import_node->status : 0,

#### How to create date with times?
#Every Version causes that error -> Array to string conversion in ....
### Version 1
'field_event_date_start' => [[ "value"=> date('Y-m-d H:i:00',$imported_date) ]],
'field_event_date_end' => [[ "value"=> date('Y-m-d H:i:00',$imported_date) ]],
### Version 2
'field_event_date_start' => [ "value"=> date('Y-m-d H:i:00',$imported_date) ],
'field_event_date_end' => [ "value"=> date('Y-m-d H:i:00',$imported_date) ],

### How to add a url?
'field_event_url' => (!empty($import_node->field_event_url)) ? array('value'=> $imported_url) : null,
];

UPDATE:
Another try for datetime field:

'field_event_date_start' => array(
    "value" => array(
        "date" => date('Y-m-d',$imported_date),
        "time" => date('H:i:00',$imported_date)
    ),
),

Now I'm getting following error:
Placeholders must have a trailing [] if they are to be expanded with an array of values.

Datetime fields in Drupal 8 are stored as strings. So you need to convert it into string.

You can use the format method, e.g.

$formatted_date = $date->format('Y-m-d H:i:s');

Refer Inserting the value from Datetime field form

You can also use T as separator,

Like:

\DateTime::format("Y-m-d\TH:i:s"); //need a escape character in front of T.

Refer Why is my Datetime field not saved?


Menu unserialized warning when using autocomplete in a custom module I am working on creating a form with Autocomplete feature for the text field. This is the code I have so far..

    /**
     * Implementation of hook_menu()
     */
    function suggest_feature_menu() {
      $item['suggest_feature/autocomplete'] = array(
        'page callback' => '_suggest_feature_autocomplete',
        'access arguments' => user_access('access example autocomplete'),
        'type' => MENU_CALLBACK
        );

        return $item;
      }

    /**
     * Implementation of autocomplete
     */

 function suggest_feature_autocomplete($string){

    $query = db_select('node', 'n')
    ->fields('n', array('nid', 'title'))
    ->condition('status', 1) //Published.
    ->condition('type', array('e_hood', 'oranization'))
    ->condition('n.title','%'.db_like($string) . '%', 'LIKE')
    ->orderBy('created', 'DESC') //Most recent first.
    ->range(0,10)
    ->execute();

    $items = array();

    foreach ($query as $node){
       $items[$node->nid] = check_plain($node->title);
    }

    return drupal_json_output($items);

  }

    /**
     * Implementation of hook_form()
     */

    function suggest_feature_form($form_state) {
     $form = array();

       $form['test_item'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'suggest_feature/autocomplete'
        );

      return $form;
    }

all my functionality works but i get a warning which says

  Warning: Invalid argument supplied for foreach() in menu_unserialize()
  (line 393 of C:\xampp\htdocs\drupal7\includes\menu.inc).

Please let me know how to solve this. Is this an issue with my code ? Also I use superfish menu's in my drupal. Is this related ?

There are three functions calling menu_unserialize(), the function for which the error is reported:

menu_get_item() uses it in the following code

  if ($router_item['access']) {
    $router_item['map'] = $map;
    $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
    $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  }

_menu_check_access() uses it in the following code

$arguments = menu_unserialize($item['access_arguments'], $map);

_menu_item_localize() uses it in the following code

$item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));

The Invalid argument supplied for foreach() error simply means that foreach() is getting a value that is not an array. With the code you are showing, that is happening only for $arguments = menu_unserialize($item['access_arguments'], $map); since you are setting $item['suggest_feature/autocomplete']['access arguments'] to TRUE when it should be an array.

In your case, the code should be the following one.

/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

For Drupal that code would be equivalent to the following one.

/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

You can understand now why your code is wrong.

It's not the access arguments that you can set to a boolean value, but the access callback. See what the documentation for hook_menu() says. (Emphasis is mine.)

  "access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).

And for the access arguments, it says:

  "access arguments": An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.


Unban repeated attempts via command or mysql? Natively, in Drupal 7 after repeated unsuccessful attempts a particular user would be banned after repeated offending logins.

Is it possible to programmatically unban a particular user? I heard if you truncate the flood table you can be unbanned. Is this true?

Yes, it is true, but it is also excessive.

That table is also used for users sending emails with the contact form. Rather than truncating that table, it is better to remove only the necessary entries.
user_login_final_validate() contains the following code.

  if (empty($form_state['uid'])) {
    // Always register an IP-based failed login event.
    flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
    // Register a per-user failed login event.
    if (isset($form_state['flood_control_user_identifier'])) {
      flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
    }

Just remove any row in the "flood" table where the "event" field is equal to "failed_login_attempt_ip" or "failed_login_attempt_user"; in that way, any login ban is removed.
This would remove the login ban for every user, including the ones who are trying to access somebody else's account by brute force. Unfortunately, without to know the IP of the user to unblock, it is not possible to unblock just a specific user: The login validation callbacks first check if the user is login banned basing on the IP, then basing on the user ID for the account used to login.


Get the latitude and longitude from the user ip I am trying to get the latitude and longitude from the user who connected to my website to draw or show his position on a map, but it showed him in the wrong postion. Is there any way to get the accurate latitude and longitude?

    <?php drupal_add_js('http://maps.google.com/maps/api/js?sensor=true'); ?>
     `
    <?php

     echo "

";
?>

Converting an IP to a latitude and longitude isn't a good idea since the user could be using a proxy. A better way would be to use HTML5 geolocation, which tries to get a location based on a couple of parameters: IP, wireless connection, cell tower location, GPS ...

Try:

navigator.geolocation.getCurrentPosition(show_map);

function show_map(position) {
  initialize(position.coords.latitude, position.coords.longitude, 'title');
}

More info on HTML5 geolocation here, make sure you have a fallback in case the browser doesn't support geolocation or the user declines your request to share his/her location (graceful degradation).


how to prevent warnings from displaying to anonymous users As in subject: how to prevent warnings from displaying to anonymous users? They contain paths etc. Even better, how to display warnings only to priviledged users?

First you should turn down the error_reporting options on your production server. This will erase most of PHP's warnings and notifications.

Also you can configure drupal to only log the errors. To do that go to Administration > Configuration > Development > Logging and errors or directly to the path /admin/config/development/logging and set "Error messages to display" to none. Drupal then still logs errors but doesn't display them to users.

If you still need finer control over messages surely the module disable_messages can help you.


How do I use Font Awesome on a form submission button? So I've got Font Awesome working on my Drupal 7 site. I'm not using the Font Awesome Drupal module. I'm just declaring the style sheet in the template.php.

function genchstyle_preprocess_html(&$variables) {
  drupal_add_css(
    'http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css',
    array('type' => 'external')
  );
}

Now, if I use <i class="icon-search"></i>, I get a nice little magnifying glass icon.

I've recently learned how to replace a form's Submit button with an image like this.

function genchstyle_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['submit']['#type'] = 'image_button';
    $form['actions']['submit']['#src'] = drupal_get_path('theme', 'genchstyle') . 'images/search.png';
    $form['actions']['submit']['#attributes']['class'][] = 'icon-search';
  }
}

I can't figure out how to replace the submit button with the Font Awesome icon. I tried adapting the above script to use $form['actions']['submit']['#markup'] and I can get it to replace the button with the icon, but then the icon is no longer a functioning submission trigger (or even a link).

I've reviewed all the Font Awesome examples and googled the heck out of this but I can't find a solution.

Any suggestions?

I normal replace search button value into Fontawesome Unicode code.

In your css just define fontawesome font-family.

E.G  In your own module call hook_form_alter()

if($form_id = 'search_block_form'){
  $form['actions']['submit']['#value'] = decode_entities('&#xf002;');

}

remeber use decode_entities() to parse the Unicode code.

CSS

.block-search input[type="submit"]{
  border: 0;
  font-size: 1.3em;
  vertical-align: top;
  margin-left: -45px;
  font-family: 'FontAwesome';
}

You should get search icon on button and place inside of your text input field.

ref. Font-Awesome cheatsheet


Regarding menus for authenticated users only Using Structures/Menus/User Menu in DRUPAL 7 i am adding a custom menu link under it and providing a path to it as node/whatever_my_nid. It is working fine. I have cleared all cache. However this menu link is being displayed for all users. I want it to be displayed only for authenticated users and admin. This should be a simple thing to figure out but apparently i cannot. I thought it would have been a permission issues but i don't think so. Would appreciate any help.
Thanks

Edit: I found that this code may help:

<?php
global $user;
if ($user->uid) {
if ($menu = theme_menu_tree()) {
   $menu = "
". $menu . "
";
   return $menu;
}
}
else {return;}
?>

But where do i place this code...In my page.tpl.php or somewhere else like in template.php in my themes?

I tried placing the above function in my theme's preprocess function as:

function ypwb_preprocess_block(&$variables, $hook) {
     if ($user->uid) {
        if ($menu = theme_menu_tree()) {
           $menu = "
". $menu . "
";
           return $menu;
        }
      }
        else {return;}
    }

However, the menu is still showing for anonymous user as well.

What I usually do is:

Install and enable Taxonomy Access
Create a vocabulary called Access
Create 2 terms in the new Access vocabulary: Public and Private
Attach the term reference fields for Access vocabulary to each node type you wish to protect. You may want to set the default value to "Public".
Go to Taxonomy Access configuration page and set D (deny) View access to Anonymous users on Private term. Leave the rest of the options (update delete view tag etc) I (ignore).
Configure the access control for Authenticated users and set A (allow) View access to Authenticated users on Private term, and set I (ignore) for all else.
Now all you need to do is set Private on nodes you wish to protect, and set Public for all else.