Views, get data for parent term as well I will try to keep the question simple and short. I have (Drupal 7):

a Vocabulary "Country regions" (depth 1 level):
Austria
-Burgenland
-Tyrol
Belgium
-Arlon
-Liege
-Namur
...

a Content type "Regional development programs" with a "Applies to:" field on this vocabulary, a terms multi-select field.

a View with an URL argument (a region) - contextual filter.

I'm trying to build a View to show all "Regional development programs" that use the parent of the given region.

Example:
URL: /get-programs/Liege/
I want to retrieve all programs that apply to Liege (given argument), which is easy, BUT I also need all programs that apply to the region parent, which is Belgium (because, of course, all Belgium programs apply to its regions as well).

Sorry if the solution is already given in another question, but I couldn't find a similar question (I found several questions for getting the children of an argument, but not for the parent).

Thanks a lot!

I believe that your problem would be solved by adding a relationship to your view. Here are the steps:

Add Relationship: taxonomy terms on node
Select the vocabulary you want to use.
Add Relationship: parent term

Now you should be able to add fields from any of the terms or their parents, and to use them as contextual filters as well.


How to use the Leaflet 'maxBounds' option? I'd like to restrict the panning of my leaflet map in Drupal.

The Leaflet documentation mentions the maxBounds option

And I'd like to know the best way to implement it for my map.

Got it working. Override the leaflet.drupal.js file as follows. See the leaflet markercluster module for how to override in an 'As You Like it kind of way.' in a custom module. Pretty useful.

// instantiate our new map
  var lMap = new L.Map(this.mapId, settings);
//note, the comma (NOT A semi-colon) at the end of the next line - this is  important.
  lMap.bounds = [],
// Now set your maxbounds, see the leaflet documentation for reference.
    lMap.setMaxBounds([
      [40.712, -74.227],
      [40.774, -74.125]
    ]);


Replace field label in content type template I'm outputting fields in a template for my content type like so:

print render($content['group_details']['field_city']);

However, I would like to replace the default label that is attached to the 'city' field. I cannot alter the label in Drupal's content type so I'd really need to do so directly in the template. How can I instruct Drupal to hide the current label and replace it with a custom label in the content type template?

OK it's a bit round the houses, but you should be able to do:

$content['group_details']['field_city']['#label_display'] = 'hidden';
print '
Title
'; // change to any HTML
print render($content['group_details']['field_city']);


Is it safe to call field_view_field() for a field that isn't attached to the given node? My page.tpl.php includes:

if ($node) {
    // field_suburb is a "text" field that doesn't exist on this node type
    $f = field_view_field('node', $node, 'field_suburb');
    print render($f);
}

This triggers:

  PHP Fatal error: Cannot access empty property in field/field.attach.inc

I added the following debug code in field.attach.inc ("if field name is null" block):

foreach ($languages as $langcode) {
    if ($field_name === null) {
        print $field_name === null ? "FIELD NAME IS NULL\n" : '';
        print $instance == null ? "INSTANCE IS NULL\n" : '';
        print "$entity_type $bundle\n";
        print_r($instances);
        print_r($options);
    }
    $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
    // Group the instances and entities corresponding to the current field
    $grouped_instances[$field_id][$langcode][$id] = $instance;
    $grouped_entities[$field_id][$langcode][$id] = $entities[$id];
}

That code prints:

FIELD NAME IS NULL
INSTANCE IS NULL
ENTITY TYPE: node BUNDLE: news
Array
(
    [0] =>
)
Array
(
    [field_name] => field_suburb
    [language] =>
    [default] => 1
    [deleted] =>
)

This is easy enough to protect against - I can just check my node type before accessing the field - but surely field_view_field should just return null for a field that doesn't exist instead of having the entire site die?!?

Should it be safe to call field_view_field() - i.e. is this a bug? If it's not a bug, then what's the easiest way to check to see if my given node content type actually has the field I'm rendering? Checking the type against a list of known safe types isn't very flexible, and calling field_get_items() followed by field_view_value() seems redundant when field_view_field() is available.

Drupal version is 7.22.

Source code of this function looks as follows:

function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) {
  $output = array();

  if ($field = field_info_field($field_name)) {
  // Actual work on field, not needed here in this answer
  }

  return $output;
}

It means that if there is no field, empty array will be returned. That's all. Is it safe? Depends what are you doing with that array down the road. For example you cannot render empty arrays with render(), as it accepts only arrays representing Drupal's renderable elements.

Note that this is from the current, 7.23 version of Drupal.


Get all available permission after NodeType delete - Drupal 8 I know that to get all available permissions you can do

var_dump(array_keys(\Drupal::service('user.permissions')->getPermissions()));

which give you a list of all permissions' name.

I also know that when you create a NodeType, it refresh this list.

So what I want to do here, is to fill a table of my database with a list of all available permissions, that update when permission is add or removed.

When I create a NodeType :

function inside_entity_insert(\Drupal\Core\Entity\EntityInterface $entity) : void
{
    if (get_class($entity) === 'Drupal\node\Entity\NodeType') {
        $permissions = array_keys(\Drupal::service('user.permissions')->getPermissions());

        foreach ($permissions as $permission) {
        // somestuff -> updating database permission table
        }
     }
}

So that means when NodeType is created the Drupal permissions list is updated and I must update my database too.

What I want to do here is the same thing but when a NodeType is deleted.

I tried :

hook_entity_delete
hook_entity_predelete

But in both hook the user.permission list didn't change, I still get the same permissions, and what I though is that the permissions of my actual nodetype dissapeared, because of the deletion.

I do not know where to look..

Is getting the name of the nodeType and delete matchings rules' name of the database, a good alternative ?

I also wanted where can I initialize these database, because actually it's created & updated only when someone create a NodeType. But that's not urgent at the moment.

Thanks to all

You are using the wrong hooks. I am not sure what your objective is, but you want hook_ENTITY_BUNDLE_delete I believe:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_bundle_delete/8.6.x

function mymodule_entity_bundle_delete($entity_type_id, $entity) : void
{
    if ($entity_type_id == 'node' && $bundle == 'node type to check') {
        $permissions = array_keys(\Drupal::service('user.permissions')->getPermissions());

        foreach ($permissions as $permission) {
        // somestuff -> updating database permission table
        }
     }
}

I don't know if you care to check $bundle or not, but if you delete any node type, this code should fire.


How to add a custom module to a menu? I am using Drupal 7. I have just built a wonderful custom module. Now I need to add it to my main menu, under the parent item "Tools and Resources."

I know I can go to the homepage and click on the little gear and go to "List links", which will take me to admin/structure/menu/manage/main-menu/list?destination=node and I can click-and-hold on the little compass and drag-and-drop my module in the desired place. But, is there a way to do this through the PHP code in the module itself?

Menu items are nested using the item path. Take look to the paragraphs module:

/**
 * Implements hook_menu().
 */
function paragraphs_menu() {
  $items = array();
  $items['admin/structure/paragraphs'] = array(
    'title' => 'Paragraph Bundles',
    'description' => 'Manage Paragraph bundles',
    'page callback' => 'paragraphs_admin_bundle_overview',
    'access arguments' => array('administer paragraphs bundles'),
    'file' => 'paragraphs.admin.inc',
  );

  $items['admin/structure/paragraphs/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/structure/paragraphs/add'] = array(
    'title' => 'Add Paragraph Bundle',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('paragraphs_admin_bundle_form'),
    'access arguments' => array('administer paragraphs bundles'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'paragraphs.admin.inc',
  );

  $items['admin/structure/paragraphs/%paragraphs_bundle'] = array(
    'title' => 'Edit paragraph bundle',
    'title callback' => 'paragraphs_bundle_title_callback',
    'title arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('paragraphs_admin_bundle_form', 3),
    'access arguments' => array('administer paragraphs bundles'),
    'file' => 'paragraphs.admin.inc',
  );

  ...

  return $items;
}

Also if you want to add your menu item to an existing menu other than administration use the menu key.

$items['menu-item'] = array(
  'title' => 'Foo bar',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('foo_bar'),
  'menu' => 'user_menu'
);

Check the hook documentation for more information.


Can Panels provide a panels context based on the URL string or URL query? I need to know if Panels can provide a panels context based on the URL string or URL query. This context may then be used to set in the panel pane settings.

Background info:
I have panels that contain panel views panes. The panels pane settings use the available panel context.

I therefore want to create a panel context based on the current URL string or URL query. Is that possible?

Note: if that is not possible, I would have to create new views panes that get their contextual filter directly from the URL instead of the available panel contexts. Using panels contexts would allow me to re-use views more efficiently.

Page Manager can take arguments from the URL and provide them as context.

For instance if you create a path in Page Manager lik foo/%bar/%baz both 'bar' and 'baz' will be automatically available as Arguments.  You just need to tell Page Manager what it is looking for (i.e. should it be a taxonomy term id? a node number? maybe just a plain string...)


Why is the CSS in my sub-theme not working? I'm a Drupal newbie, but hoping someone can assist. The site was working okay, but I've tried to implement a sub-theme and things seem to have gotten messed up.
What I was trying to achieve is to include my own CSS/JS files, and figured that a sub-theme seems like the proper way to do it. Well, I did install the sub-theme, but no CSS or JS from the sub-theme was loading (or referenced in the page anywhere). So, I played around some more and eventually stopped the entire site from loading.
So, now I'm getting "The website encountered an unexpected error. Please try again later.", and the Apache error log says:
"Uncaught PHP Exception Drupal\\Core\\Asset\\Exception\\IncompleteLibraryDefinitionException: "
 Incomplete library definition for definition 'global-styling' in extension 'my_theme'" at ..."

My theme is called "my_theme", and is meant to be a sub-theme of awesome_zymphonies_theme. Went to loads of places trying to figure out the sub-theme stuff, given the abysmal Drupal documentation, but ended up with a directory called "my_theme", under /drupal/themes/, and directories of /css/ and /js/, with CSS and JavaScript files in each, respectively, and two files: my_theme.info.yml and my_theme.libraries.yml. Permissions are all okay, and owned by apache:apache.
drwxr-xr-x. 2 apache apache   26 Mar 24 20:30 css
drwxr-xr-x. 2 apache apache   25 Mar 24 20:30 js
-rw-r--r--. 1 apache apache 1300 Mar 24 20:57 my_theme.info.yml
-rw-r--r--. 1 apache apache   86 Mar 24 20:30 my_theme.libraries.yml

The file my_theme.libraries.yml looks like this:
global-styling:
css:
  theme:
    css/my_theme.css: {}

js:
    js/my_theme.js: {}

The top portion of the my_theme.info.yml file looks like this:
name: My Theme
type: theme
description: Sub-theme of 'Awesome Zymphonies Theme.'
package: core
base theme: awesome_zymphonies_theme
core: 8.x
core_version_requirement: ^8 || ^9

#Libraries
libraries:
  - awesome_zymphonies_theme/bootstrap
  - awesome_zymphonies_theme/global-components
  - my_theme/global-styling

#Regions
regions:
  header: 'Header'
  primary_menu: 'Primary Menu'
  slideshow: 'Slideshow'
  homepagemessage: 'Home page message'
  topwidget_first: 'Top First Widget'
  topwidget_second: 'Top Second Widget'
  topwidget_third: 'Top Third Widget'
  ....
  ....

Additionally, not sure if I need to include the two lines:
  - awesome_zymphonies_theme/bootstrap
  - awesome_zymphonies_theme/global-components

... or do they get inherited from the parent theme?
So, I guess three questions there really. Any assistance would be most appreciated. Thanks!

The my_theme.libraries.yml isn't indented correctly.
global-styling:
  css:
    theme:
      css/my_theme.css: {}
  js:
    js/my_theme.js: {}


Why making a Views page instead of Views block? In most of my projects views are displayed in a block instead of a page, eventhough it would be perfectly possible to make a views page in these cases.

The reasons why I do this:

If the client wants to add some content on top of the view, he can
easily do so by clicking the "edit" tab of the page the block is
nested in. This is more accessible and easier to understand than
creating/positioning blocks and setup their visibility, or even worse: use the header field feature of Views
(which the client has no access to in normal cases).
It's cleaner to manage the translated menu items to that page (taking in account that the menu items are manually grouped by language)
If the client needs to, he can easily translate the page, and alter
the visibility settings of the block so it would appear on the
translated page as well. This makes more sense to clients than to fiddle
around with translated alias urls.

Ofcourse, there must some downsides to this approach. One I believe is that it may increase the loading time of pages when there are a lot of other blocks in use (is that true?), but one should be able to counter this with the Context module I believe.

I'm bringing up this question to check this approach with other dev's to figure out if I should maintain this, or if I should reconsider it.

I live in Belgium, a country with two language communities (Dutch and French), so almost every project is multilingual, which is is also an important factor in the motivation above.

Blocks are appropriate to display piece of content but a Page is for displaying the whole content.

If you create a block of a View, using admin UI you can easily place it in any region (or panels) and reorder it but this option is not available if you use Page.

In Panels, if you use Place In-Editor option to build the pages (like the following image) pages will not be available. This is a very powerful tool in Drupal so if you don't use the appropriate structure you will miss it.

So as a result, by using blocks even a regular user can also easily change the structure of the site and no coding is necessary.

If you create a Page display of a View, to display it's result in some section of the page you must use views_embed_view (or similar ones) function to load that View. This function doesn't load the View title, widgets and ... .

You can use 30 variables to store 30 numbers but you can also use an array with 30 cells. Both approaches work but you should use the reasonable one. It is like your question. you can build your site using both display modes but you should use each one in it's right position.


Is it possible to include extra arguments when migrating via command line? Is it possible to include extra arguments when migrating via command line?

I have a custom migration which migrates XML content into Drupal as entities. However, each XML document of migrated entities need to be associated with a different node.

I'm successfully doing this entities to node association via the following code:

function complete($entity, stdClass $row) {
    $node = node_load(1);
    $node->field_questions[$node->language][ sizeof($node->field_questions[$node->language]) ]['target_id'] = $entity->id;
    node_save($node);
}

As you can see from the code, the NID is hardcoded. Of course, the NID could be extracted from the XML input but it is unknown in advance of the migration.

So, I just wonder if running drush migrate Questions could be run with custom arguments where I could specify the target NID to associate my migrations with?
Something like, drush migrate Questions --nid=10

In the URL below you can find Dush arguments for migrations. Following the documentation you need --idlist argument.

See here https://www.drupal.org/node/1561820

Hope that helps.


Check if available values of a list-field is already used by other node of content type i have a problem regarding fields of type list.

The scenario is the following. I have a content type with several fields, among them a field of type list. This field have 3 values ("1" to "3"). I want any of those 3 values to belong only in ONE node of this specific content type.

In other words, if a node of that content type has the value "1" in that field, i want that value to be "disabled" when creating new nodes of that content type (so, only available options to be "2" and "3").

Do you have any ideas? Is it possible at all?

Thanks in advance!

you need to build a custom module in which you implement hook_form_FORM_ID_alter. since we're dealing with node create/edit forms, try yourmodule_form_yourcontenttype_node_form_alter().

(you could go for hook_form_alter(), but that would yield less performance, especially since you have a query to run.)

your implementation should include a query for that specific field, probably the table field_data_field_yourfield. narrow it by bundle and if it returns any entity_id, that's the one you're filtering out of your dropdown.

here's a few links to help you sort things out:

function hook_form_FORM_ID_alter():
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7.x
function db_select(): https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7.x
also look up "D7 Form API reference" (I can't post more than two links atm, sorry)

please write back if it works. good luck!

cheers,
Luco


User Webform as user registartion pages I have 3 pages in my website where user can either register register of login. On each page the amount of data required for registration is different. Problem is that i need to use webforms for the user registration pages and create 3 different forms with different level of data being asked. And when the user enters his email ID in the registration form, if he has already submitted the form once, his previous data should be filled up in the user registration for editing purpose.

Webform isn't the right choice here because Webforms are designed for multiple submissions against a template. You seem to want to extend/create user profiles and include these fields in registration. I recommend you use the Profile 2 module instead.


AJAX callback: error with firefox I've a custom callback with a form which works well in last chrome and last FF.

$form['foo']['bar'] = array(
  '#type' => 'submit',
  '#value' => t(''),
  '#attributes' => ['class' => array('search-api glyphicon glyphicon-refresh btn-primary')],
  '#ajax' => [
    'callback' => '::fetchApiData',
    'event' => 'click',
    'effect' => 'none',
    'progress' => [
      'type' => 'throbber',
      'message' => NULL,
    ],
  ],
);

However, my customer has a old version of firefox, the esr 45.9.0 version, and when we click on the button that trigger the callback, we have an alert error.

  An error occurred while attempting to process
  /declaration?ajax_form=1&_wrapper_format=drupal_ajax: invalid regular
  expression flag a

Does anybody know how to debug this?

This issue is related to drupal/boostrap theme. It doesn't occur with default drupal theme.
Replace methods in Attributes.cleanClass pass the identifier as a 3rd parameter isn't needed because string replacements in JS are chained.
https://www.drupal.org/project/bootstrap/issues/2969106


How to save field data I need to programmatically save field data (during node save I want to take the title & path alias and store it in a link field called field_alternative_titles_title).

Which functions can I use here? Do I use field_attach_insert or hook_field_storage_pre_insert to save the link field?

At first you need to implement hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database. Parameters

  $node: The node that is being inserted or updated.

So it reacts when a node is going to be saved , then you have to check if the node type is the proper node type . then setting field value , so this is some code snippet :

function mymodule_node_presave($node) {
  if($node->type == "Your Node Type") {
      //dsm($node);//it will show the structure of node
      // as example
      $data = $node->title.'-'.drupal_get_path_alias('node/'$node->nid);
      $node->field_alternative_titles_title[$node->language][0]['value'] = "data";//check the node structure,this code wont work for sure
  }
}

of-course this is just an snippet , to make it work you have to know the structure of your content type , Devel module will help you , install and enable it so dsm function will work.


Drupal 7 - Module with form and view I'm trying to develop a module that creates a form and a view that displays that page.

In my module I used hook_menu() and hook_form().
Also I saw some tutorials 1 & 2

What I cannot understand where & how to add my form to the view?

I have never used it in that way, but some thoughts:

The second link doesn't seem relevant, as I suppose that you use Views 3.

If you use the approach described in the first link, than you don't need to implement hook_form() in your module, instead you need to create a views field handler and there you need to define the methods views_form()and views_form_submit(), optionally also views_form_validate(). You would then "add the form to the view" using the Views UI where you can add the field (the one that you have written a handler for) to the display. That's  how your handler get's called and is responsible for the rendering of the element, which usually renders a value wrapped in some markup, but in your case it would render a form.

The first link explains that all very well. Just go through it again and try to follow it in detail.


Can a node belong to multiple menus? I have a few pages such as a general "contact us" page. I'd like this page to exist inside of the Main Menu but be able to be linked from other menus (Theatre menu, for example). I create the contact us page and assign it to the Main menu on the node's form. Then, I add the link from the Theatre menu.

However, the contact us page now shows the Theatre menu.

How do I accomplish linking a page from multiple menus but keeping it inside of it's own menu?

I thought the old convention was to add existing links such as http:/learn/contact_us. If I add the link learn/contact_us to Theatre's menu, the Contact us page now shows the Theatre menu (instead of the Main menu).

Additional folks running across this problem:
https://drupal.org/node/1314742

Actually, the project menu token allowed me to find a good work around. I set it up as pictured below. By using the token [site:url] followed by an existing path, a effectively have a link to an existing node without changing the existing nodes current parent menu.


How do I replace comma with a line break in a views field? I am working with a custom view handler that renders a comma separated list.  This field is used throughout the site this way.

Now, I have a new view that needs to render the list using line breaks instead of commas. Is there a way to do this in the view settings?

I don't want to hard-code the new view name in the view handler code to render it differently. Do I have to create a views template to solve this?

You can use the options_form() method on your field handler to provide a setting. That setting could be a text field in which you enter separator to be used, , or
 or whatever you need. Or that setting could be a select list that contained only , and
 options.

Here is an example of an field handler that uses that method:

http://cgit.drupalcode.org/views/tree/modules/node/views_handler_field_node_link.inc?h=7.x-3.13

The key pieces are the options_form()

  function options_form(&$form, &$form_state) {
    $form['text'] = array(
      '#type' => 'textfield',
      '#title' => t('Text to display'),
      '#default_value' => $this->options['text'],
    );
    parent::options_form($form, $form_state);

    // The path is set by render_link function so don't allow to set it.
    $form['alter']['path'] = array('#access' => FALSE);
    $form['alter']['external'] = array('#access' => FALSE);
  }

and then the usage of the option

  $text = !empty($this->options['text']) ? $this->options['text'] : t('view');


unset form elements with hook_form_alter() I've created my module, but I have a problem when its code executes the following code:

dpm($form);

I can't see the notifications fields (from the Notifications module); also, I can't remove the "Format" fieldset from the node create page ("node/add/question"; my content type is called "question").

The following snippet works great, but is there any other method to print all the form's fieldsets? I just stuck at this notifications field set, as I can't remove it.

unset($form['menu'], $form['comment_settings']);

Notification does add its own form elements in its own hook_form_alter(), which is probably executed after yours.

Check the module weight in the {system} table, and set your module to a higher value to have it run later.

Note: Instead of using unset() to hide form elements, you should instead set the #access property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.


How to show last login time and user email to all authenticated users? I have created a view for user profile page. I also want to show the user's current email address and last login time. It is working fine for admin but email and last login time is not visible to authenticated user on front end.
I have granted the View User Information permission to authenticated users but no success after that too.
Is it a permission issue or something else ?
What I am missing ?

EDIT:

I set up a test View myself and confirmed the issue you reported. Upon some search, I see this is intended behaviour.

There is a thread discussing it here: https://www.drupal.org/project/drupal/issues/2799049

The thread has a very simply Core patch to resolve the issue that could be applied. Or, there's also information on using hook_entity_field_access() to grant field-level access to User fields.

https://www.drupal.org/project/drupal/issues/2773645

************************ORIGINAL INFO***************************

From what you've said, it seems like it should work as you'd expect.

One thing you can try is checking the "Disable SQL rewriting" checkbox in your View. This will bypass ALL permission checking for the View. It is located in the Query Options setting in the Advanced section of your View config.

If checking this works then you'll know that,at least, the issue is permissions related.


How do you theme an autocomplete dropdown I'm trying to theme an autocomplete dropdown from a textfield. In this case the autocomplete is provided from the finder module.

I need to theme it beyond just simply adding css. Ideally I'd like a theme function to override or a template file but I can't find one.

I have tried using the theme function which is provided by the finder module, however all that does is theme the resulting page, not the autocomplete drop down.

Can anyone advise?

To theme the Drupal 7 finder autocomplete dropdown take a look at this video. Generally you write PHP into the 'Rewrite' settings on the advanced options of the finder. I would avoid using the theme() function, it might be obsolete.

To theme the Drupal 6 finder version, you may find this article helpful. It uses theme functions.


Avoid redirect to comment page if comment is invalid I have configured comments to display in the node page, but if submit an invalid comment (e.g. without text in the comment field) I get redirected to the /comment/reply/ page. I would like to remain in the node page.

You can do this, by using hook_form_alter and then change the $form['#action'] value to point to the current destination.


Fatal error: Class 'RulesI18nStringController' not found in entity.i18n.inc on line 31 My client drupal site stopped working suddenly and gave me this error Fatal error: Class 'RulesI18nStringController' not found in entity.i18n.inc on line 31 i checked the rules module and entity module and nothing seems to be messing.
I searched for a solution on the internet with no luck.
I have rules 7.x-2.2 and entity 7.x-1.0-rc3 but i can't login to the site so i can't access update.php to update the rules and entity modules to the latest versions "as it may fix this problem".

So can anybody help me find solve this problem?

PS: If you need any additional information about the problem just ask about it in the comments.

Thanks in advance for you all.

You have $update_free_access variable in your settings.php file. Set it to:

$update_free_access = TRUE;

You will be able to run update.php without login. Don't forget to turn it back to FALSE when done - if left TRUE, it can open your site to DoS attacks.


"Censor" View results/ CCK fields (Censor based on a role) Drupal 6 Nodes + CCK allow the creation of custom fields on nodes and per Role based Permissions to view / edit / delete on a per Field basis. Whilst I don't want to simply "switch off" fields (disable the Permission to View a field based on a Role), I want the field to display "********", or "withheld".

So essentially I want to add additional permissions to the View CCK field, called "View Censored", which doesn't allow them to see the content, but know at least the content exists. In addition, it means that I don't have to have duplicate Views (one with full details, one with some sort of templated *** instead of fields) and the linked Nodes will display, but with censored fields automatically.

The only way I can think of to do this without making two views (which would be my preference to be honest) would be to use the Views Customfield module and use a PHP snippet to check permissions and display the result accordingly.

Create your view as normal and when choosing the field that you wish to change, make sure you check the bock that says "Exclude from display".  Then add a custom PHP field directly after it and use code along these lines:

<?php
  // Check the logged in user
  global $user;
  // Check if the user has a certain role
  if (in_array('USER ROLE', array_values($user->roles))) {
    print $data->FIELDNAME;
  }
  else {
    print "Withheld";
  }
?>

Obviously you'll need to replace 'USER ROLE' with the role that you're looking for and you'll need to replace $data->FIELDNAME with whatever the Views fieldname is, for example $data->nid or $data->title.

Otherwise you could use a View with two slightly different block displays, embedded in a contextual Panel that checks for users permissions and displays accordingly.

Edit after asker comment: Craig, a few things. Firstly, I don't think you're approaching the problem correctly at all.  What you want to do is difficult and a  outside of the scope of your question - you asked how to alter a value on a view, not show two different values globally depending on permissions. Before you can get the solution you need to ensure you're tackling the right problem. You simply need to hide a value in two situations depending on a permission, nothing more.

Secondly, I'm not going to give you another solution as I have given you a perfectly good solution to your question.  This may not be perfect for you but with some initiative you could very easily solve this problem with what I've given you. If you persevere with this information you can use the Content Templates module and the same code as above to hide the value on a node.

Thirdly, never hack modules.  If you want to change the behaviour of a module, write another module to alter it.


submitForm() isn't called Goal: Have a custom page that shows various elements including links, logos, images and a custom form to help the users reset their passwords (we have a custom reset password interface which sends the user a code so we are over-riding the default reset password interface).
Problem: The submit button is not firing the submitForm function on the reset password form.
Here is my code now:
In my module:
function example_theme($existing, $type, $theme, $path) {
  return array(
    'reset_password' => array(
            'variables' => array(
                'form' => NULL,
                'url'=> '',
                'main_logo_url' => '',
                'foot_logo_url' => '',
            )
        )
  );
}

In my routing:
example.reset_password:
  path: '/reset-password'
  defaults:
    _controller: '\Drupal\example\Controller\ResetPasswordController::resetPassword'
    _title: 'Reset password'
  requirements:
    _permission: 'access content'

In my Controller:
namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;

class ResetPasswordController extends ControllerBase {
  public function resetPassword() {

    //code here that sets the variables in the return array

    $form_state = new FormState();
    $reset_password_form = \Drupal::formBuilder()->getForm('Drupal\example\Form\ResetPasswordForm', $form_state);

    return array(
      '#theme' => 'reset_password',
      '#form' => $reset_password_form,
      '#url' => $url,
      '#main_logo_url' => $main_logo_url,
      '#foot_logo_url' => $foot_logo_url,
    );
  }
}

in my form:
namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ResetPasswordForm extends FormBase {
  public function getFormId() {
    return 'reset_password';
  }

  public function buildForm (array $form, FormStateInterface $form_state) {
    \Drupal::logger('rp-form')->notice('hello from build Form');

    $form['#theme'] = 'reset_password';

    $form['step_one_user_exists'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#attributes' => array(
        'placeholder' => t('Enter here')
      )
    ];

    $form['actions'] = ['#type' => 'actions'];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Send Code'),
    ];

    return $form;
  }

  public function validateForm (array &$form, FormStateInterface $form_state) {
    \Drupal::logger('rp-form')->notice('hello from validate');
  }

  public function submitForm (array &$form, FormStateInterface $form_state) {
   \Drupal::logger('rp-form')->notice('hello from submit');
  }
}

and in my twig template:
// I have other elements on the page here

 {{ form.step_one_user_exists }}

 {{ form.actions.submit }}

As I said above, the problem is that the submitForm function from the form class is not firing when I click the submit button. The form shows up on the page, you can type in the text field, you can click the button, but then nothing happens.  I have loggers in the buildForm (which logs), and in validateForm and submitForm (which do not log).
I want to use a controller because there are other variables needed on the page that change based on language and other factors, but am open to other methods of doing this (although I'd prefer to keep most of the logic out of the template).
Thanks!

The code in the question is mixing three different types of templates:

Custom twig template in a controller
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/create-custom-twig-templates-for-custom-module

Overriding form.html.twig
How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?

Adding a custom form template
How to render specific form elements from the *.theme file

The confusing part of your question is that you are using the same template reset-pasword.html.twig for 1. and 3.
The issue discussed in the comments about the special form elements applies only to 2.
You can use all three template levels at the same time. Then they are nested inside of each other which you see when you enable twig debugging.
More info Custom registration twig template.


How do I print out a field I created a new content type with several fields in it. How would I print out those fields anywhere on the page that I need them like in the sidebar and other areas? What is the syntax for printing out a field? Also, I think I have to name a PHP file after the content type. What do I name it in Drupal 7?

This is best accomplished with Render Arrays. Please read Theming Node Form into Regions for a tutorial.


Jsonapi query to return specific field In a simple article content type, is there a way we can have a jsonapi query to return specific field only? The same as how REST export view is doing, we can select what field to be displayed in the output.

E.g. http://localhost:8080/jsonapi/node/article/<return body field value>

If not, is there a method I can create a list of string then I would want to call a jsonapi to get that list. Thanks in advance!

Yes, with the caveat it still contains the JSONAPI document payload around your requested field. This is mandated by the spec so you can't just have an arbitrary JSON structure that contains only the field data you want.

This is called a sparse fields query. When you add a ?fields[$RESOURCE_ENTITY]=field1,field2... to a:

index endpoint (/jsonapi/node/article)
resource endpoint (/jsonapi/node/article/$UUID) endpoint

It will trim down the list of fields to the comma-delimited list you've specified.

To use your example, http://localhost:8080/jsonapi/node/article?fields[node--article]=body will return a JSONAPI document with all article nodes with only the body property in the attributes object.

See the JSONAPI docs about fetching resources for more info.


How do I overwrite a page template? I created a bunch of products, but I need to style them per the designer's design. I know that I have to overwrite the template from /modules/contrib/commerce/modules/product/templates/commerce-product.html.twig but where do I put it in my theme?

Does it go to the root of my templates folder? What is the correct way to style the single product page?

To do this, just create a copy of commerce-product.html.twig from the product module in commerce to your theme's template directory.

for more instruction to visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product.


what is the difference between "Commerce Product Attributes" and "Commerce Customizable Products" Commerce Product Attributes

Commerce Customizable Products

What is the difference between these 2 modules.?

I'm creating orders from a view table, without a product display for each product. I've added a text field to a custom line item with "Commerce Customizable Products" module. The line item display shows the fields but I cant find how to edit it. (working on panels btw.)

i'm bad in english, but still try to explain.

Product attributes are always set by the administrator, and customer can not change it. For example, if you set a colour as product attribute, you also have to define all possible variants of colors. There is no difference whether you are using conversion rates depending on the color value of the attribute or not.

Customizable products, however, allow the customer to select an attribute value depending on the preference. For example, if you sell T-shorts, you are able to allow customers choose an inscription on a T-shirt, without price changing. Customer may order T-short with any inscription that he wants to.

To be more precise, trying to explain the difference in terms of data structures. Product attributes add fields to commerce product entity, and customizable products add fields to line item entity. So there is the main difference with all the consequences.

Based on my experience:

I use a Customizable products to sell tea sold by weight. Customer allowed to enter any amount of tea in grams, and then i recalculate sell price using rules.


Find and display lowest value from one field in a node type I have a Drupal 7 website that tracks values associated with "Content Type A". I have another content type, "Content Type B", which is a part that is associated with Content Type A. Any A item may have one or more B items associated with it:

A-101 (B-201 B-202 B-203)

A-102 (B-301)

Each B item has a field that shows its total number of available uses (its limit, if you will). This is a static integer field. Each A item has a field that shows "aggregated uses" of that item, based on a third content type: "Content Type A-Usage". The "aggregated uses" field in A uses Views and aggregation to add up the A-Usage items referenced/linked to that A item.

I need to take that aggregated A-Usage value and subtract it from the "B-available uses/limit" value, and then display that result in a view or a CCK field.

So let's say A-101 has an aggregated usage of "100", and B-201 has a limit of 500 uses. I need to display the remaining uses for B-201 (400, in this case) in a view or CCK field.

One step further, I also need to take into account the remaining uses for B-201, B-202, and B-203, and pluck the lowest value from those remaining uses and display it in a view/CCK field. Let's say B-201 has 400 remaining uses, B-202 has 350 remaining uses, and B-203 has 100 remaining uses. The view/field in question would simply display "100", as that is the lowest remaining value of those B items.

I'm hoping someone can point me in the right direction, or provide some type of php snippet or guidance to help me accomplish these tasks. Views would be my method of choice, as much of the site's pages are already compiled using Views.

Thanks!

It is not clear from your question if your 'aggregated uses' and 'available uses' are CCK fields already. If they are, I hope this helps... You can access each of the fields available $a and aggregated $b with this code:

$items = field_get_items('node', $node, 'field_YOUR_FIELDNAME');
$first_item = array_shift($items);
$YOUR_VAR = $first_item['value'];

then deduct $a-$b=$c and store $c in another CCK field using the node_load and node_save:

 $node = node_load($nid = YOUR_NID);
 $node->field_YOUR_FIELDNAME[$node->language] = array(
    0 => array('value' => $c)
 );

once $c field is stored in your node, you will be able to access and display it from Views.


How can I add a menu link to a page with a form in DrupalGap? I made a custom page that has a form on it. How can I add a menu link to the authorised user menu? There is this very useful documentation http://docs.drupalgap.org/7/Menus/Adding_Links_to_Menus but how do I get the path to the custom page with the form?

In settings.js I have added this and the new link shows up.

drupalgap.settings.menus['user_menu_authenticated'] = {
  options: menu_popup_get_default_options(),
  links: [
{
  title: 'My Account',
  path: 'user',
  options: {
    attributes: {
      'data-icon': 'user',
      'class': 'ui-btn ui-btn-icon-right'
    }
  }
},
{
  title: 'Logout',
  path: 'user/logout',
  options: {
    attributes: {
      'data-icon': 'delete'
    }
  }
}, //NEW LINK
 {
  title: 'Buy points',
 // path: 'user/logout', // what path?
 page_callback: 'drupalgap_get_form',
  page_arguments: ['my_module_payment_form'],
  options: {
    attributes: {
      'data-icon': 'delete'
    }
  }
}
  ]
};

In my_module.js I have added the form like so and it shows up:

function my_module_menu() {
  try {
  var items = {};
  items['in-app'] = {
    title: 'get points',
    page_callback: 'drupalgap_get_form',
    page_arguments: ['my_module_payment_form']
};
return items;
}
   catch (error) {
      console.log('my_module_menu - ' + error);
    }
 }

Figured it out finally:

path: 'in-app'

Comes from the hook_menu items array.


PHPExcel in Drupal 7 I'm trying to export my Webform settings to an Excel file by using the PHPExcel module, but it looks like it's documentation isn't modified for Drupal 7...

When trying to define the two-dimensional array $data[row][column] (as mentioned in the API), I keep stumbling upon an errors...

I try to add "John Doe" in Cell A1, "john@example.com" in Cell B1, etc.

$data = array(
    1 => array(
        'A' => 'John Doe',
        'B' => 'john@example.com'
    ),
    1 => array(
        'A' => 'Jane Doe',
        'B' => 'jane@example.com'
    ),
  );

But nothing ends up in the Excel file. Sometimes the first letter, but nothing more...
What does this module require as $data?

The data table shold look like this:

 $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

And whole working example will look like this:

function hoook_export_excel() {
    module_load_include('inc', 'phpexcel');
    $data = array();
    $headers = array();
    // First worksheet
    // Get the nodes
    $data = array
    (
        array("Volvo",22,18),
        array("BMW",15,13),
        array("Saab",5,2),
        array("Land Rover",17,15)
    );

    $headers = array("CAR","COUNT1","COUNT2");

    // Store the file in sites/default/files
    $dir = file_stream_wrapper_get_instance_by_uri('public://')->realpath();
    $filename = 'export1.xls';
    $path = "$dir/$filename";
    // Use the .xls format
    $options = array('format' => 'xls');
    $result = phpexcel_export($headers, $data, $path, $options);
    if ($result == PHPEXCEL_SUCCESS) {
        drupal_set_message(t("Ok"));
    }
    else {
        drupal_set_message(t("Error"), 'error');
    }
}

This will return Excel:


How to access individual theme settings from code? I was building a block for which I have to provide bubblable metadata. The data in this block is depending on individual theme configurations as well as the global theme settings.

So I tried the following:

$config = \Drupal::config('system.theme.global');
$bubbleable_metadata->addCacheableDependency($config);

$config2 = \Drupal::config('bartik.settings');
$bubbleable_metadata->addCacheableDependency($config2);

This however obviously does not work if the theme is not set to bartik. I have been attempting to find the theme configuration in \Drupal::theme()->getActiveTheme(), but that does not provide this data.

I suppose I could try $config = \Drupal::theme()->getActiveTheme()->getName() . '.settings';, but I'd like to learn if there are better ways.

How to get the configuration (or config name) of the current active theme?

It seems this is actually the recommended way. It is used in theme_get_settings() as well:

$theme = \Drupal::theme()->getActiveTheme()->getName();
...
  if ($theme_settings = \Drupal::config($theme . '.settings')->get()) {
    ...
  }


How can I create a product with a single variation for a store? I am having trouble with creating products for a commerce project with multiple sellers (each with their own store).  The products these sellers are selling is a baseball card.

When a user adds a new product to sell, in the form submission I create the form as:

// create price...
$price = new Price($vals['price']['number'], $vals['price']['currency_code']);

// init variation
$variation_vals = [
  'type' => 'card_type_baseball',
  'status' => 1,
  'sku' => 'baseball-1',
  'price' => $price,
  'field_card_image' => [$vals['image_fid']]
];
$variant = ProductVariation::create($variation_vals);
$variant->save();

// init product
$product_vals = [
  'uid' => $this->getUID(),
  'title' => $vals['name'],
  'type' => 'card',
  'stores' => [$this->store],
  'variations' => [$variant],
];
$product = Product::create($product_vals);
$product->save();

It works, however, when I view the product after creation, I have many copies of image and field values for some reason.

I think I'm missing a concept.

When a user wants to sell their product, and they upload the product image, set the price, and enter the title for that card (through the form I provide via the Form API) I want to create the product that I can display in a view for the front page, or under their store on their store pages (which I can display via Views).

Every card has the same properties: an image, title, and a price. Examples,

1 - Barry Bonds, $20.00 (with img)
2 - Mark McGuire, $15.00 (with img)

Am I missing something in relation to creating products?

The code in my example was fine.  In my product variation's display I was rendering the product entity, and in my product entity I was rendering my variant.  If anyone encounters multiple copies of their product rendered, check how the fields are rendered in the display.


Various View-panes with arguments from url in the same panel-page. It is possible? I'm making a web about football and this is the situation of my problem:

I have a content-type called 'player stats' taxonomized with the vocabularies 'season' & 'day' and another content-type called 'chronicle' with the same tag-system of the 'player stats' content-type.

I want to have my custom node-template for all the content of type 'Chronicle', but including in any content-pane a Views-pane with content from the 'player stats' for a given 'season' and a given 'day'. My url structure is: example.com/chronicle/season-x/day-y and I tried to get arguments from url but the internal path node/% impossibilite it (as far I know)...

My second option is to create a Panel page, and try to insert content (using views pane's with contextual filters) from both content-types 'chronicle' and 'player stats' to make a chronicle with complete stats of the players in the same page. But my problem is that I only get visible ONE View-pane, the other ones seems not to work an I can't see any more view-panes that compose my panel-page. (please, see attached snapshots)

I am doing anything wrong? I'll glad to read you suggestions and your help.
(sorry for my bad english, I'm catalonian from Barcelona). Thanks.

Attached files::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

It's my first time posting here, so I have not enough privilieges to attach more than 2 links. But snapshots & export-files are available in the original post, at drupal.org:

http://drupal.org/node/1392700

This discussion has gotten long in the issue queue already, so instead of repeating what's been said there, I'm try to explain from scratch how you can have two Views in the same Page, with the same arguments.

Create two Views. In both Views, add only a single "Content pane" display. No page displays.
Configure your contextual filters on both content panes, make sure they expect the same type of argument.
In the pane-specific settings, set both panes to get their arguments from context, pick appropriate context objects.
Create a new custom page, or use an existing one. Add both content panes.
Done.

Additional comments: I guess the settings of both Views have more similarites than their arguments, so I would put both of the content panes into one View.


How to add a "?destination=URL" to the node links I am trying to override node links by using hook_node_view_alter(), so my code looks like:

$cancel_link = 'admin/some_path/'.$found_id.'cancel';

$build['links']['node']['#links']['cancel'] = array(
        'title' => t('Cancel'),
        'href' => $cancel_link,
        'html' => TRUE,
        'attributes' => array(
          'title' => 'Cancel',
        ),
      );

and it works fine. But I also need to add "?destination=URL" to links and unfortunately, trying several different approaches didn't work for me. In particular:

I copied the whole Good Example code from https://www.drupal.org/docs/7/theming/overriding-themable-output/how-to-add-a-destinationurl-to-the-request-new-password and replaced my code with:

$build['links']['node']['#links']['cancel'] = l(t('Request new password'), 'user/password', array('query' => array('destination' => 'homepage', 'foo' => 'bar'), 'attributes' => array('title' => t('Request new password via e-mail.'))));

but the link didn't show up at all.

Example on https://www.zyxware.com/articles/5195/how-to-set-destination-as-the-link-value-in-the-l-in-case-of-urls-with-parameters didn't work.

Tried to adapt the accepted answer on use URL with query as URL destination as:

  $query_string = array('destination' => 'service/922');
  $url = url($cancel_link, array('query' => $query_string));
  $build['links']['node']['#links']['cancel'] = array(
    'title' => t('Cancel'),
    'href' => $url,
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Cancel',
    ),
  );

unfortunately, it is also giving %3Fdestination%3Dservice/922 in the browser address bar. What I am doing wrong here?

Addition: Using dpm() I've figured out the above examples all output ready to use links like Request new password

However, if I dpm the link in my function it still gives raw array:

(Array, 4 elements)
title (String, 6 characters ) Cancel
href (String, 33 characters ) admin/some_path/id/cancel
html (Boolean) TRUE
attributes (Array, 1 element)
title (String, 6 characters ) Cancel

And I wonder is it possible to add destination at this stage at all or do I have to intercept the link at a later steps like for example while themeing?

You are doing it correctly but the theme_links() function is called after you create the link. That function calls the l() function, which in turn calls the url() function, which in turn calls drupal_encode_path(), and it's here your Url is getting encoded.

If you override the theme_links() function, you can undo the encoding. Copy the theme_links() function from theme.inc into the template.php of your theme. The function should be named mytheme_links() or, if you want it to apply only to nodes, you can name it mytheme_links__node(). The original theme_links() function has this:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You can replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}

This is just a basic explanation. There are good reasons for encoding links, so you might want to restrict the links you decode.


Rewrite link on other field in Views I'm using Drupal 7 and Clean theme. My main module is Views. And created 2 field in a content type and listed via Views on page.

I want, rewrite a field link on a other field.

e.g.
My Field:

Head: Content Head
Link: www.site.com

When click content head go to www.site.com

How can i do this?

Say you have two fields, title and link, in your view. Click the title field and exclude from display so it doesn't show. Then click the link field and rewrite results. Under rewrite results I think you can check BOTH "Rewrite the output of this field" and "Output this field as a link". In rewrite results text box, put in the replacement pattern [title] and in link path [link] (you can get a full list of replacement patterns below).

If that doesn't work just do a simple href in the rewrite results text box:

[title]


Ranking items (groups, nodes) by the number of Facebook likes I am on Drupal 7.

I need to add a Facebook like button that will be associated with organic groups pages. Each group will have a different like button so that each group has an independent "Likes" count. I can do this by simply configuring and adding a Facebook iframe or XFBML interface. More about this here: http://developers.facebook.com/docs/reference/plugins/like/.

What I cannot figure out is how to retrieve this information from Drupal and use it in a Views. I would like to rank the organic groups according to the number of Likes clicked for each... I figure out I would need some kind of integration with Facebook... Is there any kind of module that will allow an intregration between Drupal and Facebook for this specific functionality? I have been using Janrain for logging users, but as far as I know, it won't provide this kind of integration I am talking about... Or maybe some Views-Facebook, or even Flags-Facebook integration where I could associate Likes with flags for a certain item...

Thank you.

This question recently came up at work (small world), my thoughts:

Render the Facebook like button using the XFBML version of the button
Attach a handler to the click event (see the docs)

FB.Event.subscribe('edge.create',
  function(response) {
    // do some AJAX stuff here
    alert('You liked the URL: ' + response);
  }
);

In the above callback, fire an AJAX request back to drupal, to update either a custom table, or alternatively you can use the core statistics table. If you wish to use the core statistics table (or even create your own table) you can leverage the code from my module https://drupal.org/project/statistics_ajax

One advantage of using core statistics, is that it has views integration out of the box, although in saying that writing custom views data sources for your table is easy too.


How do you handle long runtime updates needed in hook_install()? I have a new module that includes a series of hook_update_N()s. I had written these without knowing that during module install the modules schema value is set to the highest value of hook_update_N() defined while the hook_update_N()s aren't actually run.

Several of the hook_update_N()s take advantage of $sandbox (Batch API), as they are lengthy database changes. As far as I know Batch API does not appear supported in hook_install().

What are my options to get these to run during module installation/deployment?

My suggestion is to not make it automatic on install. Provide a page from where an admin can launch the batch job.

However, if it absolutely must be automated, I have a suggestion, albeit a some what crude such:

hook_init() {
  $run_batch = variable_get('NOT_INSTALLED_YET', FALSE);
  if ($run_batch) {
    // Redirect to batch launch, or possible just set an approprite message.
  }
}

hook_install() {
  variable_set('NOT_INSTALLED_YET', TRUE);
}


Adding node into search api solr programatically We are importing large number of data into our drupal website with custom script and we are using Search api and Search api solr module into our website to index and search large number of data.

When we import data using custom script, Search api solr is not fetching this data and new nodes are not indexing into Solr,

If we update the node, its indexing successfully into solr.

I am trying to adding node programatically into solr but its did not work for us.

search_api_track_item_change($type, array($id));

Can anyone suggest me?

Two things first. These two items are purely a suggestion and have no impact on the code samples bellow:

You should post the code that saves your nodes. The Solr API module should automatically pick up nodes when you save and update them (the search_api module code runs when you call "node_save"). It is odd that it doesn't for you.
You should think about running your solr re-indexing operation after you import all of your data. This will speed up your bulk imports and you can schedule the solr re-index via cron or run it via drush.

The following information comes straight from the search_api module.

These are the pre-conditions for the code examples bellow:

You need to run these after you call the node_save function.
The $type variable refers to the entity type (node, user, term, etc..). In your case it sounds like $type='node'
the $entity variable refers to the node object you're saving. You would pass this object to the node_save($entity) function during the bulk import operation.

If you're inserting nodes:

  $type='node';
  list($id) = entity_extract_ids($type, $entity);
  if (isset($id)) {
    search_api_track_item_insert($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_insert('multiple', array($combined_id));
  }

If you're updating nodes:

$type='node';
list($id) = entity_extract_ids($type, $entity);
if (isset($id)) {
    search_api_track_item_change($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_change('multiple', array($combined_id));
}


PCI compliance with authorize.net payment- Drupal7.x I am looking for a solution where I can collect simple payments from my users but not collect the payment details on drupal server. SO i need to

Attach a payment component to a webform
User can fill up the details and click on pay
On clicking on pay user will be redirected to Authorize.net servers where the user can fill the details and on successful completion return back to Drupal end.

I am using webform_pay module to achieve this. It satisfies most of the points but only problem with this module is it collects the payment details on drupal server which I dont want.
Any suggestion?

It's pretty easy to implement Authorize.net PHP SDK for this purpose. I also had started with Webform Pay (6.x) but it was not reliable in the fact that if a payment failed, or you wanted to do different form widgets (radio, select, text) to represent dollar value, it wasn't very feasible.

I wound up creating my own module that implements specialized Form API fields (CC number, CC date, CC cvv): https://www.drupal.org/project/creditfield

If you are comfortable with Form API, it is very easy to construct simple payment forms (simple donations, bill pay), and then handle the payment submission in your form submit handler. This module makes it possible to create one or more standard forms with Form API without having to implement the same validations all the time on the credit card fields.

I never had a need to store any data locally, not even the user information. If the payment did not succeed, the error was caught and logged and the user was asked to try again. If it succeeded, all of the submitted information was visible in the Authorize.net transaction logs. Check the SDK payload information to see what is available. It's been a while since I have done one, but you could use the card authorization method to create a transaction to be validated, and then perform the transaction.

For other methods, like off-site payment on a service like Authorize.net, you will probably need the applicable walkthrough. It also looks like the Webform Pay module has been abandoned with no stable Drupal 7 release, so this could be a good opportunity to roll up your sleeves and learn Form API + menu routes.

https://developer.authorize.net/api/reference/index.html#payment-transactions


Overriding the output for the primary navigation links Is there another way the primary navigation is supposed to printed out besides how it is done in the core system template?

print theme('links__system_main_menu', array('links' => $main_menu));`

None of the changes I made via the theme_menu_link() function are recognized when the links are printed this way. Are they only seen if I manually put the primary links block into a region?

Which is the function that I could use to override the primary links when printed out this way? Everything I have with theme_menu_link() does nothing.

That syntax (two underscores) means that it first looks for a theme_links__system_main_menu()theme function and then falls back to theme_links() if that doesn't exist.

So to override only the main menu, create the following theme function for your theme: yourtheme_links__system_main_menu().


How to display a block in the webform confirmation page? I'm looking for a way to display a block (a view) in the page that is displayed when a webform is submitted.
This is the url of the confirmation/done page :

domain.com/node/*/done

I can't figure out a way to target this url structure by using the Show block on specific pages or context path settings.

Any ideas ?

It is funny how you have a part of answer in your question. Since you have a block, in "Show block on specific pages", check "Only on the listed pages" and type-in node/*/done (more on wildcards)

Get back if I missed something here.


Views show referencing nodes I have a custom content type called "questions" and few others , "A", "B","C" . (the naming is irrelevant, actually).
Each one of the following content types "A","B","C" has a field that is referencing to a particular node with content type "question".

What I would like to do is to display in a View all questions and next to each question, the titles of referencing nodes(with links to the node).

What approach should be taken ?

You could do the following.

Add the title node with link.
Filter it with Content Type A B and C (Which all content types you want to display.
Add the reference field in Content Type A B and C
Group by the Reference Field.


I want to add functionality into my site that users may be able to sign agreement, pay, and then submit I want to add functionality into my site that users may be able to sign agreement, pay, and then submit. Also I would like to use this data in the future...
Any advice??
EDIT: I want something like web form with payment option on it, I just want a user to be able to pay via Credit card, if the form is filled correctly and all required fields are good... Don't need HIGH-END commerce or online store ??? Please help :(

You can use the Webform module to allow the users to fill it out and then use the Payment for Webform module for payment options.

  This module provides a payment reference Webform component, which
  allows users to associate payments (made through Payment) with Webform
  submissions. A possible use case is requiring users to pay before
  submitting a webform.

or you can do it with Commerce Webform module, by following this tutorial you can easily set up the payment options.


Drupal Commerce product display text input on specific option I have a Product Display that shows a group of products with color and size options. However, I want to show "Custom" as a color option, and if the user selects it, I want a text box to appear where they can input custom text. I can do a custom submit hook to handle the input no problem, but is there a "Drupal way" to add a text box on a certain product option?

you can use drupal conditional field module , and then on a certain value configure your text field to be displayed .
conditional fields


How to encrypt drush backups with gnupg I am trying to set up a cron job that automatically backups up a Drupal site using drush but then encrypts that file. I would like to accomplish this using a single command but am not sure how to go about it.

Here is the command that does the backup and logs any messages (this works):

drush @mysite archive-dump --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" &>> /var/log/mysites/$(hostname -s)/drush-cron.log

However when I try this:

drush @mysite archive-dump --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" | gpg -e -r mypublickey &>> /var/log/mysites/$(hostname -s)/drush-cron.log

It does not work. Any ideas where I am going wrong? What is the correct command?

Thanks.

You're piping the output of the Drush command to gpg, but it's expecting a file path.

By default the output will not be something that gpg can use, but archive-dump has a handy --pipe option which will print just the path to the output file; gpg can use that:

drush @mysite archive-dump --pipe --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" | gpg -e -r mypublickey &>> /var/log/mysites/$(hostname -s)/drush-cron.log


Drupal7 template suggestions for node is not working I created a new content type named job. Now I want to use custom node template for this content type.

I created file name node--job.tpl.php and cleared the cache, but it doesn't pick that file, it is picking only node.tpl.php file.

Anybody have any idea about this?

Your usage is right.Check your code in detail!


Get paragraph delta/weight in template I have defined a paragraph type that has a text field and an image field. At the moment the twig template is something like this

{{ content.field_text }}

{{ content.field_image }}

The problem is I want to alternate the positions of the text & image containers for each paragraph. For example the first one would have text then the image, the next would have the image then the text and so on.

How do I get the paragraph template to be aware of its order in the list? If I use a preprocess function how do I get the order than pass the value as a variable to Twig?

I'm not sure what template you're using, and I'm not sure how your site is setup. But if you have a template that is looping through and displaying these paragraphs, you can add a check in your twig file that checks if the paragraph is even or odd.

{% for paragraph in paragraphs %}
    {% if loop.index is divisibleby(2) %}

{{ paragraph.field_text }}

{{ paragraph.field_image }}

    {% else %}

{{ paragraph.field_image }}

{{ paragraph.field_text }}

    {% endif %}
{% endfor %}


How do you add a custom search box at code level? I have a Drupal 6 site that runs Apache Solr. I need to programmatically add a search form to a custom block that is created by code.

Here is what I'm using:

  $form = array();

  $form['#action'] = 'sitesearch/';

  // search form
  $form['keys'] = array(
    '#title' => NULL,
    '#type' => 'textfield',
    '#value' => t('Search for questions and answers'),
  );

  // add in the click in erase routine
  $form['keys']['#attributes'] = array(
    'class' => 'NormalTextBox txtSearch',
    'onblur' => "if (this.value == '') {this.value = '" . $form['keys']['#value'] . "';} ;",
    'onfocus' => "if (this.value == '" . $form['keys']['#value'] . "') {this.value = '';} ;"
  );

  $form['submit'] = array(
    '#value' => t('Search'),
    '#type' => 'submit',
    '#attributes' => array('class' => 'filtered-search-form-submit'),
  );

  return $form;

When I submit the form I get to the search results page but it's blank, as if nothing was searched. Any ideas or guidance would be great.

I'm pretty brain-dead. I just set up a custom submit handler for a custom form for search to redirect after form submission to the search results page with the right URL, e.g., passing the query and filter in manually.


Add counter to comments I would like to add a coutner to comments, so when I view a node I've something like:

Comment #1 - Text
Comment #2 - Text
Comment #3 - Text

and so on..

Is there a way to obtain this?
Obviously #1, #2 and #3 are number relative to every singole node.

Thanks!

Override comment.tpl.php and add the following to it:

<?php print 'Comment #' . $id; ?>

(You obviously add it to the spot in the template where you want the comment number to appear.)

Here is the contents of my override for comment.tpl.php for Bartik;

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php print $picture; ?>

        <?php print $author; ?>
        <?php print 'comment #' . $id; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

    <?php if ($new): ?>
      <?php print $new; ?>
    <?php endif; ?>

    <?php print render($title_prefix); ?>
    <h3<?php print $title_attributes; ?>><?php print $title; ?>

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

    <div class="content"<?php print $content_attributes; ?>>
      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['links']);
        print render($content);
      ?>
      <?php if ($signature): ?>

        <?php print $signature; ?>

      <?php endif; ?>

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


Webform Fields not hidden anymore after update to 8.x-5.0-rc19 After updating to Webform 8.x-5.0-rc19 fields that should be visible only after filling another field, are instead always visible. I guess this has something to do with "Elements, containers, and pages that are hidden using conditional logic will have their submission data cleared when a webform is submitted" (https://www.drupal.org/node/2956589), but I do not understand how.

Please see #states breaks when OR is used


cmis configuration alfresco cloud I'd like to use the Alfresco Cloud ECM with my Drupal instance. I created an alfresco site. I installed and activated the CMIS module. Here is my configuration script:

$conf['cmis_repositories'] = array(
    'default' => array(
      'label' => 'cmis.alfresco.com',
      'user' => 'my_alfreso_cloud_username@example.de',
      'password' => 'my_alfreso_cloud_password',
      'url' => 'https://cmis.alfresco.com/cmisatom'
    ),
  );

I only find these lines to configure the module. Then I added a CMIS field to my content type. When I add a new node then there is an error:

  Notice: Undefined index: cmis_field_rootFolderPath in cmis_field_field_widget_form() (line 123 of D:\Inetpub\SK1913\sites\all\modules\cmis\cmis_field\cmis_field.module).

I cannot find any other configuration forms (beside the root path setting).

What am I doing wrong? Does this module work with the alfreso cloud solution? I don't want to install alfreson on my server until I know how to use it, or even if I use it...

I think there is one more configuration in setting.php for content type mapping with its fields.

In this example i have mapped article content type with cmis type.

$conf['cmis_sync_map'] = array(
 'article' => array(
     'enabled' => TRUE,
     'cmis_sync_cron_enabled' => TRUE,
     'cmis_folderPath' => '/Sites/New/Article',
     'full_sync_next_cron' => TRUE,
     'cmis_sync_nodeapi_enabled' => TRUE,
     'subfolders' => TRUE,
     'cmis_type' => 'alf:article',
     'content_field' => 'body',
   ),
);

$conf['cmis_sync_map']['article']['fields'] = array(
  array('drupal' => 'title', 'cmis' => 'cmis:name', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'body', 'cmis' => 'cm:content', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
  array('drupal' => 'field_object_id', 'cmis' => 'cmis:objectId', 'drupal to cmis' => TRUE, 'cmis to drupal' => TRUE),
);

I hope it will works for you.


Lock editing on node except for Admin I have a content type with a select field. When the selected value from that field is "Locked", I would like to lock editing on that node for all roles except admin (or other role I choose to be admin). Then if the admin selects a different value, I would like to unlock editing on the node. For this reason it seems that rules are the best way to trigger an action like this. I have the content access module installed, which allows targeted access permission both for content types, and individual nodes. But how can I combine the two parts to lock editing automatically based on the select list? If I couldn't do it automatically, is there some way to restrict all access per node?

Edit:
This is possible with Rules and content access. There is an action provided by the content access module which will revoke access to a node based on role.

It sounds like you could accomplish this with a combination of rules and user roles. I assume to don't want the node to be editable by anonymous users so set the rule to grant editing permissions to all users who have a particular role when the value of the field changes from locked to unlocked (or whatever your corresponding value is). If you want more granular control, (i.e. when a node is unlocked some fields are editable but others remain editable only by admin users), you'll need to install the field permissions module (https://drupal.org/project/field_permissions.


block for the navigation I'm getting to grips with Drupal 7 at the moment. One thing that I'm finding frustrating at the moment (perhaps because I'm misunderstanding) is blocks.

Can you not just have a blank block give it a template and do what you want? I'm creating a sub theme off of Bartik and would like to put the main navigation into it's own block (to keep things tidy) and then just call the region this block is set but this doesn't seem to work. It seems I have to have the body text from the block included and the navigation doesn't seem to work either. I have come from developing in wordpress which has the loop, if you're in the loop you can call what you please, but this doesn't seem to be the case for Drupal?

Block

Define region in theme information file (https://www.drupal.org/node/171205).

Example: regions[main-menu] = Main Menu
Call the region in template file (html.tpl.php or page.tpl.php)

Example: <?php print render($page['main-menu']); ?>
Clear website cache

Procedure:  Configurations -> Performance -> Clear all caches
Now you can assign any block to the region.

Procedure: Structure -> Blocks -> Here you can see 'Main Menu' region as unassigned. Assign any block to this region (example: assign menu menu block to main menu region).

Templating

To know more about templating: https://www.drupal.org/documentation/theme

Since you are coming from a WordPress background, please get familiar with theme structure of Drupal and then start working on themeing.


How to export user's content via features to new site in Drupal 7 Can anyone tell me how to export contents of users through some contributed modules?? like features,because I have a site which has 100 users,all contents are migrating through features but user's info and their images are not being moved with features module..

Your solicited help is needed.

You can use Data export import module
Here ls the link of module - https://www.drupal.org/project/data_export_import


Drupal 8 Webform URL alias with parameters On the URL PATH SETTINGS,  I want to define the Webform URL alias to include a variable parameter e.g. /my-web-form-url/{id}
Is this possible? I want to pass this 'id' as a hidden value in the form.

You would need to write some custom code to support custom URL parameters. (see How to (truly) alter a URL in Drupal 8)

You could easily pass the 'id' as a query string parameter, which is supported as long as you enable 'Allow elements to be populated using query string parameters.' under a Webform's > Settings > Form Behaviors.


What is the default operator in Rules module conditions? I have an issue on production site that I cannot reproduce.

The Rule below should trigger an email if the new content is published. But emails are being send even if content is not published.

{ "rules_content_new" : {
  "LABEL" : "Notify new content",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--article" : { "bundle" : "article" } },
  "IF" : [
  { "data_is" : { "data" : [ "node:status" ], "value" : "1" } },
  { "data_is" : { "data" : [ "node:field-custom" ], "value" : "13" } }
  ],
  "DO" : [
  { "mail" : {
  "to" : "test@mail.com",
  "bcc" : "[site:full-mailing-list]",
  "subject" : "[node:title]",
  "message" : "new content available",
  "from" : "test@from.com",
  "language" : [ "" ]
  }
  }
  ]
  }
 }

From official Rules documentation:

  By default, Rules assumes AND operators between conditions (if no OR
  group is explicitly used).

Syntactically there is nothing wrong with your rule.

A little tip for troubleshooting this rule (because obviously that rule does not give you any error messages) - add action "Show a message on the site" and output values from your conditions in that message. If the values shown are correct but the rule still malfunctions - try deleting it and then recreate it.

Also, you can try using Rules condition "Content is published" instead of checking the value of node:status. It is basically the same thing, but maybe in your situation will give a different result.


How do I create a view with filter on a field built using the date module? I created a content type that includes a date field.  I want to create a view that filters on this field, but it appears that the field is being seen as a text field because there are no operators for greater than or less than like I would see if I were filtering on the posted date.  I only see text based operators like length, starts with, etc.  What do I need to do?  I'm running Drupal 7.  How do I make this work?

You have 2 types of date filter handlers in Views ; try not to use the one that is your field but the date field, that will ask you on which date field it'll filter.


How would you migrate a large list of (taxonomy) vocabulary list? I'm moving a large series of vocabulary lists to a new D7 install. I used features to copy over taxonomy groups. However, I only copied over the taxonomy not the vocabulary lists. Is there an extension to features to handle this?

I have never used it quite for this purpose, but the Feeds module will import from CSV files and can create taxonomy terms.  The Drupal 7 version still says it is alpha status, but I have been using it for a while now without any real problems with CSV files.

Just make sure your CSV is UTF-8 clean, otherwise you may get some obscure SQL errors if your data has characters with diacriticals, etc.


How do I add default header and footer regions to my site? i have added regions in my theme.info file. now i want to add default header and footer with logo in all the pages of my site.This is my page.html.twig

    {{ page.header }}

  {{ page.primary_menu }}
  {{ page.secondary_menu }}

  {{ page.breadcrumb }}

  {{ page.highlighted }}

  {{ page.help }}

    {# link is in html.html.twig #}

      {{ page.content }}

{# /.layout-content #}

    {% if page.sidebar_first %}

        {{ page.sidebar_first }}

    {% endif %}

    {% if page.sidebar_second %}

        {{ page.sidebar_second }}

    {% endif %}

  {% if page.footer %}

      {{ page.footer }}

  {% endif %}

{# /.layout-container #}

I have placed files region--header.html.twig and region--footer.html.twig .Please help me how to place logos and other contents in header and footer

You define a region in your theme's info file and then print it in your page.html.twig. Content to each region is added via blocks. You only add your own region templates when you need to make some changes to the markup.

OK, so you added the regions in your info file, and printed them in your page template, fine. First of all, delete your region--header.html.twig and region--footer.html.twig again. Then in the backend of your site go to Structure > Blocks. Your newly added regions should appear there. Now place some blocks in your newly added regions. Save, flush cache and visit your frontend again. Your regions should be populated now.

And regarding the region--YOURREGION.html.twig templates you should have deleted by now, these only will be picked up when these regions are populated – with blocks. Otherwise these regions simply won't get printed at all.


How to update a views row class in real time clicking a Flag (ajax) link Flag allows flag toggle link to use ajax, but that does not update the row class in real time. Only the field class is changed.
Question is how to make the row to have a class when the flag link is clicked.
In my case, its a simple common case scenario of task list and the flag toggle is used to make a task 'completed', which should make the whole row another color in real time, not after page refresh.

I got as far as this script, which doesnt yet seem to work. It adds the class .highlight_row to the row in which a flag link is clicked. The flag link has a class .unflagged before clicking.

$(document).ready(function(){
    $('.flag').click(function() {
       if ($(this).is("unflagged")) { //If unflagged
        $(this).closest('tr').addClass("highlight_row");
    } else {
        $(this).closest('tr').removeClass("highlight_row");
    }
    });
});

EDIT
The following code worked eventually:

(function($) {
   $(document).ready(function(){
        $(".rules-link-set_completed").children("a").click(function() {
            $(this).closest('tr').addClass("completed");
        });
   });
})(jQuery);

Add a javascript file to your theme, or if you're using a theme that has a template, use that.  Omega 4 has a brilliant template file with explanations on how it works and a short example.  There is also a very good tutorial on using javascript and JQuery with Drupal on Drupal.org.

Basically I would set a click event on the flag checkbox and then use the .closest() method to find the row which the checkbox is inside and add or subtract classes accordingly.


Pathauto module doesn't translate urls generated by l(), url() to aliases, should it? Pathauto readme says:

  If you use the "system path" (i.e.
  node/10) for menu items and settings
  like that, Drupal will replace it with
  the url_alias.

But in my case links stay the same:

echo l('test', 'node/329'); // returns: node/329, should return: about-us

It is first time I'm using Pathauto, I was expecting it to work out-of-the-box as I followed all the instructions and there was nowhere mentioned any special url-translation activation procedure or something (is there one?).

When I paste domain.com/about-us into the browser address bar it manages to load proper page. But it doesn't translate my links.

Any idea what could be wrong or where I should I start to repair it?

Ok, found the reason. My admin area is dual-languaged and while I generate aliases in English, front-end runs in Dutch. Once I switched admin and front-end to the same language I got it working as expected.


How to push changes from a dev environment to prod Our team of 10 developers would like to use Dev, Test, Staging and Production environments for our large site.  How can we streamline pushing our changes from one site to another, keeping them as identical as possible?

The difference between this question and How to migrate from test environment to production environment? is that we would like to push changes automatically/regularly so that the environments not very different.

We have been using a Dev and Production environment for the past few years, and each environment has its own SVN code repo.  The Features module has been used in a few places, but it does not work with Blocks or Content.

One proposal was to use Drush and use archive-dump and archive-restore to push the changes between the environments, but Production has content provided by visitors and users and pushing to Production would wipe out that content.

Has anybody answered this question before?

I use a custom script to automatically pull production to backup and update servers (an update server is a sanitized clone of production with updates applied via pm-update, standing by and ready for testing).  You might get some ideas looking at that.  However, I'd say that it would be a bad idea to automatically sync either prod to dev, or dev to prod.  Only publish to production after a human has tested and validated the release you'd like to bring live.  As for automating prod to dev updates, I'd think that the devs would find that very annoying.

One thing that you could pretty easily do is automate the updates of your staging server.  Just pull the database down from production, pull the latest code up from the dev branch of your repository, and run updatedb and your test suite.  A human could then validate the results and publish the code to production if it was ready.


What are the effects of the "access commerce administration pages" permission The SA-CONTRIB-2020-020 security patch was titled "Further restrict anonymous user access to anonymous orders."
Unfortunately it seems to have broken some sites I work on.  We are now seeing access denied errors on admin/commerce/orders/xxx for "semi-trusted" users who have permission "Default: Update orders".  For these sites the security patch was a non-back-compatible change and I have raised an issue for that.
The solution that worked for me is to grant the semi-trusted users the "access commerce administration pages" permission.
However I am nervous because this permission doesn't seem to have clear documentation.  I don't wish for these "semi-trusted" users to suddenly gain extra access that they should not have such as to edit products.
Please can anyone confirm the effects of this permission?  Does it do nothing alone and only work if other permissions are added?

Does it do nothing alone and only work if other permissions are added?

Currently, yes (although that could theoretically change in the future).
The permission is added to all HTML admin routes for the order entity type (add/edit/etc), and for admin overview pages, which essentially list sub-pages that the user has access to.
If the user doesn't have access to those sub-pages, all provided by separate permissions, they won't see the links, and won't be able to visit them. Similarly, if they don't have the correct entity access permission, they won't be able to perform the respective operation on the entity.


How do I update a node's file field from within a module? I have a file: /tmp/new.zip and I have a node, $node, that has a file field, field_ios_file. Currently, old.zip is the file saved in to the field_ios_file field. I'd like to put /tmp/new.zip there.

What I have now:

$file = file_uri_to_object('/tmp/new.zip');
print_r($node->field_ios_file);
$node->field_ios_file['und'][0] = $file ;
print_r($node->field_ios_file);
node_save($node);

the node_save() fails here because $node->field_ios_file['und'][0] should be an array, not an object. I would imagine there is a function that looks something like field_update($node, $my_field, $data), but I can't find anything like that.

The file field type has a fid column (file ID); you just need to save the file so an ID is populated, and add it to the node like this:

$file = file_uri_to_object('/tmp/new.zip');
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$node->field_ios_file[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);


Unsupported operand types hi suddenly i started to get
Fatal error: Unsupported operand types in E:\localhost\htdocs\drupal\modules\field\field.info.class.inc on line 479

any page i visit just display this error

how to fix this ?

The problem here is that in the given file, the line

$field['settings'] += field_info_field_settings($field['type']);

fails (i.e line 479), because field_info_field_settings() doesn't return an array. This shouldn't happen and it is probably caused by a custom or contrib module or by faulty data in your database.

You can try to trace the error down. Open field.info.class.inc in a text editor and put the following code directly above the line 479:

$field_settings = field_info_field_settings($field['type']);
if (!is_array($field_settings)) {
  print_r($field);
  die();
}

Then load a page where you would normally get that error and look at the printed details (I hope there are any). Then ask yourself the following questions:

For which field are the settings requested?
Does this field still exists?
Is it a field declared by a module that you have disabled?

This should help you to trace down the problem.

Remember to remove the debug code!


Content Type - turn in to Form on front end to be used Im fairly new to Drupal.
Coming from Joomla.
I created content type that works flawlesly and now i would like to take that form thats in the admin area and show it on front end for public to fill out.

Is this easely possible or do i need to use the Form API and rebuild the form and some how map to the fields in DB ?

Please let me know whats the best way to go about this.

Thanks In advance

Under /admin/people/permissions you can grant a role access to create/edit/delete content of a specific type.

Look for the sub-heading Node and pick your content type from any listed. I've highlighted Poll in my example.

Click here for full size image

Here is the guide for roles and permissions from Drupal:
https://drupal.org/node/120614


Expose filter with collabsible div on click in a Calendar I have created a calendar showing Events in different cities.The City names are taken as Taxonomy and are displayed as a filter.On selecting a Particular city the Calendar shows all the events of that particular city in that month.I want the number of events in that particular city in the filter next to the city name.On clicking the City name in filter it should display the event details under it. Eg.If Atlanta have 4 events and Chicago have 1 event London doesnt have any event in July it should be displayed as

Atlanta(4)
Chicago(1)
London(0)

for that particular month. On clicking the City the display is like-

Atlanta

Event1
Event2
Event3

Chicago(2)

London(0)

ALong with calendar filtering and showing only Events related to Atlanta.

How to get this Functionality please help.

I'm going to assume that each event is a node in Drupal, yes?

The filters you are describing are called 'facets', and there are a number of ways you can get them, but probably the most robust is to:

Install Apache Solr on your server if you haven't already
Install the Solr Search module in Drupal and configure it to search your events
Install the Facets API module and enable facets for your Country attribute

All of these things are well documented.

The one I had the most trouble with was the initial install of Apache Solr, but the instructions are specific to your O/S so unless you're using RedHat or a derivative, the blog post that helped me won't be very useful.


Showing local tasks in toolbar with hook_toolbar: caching problem I'm creating a module using the toolbar api showing all administrative functions in a more compact toolbar. I'm having "cache" troubles showing the local tasks in the toolbar... How can I keep these items outside the toolbar cache?

In my custom module I use hook_toolbar to add the local tasks

/**
 * Implements hook_toolbar().
 */
function compact_toolbar_toolbar() {

    $items = [];
    ...

    $tasks = _compact_toolbar_local_tasks();
    $items = array_merge($items,$tasks);

    return $items;
}

And a function to generate the toolbar local tasks...

/**
 * Create local tasks toolbar items
 */
function _compact_toolbar_local_tasks() {

    $items = [];
    $route = \Drupal::routeMatch()->getRouteName();
    $manager = \Drupal::service('plugin.manager.menu.local_task');
    $primary = $manager->getLocalTasks($route, 0);

    foreach($primary['tabs'] as $key => $tab) {

        // add toolbar tab
        $items[$key] = [
            '#type' => 'toolbar_item',
            '#cache' => [ // Can I overrule the toolbar cache here?
                'max-age' => 0,
            ],
            'tab' => [
                '#type' => 'link',
                '#title' => $tab['#link']['title'],
                '#url' => $tab['#link']['url'],
                '#access' => $tab['#access'],
                '#attributes' => [
                    'title' => $tab['#link']['title'],
                ],
            ],
            '#weight' => $tab['#weight'],
        ];

        // check if task is active
        if($tab['#active']) {
            $items[$key]['tab']['#attributes']['class'][] = 'is-active';
        }

        // get secondary tabs for each primary tab
        $route = $items[$key]['tab']['#url']->getRouteName();
        $secondary = $manager->getLocalTasks($route, 1);

        // get secondary tabs as tray
        if (!empty($secondary['tabs'])) {

            $links = [];
            $items[$key]['tab']['#attributes']['class'][] = 'toolbar-parent';

            // create renderable array of secondary links
            foreach ($secondary['tabs'] as $skey => $stab) {
                $sname = substr($skey, strrpos($key, '.') + 1);
                $links[$sname] = [
                    'type' => 'link',
                    'title' => $stab['#link']['title'],
                    'url' => $stab['#link']['url'],
                ];
            }

            // add tray with secondary tasks
            $items[$key]['tray'] = [
                '#heading' => t('Secondary tasks'),
                'toolbar_secondary_tasks' => [
                    '#theme' => 'links__toolbar',
                    '#links' => $links,
                    '#attributes' => ['class' => ['toolbar-menu']],
                ],
            ];

        }

    }

    return $items;
}

When I disable the cache in hook_page_top in core/modules/toolbar/toolbar.module everything works like a charm. Otherwise my custom items won't follow the current page...

/**
 * Implements hook_page_top().
 *
 * Add admin toolbar to the top of the page automatically.
 */
function toolbar_page_top(array &$page_top) {
  $page_top['toolbar'] = array(
    '#type' => 'toolbar',
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
    /*
    '#cache' => [
      'keys' => ['toolbar'],
      'contexts' => ['user.permissions'],
    ],
    */
  );
}

Can I overrule the toolbar cache by using the #cache array in my custom toolbar items? Which tags/context should I use?

This is how the toolbar looks like with my compact_toolbar module enabled... (but toolbar cache disabled) I really like the result! - I also made the menu behave like a simple dropdown menu and added a "content menu" to quickly add new content...

"The toolbar is a container for administrative and site-global interactive components."

https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/function/hook_toolbar/8.2.x

That would indicate that the toolbar is not the solution you are looking for as the more contextual tabs are not site global but page specific.